diff --git a/docs/dsh-ai-backlog-2026-10-29.md b/docs/dsh-ai-backlog-2026-10-29.md index 48bfeda..bd9ef5f 100644 --- a/docs/dsh-ai-backlog-2026-10-29.md +++ b/docs/dsh-ai-backlog-2026-10-29.md @@ -4,17 +4,17 @@ ## 当前基线 -按32个能力组核对:11项已具备、14项部分接入、7项未接入;下表21项均保持待办。完整现状、代码位置及验证边界见 [能力扫描报告](dsh-ai-management-audit-2026-10-29.md) 和 [机器可读清单](research/dsh-capability-audit-2026-10-29.json)。 +最初按32个能力组留档:11项已具备、14项部分接入、7项未接入。PR #4审查修复后为13项已具备、12项部分接入、7项未接入;最初21项保留在下表,M05/M10已闭环,剩余19项仍未完整。完整现状、代码位置及验证边界见 [能力扫描报告](dsh-ai-management-audit-2026-10-29.md) 和 [机器可读清单](research/dsh-capability-audit-2026-10-29.json)。 -## 优先修复的确定问题 +## 已完成的确定问题修复 | 编号 | 优先级 | 问题 | 验收要求 | |---|---|---|---| -| REL-01 | P2 | 定时投递在模型建轮前失败后无法恢复 | 配额或模型恢复后可人工重试明确未调用的投递;结果未知不自动重试,且不能重复执行同次消息。 | -| REL-02 | P2 | 周期任务达到原会话100轮后持续失败 | 容量预警、停止或迁移有明确状态,安全续接后无丢失或重复。 | -| REL-03 | P2 | 固定操作成功后审计失败被归为普通失败 | 保留副作用结果,标记needs_review,禁止不经核验的重复执行。 | -| REL-04 | P3 | 过期或版本失效建议无法拒绝 | 所属用户仍能拒绝/归档无效建议;拒绝不要求建议仍可执行。 | -| REL-05 | P3 | 定时队列恢复后旧全局错误不清除 | 成功恢复后更新健康状态,管理页可重新编辑,历史错误证据仍可追溯。 | +| REL-01(已修复) | P2 | 定时投递在模型建轮前失败后无法恢复 | 配额或模型恢复后可人工重试明确未调用的投递;结果未知不自动重试,且不能重复执行同次消息。 | +| REL-02(已修复) | P2 | 周期任务达到原会话100轮后持续失败 | 容量预警、停止或迁移有明确状态,安全续接后无丢失或重复。 | +| REL-03(已修复) | P2 | 固定操作成功后审计失败被归为普通失败 | 保留副作用结果,标记needs_review,禁止不经核验的重复执行。 | +| REL-04(已修复) | P3 | 过期或版本失效建议无法拒绝 | 所属用户仍能拒绝/归档无效建议;拒绝不要求建议仍可执行。 | +| REL-05(已修复) | P3 | 定时队列恢复后旧全局错误不清除 | 成功恢复后更新健康状态,管理页可重新编辑,历史错误证据仍可追溯。 | 另有一个未验证风险:关停时是否完整等待定时审批的最终审计,需要专门故障注入验证,不计为已确认缺陷。 @@ -34,10 +34,10 @@ | AI16 | 代码修复闭环 | 部分接入,待办 | 隔离执行和恢复证据完整;合并、部署与本机执行风险有清晰边界。 | | M02 | 会话标题与整理 | 未接入,待办 | 支持本人会话改名与整理,版本冲突和跨用户访问均被拒绝。 | | M03 | 模型能力管理 | 部分接入,待办 | 模型能力来源、目录刷新、失效状态和健康检查可核验。 | -| M05 | 失败定时调用恢复 | 部分接入,待办 | 区分未调用模型与结果未知,只有明确安全的投递可由用户重新入队。 | +| M05 | 失败定时调用恢复 | 已具备,审查修复完成 | 区分未调用模型与结果未知,只有明确安全的投递可由用户重新入队。 | | M06 | 长期周期任务续接 | 部分接入,待办 | 接近容量上限时预警;用户可将周期任务安全续接到新会话且不重复触发。 | | M07 | 定时历史与追踪 | 部分接入,待办 | 逐任务历史可分页并跳转到对应消息,正确展示保留期限与截断范围。 | -| M10 | 操作结果与审计闭环 | 部分接入,待办 | 副作用已发生后记录失败显示待核实并保留结果证据,不能自动重放。 | +| M10 | 操作结果与审计闭环 | 已具备,审查修复完成 | 副作用已发生后记录失败显示待核实并保留结果证据,不能自动重放。 | | M11 | 额度与费用观测 | 部分接入,待办 | 提供用户级额度与token/费用观测,不将估算当作实际计费。 | | M12 | 运行诊断与恢复 | 部分接入,待办 | 队列错误恢复、模型错误及失败任务状态可追踪和恢复。 | | M13 | 附件资产管理 | 部分接入,待办 | 独立附件列表、归属、容量和删除策略可管理,不泄露跨会话图片。 | @@ -52,8 +52,8 @@ ## 执行顺序 -1. 先处理REL-01~REL-03,并进行重启、审计失败、配额耗尽和并发的故障注入。 -2. 再处理REL-04~REL-05、任务历史与消息跳转、长对话和流式体验。 +1. 保持REL-01~REL-05故障注入回归,并进行实际运行复核。 +2. 继续补任务历史与消息跳转、未来周期规则显式迁移、长对话和流式体验。 3. 联网、Office/OCR、技能管理、计划和子代理按实际场景单独设计,不以功能数量代替可靠性。 本次PR用于评审并集成已有能力,不代表这些待办已完成,不执行自动合并。 @@ -61,3 +61,5 @@ ## 合并请求验证补充 见 [验证记录](dsh-pr-verification-2026-10-29.md)。TEST-01:并发冷启动下邮件管理入口测试曾超时,单独重跑通过,等待稳定性复核;它不计为已确认业务缺陷。当前请求保留草稿,未自动合并。 + +PR #4行级评论66~69的修复和测试映射见 [本轮修复记录](dsh-pr4-review-fixes-2026-10-29.md)。容量停止不等于自动迁移未来周期规则,原始未调用消息可经确认转到本人其他会话,旧附件不会自动迁移。 diff --git a/docs/dsh-ai-management-audit-2026-10-29.md b/docs/dsh-ai-management-audit-2026-10-29.md index 8191905..2a91f60 100644 --- a/docs/dsh-ai-management-audit-2026-10-29.md +++ b/docs/dsh-ai-management-audit-2026-10-29.md @@ -2,9 +2,9 @@ 范围:dsh 当前工作区(包含未提交修改),对照本机固定版 DeepSeek Harness 0.2.1-rc.2。未将包已安装当作功能已接入,也未宣称与实时上游最新版本完全一致。 -**32 个能力组:11 项已具备、14 项部分接入、7 项未接入。共 21 项尚未完整,不等于 21 个缺陷;联网、子代理等是否补齐需按产品需要选择。** 已具备指所列范围,不表示整个系统已完成全流程验收。 +**PR #4 审查修复后,32 个能力组:13 项已具备、12 项部分接入、7 项未接入。共 19 项尚未完整,不等于 19 个缺陷;联网、子代理等是否补齐需按产品需要选择。** 已具备指所列范围,不表示整个系统已完成全流程验收。 -## 当前确定的5个闭环问题 +## 审查中确认并已修复的5个闭环问题 | 优先级 | 问题 | 影响 / 位置 | |---|---|---| @@ -14,7 +14,7 @@ | P3 | 过期/版本失效建议无法拒绝 | reject复用执行guard,卡片可能永久proposed。configuration-approval.cjs guard/reject | | P3 | 定时队列旧全局错误未自动清除 | 已恢复后catalog仍带error,管理页可能持续只读。native-schedules.cjs kick、schedule-manager.js refresh | -以上5项本轮记录为待修复。另有关停时任务审批是否完整等待的风险尚未故障注入,不计确定缺陷。 +以上5项已在PR #4审查修复中处理,故障注入和界面验证见 [修复记录](dsh-pr4-review-fixes-2026-10-29.md)。下面的问题描述保留为原始发现,不代表仍未修复。另有关停时任务审批是否完整等待的风险尚未故障注入,不计确定缺陷。 ## 能力清单 @@ -40,14 +40,14 @@ | M02 | 会话标题与整理 | 未接入 | 标题取首条40字;无手工改名、置顶与文件夹整理。(`src/modules/assistant/conversation-history.cjs`) | | M03 | 模型能力管理 | 部分接入 | 有模型元数据与视觉标记;没有统一能力探测、供应商健康看板和实时自动刷新。(`src/modules/assistant/provider-catalog.cjs`) | | M04 | 定时任务增删改查 | 已具备 | 官方ScheduleService、本人跨会话管理、搜索筛选、详情及逐次授权。(`web/modules/assistant/schedule-manager.js`) | -| M05 | 失败定时调用恢复 | 部分接入 | 失败可见,但没有失败投递的安全重试/重新入队接口。(`src/modules/assistant/native-schedules.cjs`) | -| M06 | 长期周期任务续接 | 部分接入 | 原会话100轮上限后任务仍active,没有容量预警、迁移或滚动会话。(`src/modules/assistant/store.cjs`) | +| M05 | 失败定时调用恢复 | 已具备 | 未建轮消息可明确授权后重试,保持同次请求标识;已有调用或结果未知不重放,归档取消不会复活。(`src/modules/assistant/native-schedules.cjs`) | +| M06 | 长期周期任务续接 | 部分接入 | 剩余10轮起预警,容量用尽停止原生未来计时并保留规则快照;未调用消息可确认转到本人其他会话。未来周期规则仍需在新会话重新安排。(`src/modules/assistant/store.cjs`) | | M07 | 定时历史与追踪 | 部分接入 | 有真实模型调用状态;汇总最近200条,缺逐任务完整分页和从记录跳转到对应消息。(`src/modules/assistant/native-schedules.cjs`) | | M08 | AI能力权限目录 | 已具备 | 本轮新增角色、资源范围、服务就绪、写字段、人工边界可见面板。(`src/modules/assistant/management.cjs`) | | M09 | 逐次授权与隔离 | 已具备 | owner/role、会话绑定、时效、版本、审查token与防重放。(`src/modules/assistant/configuration-approval.cjs`) | -| M10 | 操作结果与审计闭环 | 部分接入 | 有持久审计;旧固定操作副作用后的记录失败尚未统一needs_review。(`src/modules/assistant/service.cjs`) | +| M10 | 操作结果与审计闭环 | 已具备 | 固定操作开始后异常标记needs_review,保留已返回结果;审计或结果保存失败不会被误标为普通失败。(`src/modules/assistant/service.cjs`) | | M11 | 额度与费用观测 | 部分接入 | 按次全局日额度;本轮多次模型调用逐次计数。缺用户配额、token及费用统计。(`src/modules/assistant/store.cjs`) | -| M12 | 运行诊断与恢复 | 部分接入 | 有服务就绪和探测;缺集中模型错误详情、失败任务恢复和队列管理。(`src/modules/assistant/service.cjs`) | +| M12 | 运行诊断与恢复 | 部分接入 | 队列恢复后清除当前全局错误;仍缺统一模型诊断、队列容量与更细恢复管理面板。(`src/modules/assistant/service.cjs`) | | M13 | 附件资产管理 | 部分接入 | 可发前预览移除、会话内复用和删除清理;无独立附件库与容量面板。(`web/modules/assistant/attachments.js`) | | M14 | 备份恢复 | 已具备 | 既有加密载荷AAD迁移与provider/会话恢复;本轮未重做整机灾备演练。(`src/platform/backup/restore.cjs`) | | M15 | 对话与诊断导出 | 未接入 | 未接Harness会话日志导出和本应用结构化诊断包导出。(`src/modules/assistant/api.cjs`) | @@ -69,8 +69,8 @@ AI通过受控JSON查询协议按需读取,然后继续生成回答;最多2 ## 建议下一轮顺序 -1. 先修复上述3个P2,确保自动任务与操作结果可恢复、可核验。 -2. 再修复两个P3,补齐失效建议清理、队列健康恢复、逐任务历史和消息跳转。 +1. 保持本轮恢复/停止/取消/审计故障回归,复核真实运行结果。 +2. 继续补逐任务完整历史、消息跳转和未来周期规则的显式迁移。 3. 再补流式正文、长上下文摘要、全文搜索、调用/token费用可观测。 4. 原生只读工具、结构化追问、计划和技能管理按实际工作流接入;联网、Office/OCR、子代理单独评估。 diff --git a/docs/dsh-pr4-review-fixes-2026-10-29.md b/docs/dsh-pr4-review-fixes-2026-10-29.md new file mode 100644 index 0000000..baffa61 --- /dev/null +++ b/docs/dsh-pr4-review-fixes-2026-10-29.md @@ -0,0 +1,16 @@ +# PR #4 审查修复记录(2026-10-29) + +对应审查1的行级评论66~69。保留人工复审,不自动合并。 + +| 评论 | 修复 | 验证 | +|---|---|---| +| 66:失败定时投递不可恢复 | 区分not_started与已有调用/未知状态;人工确认后沿用同次请求ID重新入队,跨本人会话也检查是否已有请求。待处理消息不随普通200条终态历史裁剪。 | 配额耗尽、重启、并发重复重试、建轮后审计失败、已有请求与中断恢复、HTTP角色/归属/参数校验、界面确认。 | +| 67:副作用后记录失败被当普通error | 固定操作开始后异常保守标needs_review,保留已返回result并记录核验证据。同一卡片不允许重放,前置审计失败仍在调用前停止。 | workspace审计、最终journal和结果保存分别注入故障,验证副作用只发生一次且结果保留。 | +| 68:失效建议无法拒绝 | 拒绝只验证账号/归属/权限/状态和审计可用性,不要求建议仍可执行;删除审批token和写rejected同事务完成,界面提供直接拒绝。 | 过期、版本变化、关闭操作开关、token失效、防重复拒绝及实际界面。 | +| 69:100轮后周期任务持续失败 | 剩余10轮起警告。容量满时先持久保存规则快照和消息,再通过官方ScheduleService.delete停止未来计时;支持stopping/stopped状态和重启核验。 | 100轮时不调用模型、原生任务已移除、规则快照仍可见、停止回执丢失后恢复、未调用消息明确授权转到本人其他会话。 | + +容量停止只处理原有未来计时器,重试只处理那一条已接受但尚未调用的消息;未来周期规则不自动迁移,目标模型/历史与旧附件范围在重试前告知。 + +同时修复队列全局错误恢复后未清除(REL-05),历史投递错误仍保留。复审中发现的旧排队快照取消竞态也已修复:逐条重读并CAS认领,归档先取消排队消息再等待原生服务,catch/finish不覆盖已取消或迁移的当前状态。 + +专项故障与恢复用例位于tests/assistant/review-recovery.test.cjs,共16项;最新管理/审批/集成定向31项通过。完整业务回归使用npm test重新执行,最终结果将写入PR验证记录。测试使用隔离数据与模拟模型,未操作真实邮箱、BPM节点、正式发布或生产业务配置。 diff --git a/docs/research/dsh-capability-audit-2026-10-29.json b/docs/research/dsh-capability-audit-2026-10-29.json index 5965148..6d47a8c 100644 --- a/docs/research/dsh-capability-audit-2026-10-29.json +++ b/docs/research/dsh-capability-audit-2026-10-29.json @@ -4,8 +4,8 @@ "branch": "dsh", "baseline": "installed @deepseek-ai/dsh 0.2.1-rc.2; current working tree including uncommitted changes", "counts": { - "ready": 11, - "partial": 14, + "ready": 13, + "partial": 12, "missing": 7 }, "capabilities": [ @@ -152,15 +152,15 @@ { "id": "M05", "name": "失败定时调用恢复", - "status": "partial", - "finding": "失败可见,但没有失败投递的安全重试/重新入队接口。", + "status": "ready", + "finding": "未建轮消息可明确授权后重试,保持同次请求标识;已有调用或结果未知不重放,归档取消不会复活。", "evidence": "src/modules/assistant/native-schedules.cjs" }, { "id": "M06", "name": "长期周期任务续接", "status": "partial", - "finding": "原会话100轮上限后任务仍active,没有容量预警、迁移或滚动会话。", + "finding": "剩余10轮起预警,容量用尽停止原生未来计时并保留规则快照;未调用消息可确认转到本人其他会话。未来周期规则仍需在新会话重新安排。", "evidence": "src/modules/assistant/store.cjs" }, { @@ -187,8 +187,8 @@ { "id": "M10", "name": "操作结果与审计闭环", - "status": "partial", - "finding": "有持久审计;旧固定操作副作用后的记录失败尚未统一needs_review。", + "status": "ready", + "finding": "固定操作开始后异常标记needs_review,保留已返回结果;审计或结果保存失败不会被误标为普通失败。", "evidence": "src/modules/assistant/service.cjs" }, { @@ -202,7 +202,7 @@ "id": "M12", "name": "运行诊断与恢复", "status": "partial", - "finding": "有服务就绪和探测;缺集中模型错误详情、失败任务恢复和队列管理。", + "finding": "队列恢复后清除当前全局错误;仍缺统一模型诊断、队列容量与更细恢复管理面板。", "evidence": "src/modules/assistant/service.cjs" }, { @@ -311,5 +311,27 @@ "id": "users", "name": "成员目录" } - ] + ], + "previousCounts": { + "ready": 11, + "partial": 14, + "missing": 7 + }, + "reviewFixes": { + "pullRequest": 4, + "comments": [ + 66, + 67, + 68, + 69 + ], + "knownReliabilityItemsFixed": [ + "REL-01", + "REL-02", + "REL-03", + "REL-04", + "REL-05" + ], + "validation": "16 recovery, fault-injection, cancellation, permission and UI cases; full business suite rerun pending" + } } diff --git a/docs/user-guide.md b/docs/user-guide.md index e8d91ec..37d1e9a 100644 --- a/docs/user-guide.md +++ b/docs/user-guide.md @@ -206,3 +206,11 @@ 配置建议涵盖邮箱安全字段、发送计划、助手额度和超时、新对话默认模型、单日业务日历,以及分类规则的收件人草稿。管理员须审查最终差异和风险,再逐次授权。日历仅修改一个日期;收件人仅保存一条真实分类规则的草稿并重置试运行验证,正式发布、发信和业务执行仍需人工处理。旧群组写入口不通过AI恢复。 成员与角色、凭据和登录会话、实际发信或补发、BPM节点提交、正式规则发布、任意Shell/插件/MCP/主机配置划入人工边界。只读成员没有修改权限;其他成员的连接、订单、批次和定时任务不会因AI查询而越权可见。扫描/归档查询目前分别仅覆盖最近30/100条,并返回范围标识;未查到不能证明更早记录不存在。回答仍为所标时间的快照,不等于实时系统状态。 + +### 定时消息恢复与容量停止 + +未创建调用轮次的定时消息会显示“尚未调用”,可以在任务管理页或会话右侧任务面板点击“重试未调用消息”。需要明确确认并选择本人目标会话;工作台会重新校验当前权限、消息状态和请求标识。已有调用记录、结果未知、已取消或已完成的消息不提供安全重试,不会自动重放。 + +会话剩余10轮起提示容量。达到100轮时,原生未来计时会停止,管理页显示“容量已满,已停止”,保留规则和未调用消息。可以确认把未调用消息转到本人其他会话,使用目标会话的模型和历史;旧附件不会自动迁移。未来周期任务须在新会话重新安排,本次消息重试不会自动复制或恢复周期规则。 + +操作建议即使过期、配置版本变化或操作开关关闭,原有权限范围内的所属用户仍可直接“拒绝建议”,无需先取得执行授权。已经执行或结果待核实的卡片不能用拒绝操作改变结果。固定操作已开始后,记录失败会显示“待核实”并保留已返回证据,请到原功能页核验,不要重复执行。 diff --git a/package.json b/package.json index 206908c..6a690c8 100644 --- a/package.json +++ b/package.json @@ -13,7 +13,7 @@ "service:stop": "node scripts/service.cjs stop", "service:restart": "node scripts/service.cjs restart", "test": "npm run test:business", - "test:business": "node --test --test-concurrency=1 tests/service/supervisor-crash.test.cjs tests/app/business-home-ui.test.cjs tests/order-rules/home-summary.test.cjs tests/order-rules/carry-forward-core.test.cjs tests/order-rules/carry-forward-integration.test.cjs tests/order-rules/dispatch-unsent-proof.test.cjs tests/order-rules/dismiss-task.test.cjs tests/app/carry-dismiss-ui.test.cjs tests/workspace/business-issues.test.cjs tests/mail/unified-account.test.cjs tests/mail/unified-account-ui.test.cjs tests/assistant/assistant.test.cjs tests/assistant/assistant-http-ui.test.cjs tests/assistant/controlled-operations.test.cjs tests/assistant/dsh-runtime.test.cjs tests/assistant/dsh-runtime-installer.test.cjs tests/assistant/repair-validator.test.cjs tests/assistant/repair-runner.test.cjs tests/app/automatic-pdf-ledger.test.cjs tests/app/job-records.test.cjs tests/order-rules/version-compatibility.test.cjs tests/bpm-display-policy.test.cjs tests/bpm-dynamicarea.test.cjs tests/bpm-readonly-form.test.cjs tests/bpm-form-contracts.test.cjs tests/bpm-obsolete-display-fields.test.cjs tests/order-rules/snapshot-read-context.test.cjs tests/order-rules/summary.test.cjs tests/order-rules/execution-single-flight.test.cjs tests/order-rules/execution-responsiveness.test.cjs tests/order-rules/readiness-pending-ui.test.cjs tests/dependency-compatibility.test.cjs tests/order-rules/slow-cutoff.test.cjs tests/order-rules/removed-discovery-barrier.test.cjs tests/mail/template-test-policy.test.cjs tests/mail/sample-send.test.cjs tests/mail/template-editing.test.cjs tests/mail/template-editor-ui.test.cjs tests/order-rules/scope-catalog.test.cjs tests/order-rules/field-mapping-ui.test.cjs tests/order-rules/scope-search-ui.test.cjs tests/order-rules/excel-import-contract.test.cjs tests/order-rules/excel-execution-bridge.test.cjs tests/order-rules/excel-import-flow-ui.test.cjs tests/order-rules/collecting-batches.test.cjs tests/order-rules/collecting-batches-ui.test.cjs tests/order-rules/query.test.cjs tests/order-rules/scheduled-mail-policy.test.cjs tests/system-update/checker.test.cjs tests/system-update/system-update.test.cjs tests/order-rules/configuration.test.cjs tests/order-rules/configuration-ui.test.cjs tests/order-rules/workbench-ui.test.cjs tests/app/asset-delivery.test.cjs tests/app/authentication-responsiveness.test.cjs tests/app/backend-refresh-performance.test.cjs tests/app/read-refresh-performance.test.cjs tests/app/polling-performance-ui.test.cjs tests/order-rules/query-read-performance.test.cjs tests/mail/history.test.cjs tests/storage/storage-range.test.cjs tests/app/region-revisions.test.cjs tests/app/region-revisions-http.test.cjs tests/app/region-refresh.test.cjs tests/app/region-refresh-ui.test.cjs tests/app/region-selection.test.cjs tests/app/module-loader.test.cjs tests/app/module-loader-ui.test.cjs tests/service/service-supervisor.test.cjs tests/bpm/windows-directory.test.cjs tests/assistant/workspace-events.test.cjs tests/assistant/dsh-events.test.cjs tests/assistant/workspace-http.test.cjs tests/assistant/events-client.test.cjs tests/assistant/diagnostic-workspace-ui.test.cjs tests/assistant/providers.test.cjs tests/assistant/providers-runtime.test.cjs tests/assistant/provider-http.test.cjs tests/assistant/providers-ui.test.cjs tests/assistant/action-results-ui.test.cjs tests/assistant/native-schedules.test.cjs tests/assistant/schedule-manager.test.cjs tests/assistant/schedules-http.test.cjs tests/assistant/schedule-proposals.test.cjs tests/assistant/schedules-ui.test.cjs tests/assistant/management.test.cjs tests/assistant/configuration.test.cjs tests/assistant/configuration-approval.test.cjs tests/assistant/configuration-ui.test.cjs tests/assistant/attachments.test.cjs tests/assistant/attachments-http.test.cjs tests/assistant/attachments-ui.test.cjs tests/assistant/model-capabilities.test.cjs tests/assistant/image-attachments.test.cjs tests/assistant/image-http.test.cjs tests/assistant/image-ui.test.cjs tests/assistant/toolbar-sidebar-ui.test.cjs tests/assistant/vision-transport.test.cjs tests/assistant/vision-runtime.test.cjs tests/assistant/conversation-trash.test.cjs tests/assistant/conversation-trash-ui.test.cjs tests/assistant/assistant-restore.test.cjs tests/assistant/main-integration.test.cjs", + "test:business": "node --test --test-concurrency=1 tests/service/supervisor-crash.test.cjs tests/app/business-home-ui.test.cjs tests/order-rules/home-summary.test.cjs tests/order-rules/carry-forward-core.test.cjs tests/order-rules/carry-forward-integration.test.cjs tests/order-rules/dispatch-unsent-proof.test.cjs tests/order-rules/dismiss-task.test.cjs tests/app/carry-dismiss-ui.test.cjs tests/workspace/business-issues.test.cjs tests/mail/unified-account.test.cjs tests/mail/unified-account-ui.test.cjs tests/assistant/assistant.test.cjs tests/assistant/assistant-http-ui.test.cjs tests/assistant/controlled-operations.test.cjs tests/assistant/dsh-runtime.test.cjs tests/assistant/dsh-runtime-installer.test.cjs tests/assistant/repair-validator.test.cjs tests/assistant/repair-runner.test.cjs tests/app/automatic-pdf-ledger.test.cjs tests/app/job-records.test.cjs tests/order-rules/version-compatibility.test.cjs tests/bpm-display-policy.test.cjs tests/bpm-dynamicarea.test.cjs tests/bpm-readonly-form.test.cjs tests/bpm-form-contracts.test.cjs tests/bpm-obsolete-display-fields.test.cjs tests/order-rules/snapshot-read-context.test.cjs tests/order-rules/summary.test.cjs tests/order-rules/execution-single-flight.test.cjs tests/order-rules/execution-responsiveness.test.cjs tests/order-rules/readiness-pending-ui.test.cjs tests/dependency-compatibility.test.cjs tests/order-rules/slow-cutoff.test.cjs tests/order-rules/removed-discovery-barrier.test.cjs tests/mail/template-test-policy.test.cjs tests/mail/sample-send.test.cjs tests/mail/template-editing.test.cjs tests/mail/template-editor-ui.test.cjs tests/order-rules/scope-catalog.test.cjs tests/order-rules/field-mapping-ui.test.cjs tests/order-rules/scope-search-ui.test.cjs tests/order-rules/excel-import-contract.test.cjs tests/order-rules/excel-execution-bridge.test.cjs tests/order-rules/excel-import-flow-ui.test.cjs tests/order-rules/collecting-batches.test.cjs tests/order-rules/collecting-batches-ui.test.cjs tests/order-rules/query.test.cjs tests/order-rules/scheduled-mail-policy.test.cjs tests/system-update/checker.test.cjs tests/system-update/system-update.test.cjs tests/order-rules/configuration.test.cjs tests/order-rules/configuration-ui.test.cjs tests/order-rules/workbench-ui.test.cjs tests/app/asset-delivery.test.cjs tests/app/authentication-responsiveness.test.cjs tests/app/backend-refresh-performance.test.cjs tests/app/read-refresh-performance.test.cjs tests/app/polling-performance-ui.test.cjs tests/order-rules/query-read-performance.test.cjs tests/mail/history.test.cjs tests/storage/storage-range.test.cjs tests/app/region-revisions.test.cjs tests/app/region-revisions-http.test.cjs tests/app/region-refresh.test.cjs tests/app/region-refresh-ui.test.cjs tests/app/region-selection.test.cjs tests/app/module-loader.test.cjs tests/app/module-loader-ui.test.cjs tests/service/service-supervisor.test.cjs tests/bpm/windows-directory.test.cjs tests/assistant/workspace-events.test.cjs tests/assistant/dsh-events.test.cjs tests/assistant/workspace-http.test.cjs tests/assistant/events-client.test.cjs tests/assistant/diagnostic-workspace-ui.test.cjs tests/assistant/providers.test.cjs tests/assistant/providers-runtime.test.cjs tests/assistant/provider-http.test.cjs tests/assistant/providers-ui.test.cjs tests/assistant/action-results-ui.test.cjs tests/assistant/native-schedules.test.cjs tests/assistant/schedule-manager.test.cjs tests/assistant/schedules-http.test.cjs tests/assistant/schedule-proposals.test.cjs tests/assistant/schedules-ui.test.cjs tests/assistant/management.test.cjs tests/assistant/configuration.test.cjs tests/assistant/configuration-approval.test.cjs tests/assistant/configuration-ui.test.cjs tests/assistant/attachments.test.cjs tests/assistant/attachments-http.test.cjs tests/assistant/attachments-ui.test.cjs tests/assistant/model-capabilities.test.cjs tests/assistant/image-attachments.test.cjs tests/assistant/image-http.test.cjs tests/assistant/image-ui.test.cjs tests/assistant/toolbar-sidebar-ui.test.cjs tests/assistant/vision-transport.test.cjs tests/assistant/vision-runtime.test.cjs tests/assistant/conversation-trash.test.cjs tests/assistant/conversation-trash-ui.test.cjs tests/assistant/assistant-restore.test.cjs tests/assistant/main-integration.test.cjs tests/assistant/review-recovery.test.cjs", "test:full": "node --test --test-concurrency=2 \"tests/**/*.test.cjs\"", "test:assistant": "node --test --test-concurrency=1 \"tests/assistant/*.test.cjs\"", "format:assistant": "prettier --write \"src/modules/assistant/**/*.cjs\" \"web/modules/assistant/**/*.js\" \"tests/assistant/**/*.cjs\" \"tests/fixtures/isolated-vault-key.cjs\" \"tests/fixtures/provider-streams.cjs\"", diff --git a/src/app/assets.cjs b/src/app/assets.cjs index a21e581..70fb63b 100644 --- a/src/app/assets.cjs +++ b/src/app/assets.cjs @@ -50,7 +50,7 @@ function createAssets(){ '/notifications.js':{path:path.join(webRoot,'modules/notifications/view.js'),type:'text/javascript'}, '/assistant-operations.js':{path:path.join(webRoot,'modules/assistant/operations.js'),type:'text/javascript'}, '/assistant.js':{path:path.join(webRoot,'modules/assistant/view.js'),type:'text/javascript'}, - ...Object.fromEntries(['dsh-native','layout','conversation','commands','context-panel','events-client','providers','model-picker','settings-review','attachments','schedules','schedule-manager'].map(name=>['/assistant-'+name+'.js',{path:path.join(webRoot,'modules/assistant',name+'.js'),type:'text/javascript'}])), + ...Object.fromEntries(['dsh-native','layout','conversation','commands','context-panel','events-client','providers','model-picker','settings-review','attachments','schedule-recovery','schedules','schedule-manager'].map(name=>['/assistant-'+name+'.js',{path:path.join(webRoot,'modules/assistant',name+'.js'),type:'text/javascript'}])), '/assistant-workspace.css':{path:path.join(webRoot,'modules/assistant/workspace.css'),type:'text/css'}, '/vendor/marked.js':{path:path.join(path.dirname(require.resolve('marked')),'marked.umd.js'),type:'text/javascript'}, '/health.js':{path:path.join(webRoot,'modules/health/view.js'),type:'text/javascript'}, diff --git a/src/modules/assistant/configuration-approval.cjs b/src/modules/assistant/configuration-approval.cjs index ad997d6..8a0e52c 100644 --- a/src/modules/assistant/configuration-approval.cjs +++ b/src/modules/assistant/configuration-approval.cjs @@ -4,7 +4,7 @@ const crypto = require('node:crypto'), scheduleProposals = require('./schedule-proposals.cjs'); const fail = (message, status = 400) => Object.assign(Error(message), { status }), hash = (value) => crypto.createHash('sha256').update(value).digest('hex'); -function guard(service, id, actionId, principal) { +function guard(service, id, actionId, principal, { executable = true } = {}) { if (service.stopped) throw fail('助手服务正在停止。', 503); if (!principal?.user?.id || !principal.sessionId || principal.user.role === 'viewer') throw fail('账号无授权此操作的权限。', 403); @@ -15,11 +15,16 @@ function guard(service, id, actionId, principal) { if (!['update_configuration', 'manage_schedule'].includes(action?.kind)) throw fail('修改建议不存在。', 404); const scheduled = action.kind === 'manage_schedule'; - if (!scheduled && (principal.user.role !== 'admin' || !service.store.settings().allowActions)) + if ( + !scheduled && + (principal.user.role !== 'admin' || (executable && !service.store.settings().allowActions)) + ) throw fail('仅已开放操作权限的管理员可修改系统配置。', 403); if (action.status !== 'proposed') throw fail('此建议已处理或待核实,不能重复执行。', 409); - if (scheduled) scheduleProposals.check(service.schedules, action, id, principal.user); - else configuration.check(action, service.deps, service.store, principal.user); + if (executable) { + if (scheduled) scheduleProposals.check(service.schedules, action, id, principal.user); + else configuration.check(action, service.deps, service.store, principal.user); + } if (!service.journal) throw fail('操作审计不可用,未执行修改。', 503); return action; } @@ -65,7 +70,7 @@ function review(service, id, actionId, principal) { }; } function reject(service, id, actionId, principal) { - const a = guard(service, id, actionId, principal); + const a = guard(service, id, actionId, principal, { executable: false }); service.record( a.id, principal, @@ -74,11 +79,14 @@ function reject(service, id, actionId, principal) { a.label + ';用户拒绝,未执行修改', ); table(service); - service.store.db - .prepare('DELETE FROM assistant_configuration_approvals WHERE action_id=?') - .run(actionId); - service.store.action(id, principal.user.id, actionId, (item) => { - item.status = 'rejected'; + service.store.transaction(() => { + service.store.db + .prepare('DELETE FROM assistant_configuration_approvals WHERE action_id=?') + .run(actionId); + service.store.action(id, principal.user.id, actionId, (item) => { + if (item.status !== 'proposed') throw fail('此建议已处理或待核实,不能重复拒绝。', 409); + item.status = 'rejected'; + }); }); return { status: 'rejected' }; } diff --git a/src/modules/assistant/management.cjs b/src/modules/assistant/management.cjs index 8889913..9b8812e 100644 --- a/src/modules/assistant/management.cjs +++ b/src/modules/assistant/management.cjs @@ -375,6 +375,10 @@ async function rows(service, resource, user, principal, request) { 'weekdays', 'expression', 'lastError', + 'turnCount', + 'remainingTurns', + 'maxTurns', + 'capacityWarning', ]), ); case 'configuration': diff --git a/src/modules/assistant/native-schedules.cjs b/src/modules/assistant/native-schedules.cjs index 3cf4c40..eb7d1a8 100644 --- a/src/modules/assistant/native-schedules.cjs +++ b/src/modules/assistant/native-schedules.cjs @@ -2,6 +2,7 @@ const path = require('node:path'), crypto = require('node:crypto'), { pathToFileURL } = require('node:url'); +const recovery = require('./schedule-recovery.cjs'); const { redact } = require('../../shared/redact.cjs'); const fail = (message, status = 400) => Object.assign(Error(message), { status }), hash = (value) => crypto.createHash('sha256').update(value).digest('hex'); @@ -96,6 +97,18 @@ class NativeSchedules { this.store.db.exec( "CREATE TABLE IF NOT EXISTS assistant_schedule_tasks(id TEXT PRIMARY KEY,conversation_id TEXT NOT NULL,owner TEXT NOT NULL,payload BLOB NOT NULL,last_error TEXT NOT NULL DEFAULT '');CREATE TABLE IF NOT EXISTS assistant_schedule_inbox(id TEXT PRIMARY KEY,conversation_id TEXT NOT NULL,owner TEXT NOT NULL,task_id TEXT NOT NULL,status TEXT NOT NULL,turn_id TEXT,payload BLOB NOT NULL,created_at TEXT NOT NULL);CREATE INDEX IF NOT EXISTS schedule_inbox_owner ON assistant_schedule_inbox(owner,created_at);UPDATE assistant_schedule_inbox SET status='queued' WHERE status='running';", ); + if ( + !this.store.db + .prepare('PRAGMA table_info(assistant_schedule_inbox)') + .all() + .some((c) => c.name === 'paused_conversation_id') + ) + this.store.db.exec( + 'ALTER TABLE assistant_schedule_inbox ADD COLUMN paused_conversation_id TEXT', + ); + this.store.db.exec( + 'CREATE INDEX IF NOT EXISTS schedule_inbox_paused ON assistant_schedule_inbox(owner,paused_conversation_id)', + ); require('../../shared/refresh-revisions.cjs').installRevisionTracking(this.store.db, [ ['assistant_schedule_tasks', "'owner:' || $row.owner"], ['assistant_schedule_inbox', "'owner:' || $row.owner"], @@ -184,6 +197,7 @@ class NativeSchedules { deliveryHistoryRecords: 200, }); await this.native[Service.init](); + await recovery.reconcileStops(this); this.timer = setInterval(() => this.kick(), 1000); this.timer.unref(); this.kick(); @@ -265,6 +279,9 @@ class NativeSchedules { kick() { if (this.stopping || this.draining) return; this.draining = this.drain() + .then(() => { + this.lastError = ''; + }) .catch((error) => { this.lastError = error.status ? redact(error.message) @@ -275,26 +292,53 @@ class NativeSchedules { }); } async drain() { - for (const row of this.store.db + await recovery.reconcileStops(this); + for (const queued of this.store.db .prepare( "SELECT * FROM assistant_schedule_inbox WHERE status='queued' ORDER BY created_at,id LIMIT 100", ) .all()) { if (this.stopping) break; + const row = this.store.db + .prepare("SELECT * FROM assistant_schedule_inbox WHERE id=? AND status='queued'") + .get(queued.id); + if (!row) continue; if (this.assistant.running.size >= 2) break; if ( [...this.assistant.running.values()].some((r) => r.conversationId === row.conversation_id) ) continue; + const claimed = this.store.transaction( + () => + this.store.db + .prepare( + "UPDATE assistant_schedule_inbox SET status='running' WHERE id=? AND owner=? AND conversation_id=? AND status='queued'", + ) + .run(row.id, row.owner, row.conversation_id).changes, + ); + if (!claimed) continue; + row.status = 'running'; let turn; try { const user = this.user(row.owner), conversation = this.store.row(row.conversation_id, row.owner); if (conversation.archived) throw fail('任务会话已归档。', 409); + const links = recovery.requestLinks(this.store, row); + if ( + links.some((link) => link.conversation_id !== row.conversation_id) || + (row.turn_id && !links.some((link) => link.turn_id === row.turn_id)) + ) { + this.finish(row, 'needs_review', '已有调用记录无法核验,禁止自动重放。'); + continue; + } + if ( + !links.length && + !this.store.conversationCapacity(row.conversation_id, row.owner).remainingTurns + ) { + await recovery.pauseForCapacity(this, row); + continue; + } const message = this.store.decode('schedule-inbox:' + row.id, row.payload); - this.store.db - .prepare("UPDATE assistant_schedule_inbox SET status='running' WHERE id=?") - .run(row.id); turn = this.assistant.send( row.conversation_id, { user, sessionId: 'schedule:' + row.owner }, @@ -318,62 +362,114 @@ class NativeSchedules { : 'error'; this.finish(row, status, saved?.error || ''); } catch (error) { - this.finish(row, 'error', error.status ? error.message : '定时消息未完成,请核实。'); + const fresh = this.store.db + .prepare('SELECT * FROM assistant_schedule_inbox WHERE id=?') + .get(row.id); + if (!fresh || fresh.status !== 'running' || fresh.conversation_id !== row.conversation_id) + continue; + const links = recovery.requestLinks(this.store, fresh || row); + if (links.length && fresh && !fresh.turn_id) + this.store.db + .prepare('UPDATE assistant_schedule_inbox SET turn_id=? WHERE id=?') + .run(links[0].turn_id, row.id); + this.finish( + row, + !turn && recovery.unstarted(this.store, fresh || row) ? 'not_started' : 'needs_review', + error.status ? error.message : '定时消息未完成,请核实。', + ); } } } finish(row, status, error) { - const payload = this.store.decode('schedule-inbox:' + row.id, row.payload); - this.store.db.prepare('UPDATE assistant_schedule_inbox SET status=?,payload=? WHERE id=?').run( - status, - this.store.encode('schedule-inbox:' + row.id, { - ...payload, - ...(error ? { error: redact(error) } : {}), - }), - row.id, - ); + const current = this.store.db + .prepare( + "SELECT * FROM assistant_schedule_inbox WHERE id=? AND status='running' AND conversation_id=? AND owner=?", + ) + .get(row.id, row.conversation_id, row.owner); + if (!current) return; + const payload = this.store.decode('schedule-inbox:' + row.id, current.payload); this.store.db .prepare( - "DELETE FROM assistant_schedule_inbox WHERE conversation_id=? AND status NOT IN ('queued','running') AND id NOT IN (SELECT id FROM assistant_schedule_inbox WHERE conversation_id=? ORDER BY created_at DESC,id DESC LIMIT 200)", + "UPDATE assistant_schedule_inbox SET status=?,payload=? WHERE id=? AND status='running'", + ) + .run( + status, + this.store.encode('schedule-inbox:' + row.id, { + ...payload, + ...(error ? { error: redact(error) } : {}), + }), + row.id, + ); + this.store.db + .prepare( + "DELETE FROM assistant_schedule_inbox WHERE conversation_id=? AND status NOT IN ('queued','running','not_started','waiting_capacity','needs_review') AND paused_conversation_id IS NULL AND id NOT IN (SELECT id FROM assistant_schedule_inbox WHERE conversation_id=? ORDER BY created_at DESC,id DESC LIMIT 200)", ) .run(row.conversation_id, row.conversation_id); } + taskCatalogue(owner, nativeRows, id) { + const native = nativeRows.filter((t) => !id || t.sessionId === id); + const paused = recovery.suspended(this, owner, id); + const pausedIds = new Set(paused.map((t) => t.id)); + return [...native.filter((t) => !pausedIds.has(t.id)), ...paused] + .filter((task) => + this.store.db + .prepare('SELECT 1 FROM conversations WHERE id=? AND owner=? AND deleted_at IS NULL') + .get(task.sessionId, owner), + ) + .map((task) => { + const error = this.store.db + .prepare('SELECT last_error FROM assistant_schedule_tasks WHERE id=?') + .get(task.id)?.last_error; + return recovery.withCapacity( + this, + { ...task, lastError: error || task.lastError || '' }, + owner, + ); + }); + } snapshot(id, user) { if ( !id || !this.store.db.prepare('SELECT 1 FROM conversations WHERE id=? AND owner=?').get(id, user.id) ) return []; - return [...this.tasks.values()] - .filter((t) => t.sessionId === id) + const rows = [...this.tasks.values()].map((t) => ({ + ...t.record, + sessionId: t.sessionId, + status: t.status, + })); + return this.taskCatalogue(user.id, rows, id) .slice(0, 30) - .map((t) => ({ ...t.record, prompt: t.record.prompt.slice(0, 250), status: t.status })); + .map((t) => ({ ...t, prompt: t.prompt.slice(0, 250) })); + } + retryDelivery(id, inboxId, principal, body) { + return recovery.retry(this, id, inboxId, principal, body); + } + conversationOptions(owner) { + return this.store + .listConversations(owner, { scope: 'active', page: 1, pageSize: 50 }) + .items.map((c) => ({ ...c, ...this.store.conversationCapacity(c.id, owner) })); + } + retainedTask(taskId, owner, id) { + const stopped = recovery.suspended(this, owner, id).find((t) => t.id === taskId); + if (stopped) { + const { sessionId, status, lastError, ...record } = stopped; + return { record, sessionId, status }; + } + return this.tasks.get(taskId) || null; } async list(id, principal) { this.own(id, principal); return { error: this.lastError || '', - tasks: (await this.native.catalog()) - .filter((t) => t.sessionId === id) - .map((t) => ({ - ...t, - lastError: - this.store.db - .prepare('SELECT last_error FROM assistant_schedule_tasks WHERE id=?') - .get(t.id)?.last_error || '', - })), + conversations: this.conversationOptions(principal.user.id), + tasks: this.taskCatalogue(principal.user.id, await this.native.catalog(), id), history: this.store.db .prepare( - 'SELECT * FROM assistant_schedule_inbox WHERE conversation_id=? AND owner=? ORDER BY created_at DESC LIMIT 100', + "SELECT * FROM assistant_schedule_inbox WHERE conversation_id=? AND owner=? ORDER BY CASE WHEN status IN ('not_started','waiting_capacity','needs_review') THEN 0 ELSE 1 END,created_at DESC LIMIT 100", ) .all(id, principal.user.id) - .map((r) => ({ - id: r.id, - status: r.status, - turnId: r.turn_id, - createdAt: r.created_at, - ...this.store.decode('schedule-inbox:' + r.id, r.payload), - })), + .map((r) => recovery.view(this, r, principal.user)), }; } @@ -393,40 +489,32 @@ class NativeSchedules { }, ]), ); - const tasks = (await this.native.catalog()) + const records = (await this.native.catalog()).filter((t) => owned.has(t.sessionId)); + const tasks = this.taskCatalogue(owner, records) .filter((t) => owned.has(t.sessionId)) .map((t) => ({ ...t, conversationTitle: owned.get(t.sessionId).title, conversationArchived: owned.get(t.sessionId).archived, - lastError: - this.store.db - .prepare('SELECT last_error FROM assistant_schedule_tasks WHERE id=?') - .get(t.id)?.last_error || '', })); const history = this.store.db .prepare( - 'SELECT i.* FROM assistant_schedule_inbox i JOIN conversations c ON c.id=i.conversation_id AND c.owner=i.owner WHERE i.owner=? AND c.deleted_at IS NULL ORDER BY i.created_at DESC LIMIT 200', + "SELECT i.* FROM assistant_schedule_inbox i JOIN conversations c ON c.id=i.conversation_id AND c.owner=i.owner WHERE i.owner=? AND c.deleted_at IS NULL ORDER BY CASE WHEN i.status IN ('not_started','waiting_capacity','needs_review') THEN 0 ELSE 1 END,i.created_at DESC LIMIT 200", ) .all(owner) - .map((r) => ({ - id: r.id, - conversationId: r.conversation_id, - status: r.status, - turnId: r.turn_id, - createdAt: r.created_at, - ...this.store.decode('schedule-inbox:' + r.id, r.payload), - })); + .map((r) => recovery.view(this, r, principal.user)); return { error: this.lastError || '', tasks, history, - conversations: [...owned.values()].filter((c) => !c.archived), + conversations: this.conversationOptions(owner), }; } async createTask(id, principal, body) { this.own(id, principal, true); if (body?.confirm !== true) throw fail('请明确确认定时任务的内容、时间及调用风险。', 403); + if (!this.store.conversationCapacity(id, principal.user.id).remainingTurns) + throw fail('会话已满,请选择其他会话或新建对话。', 409); const request = this.clean(body.request); if ((await this.native.list({ sessionId: id })).length >= 30) throw fail('每个会话最多30个活跃任务。', 409); @@ -540,6 +628,7 @@ class NativeSchedules { async deleteTask(id, taskId, principal, body) { this.own(id, principal, true); if (body?.confirm !== true) throw fail('请明确确认删除任务。', 403); + const suspended = recovery.suspended(this, principal.user.id, id).some((t) => t.id === taskId); const operationId = crypto.randomUUID(); this.record( principal, @@ -550,7 +639,15 @@ class NativeSchedules { ); let result; try { - result = await this.native.delete({ sessionId: id, id: taskId }); + result = this.tasks.has(taskId) + ? await this.native.delete({ sessionId: id, id: taskId }) + : { id: taskId, deleted: suspended }; + if (suspended) + this.store.db + .prepare( + 'UPDATE assistant_schedule_inbox SET paused_conversation_id=NULL WHERE owner=? AND paused_conversation_id=? AND task_id=?', + ) + .run(principal.user.id, id, taskId); if (!result.deleted) throw fail('任务不存在。', 404); this.record(principal, operationId, 'schedule_delete', 'success', '未来触发已停止 ' + taskId); return result; @@ -575,13 +672,18 @@ class NativeSchedules { async stopSession(id) { this.cleaning.add(id); try { - for (const task of (await this.native.catalog()).filter((t) => t.sessionId === id)) - await this.native.delete({ sessionId: id, id: task.id }); this.store.db .prepare( - "UPDATE assistant_schedule_inbox SET status='cancelled' WHERE conversation_id=? AND status='queued'", + "UPDATE assistant_schedule_inbox SET status='cancelled' WHERE conversation_id=? AND status IN ('queued','not_started','waiting_capacity')", ) .run(id); + this.store.db + .prepare( + 'UPDATE assistant_schedule_inbox SET paused_conversation_id=NULL WHERE paused_conversation_id=?', + ) + .run(id); + for (const task of (await this.native.catalog()).filter((t) => t.sessionId === id)) + await this.native.delete({ sessionId: id, id: task.id }); } finally { this.cleaning.delete(id); } diff --git a/src/modules/assistant/schedule-proposals.cjs b/src/modules/assistant/schedule-proposals.cjs index 5ea04a2..bcc356a 100644 --- a/src/modules/assistant/schedule-proposals.cjs +++ b/src/modules/assistant/schedule-proposals.cjs @@ -37,7 +37,7 @@ function binding(s, id, user, taskId) { const row = s.store.row(id, user.id); if (row.archived) throw fail('请先恢复会话。', 409); const c = s.store.conversation(id, user.id), - task = taskId ? s.tasks.get(taskId) : null; + task = taskId ? s.retainedTask(taskId, user.id, id) : null; if (taskId && (!task || task.sessionId !== id)) throw fail('任务不存在或不属于当前会话。', 404); return { owner: user.id, diff --git a/src/modules/assistant/schedule-recovery.cjs b/src/modules/assistant/schedule-recovery.cjs new file mode 100644 index 0000000..f718dba --- /dev/null +++ b/src/modules/assistant/schedule-recovery.cjs @@ -0,0 +1,217 @@ +'use strict'; + +const crypto = require('node:crypto'); +const fail = (message, status = 400) => Object.assign(Error(message), { status }); +const recoverable = new Set(['not_started', 'waiting_capacity']); + +function requestLinks(store, row) { + const key = crypto + .createHash('sha256') + .update('schedule-' + row.id) + .digest('hex'); + return store.db + .prepare( + 'SELECT r.turn_id,r.conversation_id FROM assistant_requests r JOIN conversations c ON c.id=r.conversation_id WHERE c.owner=? AND r.request_key=?', + ) + .all(row.owner, key); +} + +function unstarted(store, row) { + return !row.turn_id && requestLinks(store, row).length === 0; +} + +function view(host, row, user) { + const payload = host.store.decode('schedule-inbox:' + row.id, row.payload); + const conversation = host.store.row(row.conversation_id, row.owner); + return { + ...payload, + ...(row.paused_conversation_id && row.status === 'waiting_capacity' + ? { + error: host.tasks.has(row.task_id) + ? '会话已满,未来任务停止结果待核实;尚未调用模型。' + : '原会话已满,未来任务已停止;请选择其他会话重试这条未调用消息。', + } + : {}), + id: row.id, + conversationId: row.conversation_id, + status: row.status, + turnId: row.turn_id, + createdAt: row.created_at, + retryable: + recoverable.has(row.status) && + unstarted(host.store, row) && + user.role !== 'viewer' && + !conversation.archived, + retryNeedsTarget: row.status === 'waiting_capacity', + }; +} + +function suspended(host, owner, conversationId) { + const rows = host.store.db + .prepare( + 'SELECT * FROM assistant_schedule_inbox WHERE owner=? AND paused_conversation_id IS NOT NULL ORDER BY created_at,id', + ) + .all(owner); + const tasks = new Map(); + for (const row of rows) { + if (conversationId && row.paused_conversation_id !== conversationId) continue; + const payload = host.store.decode('schedule-inbox:' + row.id, row.payload); + const capacity = payload.capacity; + if (!capacity?.record || tasks.has(row.task_id)) continue; + tasks.set(row.task_id, { + ...capacity.record, + sessionId: row.paused_conversation_id, + status: host.tasks.has(row.task_id) ? 'capacity_stopping' : 'capacity_stopped', + lastError: host.tasks.has(row.task_id) + ? '会话已满,原生任务停止结果待核实。' + : '原会话已满,周期任务已停止;请在其他会话重新安排。', + }); + } + return [...tasks.values()]; +} + +async function pauseForCapacity(host, snapshot) { + const row = host.store.db + .prepare('SELECT * FROM assistant_schedule_inbox WHERE id=?') + .get(snapshot.id); + if ( + !row || + row.status !== snapshot.status || + row.conversation_id !== snapshot.conversation_id || + !['queued', 'running', 'waiting_capacity'].includes(row.status) + ) + return; + const payload = host.store.decode('schedule-inbox:' + row.id, row.payload); + const record = payload.capacity?.record || host.tasks.get(row.task_id)?.record; + const sourceId = row.paused_conversation_id || row.conversation_id; + const value = { + ...payload, + error: '原会话达到容量上限,正在停止未来任务;尚未调用消息保留待处理。', + capacity: { record, stoppedAt: payload.capacity?.stoppedAt || new Date().toISOString() }, + }; + // Save the reminder and native rule before stopping its future timer. A lost + // acknowledgement can be reconciled after restart without replaying a model call. + host.store.db + .prepare( + "UPDATE assistant_schedule_inbox SET status='waiting_capacity',paused_conversation_id=?,payload=? WHERE id=?", + ) + .run(sourceId, host.store.encode('schedule-inbox:' + row.id, value), row.id); + if (host.tasks.has(row.task_id)) { + const result = await host.native.delete({ sessionId: sourceId, id: row.task_id }); + if (result.code || host.tasks.has(row.task_id)) throw fail('原生任务停止结果待核实。', 502); + } +} + +async function reconcileStops(host) { + for (const row of host.store.db + .prepare( + "SELECT * FROM assistant_schedule_inbox WHERE paused_conversation_id IS NOT NULL AND status='waiting_capacity'", + ) + .all()) { + if (!host.tasks.has(row.task_id)) continue; + try { + await pauseForCapacity(host, row); + } catch { + host.store.db + .prepare('UPDATE assistant_schedule_tasks SET last_error=? WHERE id=?') + .run('会话已满,原生任务停止结果待核实。', row.task_id); + } + } +} + +function withCapacity(host, task, owner) { + const capacity = host.store.conversationCapacity(task.sessionId, owner); + return { ...task, ...capacity }; +} + +async function retry(host, conversationId, inboxId, principal, body) { + host.own(conversationId, principal, true); + if (body?.confirm !== true) throw fail('请明确确认重试这条未调用的定时消息。', 403); + if ( + body.targetConversationId !== undefined && + (typeof body.targetConversationId !== 'string' || + !/^[-\w]{1,100}$/.test(body.targetConversationId)) + ) + throw fail('重试目标会话无效。'); + const targetId = body.targetConversationId || conversationId; + host.own(targetId, principal, true); + if (!host.store.conversationCapacity(targetId, principal.user.id).remainingTurns) + throw fail('目标会话已满,请先新建对话并选择该对话。', 409); + const row = host.store.db + .prepare('SELECT * FROM assistant_schedule_inbox WHERE id=? AND conversation_id=? AND owner=?') + .get(inboxId, conversationId, principal.user.id); + if (!row) throw fail('没有找到本人会话的定时消息。', 404); + if (!recoverable.has(row.status) || !unstarted(host.store, row)) + throw fail('此消息已有调用或结果待核实,不能安全重试。', 409); + if (row.paused_conversation_id) { + await pauseForCapacity(host, row); + host.own(conversationId, principal, true); + host.own(targetId, principal, true); + } + const operationId = crypto.randomUUID(); + host.record( + principal, + operationId, + 'schedule_retry', + 'running', + '用户明确授权重试未调用消息 ' + inboxId + ';目标会话 ' + targetId, + ); + let queued = false; + try { + host.store.transaction(() => { + const current = host.store.db + .prepare( + 'SELECT * FROM assistant_schedule_inbox WHERE id=? AND conversation_id=? AND owner=?', + ) + .get(inboxId, conversationId, principal.user.id); + if (!current || !recoverable.has(current.status) || !unstarted(host.store, current)) + throw fail('定时消息状态已变化,请刷新核实。', 409); + const payload = host.store.decode('schedule-inbox:' + inboxId, current.payload); + const { error, ...clean } = payload; + const saved = { + ...clean, + attempts: (payload.attempts || 0) + 1, + originalConversationId: payload.originalConversationId || conversationId, + retriedAt: new Date().toISOString(), + }; + const result = host.store.db + .prepare( + "UPDATE assistant_schedule_inbox SET status='queued',conversation_id=?,payload=? WHERE id=? AND status=? AND turn_id IS NULL", + ) + .run( + targetId, + host.store.encode('schedule-inbox:' + inboxId, saved), + inboxId, + current.status, + ); + if (!result.changes) throw fail('消息已被处理,不能重复入队。', 409); + }); + queued = true; + host.record( + principal, + operationId, + 'schedule_retry', + 'success', + '已重新入队 ' + inboxId + ';沿用同次投递请求标识,未执行其他操作', + ); + setImmediate(() => host.kick()); + return { id: inboxId, conversationId: targetId, status: 'queued' }; + } catch (error) { + if (queued) + throw Object.assign(fail('消息可能已入队,请刷新核实,勿重复提交。', 502), { + mutationApplied: true, + }); + throw error; + } +} + +module.exports = { + requestLinks, + unstarted, + view, + suspended, + pauseForCapacity, + reconcileStops, + withCapacity, + retry, +}; diff --git a/src/modules/assistant/schedules-api.cjs b/src/modules/assistant/schedules-api.cjs index 8e5af6e..7501dfe 100644 --- a/src/modules/assistant/schedules-api.cjs +++ b/src/modules/assistant/schedules-api.cjs @@ -20,6 +20,19 @@ async function schedulesApi({ reply(200, await assistant.schedules.catalog(principal)); return true; } + const delivery = + /^\/api\/assistant\/conversations\/([\w-]+)\/schedules\/deliveries\/([\w-]+)\/retry$/.exec( + route, + ); + if (delivery) { + if (method !== 'POST') throw fail('未开放此定时消息操作。', 404); + if (!assistant.schedules) throw fail('原生定时服务尚未就绪。', 503); + if (!secureBpmTransport(request, trustedProxy)) + throw fail('请在部署机本地或HTTPS页面重试定时消息。', 403); + keys(body, ['confirm', 'targetConversationId']); + reply(200, await assistant.schedules.retryDelivery(delivery[1], delivery[2], principal, body)); + return true; + } const match = /^\/api\/assistant\/conversations\/([\w-]+)\/schedules(?:\/([\w-]+)\/(update|delete))?$/.exec( route, diff --git a/src/modules/assistant/service.cjs b/src/modules/assistant/service.cjs index e3d2100..1cab9d2 100644 --- a/src/modules/assistant/service.cjs +++ b/src/modules/assistant/service.cjs @@ -369,10 +369,13 @@ class AssistantService { throw fail('操作审计不可用,未执行。', 503); } const task = (async () => { + let result; + let operationStarted = false; try { - let result; + const runner = action.kind === 'repair_code' ? this.repairRunner(principal) : null; + operationStarted = true; if (action.kind === 'repair_code') - result = await this.repairRunner(principal).run({ + result = await runner.run({ actor: principal.user.id, isAdmin: true, files: action.files, @@ -445,23 +448,36 @@ class AssistantService { Object.assign(a, { status: 'success', result, finishedAt: new Date().toISOString() }), ); } catch (e) { + const uncertain = operationStarted || e.mutationApplied === true; + const status = uncertain ? 'needs_review' : 'error'; + const message = uncertain + ? '操作可能已产生影响,请到原功能页面核实;请勿重复执行。' + : e.status + ? redact(e.message) + : '操作未完成,请核实结果。'; try { this.record( action.id, principal, 'execute', - 'error', - redact(e.status ? e.message : '操作失败,请核验结果'), + status, + JSON.stringify({ + message, + ...(result !== undefined ? { result } : {}), + }), ); } catch {} this.store.action(conversationId, principal.user.id, actionId, (a) => Object.assign(a, { - status: 'error', - error: redact(e.status ? e.message : '操作未完成,请在原功能页面核实结果。'), + status, + error: message, + ...(result !== undefined ? { result } : {}), finishedAt: new Date().toISOString(), }), ); - throw fail(e.status ? redact(e.message) : '操作未完成,请核实结果。', e.status || 502); + throw Object.assign(fail(message, e.status || 502), { + outcome: uncertain ? 'uncertain' : 'rejected', + }); } })(); this.actions.add(task); diff --git a/src/modules/assistant/store.cjs b/src/modules/assistant/store.cjs index 794bde9..a370ff4 100644 --- a/src/modules/assistant/store.cjs +++ b/src/modules/assistant/store.cjs @@ -9,6 +9,7 @@ const fail = (message, status = 400) => Object.assign(new Error(message), { stat now = () => new Date().toISOString(); const { ConversationHistory } = require('./conversation-history.cjs'); const { ConversationEvents } = require('./conversation-events.cjs'); +const MAX_TURNS = 100; const day = () => new Intl.DateTimeFormat('en-CA', { timeZone: 'Asia/Shanghai' }).format(new Date()); function installedRuntime() { @@ -321,6 +322,22 @@ class AssistantStore { history(id, owner) { return this.conversationHistory.history(id, owner); } + conversationCapacity(id, owner) { + this.row(id, owner); + const count = this.db.prepare('SELECT COUNT(*) n FROM turns WHERE conversation_id=?').get(id).n; + const remainingTurns = Math.max(0, MAX_TURNS - count); + return { + turnCount: count, + remainingTurns, + maxTurns: MAX_TURNS, + capacityWarning: + remainingTurns <= 10 + ? '会话剩余 ' + + remainingTurns + + ' 轮;容量用尽后定时任务将停止,未调用消息可转到其他会话重试。' + : '', + }; + } requestTurn(id, owner, requestId, payload) { this.row(id, owner); if (requestId === undefined) return null; @@ -357,7 +374,7 @@ class AssistantStore { .prepare('SELECT COUNT(*) AS n FROM turns WHERE conversation_id=?') .get(id).n; if (row.archived) throw fail('请先恢复归档会话或继续新对话。', 409); - if (count >= 100) throw fail('此对话已达 100 轮,请新建对话。', 409); + if (count >= MAX_TURNS) throw fail('此对话已达 100 轮,请新建对话。', 409); if ( this.db.prepare("SELECT 1 FROM turns WHERE conversation_id=? AND status='running'").get(id) ) diff --git a/tests/assistant/review-recovery.test.cjs b/tests/assistant/review-recovery.test.cjs new file mode 100644 index 0000000..30779ee --- /dev/null +++ b/tests/assistant/review-recovery.test.cjs @@ -0,0 +1,619 @@ +'use strict'; + +const { test } = require('node:test'); +const assert = require('node:assert/strict'); +const fs = require('node:fs'); +const os = require('node:os'); +const path = require('node:path'); +const crypto = require('node:crypto'); +const { managementFixture } = require('./management-fixture.cjs'); +const { OperationJournal } = require('../../src/modules/assistant/operation-journal.cjs'); +const approval = require('../../src/modules/assistant/configuration-approval.cjs'); +const configuration = require('../../src/modules/assistant/configuration.cjs'); +const { NativeSchedules } = require('../../src/modules/assistant/native-schedules.cjs'); + +async function until(predicate) { + const end = Date.now() + 10000; + while (!(await predicate())) { + if (Date.now() > end) throw Error('Recovery did not settle'); + await new Promise((resolve) => setTimeout(resolve, 20)); + } +} + +function enqueue(schedules, conversation, task, owner) { + schedules.flush({ + id: conversation.id, + owner, + pending: { + id: crypto.randomUUID(), + source: { kind: 'schedule' }, + content: [ + { + type: 'text', + text: + '[SCHEDULE REMINDER]\nThis is a scheduled message from the user\nschedule_id_json: ' + + JSON.stringify(task.id) + + '\noccurrence_at: ' + + task.scheduledAt + + '\nreminder_prompt_json: ' + + JSON.stringify(task.prompt), + }, + ], + }, + }); +} + +async function setup(t, browser = false) { + require('../fixtures/isolated-vault-key.cjs')(t); + const f = await managementFixture(t, { browser }); + const journalFile = path.join(os.tmpdir(), 'review-recovery-' + crypto.randomUUID() + '.sqlite'); + f.assistant.journal = new OperationJournal({ file: journalFile }); + t.after(() => { + f.assistant.journal.close(); + fs.rmSync(journalFile, { force: true }); + }); + f.store.saveSettings({ + ...f.store.settings(), + runtimePath: process.execPath, + apiKey: 'TEST_REVIEW_RECOVERY', + allowActions: true, + }); + const user = f.users.users().find((u) => u.username === 'admin'); + return { ...f, principal: { user, sessionId: 'review-session' } }; +} + +test('expired or version-invalid proposals can be rejected after actions are disabled, without applying them', async (t) => { + const f = await setup(t), + c = f.store.create(f.principal.user.id); + const proposal = configuration.propose( + { targetId: 'assistant', changes: { dailyLimit: 80 } }, + configuration.snapshot(f.assistant.deps, f.store, f.principal.user), + f.assistant.deps, + f.store, + f.principal.user, + ); + const action = { ...proposal, id: crypto.randomUUID(), status: 'proposed' }; + const turn = f.store.beginTurn(c.id, f.principal.user.id, 'proposal'); + f.store.updateTurn(turn.id, 'success', { reply: 'review', actions: [action] }); + const review = approval.review(f.assistant, c.id, action.id, f.principal); + f.store.action(c.id, f.principal.user.id, action.id, (a) => { + a.expiresAt = 0; + }); + f.store.saveSettings({ + version: f.store.settings().version, + dailyLimit: 60, + allowActions: false, + }); + assert.deepEqual(approval.reject(f.assistant, c.id, action.id, f.principal), { + status: 'rejected', + }); + assert.equal(f.store.settings().dailyLimit, 60); + assert.equal( + f.store.conversation(c.id, f.principal.user.id).turns[0].actions[0].status, + 'rejected', + ); + assert.equal( + f.store.db + .prepare('SELECT COUNT(*) n FROM assistant_configuration_approvals WHERE action_id=?') + .get(action.id).n, + 0, + ); + await assert.rejects( + approval.execute(f.assistant, c.id, action.id, f.principal, review.approvalToken), + ); + assert.throws( + () => approval.reject(f.assistant, c.id, action.id, f.principal), + (e) => e.status === 409, + ); +}); + +for (const fault of ['workspace', 'journal', 'result-save']) + test( + 'a completed fixed operation retains evidence and becomes needs_review when ' + + fault + + ' fails', + async (t) => { + const f = await setup(t), + c = f.store.create(f.principal.user.id), + actionId = crypto.randomUUID(); + let effects = 0; + f.assistant.deps.storage = { + store: { servers: () => [{ id: 'server', name: 'fixture', enabled: true, state: {} }] }, + check: async () => { + effects++; + return { state: { readable: true, writable: false } }; + }, + }; + const turn = f.store.beginTurn(c.id, f.principal.user.id, 'fixed operation'); + f.store.updateTurn(turn.id, 'success', { + reply: 'review', + actions: [ + { + id: actionId, + kind: 'check_storage', + targetId: 'server', + label: '检查存储连接', + status: 'proposed', + }, + ], + }); + + if (fault === 'workspace') + f.assistant.deps.workspace = { + record() { + throw Error('audit write failed after effect'); + }, + }; + if (fault === 'journal') { + const record = f.assistant.record.bind(f.assistant); + t.mock.method(f.assistant, 'record', (...args) => { + if (args[2] === 'execute' && args[3] === 'success') + throw Error('final journal unavailable'); + return record(...args); + }); + } + if (fault === 'result-save') { + const action = f.store.action.bind(f.store); + t.mock.method(f.store, 'action', (id, owner, aid, work) => + action(id, owner, aid, (a) => { + const value = work(a); + if (a.status === 'success') throw Error('result persistence failed'); + return value; + }), + ); + } + await assert.rejects(f.assistant.executeAction(c.id, actionId, f.principal)); + const saved = f.store.conversation(c.id, f.principal.user.id).turns[0].actions[0]; + assert.equal(saved.status, 'needs_review'); + assert.deepEqual(saved.result, { readable: true, writable: false }); + assert.equal(effects, 1); + await assert.rejects( + f.assistant.executeAction(c.id, actionId, f.principal), + (e) => e.status === 409, + ); + assert.equal(effects, 1); + }, + ); + +test('an unstarted native delivery survives restart and supports one confirmed owner-scoped retry', async (t) => { + const f = await setup(t), + c = f.store.create(f.principal.user.id); + f.store.saveSettings({ version: f.store.settings().version, dailyLimit: 1 }); + const previous = f.store.beginTurn(c.id, f.principal.user.id, 'old call'); + f.store.updateTurn(previous.id, 'success', { reply: 'done' }); + let calls = 0; + f.assistant.runtime.chat = async () => { + calls++; + return JSON.stringify({ reply: 'Recovered reminder', actions: [] }); + }; + let schedules = await NativeSchedules.create({ assistant: f.assistant }); + const task = await schedules.createTask(c.id, f.principal, { + confirm: true, + request: { title: 'Quota reminder', prompt: 'Read only', after_seconds: 1 }, + }); + await until(async () => + (await schedules.list(c.id, f.principal)).history.some( + (h) => h.taskId === task.id && h.status === 'not_started', + ), + ); + let h = (await schedules.list(c.id, f.principal)).history[0]; + assert.equal(h.status, 'not_started'); + assert.equal(h.retryable, true); + assert.equal(calls, 0); + await schedules.stop(); + schedules = await NativeSchedules.create({ assistant: f.assistant }); + h = (await schedules.list(c.id, f.principal)).history[0]; + assert.equal(h.status, 'not_started'); + await assert.rejects( + schedules.retryDelivery(c.id, h.id, f.principal, {}), + (e) => e.status === 403, + ); + await assert.rejects( + schedules.retryDelivery( + c.id, + h.id, + { user: f.users.users().find((u) => u.username === 'viewer'), sessionId: 'viewer' }, + { confirm: true }, + ), + (e) => [403, 404].includes(e.status), + ); + f.store.saveSettings({ version: f.store.settings().version, dailyLimit: 5 }); + const results = await Promise.allSettled( + [0, 1].map(() => schedules.retryDelivery(c.id, h.id, f.principal, { confirm: true })), + ); + assert.equal(results.filter((r) => r.status === 'fulfilled').length, 1); + await until( + async () => (await schedules.list(c.id, f.principal)).history[0].status === 'success', + ); + assert.equal(calls, 1); + assert.equal(f.store.conversation(c.id, f.principal.user.id).turns.length, 2); + await assert.rejects( + schedules.retryDelivery(c.id, h.id, f.principal, { confirm: true }), + (e) => e.status === 409, + ); +}); + +test('a delivery with an existing turn or unknown model result is never admitted as a safe retry', async (t) => { + const f = await setup(t), + c = f.store.create(f.principal.user.id); + let calls = 0; + f.assistant.runtime.chat = async () => { + calls++; + return JSON.stringify({ reply: 'Unexpected replay', actions: [] }); + }; + let schedules = await NativeSchedules.create({ assistant: f.assistant }); + const task = await schedules.createTask(c.id, f.principal, { + confirm: true, + request: { title: 'Interrupted reminder', prompt: 'Read only', after_seconds: 3600 }, + }); + enqueue(schedules, c, task, f.principal.user.id); + const row = f.store.db.prepare('SELECT * FROM assistant_schedule_inbox').get(); + const text = '[定时任务:' + task.title + ']\n' + task.prompt; + const turn = f.store.beginTurn(c.id, f.principal.user.id, text, { + requestId: 'schedule-' + row.id, + requestPayload: { text, diagnostic: null, repair: null }, + }); + f.store.db + .prepare("UPDATE assistant_schedule_inbox SET status='running',turn_id=? WHERE id=?") + .run(turn.id, row.id); + await schedules.stop(); + f.store.recover(); + schedules = await NativeSchedules.create({ assistant: f.assistant }); + await until( + async () => (await schedules.list(c.id, f.principal)).history[0].status === 'needs_review', + ); + const h = (await schedules.list(c.id, f.principal)).history[0]; + assert.equal(h.retryable, false); + assert.equal(calls, 0); + await assert.rejects( + schedules.retryDelivery(c.id, h.id, f.principal, { confirm: true }), + (e) => e.status === 409, + ); + assert.equal(calls, 0); +}); + +test('a full conversation stops its recurring native task and its undelivered message can move once to an owned conversation', async (t) => { + const f = await setup(t), + c = f.store.create(f.principal.user.id); + f.store.saveSettings({ version: f.store.settings().version, dailyLimit: 1000 }); + for (let i = 0; i < 90; i++) { + const turn = f.store.beginTurn(c.id, f.principal.user.id, 'history ' + i); + f.store.updateTurn(turn.id, 'success', { reply: 'done' }); + } + const schedules = await NativeSchedules.create({ assistant: f.assistant }); + const task = await schedules.createTask(c.id, f.principal, { + confirm: true, + request: { title: 'Recurring reminder', prompt: 'Read only', every_seconds: 60 }, + }); + assert.match((await schedules.list(c.id, f.principal)).tasks[0].capacityWarning, /10/); + for (let i = 90; i < 100; i++) { + const turn = f.store.beginTurn(c.id, f.principal.user.id, 'history ' + i); + f.store.updateTurn(turn.id, 'success', { reply: 'done' }); + } + let calls = 0; + f.assistant.runtime.chat = async () => { + calls++; + return JSON.stringify({ reply: 'Continued safely', actions: [] }); + }; + enqueue(schedules, c, task, f.principal.user.id); + await until( + async () => (await schedules.list(c.id, f.principal)).history[0]?.status === 'waiting_capacity', + ); + await until( + async () => (await schedules.list(c.id, f.principal)).tasks[0]?.status === 'capacity_stopped', + ); + assert.equal((await schedules.native.list({ sessionId: c.id })).length, 0); + assert.equal(calls, 0); + const h = (await schedules.list(c.id, f.principal)).history[0]; + assert.equal(h.retryable, true); + await assert.rejects( + schedules.retryDelivery(c.id, h.id, f.principal, { confirm: true }), + (e) => e.status === 409, + ); + const other = f.store.create(f.users.users().find((u) => u.username === 'viewer').id); + await assert.rejects( + schedules.retryDelivery(c.id, h.id, f.principal, { + confirm: true, + targetConversationId: other.id, + }), + (e) => [403, 404].includes(e.status), + ); + const target = f.store.create(f.principal.user.id); + await schedules.retryDelivery(c.id, h.id, f.principal, { + confirm: true, + targetConversationId: target.id, + }); + await until(() => calls === 1); + await until( + async () => (await schedules.list(target.id, f.principal)).history[0]?.status === 'success', + ); + assert.equal(f.store.conversation(c.id, f.principal.user.id).turns.length, 100); + assert.equal( + f.store.conversation(target.id, f.principal.user.id).turns[0].reply, + 'Continued safely', + ); + assert.equal((await schedules.list(c.id, f.principal)).tasks[0].status, 'capacity_stopped'); + await schedules.deleteTask(c.id, task.id, f.principal, { confirm: true }); + assert.equal((await schedules.list(c.id, f.principal)).tasks.length, 0); +}); + +test('the owner can reject an expired card directly from the operation panel', async (t) => { + const f = await setup(t, true), + c = f.store.create(f.principal.user.id); + const proposal = configuration.propose( + { targetId: 'assistant', changes: { dailyLimit: 80 } }, + configuration.snapshot(f.assistant.deps, f.store, f.principal.user), + f.assistant.deps, + f.store, + f.principal.user, + ); + const action = { ...proposal, id: crypto.randomUUID(), status: 'proposed', expiresAt: 0 }; + const turn = f.store.beginTurn(c.id, f.principal.user.id, 'Expired suggestion'); + f.store.updateTurn(turn.id, 'success', { reply: 'Please review', actions: [action] }); + f.store.saveSettings({ version: f.store.settings().version, allowActions: false }); + let reviews = 0; + await f.page.route('**/actions/*/review', (route) => { + reviews++; + return route.abort(); + }); + await f.open(); + await f.page.getByRole('button', { name: '查看操作(1)', exact: true }).click(); + await f.page.getByRole('button', { name: '拒绝建议', exact: true }).click(); + await f.page.getByText('已拒绝,未修改', { exact: true }).waitFor(); + assert.equal(reviews, 0); + assert.equal(f.store.settings().dailyLimit, 100); +}); + +test('the task manager offers a confirmed retry only for an unstarted delivery', async (t) => { + const f = await setup(t, true), + c = f.store.create(f.principal.user.id); + f.store.saveSettings({ version: f.store.settings().version, dailyLimit: 1 }); + const old = f.store.beginTurn(c.id, f.principal.user.id, 'Old call'); + f.store.updateTurn(old.id, 'success', { reply: 'Done' }); + let calls = 0; + f.assistant.runtime.chat = async () => { + calls++; + return JSON.stringify({ reply: 'Recovered through UI', actions: [] }); + }; + const schedules = await NativeSchedules.create({ assistant: f.assistant }); + await schedules.createTask(c.id, f.principal, { + confirm: true, + request: { title: 'UI recovery reminder', prompt: 'Read only', after_seconds: 1 }, + }); + await until( + async () => (await schedules.list(c.id, f.principal)).history[0]?.status === 'not_started', + ); + f.store.saveSettings({ version: f.store.settings().version, dailyLimit: 5 }); + await f.open(); + await f.page.getByRole('button', { name: '定时任务', exact: true }).click(); + await f.page + .getByRole('button', { name: '重试定时消息 UI recovery reminder', exact: true }) + .click(); + const dialog = f.page.getByRole('dialog', { name: '重试定时消息', exact: true }); + assert.equal( + await dialog.getByRole('button', { name: '确认重试', exact: true }).isDisabled(), + true, + ); + await dialog.getByRole('checkbox', { name: '我确认仅重试这条未调用消息', exact: true }).check(); + await dialog.getByRole('button', { name: '确认重试', exact: true }).click(); + await until(() => calls === 1); + await until( + async () => (await schedules.list(c.id, f.principal)).history[0]?.status === 'success', + ); + await f.page.getByRole('button', { name: '返回对话', exact: true }).click(); + await f.page.getByText('Recovered through UI', { exact: true }).waitFor(); + assert.equal(calls, 1); +}); + +for (const restore of [false, true]) + test( + 'a queued snapshot cannot resurrect a delivery cancelled by archive; restored=' + restore, + async (t) => { + const f = await setup(t), + a = f.store.create(f.principal.user.id), + b = f.store.create(f.principal.user.id); + const schedules = await NativeSchedules.create({ assistant: f.assistant }); + const ta = await schedules.createTask(a.id, f.principal, { + confirm: true, + request: { title: 'First gate', prompt: 'Wait', after_seconds: 3600 }, + }); + const tb = await schedules.createTask(b.id, f.principal, { + confirm: true, + request: { title: 'Cancelled next', prompt: 'Do not call', after_seconds: 3600 }, + }); + let release, + calls = 0; + const gate = new Promise((r) => (release = r)); + t.after(() => release()); + f.assistant.runtime.chat = async () => { + calls++; + if (calls === 1) await gate; + return JSON.stringify({ reply: 'Done', actions: [] }); + }; + enqueue(schedules, a, ta, f.principal.user.id); + enqueue(schedules, b, tb, f.principal.user.id); + f.store.db + .prepare('UPDATE assistant_schedule_inbox SET created_at=? WHERE task_id=?') + .run(new Date(Date.now() + 1000).toISOString(), tb.id); + await until(() => calls === 1); + const archived = f.store.archive(b.id, f.principal.user.id, { + version: f.store.conversation(b.id, f.principal.user.id).version, + }); + await schedules.stopSession(b.id); + if (restore) f.store.restore(b.id, f.principal.user.id, { version: archived.version }); + release(); + await schedules.draining; + const cancelled = f.store.db + .prepare('SELECT * FROM assistant_schedule_inbox WHERE task_id=?') + .get(tb.id); + assert.equal(cancelled.status, 'cancelled'); + assert.equal(calls, 1); + assert.equal(f.store.conversation(b.id, f.principal.user.id).turns.length, 0); + }, + ); + +test('a send failure after durable turn admission cannot be retried as unstarted', async (t) => { + const f = await setup(t), + c = f.store.create(f.principal.user.id); + let calls = 0; + f.assistant.runtime.chat = async () => { + calls++; + return '{}'; + }; + const schedules = await NativeSchedules.create({ assistant: f.assistant }); + const task = await schedules.createTask(c.id, f.principal, { + confirm: true, + request: { title: 'Admission audit failure', prompt: 'Read', after_seconds: 3600 }, + }); + const record = f.assistant.record.bind(f.assistant); + t.mock.method(f.assistant, 'record', (...args) => { + if (args[2] === 'context') throw Error('audit failed after turn'); + return record(...args); + }); + enqueue(schedules, c, task, f.principal.user.id); + await until( + async () => (await schedules.list(c.id, f.principal)).history[0]?.status === 'needs_review', + ); + const h = (await schedules.list(c.id, f.principal)).history[0]; + assert.ok(h.turnId); + assert.equal(h.retryable, false); + assert.equal(calls, 0); + await assert.rejects( + schedules.retryDelivery(c.id, h.id, f.principal, { confirm: true }), + (e) => e.status === 409, + ); +}); + +test('a lost native stop acknowledgement remains stopped after restart and preserves its reminder', async (t) => { + const f = await setup(t); + f.store.saveSettings({ version: f.store.settings().version, dailyLimit: 1000 }); + // Create the rule in a free conversation, then fill it before the reminder is delivered. + const target = f.store.create(f.principal.user.id); + let schedules = await NativeSchedules.create({ assistant: f.assistant }); + const task = await schedules.createTask(target.id, f.principal, { + confirm: true, + request: { title: 'Stop receipt lost', prompt: 'Read', every_seconds: 60 }, + }); + for (let i = 0; i < 100; i++) { + const turn = f.store.beginTurn(target.id, f.principal.user.id, 'old ' + i); + f.store.updateTurn(turn.id, 'success', { reply: 'done' }); + } + const nativeDelete = schedules.native.delete.bind(schedules.native); + t.mock.method(schedules.native, 'delete', async (args) => { + await nativeDelete(args); + throw Object.assign(Error('lost receipt'), { status: 502 }); + }); + enqueue(schedules, target, task, f.principal.user.id); + await until( + async () => + (await schedules.list(target.id, f.principal)).history[0]?.status === 'waiting_capacity', + ); + await until(() => !schedules.tasks.has(task.id)); + await schedules.stop(); + schedules = await NativeSchedules.create({ assistant: f.assistant }); + const result = await schedules.list(target.id, f.principal); + assert.equal(result.tasks[0].status, 'capacity_stopped'); + assert.equal(result.history[0].status, 'waiting_capacity'); + assert.equal(result.history[0].retryable, true); +}); + +test('a recovered queue clears the current global error without deleting historical delivery errors', async (t) => { + const f = await setup(t), + schedules = await NativeSchedules.create({ assistant: f.assistant }); + await schedules.draining; + let broken = true; + const drain = schedules.drain.bind(schedules); + t.mock.method(schedules, 'drain', async () => { + if (broken) throw Error('temporary queue read failure'); + return drain(); + }); + schedules.kick(); + await schedules.draining; + assert.ok((await schedules.catalog(f.principal)).error); + broken = false; + schedules.kick(); + await schedules.draining; + assert.equal((await schedules.catalog(f.principal)).error, ''); +}); + +test('capacity-stop UI keeps the native rule stopped while moving only the accepted message', async (t) => { + const f = await setup(t, true), + c = f.store.create(f.principal.user.id); + f.store.saveSettings({ version: f.store.settings().version, dailyLimit: 1000 }); + const schedules = await NativeSchedules.create({ assistant: f.assistant }); + const task = await schedules.createTask(c.id, f.principal, { + confirm: true, + request: { title: 'Capacity UI reminder', prompt: 'Read only', every_seconds: 60 }, + }); + for (let i = 0; i < 100; i++) { + const turn = f.store.beginTurn(c.id, f.principal.user.id, 'old ' + i); + f.store.updateTurn(turn.id, 'success', { reply: 'done' }); + } + enqueue(schedules, c, task, f.principal.user.id); + await until( + async () => (await schedules.list(c.id, f.principal)).tasks[0]?.status === 'capacity_stopped', + ); + const target = f.store.create(f.principal.user.id); + let calls = 0; + f.assistant.runtime.chat = async () => { + calls++; + return JSON.stringify({ reply: 'Capacity continuation received', actions: [] }); + }; + await f.open(); + await f.page.getByRole('button', { name: '定时任务', exact: true }).click(); + const manager = f.page.getByRole('region', { name: '定时任务管理', exact: true }); + await manager + .locator('[data-task-list]') + .getByText('容量已满,已停止', { exact: true }) + .waitFor(); + await manager + .getByRole('button', { name: '重试定时消息 Capacity UI reminder', exact: true }) + .click(); + const dialog = f.page.getByRole('dialog', { name: '重试定时消息', exact: true }); + assert.match(await dialog.innerText(), /周期任务请在新会话重新安排/); + await dialog.getByLabel('目标会话', { exact: true }).selectOption(target.id); + await dialog.getByRole('checkbox', { name: '我确认仅重试这条未调用消息', exact: true }).check(); + await dialog.getByRole('button', { name: '确认重试', exact: true }).click(); + await until( + async () => (await schedules.list(target.id, f.principal)).history[0]?.status === 'success', + ); + assert.equal(calls, 1); + assert.equal((await schedules.native.list({ sessionId: c.id })).length, 0); + const output = path.resolve(__dirname, '../../output/verification/review-4'); + fs.mkdirSync(output, { recursive: true }); + await f.page.screenshot({ path: path.join(output, 'capacity-recovered.png'), fullPage: true }); +}); + +test('retry HTTP rejects missing confirmation, forged state and cross-owner targets', async (t) => { + const f = await setup(t), + c = f.store.create(f.principal.user.id), + schedules = await NativeSchedules.create({ assistant: f.assistant }); + const task = await schedules.createTask(c.id, f.principal, { + confirm: true, + request: { title: 'HTTP recovery', prompt: 'Read', after_seconds: 3600 }, + }); + const disabled = f.store.providers.read('deepseek'); + f.store.providers.save({ ...disabled, enabled: false }); + enqueue(schedules, c, task, f.principal.user.id); + await until( + async () => (await schedules.list(c.id, f.principal)).history[0]?.status === 'not_started', + ); + const row = (await schedules.list(c.id, f.principal)).history[0]; + const cookie = await f.login(), + viewer = await f.login('viewer'), + endpoint = '/assistant/conversations/' + c.id + '/schedules/deliveries/' + row.id + '/retry'; + assert.equal((await f.call(endpoint, {}, cookie)).status, 403); + assert.equal((await f.call(endpoint, { confirm: true, status: 'queued' }, cookie)).status, 400); + assert.equal((await f.call(endpoint, { confirm: true }, viewer)).status, 404); + const foreign = f.store.create(f.users.users().find((u) => u.username === 'viewer').id); + assert.equal( + (await f.call(endpoint, { confirm: true, targetConversationId: foreign.id }, cookie)).status, + 404, + ); + f.store.providers.save({ ...f.store.providers.read('deepseek'), enabled: true }); + f.assistant.runtime.chat = async () => JSON.stringify({ reply: 'Recovered API', actions: [] }); + assert.equal((await f.call(endpoint, { confirm: true }, cookie)).status, 200); + await until( + async () => (await schedules.list(c.id, f.principal)).history[0]?.status === 'success', + ); +}); diff --git a/web/modules/assistant/context-panel.js b/web/modules/assistant/context-panel.js index b1240da..8b975f6 100644 --- a/web/modules/assistant/context-panel.js +++ b/web/modules/assistant/context-panel.js @@ -10,6 +10,7 @@ window.AssistantContextPanel = { settings, isActive, onExecute, + onReject, onRepair, showRight, ensureConversation, @@ -165,10 +166,13 @@ window.AssistantContextPanel = { list .map( ({ a, t }) => - `
${esc(a.label)}
目标:${esc(a.targetId)}
影响:${esc({ check_storage: '发起一次存储连接检查', scan_bpm: '只读重新扫描,更新到达记录', retry_archive: '向原目标重试明确失败的归档', collect_field_samples: '读取待办样本并保存字段证据', collect_history_samples: '只读采集历史字段样本', prepare_field_mapping: '生成并检查草稿,不自动生效', repair_code: '在隔离 Git 工作区执行固定测试,不自动合并部署' }[a.kind] || '仅执行已列出的受控操作')}
操作编号:${esc(a.id)}
${['update_configuration', 'manage_schedule'].includes(a.kind) ? `
${a.diff.map((d) => `

${esc(d.label)}:${esc(JSON.stringify(d.before))} → ${esc(JSON.stringify(d.after))}

`).join('')}风险与影响审查并授权后才会保存;建议过期或配置变化须重新生成。
` : ''}${a.kind === 'repair_code' ? `

以本机服务身份运行固定测试;工作区不是操作系统沙箱,通过后仍待人工审查。

${a.files.map((f) => `
${esc(f.path)} · 查看修改前后
修改前
${esc(a.beforeFiles?.find((b) => b.path === f.path)?.content || '')}
建议内容
${esc(f.content)}
`).join('')}` : ''}${a.progress ? `

采样进度 ${esc(a.progress.completed)} / ${esc(a.progress.total)},成功 ${esc(a.progress.captured)},受阻 ${esc(a.progress.failed)}

` : ''}
${a.status === 'proposed' ? `` : `${esc(window.AssistantConversation.actionState(a))}`}
${a.error ? `

${esc(a.error)}

` : ''}${a.result || ['success', 'error', 'needs_review', 'interrupted'].includes(a.status) ? `
结果详情

${esc(window.AssistantConversation.actionSummary(a))}

${a.result && (typeof a.result !== 'object' || Object.keys(a.result).length) ? `
${esc(JSON.stringify(a.result, null, 2))}
` : ''}
` : ''}${a.result?.link ? '' + (a.kind === 'update_configuration' ? '查看设置' : '查看字段映射') + '' : ''}
`, + `
${esc(a.label)}
目标:${esc(a.targetId)}
影响:${esc({ check_storage: '发起一次存储连接检查', scan_bpm: '只读重新扫描,更新到达记录', retry_archive: '向原目标重试明确失败的归档', collect_field_samples: '读取待办样本并保存字段证据', collect_history_samples: '只读采集历史字段样本', prepare_field_mapping: '生成并检查草稿,不自动生效', repair_code: '在隔离 Git 工作区执行固定测试,不自动合并部署' }[a.kind] || '仅执行已列出的受控操作')}
操作编号:${esc(a.id)}
${['update_configuration', 'manage_schedule'].includes(a.kind) ? `
${a.diff.map((d) => `

${esc(d.label)}:${esc(JSON.stringify(d.before))} → ${esc(JSON.stringify(d.after))}

`).join('')}风险与影响审查并授权后才会保存;建议过期或配置变化须重新生成。
` : ''}${a.kind === 'repair_code' ? `

以本机服务身份运行固定测试;工作区不是操作系统沙箱,通过后仍待人工审查。

${a.files.map((f) => `
${esc(f.path)} · 查看修改前后
修改前
${esc(a.beforeFiles?.find((b) => b.path === f.path)?.content || '')}
建议内容
${esc(f.content)}
`).join('')}` : ''}${a.progress ? `

采样进度 ${esc(a.progress.completed)} / ${esc(a.progress.total)},成功 ${esc(a.progress.captured)},受阻 ${esc(a.progress.failed)}

` : ''}
${a.status === 'proposed' ? `${['update_configuration', 'manage_schedule'].includes(a.kind) ? `` : ''}` : `${esc(window.AssistantConversation.actionState(a))}`}
${a.error ? `

${esc(a.error)}

` : ''}${a.result || ['success', 'error', 'needs_review', 'interrupted'].includes(a.status) ? `
结果详情

${esc(window.AssistantConversation.actionSummary(a))}

${a.result && (typeof a.result !== 'object' || Object.keys(a.result).length) ? `
${esc(JSON.stringify(a.result, null, 2))}
` : ''}
` : ''}${a.result?.link ? '' + (a.kind === 'update_configuration' ? '查看设置' : '查看字段映射') + '' : ''}
`, ) .join('') + (list.length ? '' : '

建议将在这里展示,确认前不会执行。

'); + panels.actions + .querySelectorAll('[data-assistant-reject]') + .forEach((b) => (b.onclick = () => onReject(b.dataset.assistantReject, b))); panels.actions .querySelectorAll('[data-assistant-action]') .forEach( diff --git a/web/modules/assistant/operations.js b/web/modules/assistant/operations.js index 9cd394e..f939a1e 100644 --- a/web/modules/assistant/operations.js +++ b/web/modules/assistant/operations.js @@ -3,6 +3,7 @@ window.AssistantOperations = { mount(container, { api, esc, formatDate, user, settings, isActive, onRepair }) { const stepNames = { management_query: '查询受控管理资源', + schedule_retry: '重试尚未调用的定时消息', schedule_create: '创建原生定时任务', schedule_update: '修改原生定时任务', schedule_delete: '删除原生定时任务', diff --git a/web/modules/assistant/schedule-manager.js b/web/modules/assistant/schedule-manager.js index 28f0434..ca7584b 100644 --- a/web/modules/assistant/schedule-manager.js +++ b/web/modules/assistant/schedule-manager.js @@ -19,6 +19,7 @@ window.AssistantScheduleManager = { ['all', '全部'], ['active', '进行中'], ['inactive', '已结束'], + ['capacity', '容量停止'], ] .map( ([id, label]) => @@ -31,7 +32,7 @@ window.AssistantScheduleManager = { '', ) .join('') + - '

正在读取任务…

'; + '

正在读取任务…

'; root.append(page); let visible = false, disposed = false, @@ -52,6 +53,22 @@ window.AssistantScheduleManager = { message = page.querySelector('[data-task-message]'), newButton = page.querySelector('[data-task-create]'); const alive = () => !disposed && visible && isActive(); + const recovery = window.AssistantScheduleRecovery.mount( + page.querySelector('[data-task-recovery]'), + { + root, + api, + esc, + formatDate, + user, + isActive: () => alive(), + getConversations: () => conversations, + onChanged: async (id) => { + await onChanged(id); + await refresh(); + }, + }, + ); const editor = window.AssistantSchedules.mount(page.querySelector('[data-task-editor]'), { api, esc, @@ -86,7 +103,15 @@ window.AssistantScheduleManager = { return user.role !== 'viewer' && settled && !failed && !t?.conversationArchived; } function nativeTask(t) { - const { conversationTitle, conversationArchived, ...value } = t; + const { + conversationTitle, + conversationArchived, + turnCount, + remainingTurns, + maxTurns, + capacityWarning, + ...value + } = t; return value; } function target(t) { @@ -95,10 +120,14 @@ window.AssistantScheduleManager = { } function draw() { newButton.disabled = !canWrite(); + recovery.update(history); const rows = tasks .filter( (t) => - (status === 'all' || t.status === status) && + (status === 'all' || + t.status === status || + (status === 'capacity' && + ['capacity_stopped', 'capacity_stopping'].includes(t.status))) && (!conversationFilter || t.sessionId === conversationFilter) && (!query || [t.title, t.prompt, t.conversationTitle, t.id, t.sessionId].some((v) => @@ -119,7 +148,7 @@ window.AssistantScheduleManager = { tasks.length + ' 个任务;新建、详情、编辑和删除均可在此操作。' : '正在读取任务…'; - const next = JSON.stringify([rows, settled, failed, user.role]); + const next = JSON.stringify([rows, history, settled, failed, user.role]); if (next === signature) return; signature = next; list.innerHTML = rows.length @@ -129,14 +158,14 @@ window.AssistantScheduleManager = { '
' + esc(t.title) + '' + - (t.status === 'active' ? '进行中' : '已结束') + + esc(window.AssistantScheduleRecovery.taskStatus(t.status)) + '

' + esc(frequency(t)) + '
' + esc( - t.status === 'active' - ? '下次触发:' + formatDate(t.scheduledAt) - : '最后触发时间:' + formatDate(t.scheduledAt), + window.AssistantScheduleRecovery.timeLabel(t.status) + + ':' + + formatDate(t.scheduledAt), ) + '
所属会话:' + esc(t.conversationTitle || '未命名会话') + @@ -144,6 +173,9 @@ window.AssistantScheduleManager = { esc(t.prompt) + '

' + (t.lastError ? '

' + esc(t.lastError) + '

' : '') + + (t.capacityWarning + ? '

' + esc(t.capacityWarning) + '

' + : '') + '
'; + root.append(dialog); + const form = dialog.querySelector('form'); + const save = form.querySelector('[type=submit]'); + const checkbox = form.elements.consent; + const target = form.elements.target; + target.value = choices.some((c) => c.id === row.conversationId) + ? row.conversationId + : choices[0]?.id || ''; + checkbox.onchange = () => { + save.disabled = !checkbox.checked || !choices.length || dialog.dataset.locked === 'true'; + }; + form.querySelector('[data-retry-cancel]').onclick = () => { + if (!busy) dialog.close(); + }; + dialog.oncancel = (e) => { + if (busy) e.preventDefault(); + }; + dialog.onclose = () => dialog.remove(); + form.onsubmit = async (e) => { + e.preventDefault(); + if (busy || !checkbox.checked || !target.value || dialog.dataset.locked === 'true') return; + busy = true; + save.disabled = true; + target.disabled = true; + checkbox.disabled = true; + try { + const result = await api( + '/assistant/conversations/' + + row.conversationId + + '/schedules/deliveries/' + + row.id + + '/retry', + { confirm: true, targetConversationId: target.value }, + { managedOutcome: true }, + ); + if (disposed || !isActive()) return; + dialog.close(); + await onChanged(result.conversationId); + } catch (error) { + if (dialog.isConnected && !disposed) { + const uncertain = !error.status || error.status >= 500; + dialog.dataset.locked = uncertain || error.status === 409 ? 'true' : ''; + form.querySelector('[data-retry-error]').textContent = + error.message + (uncertain ? ' 请刷新调用记录核实,勿重复提交。' : ''); + target.disabled = false; + checkbox.disabled = false; + save.disabled = dialog.dataset.locked === 'true'; + } + } finally { + busy = false; + } + }; + dialog.showModal(); + } + + return { + update(rows) { + history = rows; + const pending = history.filter( + (h) => + h.retryable || ['not_started', 'waiting_capacity', 'needs_review'].includes(h.status), + ); + const next = JSON.stringify([pending, getConversations(), user.role]); + if (next === signature) return; + signature = next; + host.hidden = !pending.length; + host.innerHTML = + '

需处理的定时调用

' + + pending + .map( + (h) => + '
' + + esc(h.title) + + '

' + + esc(formatDate(h.scheduledAt)) + + ' · ' + + esc( + { + not_started: '尚未调用,可确认后重试', + waiting_capacity: '等待选择其他会话', + needs_review: '已有调用记录,需人工核实', + }[h.status] || h.status, + ) + + '

' + + (h.error ? '

' + esc(h.error) + '

' : '') + + (h.retryable && user.role !== 'viewer' + ? '' + : '') + + '
', + ) + .join(''); + host + .querySelectorAll('[data-retry-delivery]') + .forEach( + (b) => (b.onclick = () => open(history.find((h) => h.id === b.dataset.retryDelivery))), + ); + }, + dispose() { + disposed = true; + history = []; + }, + }; + }, +}; diff --git a/web/modules/assistant/schedules.js b/web/modules/assistant/schedules.js index 4e85aac..1e3e9ed 100644 --- a/web/modules/assistant/schedules.js +++ b/web/modules/assistant/schedules.js @@ -21,14 +21,31 @@ window.AssistantSchedules = { visible = false, tasks = [], history = [], + conversations = [], timer = null, loading = false, lastSignature = ''; const root = host.closest('.assistant-workspace'); host.innerHTML = - '

定时任务

使用 DSH 原生调度,在原会话中定时调用模型。关闭页面后仍可运行,服务停止期间不会调用模型。

最近调用

'; + '

定时任务

使用 DSH 原生调度,在原会话中定时调用模型。关闭页面后仍可运行,服务停止期间不会调用模型。

最近调用

'; const error = host.querySelector('[data-schedule-error]'), create = host.querySelector('[data-schedule-new]'); + const recovery = window.AssistantScheduleRecovery.mount( + host.querySelector('[data-schedule-recovery]'), + { + root, + api, + esc, + formatDate, + user, + isActive, + getConversations: () => conversations, + onChanged: async (id) => { + await onChanged(id); + await refresh(); + }, + }, + ); const writable = () => user.role !== 'viewer' && !getConversation()?.archived && !getConversation()?.deletedAt; function timing(t) { @@ -45,6 +62,7 @@ window.AssistantSchedules = { } function draw() { create.disabled = busy || !writable(); + recovery.update(history); const signature = JSON.stringify([tasks, history, busy, writable()]); if (signature === lastSignature) return; lastSignature = signature; @@ -60,12 +78,17 @@ window.AssistantSchedules = { esc( t.status === 'active' ? '下次触发:' + formatDate(t.scheduledAt) - : '已触发(不再重复)', + : t.status === 'inactive' + ? '已触发(不再重复)' + : window.AssistantScheduleRecovery.taskStatus(t.status), ) + '

' + esc(t.prompt) + '

' + (t.lastError ? '

' + esc(t.lastError) + '

' : '') + + (t.capacityWarning + ? '

' + esc(t.capacityWarning) + '

' + : '') + '