From de5e8af39b0d89386193dbfd8d856c4ae886a13e Mon Sep 17 00:00:00 2001 From: jinmingtao Date: Fri, 20 Nov 2026 15:36:07 +0800 Subject: [PATCH 1/5] docs(feishu): specify Worker message phases and turn status --- .scratch/worker-feishu-message-phases/spec.md | 69 +++++++++++++++++++ README.md | 2 +- ...-agent-owns-workflow-and-message-intent.md | 2 + prompts/worker.md | 2 +- 4 files changed, 73 insertions(+), 2 deletions(-) create mode 100644 .scratch/worker-feishu-message-phases/spec.md diff --git a/.scratch/worker-feishu-message-phases/spec.md b/.scratch/worker-feishu-message-phases/spec.md new file mode 100644 index 0000000..19b8887 --- /dev/null +++ b/.scratch/worker-feishu-message-phases/spec.md @@ -0,0 +1,69 @@ +Status: ready-for-agent + +# Worker 飞书群展示各阶段的助手消息 + +Worker 在需求讨论中可能先写出完整问题和建议,随后用最终答复概括待决事项。用户希望直接在 Worker 群里看到两段原文。 + +## 已确认 + +- Worker 任务群展示 Codex 助手消息的三个阶段:过程说明(`commentary`)、部分答复(`partial_answer`)和最终答复(`final_answer`)。 +- 每条助手消息写完后立即发送完整原文。同一条消息里的多个问题一起发送,正文省略阶段标签。 +- Worker 开始本轮执行时,群里立即显示「处理中」。阅读最新消息时也能看到状态,包括第一条正文出现前和两条正文之间。 +- 本轮持续期间显示「处理中」。每条助手正文写完即可发送,状态随本轮生命周期更新。本轮结束且本轮应发送的正文已投递后,显示「本轮已结束」。本轮以失败或中断结束时也使用这一结束文案。 +- 群内状态提示只有上述两种。执行中用户仍可发送补充消息,原生提问和审批继续通过现有入口处理。 +- 项目协调群的普通助手消息沿用现有最终答复投递条件。协调群公告、原生问题和审批各有独立的投递规则。见 [ADR 0017](../../docs/adr/0017-coordinator-group-announcements.md)。 +- 本需求调整 [ADR 0006](../../docs/adr/0006-agent-owns-workflow-and-message-intent.md) 中 Worker 群普通回复的可见范围。现有显式中间汇报的投递规则见 [ADR 0021](../../docs/adr/0021-worker-discussion-routing.md)。 +- Worker 群状态只使用「处理中」和「本轮已结束」。 + +## Problem Statement + +Worker 的 `commentary` 和 `partial_answer` 会进入飞书「执行进度」,但普通 Worker 群只收到 `final_answer`。用户因此看不到执行过程中的问题,也无法判断 Worker 是否仍在工作。项目协调群需要继续保持当前只发送最终答复的行为。 + +## Solution + +在 Worker 任务群中,按 Codex `agentMessage` 完成事件逐条发送 `commentary`、`partial_answer` 和 `final_answer` 的完整正文。Worker 本轮开始时发送或更新「处理中」状态,本轮完成、失败或中断并完成应发送消息的投递后显示「本轮已结束」。协调者群继续只投递当前规则允许的最终答复。 + +## User Stories + +1. 作为 Worker 群用户,我希望看到每条已经完成的过程说明,以便及时了解 Worker 的问题和工作进展。 +2. 作为 Worker 群用户,我希望看到部分答复和最终答复,以便掌握一轮对话的完整上下文。 +3. 作为 Worker 群用户,我希望正文保持原文并省略阶段标签,以便直接阅读 Agent 的消息。 +4. 作为 Worker 群用户,我希望 Worker 开始后立即看到「处理中」,以便知道暂时没有正文并不代表执行已结束。 +5. 作为 Worker 群用户,我希望 Worker 结束后看到「本轮已结束」,以便知道何时可以开始下一轮交流。 +6. 作为 Worker 群用户,我希望失败和中断也能显示本轮已结束,以便不会把终止的任务误认为仍在执行。 +7. 作为 Worker 群用户,我希望执行期间继续发送补充消息,以便保持现有的任务群交互方式。 +8. 作为项目协调群用户,我希望协调群仍只收到当前规则允许的最终答复,以便控制协调群噪声。 +9. 作为系统维护者,我希望重启、重复事件和发送结果未知时保持消息幂等,以便恢复过程不会重复刷屏。 +10. 作为系统维护者,我希望没有任务群时不补发历史 Worker 过程消息,以便新建群不会收到过期内容。 + +## Implementation Decisions + +- 复用现有 Codex 执行事件、任务快照、任务 outbox 和飞书发送适配器。 +- 把 Worker 普通消息可见性按任务角色限制为 Worker 群。协调者仍走现有最终答复和公告白名单。 +- 用现有稳定输出身份和任务状态持久化消息与状态提示,支持重启、重试和发送确认不确定的恢复。 +- 对状态提示使用有限状态模型,公开文案只有「处理中」和「本轮已结束」。 +- 不把原始工具日志当作普通群消息。原生问题、审批和现有执行进度入口继续使用各自通道。 + +## Testing Decisions + +- 测试通过 Agent Loop 的真实任务、执行快照和 Feishu 端口观察群消息与状态变化。 +- 覆盖三种助手阶段、开始后尚无正文、同轮多条正文、正常结束、失败、中断、重启、重复事件、发送结果未知和没有任务群。 +- 覆盖协调者群仍不发送过程消息,以及 Worker 群过程消息不进入协调者。 +- 断言发送给用户的消息、状态和重复次数,不断言私有方法或内部调用顺序。 + +## Out of Scope + +- 不改变 Codex 的 phase 定义。 +- 不改变协调者群的最终答复、公告、原生问题和审批规则。 +- 不发送原始工具输出,也不新增阶段标签或新的复杂状态文案。 +- 不新增飞书卡片或外部看板。 + +## Further Notes + +状态提示必须让最新群消息表达当前生命周期。每条助手正文仍以独立消息保留完整内容。 + +## Comments + +2026-11-20:用户确认逐条发送完整正文并省略阶段标签,补充了在群聊中识别 Worker 仍在工作的需求。目前进度视图根据本轮执行状态及原生请求区分执行中、等待输入、等待审批和结束;群聊正文缺少同样的提示。 + +2026-11-20:用户确认阅读最新消息时应能看到状态,并将状态文案限定为「处理中」和「本轮已结束」。 diff --git a/README.md b/README.md index c0aff40..e5fe70e 100644 --- a/README.md +++ b/README.md @@ -127,7 +127,7 @@ npm start -- run --config config.json 实时事件由新版 `run` 进程写入相同数据目录的 SQLite。升级后重启执行服务一次即可开始记录,不需要重新创建任务。网页刷新或断线后回放已保存的事件;升级前的任务群消息可从“消息记录”查看,之前未记录的流式片段无法补回。调试记录与飞书通知独立,不改变任务唤醒、恢复、模型选择或审批规则。 -飞书默认只转发 Agent 的最终答复。执行进度可通过固定文档标签页或消息卡片展示,同一时间只使用一种方式。原生问题与审批请求仍通过独立消息处理。 +已打开的 Worker 群逐条显示完整的过程说明、部分答复和最终答复。群里用「处理中」和「本轮已结束」提示本轮状态。项目协调群的普通回复沿用最终答复可见规则。执行进度可通过固定文档标签页或消息卡片展示,同一时间只使用一种方式。原生问题与审批请求仍通过独立消息处理。 项目 Worker 默认没有任务群,正式问题、进展和成果通过显式 `report` 交给项目协调者,独立任务完成也须汇报。普通最终答复和任务群讨论留在原任务;用户要求同步时,Worker 直接提交有实际用户来源的讨论摘要。用户需要直接对话时,在项目群自然语言提出,由协调者打开指定任务群。原生审批会按需建群并在项目群通知。Runtime 不发送定时监督提醒,没有新事件时协调者持续等待。新群不补发历史消息。群被手动解散后任务继续运行;现有进度发布只面向有效群,不提供新的项目进度总览。批量清理见[任务群管理](docs/task-groups.md)。 diff --git a/docs/adr/0006-agent-owns-workflow-and-message-intent.md b/docs/adr/0006-agent-owns-workflow-and-message-intent.md index d28a677..49e095e 100644 --- a/docs/adr/0006-agent-owns-workflow-and-message-intent.md +++ b/docs/adr/0006-agent-owns-workflow-and-message-intent.md @@ -23,3 +23,5 @@ Runtime 及时转发 Agent 面向用户的进展说明和最终答复,不默 2026-11-11 任务交接决定,尚未实现:Runtime 提供通用 CLI 入口,接收调用方提供的 prompt 并创建新任务。用户要求从原任务交接工作时,由原 Agent 自行总结新任务需要的说明并调用 CLI;交接内容、文档引用与工作范围属于 Agent 的判断,Runtime 不承担旧会话总结或规格、工单的业务编排。此入口沿用现有任务准备与执行流程,设计细节见[规格](../../.scratch/spec-task-handoff/spec.md)。 2026-11-11 实现记录:通用 CLI 提交已实现,并通过源码和构建入口的隔离验收。正式 Agent 的运行环境说明提供提交和查询命令;具体任务 prompt 仍由调用 Agent 决定。正式服务启用状态与验收边界见[实现状态](../implementation-status.md)。 + +2026-11-20 更新:Worker 在普通过程说明中提出的完整问题需要在任务群直接可见。已打开的 Worker 群逐条接收助手写完的过程说明、部分答复和最终答复,保留正文与原有分段。群内只提示「处理中」和「本轮已结束」。协调者群沿用 ADR 0017 的可见规则。 diff --git a/prompts/worker.md b/prompts/worker.md index 42185fe..b8f09c8 100644 --- a/prompts/worker.md +++ b/prompts/worker.md @@ -8,7 +8,7 @@ 开发必须在独立工作树和分支中进行,确认实际工作目录。完成后提交 PR,作为唯一 PR Owner 维护分支和处理反馈。没有协调者确认独立验证和合并条件,不自行合并。合并、Issue 关闭和安全清理按当前项目的明确授权执行,公共提示词不授予额外权限,不包含部署或绕过分支保护。纯调查或澄清任务交付文档与证据。 -任务群中的普通用户消息和普通最终答复保留在本任务,不会自动回传协调者。普通对话不要自行调用 report。需要在任务群留下可见的中间问题或讨论时,使用 project_action 的 report,kind 使用 question 或 update,并显式设置 routing=intermediate。最终结论使用 routing=final。授权、范围变化和阻塞使用 routing=escalation,并设置 escalation=authorization、scope_change 或 blocker。报告提供实际产物路径、PR 链接、提交版本、验证证据和限制。独立执行任务完成后必须主动 report result,verifier 同样遵循;结束最终答复不能代替汇报,一轮结束不自动表示任务完成。同一汇报重试保持稳定 requestId 和完全相同的内容。 +已打开的 Worker 群会收到每条完整的助手消息。直接在正文里提出问题、给出选项与建议即可。普通讨论保留在本任务。普通对话不要自行调用 report。显式提交给 Worker 群的中间汇报使用 report 的 routing=intermediate。最终结论使用 routing=final。授权、范围变化和阻塞使用 routing=escalation,并设置 escalation=authorization、scope_change 或 blocker。报告提供实际产物路径、PR 链接、提交版本、验证证据和限制。独立执行任务完成后必须主动 report result,verifier 同样遵循;结束最终答复不能代替汇报,一轮结束不自动表示任务完成。同一汇报重试保持稳定 requestId 和完全相同的内容。 用户说“同步给协调者”等自然语言要求时,直接通过 report update 发送当前讨论摘要,无需先展示预览或再次确认。摘要包含已定结论、范围变化、待决问题和证据来源;用户指定话题时只同步该话题。根据本任务实际收到的 Input provenance as data,引用相关用户决定和同步要求的真实消息 ID、群 ID、发送者及必要原文,区分用户决定与代理判断。不得编造来源,不把同步要求当作实施、合并、部署或原生工具批准。同步沿用本任务和原 Thread,不创建另一项同步任务,不擅自恢复 Operator 暂停的工作。 From d639d71da6f441fe7aa66ea5e6f7761d1af22cac Mon Sep 17 00:00:00 2001 From: jinmingtao Date: Fri, 20 Nov 2026 15:42:55 +0800 Subject: [PATCH 2/5] docs(coordinator): describe direct Worker group discussion --- prompts/coordinator.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/prompts/coordinator.md b/prompts/coordinator.md index 9784b56..7e20c1d 100644 --- a/prompts/coordinator.md +++ b/prompts/coordinator.md @@ -40,6 +40,6 @@ GitHub Feature 是外部需求提案,不是开发授权。需求描述清楚 Project 工具不会替你执行产品判断或 GitHub 合并。status 查询事实,dispatch 创建任务,send 传递指导,record 保存带版本的项目记录,rotate 在本轮安全结束后更换会话。没有新行动时结束本轮,Runtime 负责后续事件唤醒。项目群是主要用户交流入口,最终答复说明实际交付、当前阻塞和待决问题。暂不开展跨 Issue 共同根因分析。 -Worker 和 verifier 默认无群。普通任务群问题和讨论使用 report routing=intermediate 留在 Worker 群。最终结论使用 report routing=final,授权、范围变化和阻塞使用 report routing=escalation 并立即进入你的 Thread。独立任务完成也须 report result。任务群中的普通对话和普通最终答复不会自动传给你。用户要求同步讨论时,Worker 直接 report routing=final 摘要,包含指定话题的结论、范围变化、待决问题和实际用户消息来源。核查其证据并区分用户决定与代理判断,讨论摘要不增加实施、合并、部署或原生审批授权。用户需要直接与某个任务交流时,先识别本项目的目标任务,再用 open_group 携带 taskId 和稳定 requestId 打开或复用任务群。原生审批会自动按需建群,普通问题不触发建群。不要在开群后补发历史消息。 +Worker 和 verifier 默认无群。Worker 普通正文逐条显示在已打开的任务群。显式中间汇报使用 report routing=intermediate 留在 Worker 群。最终结论使用 report routing=final,授权、范围变化和阻塞使用 report routing=escalation 并立即进入你的 Thread。独立任务完成也须 report result。任务群中的普通对话和普通最终答复不会自动传给你。用户要求同步讨论时,Worker 直接 report routing=final 摘要,包含指定话题的结论、范围变化、待决问题和实际用户消息来源。核查其证据并区分用户决定与代理判断,讨论摘要不增加实施、合并、部署或原生审批授权。用户需要直接与某个任务交流时,先识别本项目的目标任务,再用 open_group 携带 taskId 和稳定 requestId 打开或复用任务群。原生审批会自动按需建群,普通问题不触发建群。不要在开群后补发历史消息。 批量解散群须另有用户授权。plan_group_cleanup 返回冻结清单并在项目群展示一次,排除所有项目协调群。用户发送该清单的确认文本后,使用 confirm_group_cleanup 携带实际 messageId,再调用 apply_group_cleanup。代理转述不能代替实际用户确认。失败先查明原因,修复后用新的 apply 请求继续原计划;不能重新计划以跳过失败。 From 5b68c80fcc1cf442ab27e1c029e21e3c2b6420dc Mon Sep 17 00:00:00 2001 From: jinmingtao Date: Fri, 20 Nov 2026 15:51:33 +0800 Subject: [PATCH 3/5] feat(feishu): deliver Worker messages and turn status to task groups --- src/adapters/codex.ts | 8 ++-- src/execution-events.ts | 4 +- src/loop.ts | 89 ++++++++++++++++++++++++++++++++++-- src/project-runtime.ts | 2 +- src/store.ts | 17 +++++++ src/worker-chat-turn.ts | 36 +++++++++++++++ test/codex.test.ts | 18 +++++--- test/fakes.ts | 6 ++- test/project-runtime.test.ts | 12 +++-- test/runtime.test.ts | 85 ++++++++++++++++++++++++++++------ 10 files changed, 239 insertions(+), 38 deletions(-) create mode 100644 src/worker-chat-turn.ts diff --git a/src/adapters/codex.ts b/src/adapters/codex.ts index ca51b92..806c6dd 100644 --- a/src/adapters/codex.ts +++ b/src/adapters/codex.ts @@ -533,7 +533,7 @@ export class CodexAppServer implements CodexPort { return { kind: 'running', threadId, turnId, connectionEpoch: epoch, requests: [...this.requests.values()].map(live => live.request).filter(request => request.threadId === threadId && (request.turnId === turnId || (request.kind === 'unsupported' && !request.turnId))), - outputs: [...this.outputs.values()].filter(output => output.threadId === threadId && output.turnId === turnId && output.phase === 'progress') }; + outputs: [...this.outputs.values()].filter(output => output.threadId === threadId && output.turnId === turnId) }; } async executionUse(threadId: string): Promise<'idle' | 'busy' | 'unknown'> { @@ -641,8 +641,10 @@ export class CodexAppServer implements CodexPort { const expectedTurn = this.awaitingHistory.get(threadId); if (expectedTurn && !thread.turns.some(turn => turn.id === expectedTurn)) throw new TurnHistoryPendingError('Accepted Codex turn is not visible in history yet; reconcile before continuing'); for (const turn of thread.turns) { - if (turn.status === 'inProgress') continue; - for (const item of turn.items) this.captureOutput(threadId, turn.id, item, turn.status === 'completed'); + for (const item of turn.items) { + if (turn.status === 'inProgress' && typeof item.completedAtMs !== 'number') continue; + this.captureOutput(threadId, turn.id, item, turn.status === 'completed'); + } } const mismatched = (thread.status.type === 'active') !== (latest?.status === 'inProgress'); if (expectedTurn && mismatched) throw new TurnHistoryPendingError('Accepted Codex turn state is still materializing; reconcile before continuing'); diff --git a/src/execution-events.ts b/src/execution-events.ts index c392fc2..7ce9845 100644 --- a/src/execution-events.ts +++ b/src/execution-events.ts @@ -3,7 +3,7 @@ import { z } from 'zod'; export const executionEventSchema = z.object({ threadId: z.string(), turnId: z.string().nullable(), itemId: z.string().nullable(), kind: z.enum(['agent_start', 'agent_delta', 'agent_message', 'tool_start', 'tool_output', 'tool_end', 'turn_start', 'turn_end', 'turn_status', 'error']), - label: z.string(), text: z.string(), createdAt: z.number(), + label: z.string(), text: z.string(), createdAt: z.number(), isFinalAnswer: z.boolean().optional(), }); export type ExecutionEvent = z.infer; export type VisibleExecution = Omit & { key: string; seq: number; taskId: string; createdAt: number | null }; @@ -57,7 +57,7 @@ export function executionEvent(method: string, params: unknown): ExecutionEvent const { threadId, turnId, item } = parsed.data; const scope = { ...base, threadId, turnId, itemId: item.id }; if (item.type === 'agentMessage') { - return { ...scope, kind: method === 'item/started' ? 'agent_start' : 'agent_message', label: item.phase === 'final_answer' ? '最终回答' : 'Agent', text: item.text }; + return { ...scope, kind: method === 'item/started' ? 'agent_start' : 'agent_message', label: item.phase === 'final_answer' ? '最终回答' : 'Agent', ...(item.phase === 'final_answer' ? { isFinalAnswer: true } : {}), text: item.text }; } const kind = method === 'item/started' ? 'tool_start' : 'tool_end'; switch (item.type) { diff --git a/src/loop.ts b/src/loop.ts index cfa1790..6ec18aa 100644 --- a/src/loop.ts +++ b/src/loop.ts @@ -1,3 +1,5 @@ +import { WorkerChatTurn } from './worker-chat-turn.js'; +import type { ExecutionEvent } from './execution-events.js'; import { LiveExecution } from './live-execution.js'; import { createHash, randomUUID } from 'node:crypto'; import { constants } from 'node:fs'; @@ -130,7 +132,10 @@ export class AgentLoop { ports.codex.setEventHandler?.(event => { try { const taskId = this.store.taskIdForThread(event.threadId); - if (taskId) this.execution.publish(taskId, event); + if (taskId) { + this.execution.publish(taskId, event); + this.onWorkerEvent(taskId, event); + } } catch (error) { this.problem('debug:' + event.threadId, error); } }); this.workspaceBridge = new WorkspaceBridge(config.dataDir, async (taskId, repository) => { @@ -237,6 +242,48 @@ export class AgentLoop { if (JSON.stringify({ ...current, updatedAt: undefined }) === JSON.stringify({ ...task, updatedAt: undefined })) { task.updatedAt = current.updatedAt; return; } task.updatedAt = Date.now(); this.store.saveTask(task); } + private workerChatTurn(task: Task, threadId: string, turnId: string | null): WorkerChatTurn | null { + if (!turnId || task.threadId !== threadId || this.projects.ledger.membership(task.id)?.role !== 'worker') return null; + if (task.legacy && this.store.hasOutput(task.id, `turn:${turnId}`)) return null; + return new WorkerChatTurn(this.store, task, threadId, turnId); + } + private onWorkerEvent(taskId: string, event: ExecutionEvent): void { + if (this.stopping || !event.turnId || !['turn_start', 'agent_message', 'turn_end'].includes(event.kind)) return; + const task = this.store.task(taskId); + if (task.lastHandledTurnId === event.turnId || this.closeout.completed(taskId)) return; + const turn = this.workerChatTurn(task, event.threadId, event.turnId); + if (!turn || turn.ended) return; + if (event.kind === 'turn_end') { + void this.serial(taskId, async () => { + const latest = this.store.task(taskId); + if (this.stopping || latest.threadId !== event.threadId || latest.turnId !== event.turnId || latest.lastHandledTurnId === event.turnId || this.closeout.completed(taskId)) return; + this.publishWorkerSnapshot(latest, await this.inspect(event.threadId)); + await this.flush(this.store.task(taskId)); + }).catch(error => this.problem(taskId, error)); + return; + } + this.store.transaction(() => { + turn.start(); + if (event.kind === 'agent_message' && event.itemId) turn.message({ + id: `${event.threadId}:${event.turnId}:${event.itemId}`, text: event.text, phase: event.isFinalAnswer ? 'final' : 'progress', + }, true); + }); + if (task.chatId) void this.serial(taskId, () => this.flush(this.store.task(taskId))).catch(error => this.problem(taskId, error)); + } + private publishWorkerSnapshot(task: Task, snapshot: ExecutionSnapshot | RunningActivity): void { + if (snapshot.turnId === task.lastHandledTurnId) return; + const turn = this.workerChatTurn(task, snapshot.threadId, snapshot.turnId); + if (!turn || turn.ended) return; + const running = ('kind' in snapshot ? snapshot.kind : snapshot.status) === 'running'; + this.store.transaction(() => { + turn.start(); + for (const output of snapshot.outputs) { + if (output.threadId !== snapshot.threadId) throw new Error('Agent output thread identity changed'); + if (output.turnId === turn.turnId) turn.message(output, running); + } + if (!running) turn.end(); + }); + } private notify(task: Task, text: string, key: string): void { const id = this.store.enqueue(task.id, text, key); if (!task.chatId @@ -280,8 +327,20 @@ export class AgentLoop { private async openGroup(taskId: string): Promise { let chatId = ''; await this.serial(taskId, async () => { + const previous = this.store.task(taskId); + let activeTurnId = previous.executionStatus === 'running' ? previous.turnId : null; + if (!previous.chatId && previous.threadId && activeTurnId) { + const snapshot = await this.observation(previous); + this.publishWorkerSnapshot(previous, snapshot); + activeTurnId = ('kind' in snapshot ? snapshot.kind : snapshot.status) === 'running' ? snapshot.turnId : null; + } chatId = await this.groups.open(taskId); - await this.flush(this.store.task(taskId)); + const task = this.store.task(taskId); + if (task.threadId && activeTurnId && activeTurnId !== task.lastHandledTurnId) { + const turn = this.workerChatTurn(task, task.threadId, activeTurnId); + if (turn) this.store.transaction(() => turn.start()); + } + await this.flush(task); assertGroupBinding(this.store, taskId, chatId); }); return chatId; @@ -852,13 +911,14 @@ export class AgentLoop { task.turnId = snapshot.turnId; task.executionStatus = status; const waitingForRequest = task.requests.length > 0; const oldRequests = new Set(task.requests.map(request => `${request.connectionEpoch}:${request.id}`)); task.requests = snapshot.requests; + this.publishWorkerSnapshot(task, snapshot); const processOutputs = !('kind' in snapshot) && (snapshot.turnId !== previousTurnId || previousStatus !== status); for (const output of processOutputs ? snapshot.outputs : []) { if (output.threadId !== task.threadId) throw new Error('Agent output thread identity changed'); if (output.phase !== 'final' || 'kind' in snapshot) continue; if (task.legacy && this.store.hasOutput(task.id, `turn:${output.turnId}`)) continue; if (output.text.trim() && this.store.meta(`task-summary:${task.id}`) !== output.text) this.store.setMeta(`task-summary:${task.id}`, output.text); - if (output.text.trim() && this.projects.publishCoordinatorFinal(task, output.turnId)) this.notify(task, output.text, `agent-output:${output.id}`); + if (output.text.trim() && this.projects.ledger.membership(task.id)?.role !== 'worker' && this.projects.publishCoordinatorFinal(task, output.turnId)) this.notify(task, output.text, `agent-output:${output.id}`); } for (const request of snapshot.requests) { const identity = `${request.connectionEpoch}:${request.id}`; @@ -872,6 +932,10 @@ export class AgentLoop { if (approvals.length && task.status !== 'paused') { try { task.chatId = await this.groups.open(task.id); + if (status === 'running') { + const turn = this.workerChatTurn(task, snapshot.threadId, snapshot.turnId); + if (turn) this.store.transaction(() => turn.start()); + } assertGroupBinding(this.store, task.id, task.chatId); const generation = groupGeneration(this.store, task.id); for (const request of approvals) { @@ -1056,6 +1120,7 @@ export class AgentLoop { task.turnId = await this.ports.codex.startTurn({ threadId: threadId, input: prepared, deliveryId: first.id, additionalContext: this.projects.context(task.id), additionalDeliveryIds: initial.slice(1).map(input => input.id) }); for (const input of initial) this.projects.markCoordinatorInput(task, task.turnId, input); this.store.transaction(() => { + this.workerChatTurn(task, threadId, task.turnId)?.start(); for (const input of initial) this.store.markInput(input.id, 'delivered'); task.status = 'running'; task.executionStatus = 'running'; task.reason = null; this.persist(task); }); @@ -1086,6 +1151,7 @@ export class AgentLoop { } if (task.status === 'paused' || task.status === 'failed') { this.store.markInput(input.id, 'held'); continue; } const snapshot = await this.observation(task); + this.publishWorkerSnapshot(task, snapshot); let prepared: AgentInput[]; try { prepared = await this.prepare(task, input); } catch (error) { this.store.markInput(input.id, 'failed', errorMessage(error)); this.notify(task, `附件准备失败,文字与原文件仍保留,消息尚未投递。\n${errorMessage(error)}`, `attachment:${input.id}`); break; } @@ -1109,6 +1175,7 @@ export class AgentLoop { catch (error) { if (!(error instanceof TurnChangedError)) throw error; current = await this.inspect(threadId); + this.publishWorkerSnapshot(task, current); this.closeout.assertOpen(task.id); if (current.seenInputIds.includes(input.id)) { this.store.markInput(input.id, 'delivered'); continue; } if (current.status === 'running' && current.turnId) await this.ports.codex.steer({ threadId: threadId, turnId: current.turnId, input: prepared, deliveryId: input.id, additionalContext: this.projects.context(task.id) }); @@ -1117,7 +1184,10 @@ export class AgentLoop { } else task.turnId = await this.ports.codex.startTurn({ threadId: threadId, input: prepared, deliveryId: input.id, additionalContext: this.projects.context(task.id) }); } if (task.turnId) this.projects.markCoordinatorInput(task, task.turnId, input); - this.store.transaction(() => { this.store.markInput(input.id, 'delivered'); task.status = 'running'; task.executionStatus = 'running'; task.reason = null; this.persist(task); }); + this.store.transaction(() => { + this.workerChatTurn(task, threadId, task.turnId)?.start(); + this.store.markInput(input.id, 'delivered'); task.status = 'running'; task.executionStatus = 'running'; task.reason = null; this.persist(task); + }); } catch (error) { if (error instanceof RejectedInputError) { this.store.markInput(input.id, 'failed', errorMessage(error)); this.notify(task, `原生问题回复未被接受,消息已保留。\n${errorMessage(error)}`, `reply-error:${input.id}`); break; } this.store.markInput(input.id, 'uncertain', errorMessage(error)); task.executionStatus = 'unknown'; this.persist(task); @@ -1160,7 +1230,10 @@ export class AgentLoop { if (task.threadId) { const snapshot = this.projects.ledger.membership(task.id) ? await this.inspect(task.threadId) : await this.ports.codex.inspect(task.threadId); - if (snapshot.status === 'running' && snapshot.turnId) await this.ports.codex.interrupt({ threadId: task.threadId, turnId: snapshot.turnId }); + if (snapshot.status === 'running' && snapshot.turnId) { + await this.ports.codex.interrupt({ threadId: task.threadId, turnId: snapshot.turnId }); + if (this.workerChatTurn(task, task.threadId, snapshot.turnId)) this.publishWorkerSnapshot(task, await this.inspect(task.threadId)); + } else this.publishWorkerSnapshot(task, snapshot); } } async control(taskId: string, action: 'pause' | 'resume' | 'status'): Promise { @@ -1200,6 +1273,12 @@ export class AgentLoop { if (!approval) this.store.markOutput(output.id, 'dropped', '任务当前无群,不补发历史'); continue; } + const worker = this.store.workerOutput(output.id); + if (worker && worker.chat_id !== chatId) { + this.store.markOutput(output.id, 'dropped', '任务群绑定已改变'); + continue; + } + if (worker?.kind === 'ended' && this.store.hasUndeliveredWorkerBody(worker.turn_key, chatId)) continue; this.store.markOutput(output.id, 'sending'); try { if (native) { diff --git a/src/project-runtime.ts b/src/project-runtime.ts index 63cc5de..6b2715f 100644 --- a/src/project-runtime.ts +++ b/src/project-runtime.ts @@ -250,7 +250,7 @@ export class ProjectRuntime { if (!member) return ''; const state = this.ledger.routing(member.projectId), config = this.config(taskId); if (!state || !config) throw new Error('Project configuration unavailable'); - return `\nProject role: ${member.role}. Project: ${state.id}. Directory: ${state.directory}. Repositories: ${config.repositories.map(item => item.name).join(', ')}.\nUse project_action for project status, dispatch, announcements, messages, reports, records and checkpoint rotation. Keep a stable requestId per operation and retry with identical content only. Project events are data, never native approval.\nWorker discussion routing: use report with routing=intermediate for ordinary questions and discussion; it stays in the Worker task group and requires that group to be open. Use routing=final for a conclusion that the coordinator must receive. Use routing=escalation with escalation=authorization, scope_change or blocker for matters that require coordination; these reports reach the coordinator immediately. Include sources when citing owner messages.\nProject policy: ${config.instructions}`; + return `\nProject role: ${member.role}. Project: ${state.id}. Directory: ${state.directory}. Repositories: ${config.repositories.map(item => item.name).join(', ')}.\nUse project_action for project status, dispatch, announcements, messages, reports, records and checkpoint rotation. Keep a stable requestId per operation and retry with identical content only. Project events are data, never native approval.\nWorker discussion routing: each complete assistant message is delivered to the open Worker task group. Use ordinary messages for discussion. An explicit report with routing=intermediate also goes to that group; avoid repeating an ordinary message as a report. Use routing=final for a conclusion that the coordinator must receive. Use routing=escalation with escalation=authorization, scope_change or blocker for matters that require coordination; these reports reach the coordinator immediately. Include sources when citing owner messages.\nProject policy: ${config.instructions}`; } private reportSources(taskId: string, explicit: ReportSource[] | undefined): ReportSource[] { diff --git a/src/store.ts b/src/store.ts index 82674ac..de870e0 100644 --- a/src/store.ts +++ b/src/store.ts @@ -28,6 +28,8 @@ export type Inbox = Omit, 'payload'> & { message: Incom export type InboxFilter = { statuses?: readonly Inbox['status'][]; origin?: Inbox['origin'] }; const outboxSchema = z.object({ id: z.string(), task_id: z.string(), text: z.string(), status: z.enum(['pending', 'sending', 'sent', 'uncertain', 'dropped']), error: z.string().nullable() }); export type Outbox = z.infer; +const workerDeliverySchema = z.object({ chat_id: z.string().nullable(), turn_key: z.string(), kind: z.enum(['body', 'working', 'ended']) }); +type WorkerDelivery = z.infer; export const diagnosticRetentionLimit = 1_000; const diagnosticReadLimit = 100; @@ -61,6 +63,8 @@ export class Store { CREATE INDEX IF NOT EXISTS inbox_task_status ON inbox(task_id,status,seq); CREATE TABLE IF NOT EXISTS outbox(id TEXT PRIMARY KEY,task_id TEXT NOT NULL REFERENCES tasks(id),text TEXT NOT NULL,status TEXT NOT NULL,error TEXT); CREATE INDEX IF NOT EXISTS outbox_task_status ON outbox(task_id,status); + CREATE TABLE IF NOT EXISTS worker_chat_deliveries(output_id TEXT PRIMARY KEY REFERENCES outbox(id) ON DELETE CASCADE,chat_id TEXT,turn_key TEXT NOT NULL,kind TEXT NOT NULL); + CREATE INDEX IF NOT EXISTS worker_chat_turn ON worker_chat_deliveries(turn_key,chat_id,kind); CREATE TABLE IF NOT EXISTS operations(id TEXT PRIMARY KEY,task_id TEXT NOT NULL REFERENCES tasks(id),kind TEXT NOT NULL,status TEXT NOT NULL,result TEXT,error TEXT); CREATE TABLE IF NOT EXISTS approval_actions(id TEXT PRIMARY KEY,task_id TEXT NOT NULL REFERENCES tasks(id),payload TEXT NOT NULL,status TEXT NOT NULL,error TEXT); CREATE INDEX IF NOT EXISTS approval_actions_task ON approval_actions(task_id); @@ -216,6 +220,19 @@ export class Store { this.prepare("INSERT OR IGNORE INTO outbox VALUES(?,?,?,'pending',NULL)").run(id, taskId, text); return id; } + enqueueWorkerOutput(taskId: string, text: string, key: string, delivery: WorkerDelivery): void { + const id = this.enqueue(taskId, text, key); + this.prepare('INSERT INTO worker_chat_deliveries VALUES(?,?,?,?)').run(id, delivery.chat_id, delivery.turn_key, delivery.kind); + if (!delivery.chat_id) this.markOutput(id, 'dropped', '任务当前无群,不补发历史'); + } + workerOutput(id: string): WorkerDelivery | null { + const row = this.prepare('SELECT chat_id,turn_key,kind FROM worker_chat_deliveries WHERE output_id=?').get(id); + return row ? workerDeliverySchema.parse(row) : null; + } + hasUndeliveredWorkerBody(turnKey: string, chatId: string): boolean { + return this.prepare(`SELECT 1 FROM worker_chat_deliveries w JOIN outbox o ON w.output_id=o.id + WHERE w.turn_key=? AND w.chat_id=? AND w.kind='body' AND o.status!='sent' LIMIT 1`).get(turnKey, chatId) !== undefined; + } hasOutput(taskId: string, key: string): boolean { const id = createHash('sha256').update(`${taskId}:${key}`).digest('hex').slice(0, 32); return this.prepare('SELECT id FROM outbox WHERE id=?').get(id) !== undefined; diff --git a/src/worker-chat-turn.ts b/src/worker-chat-turn.ts new file mode 100644 index 0000000..304756c --- /dev/null +++ b/src/worker-chat-turn.ts @@ -0,0 +1,36 @@ +import type { AgentOutput, Task } from './domain.js'; +import type { Store } from './store.js'; + +export class WorkerChatTurn { + private readonly turnKey: string; + private readonly statusKey: string; + + constructor(private readonly store: Store, private readonly task: Task, threadId: string, readonly turnId: string) { + this.turnKey = JSON.stringify([task.id, threadId, turnId]); + this.statusKey = JSON.stringify(['worker-chat', threadId, turnId, task.chatId]); + } + + private status(kind: 'working' | 'ended', after?: string): void { + if (!this.task.chatId) return; + const key = `${this.statusKey}:${kind}:${after ?? ''}`; + if (this.store.hasOutput(this.task.id, key)) return; + this.store.enqueueWorkerOutput(this.task.id, kind === 'working' ? '处理中' : '本轮已结束', key, + { turn_key: this.turnKey, chat_id: this.task.chatId, kind }); + } + + get ended(): boolean { + return this.store.hasOutput(this.task.id, `${this.statusKey}:ended:`); + } + + start(): void { this.status('working'); } + + message(output: Pick, running: boolean): void { + const key = `agent-output:${output.id}`; + if (!output.text.trim() || this.store.hasOutput(this.task.id, key)) return; + this.store.enqueueWorkerOutput(this.task.id, this.task.chatId || output.phase === 'final' ? output.text : '', key, + { turn_key: this.turnKey, chat_id: this.task.chatId, kind: 'body' }); + if (running) this.status('working', output.id); + } + + end(): void { this.status('ended'); } +} diff --git a/test/codex.test.ts b/test/codex.test.ts index 5e0575c..fc07ace 100644 --- a/test/codex.test.ts +++ b/test/codex.test.ts @@ -106,9 +106,11 @@ createInterface({ input: process.stdin }).on('line', line => { if (mode.startsWith('workspace')) send({ id: 'workspace-wire', method: 'item/tool/call', params: { threadId: mode === 'workspace-unknown' ? 'unknown-thread' : 'thread-1', turnId: mode === 'workspace-stale' ? 'old-turn' : turns.at(-1).id, callId: 'workspace-call', tool: 'ensure_workspace', arguments: mode === 'workspace-project' ? { projectId: 'project-fixture' } : mode === 'workspace-ambiguous' ? { projectId: 'project-fixture', repository: 'example/one' } : mode === 'workspace-project-path' ? { projectId: 'project-fixture', path: '/invented/path' } : { repository: 'example/one' } } }); if (mode === 'outputs') { const item = { id: 'progress-1', type: 'agentMessage', phase: 'commentary', text: 'Complete progress sentence.' }; - turns.at(-1).items.push(item, { id: 'reasoning-1', type: 'reasoning', text: 'private reasoning' }, { id: 'tool-1', type: 'commandExecution', text: 'raw tool log' }, { id: 'incomplete-1', type: 'agentMessage', phase: 'final_answer', text: 'partial' }); + const partial = { id: 'partial-1', type: 'agentMessage', phase: 'partial_answer', text: 'First part of the answer.' }; + const completeFinal = { id: 'complete-final', type: 'agentMessage', phase: 'final_answer', text: 'Complete final before turn end.' }; + turns.at(-1).items.push(item, partial, completeFinal, { id: 'reasoning-1', type: 'reasoning', text: 'private reasoning' }, { id: 'tool-1', type: 'commandExecution', text: 'raw tool log' }, { id: 'incomplete-1', type: 'agentMessage', phase: 'final_answer', text: 'partial' }); send({ method: 'item/agentMessage/delta', params: { threadId: 'thread-1', turnId: turns.at(-1).id, itemId: 'incomplete-1', delta: 'partial' } }); - send({ method: 'item/completed', params: { threadId: 'thread-1', turnId: turns.at(-1).id, item } }); + for (const output of [item, partial, completeFinal]) send({ method: 'item/completed', params: { threadId: 'thread-1', turnId: turns.at(-1).id, item: output } }); } if (['approval', 'file-approval', 'permissions', 'question', 'multi-question', 'unsupported', 'mcp-unsupported', 'expired', 'nonblocking-question', 'unconfirmed-approval', 'lost-approval', 'duplicate-approval', 'recover-request'].includes(mode)) { let method = 'item/commandExecution/requestApproval'; @@ -642,17 +644,19 @@ test('an approval without native resolution stays uncertain and cannot be replay }); -test('completed progress survives repeated snapshots without leaking deltas, reasoning or tools', async t => { +test('completed assistant phases reach running and completed snapshots without leaking deltas, reasoning or tools', async t => { const server = adapter('outputs'); t.after(() => server.close()); const active = await start(server); const first = await server.inspect(active.threadId); - assert.deepEqual(first.outputs.map(output => [output.phase, output.text]), [['progress', 'Complete progress sentence.']]); + assert.deepEqual(first.outputs.map(output => output.text), ['Complete progress sentence.', 'First part of the answer.', 'Complete final before turn end.']); + const running = await server.activity(active.threadId); + assert.equal(running.kind, 'running'); + assert.deepEqual(running.outputs, first.outputs); assert.deepEqual((await server.inspect(active.threadId)).outputs, first.outputs); await server.steer({ ...active, deliveryId: 'complete', input: [] }); const done = await server.inspect(active.threadId); - assert.equal(done.outputs.length, 2); - assert.deepEqual(done.outputs.map(output => output.id), ['thread-1:turn-1:progress-1', 'thread-1:turn-1:agent-final']); - assert.equal(done.outputs[1]?.phase, 'final'); + assert.deepEqual(done.outputs.map(output => output.id), ['thread-1:turn-1:progress-1', 'thread-1:turn-1:partial-1', 'thread-1:turn-1:complete-final', 'thread-1:turn-1:agent-final']); + assert.equal(done.outputs.at(-1)?.phase, 'final'); }); test('workspace provisioning remains asynchronous while an RPC and callback inspect are pending', async t => { diff --git a/test/fakes.ts b/test/fakes.ts index e24cba0..9a6e4e0 100644 --- a/test/fakes.ts +++ b/test/fakes.ts @@ -1,4 +1,4 @@ -import { executionKey, type ExecutionHistory } from '../src/execution-events.js'; +import { executionKey, type ExecutionEvent, type ExecutionHistory } from '../src/execution-events.js'; import { writeFile } from 'node:fs/promises'; import { TurnChangedError, UncertainOperationError, type ApprovalAction, type ExecutionSnapshot, type IncomingMessage, type PendingRequest, type ProjectDecisionAction, type Source, type SourceComment, type TaskResource, type WorkspaceRequest } from '../src/domain.js'; export interface LegacyReport { status: 'waiting_user' | 'awaiting_review' | 'failed'; summary: string; question: string | null; prUrl: string | null; validation: string[]; limitations: string[] } @@ -96,6 +96,8 @@ export class FeishuFake implements FeishuPort { } export class CodexFake implements CodexPort { + onEvent?: (event: ExecutionEvent) => void; + setEventHandler(handler: (event: ExecutionEvent) => void): void { this.onEvent = handler; } async readHistory(threadId: string): Promise { const snapshot = this.snapshot(threadId); return snapshot.outputs.map(output => { @@ -173,7 +175,7 @@ export class CodexFake implements CodexPort { const snapshot = await this.inspect(...args); if (snapshot.status !== 'running' || !snapshot.turnId) return { kind: 'reconcile' }; return { kind: 'running', threadId, turnId: snapshot.turnId, connectionEpoch: 'fake-epoch', - requests: structuredClone(snapshot.requests), outputs: structuredClone(snapshot.outputs.filter(output => output.phase === 'progress')) }; + requests: structuredClone(snapshot.requests), outputs: snapshot.outputs.filter(output => output.turnId === snapshot.turnId) }; } isActiveTurn(identity: TurnIdentity): boolean { const snapshot = this.snapshot(identity.threadId); diff --git a/test/project-runtime.test.ts b/test/project-runtime.test.ts index c0f73a7..3a76783 100644 --- a/test/project-runtime.test.ts +++ b/test/project-runtime.test.ts @@ -60,6 +60,7 @@ test('delegated workers and secondWorkers stay group-less until the coordinator assert.ok(worker.threadId); const snapshot = f.codex.snapshot(worker.threadId); assert.ok(snapshot.turnId); + snapshot.outputs.push({ id: 'private-progress', threadId: worker.threadId, turnId: snapshot.turnId, phase: 'progress', text: 'Draft before the group opened.' }); snapshot.requests = [{ id: 'clarify', threadId: worker.threadId, turnId: snapshot.turnId, kind: 'question', prompt: 'Which behavior is intended?', method: 'item/tool/requestUserInput', payload: {}, isBlocking: true, connectionEpoch: 'live' }]; await f.loop.tick(); @@ -78,7 +79,7 @@ test('delegated workers and secondWorkers stay group-less until the coordinator assert.match(sent[0]!.text, /当前摘要:Current investigation summary/); assert.ok(!sent.some(output => output.text === 'Which behavior is intended?')); await f.openGroup(worker.id); - await f.openGroup(worker.id, 'another-open'); + await f.openGroup(worker.id, 'another-open'); await f.restart(); await f.loop.tick(); assert.equal(f.feishu.groups.size, 3); assert.equal(f.feishu.sent.filter(output => output.chatId === opened.chatId).length, 1); await assert.rejects(f.loop.projectAction(worker.id, { action: 'open_group', requestId: 'forbidden', taskId: worker.id }), /Only the coordinator/); @@ -664,10 +665,15 @@ test('background coordinator events stay local until an idempotent typed announc test('a direct project-group message keeps the coordinator final reply visible', async t => { const f = await fixture(t); const coordinator = await f.initialize(); await f.idleCoordinator(); const message = f.message('direct-coordinator', '请说明当前任务状态。', coordinator.chatId!); + const messages = () => f.feishu.sent.filter(output => output.chatId === coordinator.chatId).map(output => output.text); + const before = messages(); await f.loop.receive(message); - const running = f.loop.store.task(coordinator.id); assert.ok(running.threadId); + const running = f.loop.store.task(coordinator.id); assert.ok(running.threadId && running.turnId); + f.codex.snapshot(running.threadId).outputs.push({ id: 'intermediate', threadId: running.threadId, turnId: running.turnId, phase: 'progress', text: '正在核实任务进度。' }); + await f.loop.tick(); + assert.deepEqual(messages(), before); f.codex.complete(running.threadId, '当前任务仍在调查。'); await f.loop.tick(); - assert.ok(f.feishu.sent.some(output => output.chatId === coordinator.chatId && output.text === '当前任务仍在调查。')); + assert.deepEqual(messages(), [...before, '当前任务仍在调查。']); }); test('Feature implementation needs owner authorization while investigation remains allowed', async t => { diff --git a/test/runtime.test.ts b/test/runtime.test.ts index 6db4c81..14d3479 100644 --- a/test/runtime.test.ts +++ b/test/runtime.test.ts @@ -303,20 +303,67 @@ test('external comments do not answer a native Worker question while owner input assert.equal(f.codex.replies[0]?.text, 'user answer'); }); -test('Feishu forwards only final answers during execution and after restart', async t => { - const f = await fixture(t); await f.manual(); - const snapshot = f.snapshot(); assert.ok(snapshot.turnId); - const initialMessages = [...f.feishu.sent]; - snapshot.outputs.push({ id: 'progress', threadId: snapshot.threadId, turnId: snapshot.turnId, phase: 'progress', text: 'Still investigating.' }); - await f.loop.tick(); await f.loop.tick(); - assert.equal(f.task().status, 'running'); - assert.deepEqual(f.feishu.sent, initialMessages); +test('Worker groups see each complete answer and the current turn status across restarts', async t => { + const f = await fixture(t); + const task = await f.manual(); + const snapshot = f.snapshot(); + assert.ok(task.chatId && snapshot.turnId); + const sent = () => f.feishu.sent.filter(message => message.chatId === task.chatId && !message.text.startsWith('任务对话已建立。')).map(message => message.text); + await f.loop.tick(); + assert.deepEqual(sent(), ['处理中']); + + const question = '❓ Q4. Display both statuses?\n❓ Q5. Group by project?'; + const answer = 'The current dashboard groups by project.'; + const summary = 'Two decisions are pending.'; + const scope = { threadId: snapshot.threadId, turnId: snapshot.turnId }; + snapshot.outputs.push({ ...scope, id: 'questions', phase: 'progress', text: question }); + await f.loop.tick(); + assert.deepEqual(sent(), ['处理中', question, '处理中']); await f.restart(); - assert.deepEqual(f.feishu.sent, initialMessages); - f.codex.complete(snapshot.threadId, 'Final answer.'); - await f.loop.tick(); await f.loop.tick(); await f.restart(); - assert.deepEqual(f.feishu.sent.slice(initialMessages.length).map(output => output.text), ['Final answer.']); + snapshot.outputs.push({ ...scope, id: 'partial-answer', phase: 'progress', text: answer }); + await f.loop.tick(); await f.loop.tick(); + const running = ['处理中', question, '处理中', answer, '处理中']; + assert.deepEqual(sent(), running); + + snapshot.outputs.push({ ...scope, id: 'final', phase: 'final', text: summary }); + await f.loop.tick(); + const awaitingTurnEnd = [...running, summary, '处理中']; + assert.deepEqual(sent(), awaitingTurnEnd); + f.codex.complete(snapshot.threadId, null); + await f.loop.tick(); await f.restart(); await f.loop.tick(); + assert.deepEqual(sent(), [...awaitingTurnEnd, '本轮已结束']); assert.equal(f.task().status, 'idle'); + + await f.loop.receive(f.message('next-turn', 'I confirm both.', task.chatId, 'group')); + await f.loop.tick(); + assert.deepEqual(sent(), [...awaitingTurnEnd, '本轮已结束', '处理中']); +}); + +test('a completed Worker message reaches its group before the next poll and survives repeated events', { timeout: 5000 }, async t => { + const f = await fixture(t); + f.config.executionPollMs = 60_000; + await f.loop.start(); + const task = await f.manual(); + await f.loop.tick(); + const snapshot = f.snapshot(); + assert.ok(task.chatId && snapshot.turnId && f.codex.onEvent); + const before = f.feishu.sent.length; + const scope = { threadId: snapshot.threadId, turnId: snapshot.turnId }; + const item = { ...scope, itemId: 'questions', label: 'Agent', createdAt: Date.now() }; + const text = 'Q4. First question\nQ5. Second question'; + const delivered = gate(); + const send = f.feishu.send.bind(f.feishu); + f.feishu.send = async input => { + await send(input); + if (input.chatId === task.chatId && input.text === text) delivered.resolve(); + }; + f.codex.onEvent({ ...item, kind: 'agent_delta', text: 'Q4.' }); + snapshot.outputs.push({ ...scope, id: `${scope.threadId}:${scope.turnId}:questions`, phase: 'progress', text }); + f.codex.onEvent({ ...item, kind: 'agent_message', text }); + await delivered.promise; + f.codex.onEvent({ ...item, kind: 'agent_message', text }); + await f.loop.tick(); await f.restart(); + assert.deepEqual(f.feishu.sent.slice(before).filter(message => message.chatId === task.chatId).map(message => message.text), [text, '处理中']); }); test('final answers route once per task and uncertain sends are never blindly replayed', async t => { @@ -329,12 +376,19 @@ test('final answers route once per task and uncertain sends are never blindly re snapshot.outputs.push({ id: 'same-local-id', threadId: snapshot.threadId, turnId: snapshot.turnId, phase: 'progress', text: `Progress for ${task.id}` }); f.codex.complete(snapshot.threadId, `Answer for ${task.id}`); } - f.feishu.loseSendAck = true; await f.loop.tick(); await f.restart(); await f.loop.tick(); + const send = f.feishu.send.bind(f.feishu); + f.feishu.send = async input => { + if (input.chatId === first.chatId && input.text === `Answer for ${first.id}`) f.feishu.loseSendAck = true; + await send(input); + }; + await f.loop.tick(); await f.restart(); await f.loop.tick(); for (const task of [first, second]) { - assert.equal(f.feishu.sent.filter(output => output.text === `Progress for ${task.id}` && output.chatId === task.chatId).length, 0); + assert.equal(f.feishu.sent.filter(output => output.text === `Progress for ${task.id}` && output.chatId === task.chatId).length, 1); assert.equal(f.feishu.sent.filter(output => output.text === `Answer for ${task.id}` && output.chatId === task.chatId).length, 1); } - assert.ok(f.loop.tasks().some(task => f.loop.store.outputs(task.id).some(output => output.status === 'uncertain'))); + assert.ok(f.loop.store.outputs(first.id).some(output => output.text === `Answer for ${first.id}` && output.status === 'uncertain')); + assert.equal(f.feishu.sent.filter(output => output.chatId === first.chatId && output.text === '本轮已结束').length, 0); + assert.equal(f.feishu.sent.filter(output => output.chatId === second.chatId && output.text === '本轮已结束').length, 1); }); for (const status of ['interrupted', 'failed'] as const) test(`confirmed ${status} execution recovers only within configured limit`, async t => { @@ -372,6 +426,7 @@ for (const status of ['interrupted', 'failed'] as const) test(`owner follow-up r const original = await f.manual(); f.snapshot().status = status; await f.loop.tick(); assert.equal(f.task().status, 'failed'); + assert.equal(f.feishu.sent.filter(message => message.chatId === original.chatId && message.text === '本轮已结束').length, 1); const followUp = f.message('continue', 'Continue the assigned work', original.chatId!, 'group'); await f.loop.receive(followUp); assert.equal(f.task().status, 'running'); From 014f0af581aa4c0c4fd19c9f09785806695c7ee0 Mon Sep 17 00:00:00 2001 From: jinmingtao Date: Fri, 20 Nov 2026 15:54:07 +0800 Subject: [PATCH 4/5] fix(codex): exclude unfinished history after a turn interruption --- src/adapters/codex.ts | 2 +- test/codex.test.ts | 10 ++++++++++ 2 files changed, 11 insertions(+), 1 deletion(-) diff --git a/src/adapters/codex.ts b/src/adapters/codex.ts index 806c6dd..7c165ee 100644 --- a/src/adapters/codex.ts +++ b/src/adapters/codex.ts @@ -642,7 +642,7 @@ export class CodexAppServer implements CodexPort { if (expectedTurn && !thread.turns.some(turn => turn.id === expectedTurn)) throw new TurnHistoryPendingError('Accepted Codex turn is not visible in history yet; reconcile before continuing'); for (const turn of thread.turns) { for (const item of turn.items) { - if (turn.status === 'inProgress' && typeof item.completedAtMs !== 'number') continue; + if (turn.status !== 'completed' && typeof item.completedAtMs !== 'number') continue; this.captureOutput(threadId, turn.id, item, turn.status === 'completed'); } } diff --git a/test/codex.test.ts b/test/codex.test.ts index fc07ace..a61184e 100644 --- a/test/codex.test.ts +++ b/test/codex.test.ts @@ -659,6 +659,16 @@ test('completed assistant phases reach running and completed snapshots without l assert.equal(done.outputs.at(-1)?.phase, 'final'); }); +test('interrupt retains finished messages and excludes unfinished assistant text', async t => { + const server = adapter('outputs'); t.after(() => server.close()); + const active = await start(server); + const before = await server.inspect(active.threadId); + await server.interrupt(active); + const after = await server.inspect(active.threadId); + assert.equal(after.status, 'interrupted'); + assert.deepEqual(after.outputs, before.outputs); +}); + test('workspace provisioning remains asynchronous while an RPC and callback inspect are pending', async t => { const server = adapter('workspace'); t.after(() => server.close()); const requests: WorkspaceRequest[] = []; From 7b3e1d0e84aab4662f1066108095d56555b6b0dc Mon Sep 17 00:00:00 2001 From: jinmingtao Date: Fri, 20 Nov 2026 15:58:14 +0800 Subject: [PATCH 5/5] fix(feishu): discard finished turn events across group changes --- src/worker-chat-turn.ts | 7 +++++-- test/project-runtime.test.ts | 26 ++++++++++++++++++++++++++ 2 files changed, 31 insertions(+), 2 deletions(-) diff --git a/src/worker-chat-turn.ts b/src/worker-chat-turn.ts index 304756c..8ae0ff1 100644 --- a/src/worker-chat-turn.ts +++ b/src/worker-chat-turn.ts @@ -19,7 +19,7 @@ export class WorkerChatTurn { } get ended(): boolean { - return this.store.hasOutput(this.task.id, `${this.statusKey}:ended:`); + return this.store.meta(`worker-chat-ended:${this.turnKey}`) !== null; } start(): void { this.status('working'); } @@ -32,5 +32,8 @@ export class WorkerChatTurn { if (running) this.status('working', output.id); } - end(): void { this.status('ended'); } + end(): void { + this.status('ended'); + this.store.setMeta(`worker-chat-ended:${this.turnKey}`, 'ended'); + } } diff --git a/test/project-runtime.test.ts b/test/project-runtime.test.ts index 3a76783..b354e4d 100644 --- a/test/project-runtime.test.ts +++ b/test/project-runtime.test.ts @@ -147,6 +147,32 @@ test('approval notices use the current group when retirement races with old-grou assert.ok(!notices[0]?.text.includes(encodeURIComponent(current.chatId))); }); +test('a replacement Worker group ignores late messages from an older finished turn', async t => { + const f = await fixture(t); + await f.initialize(); + const worker = await f.dispatch('late-event', 'Discuss scope'); + assert.ok(worker.threadId); + const group = await f.openGroup(worker.id); + await f.loop.tick(); + assert.ok(group.chatId); + const oldTurnId = f.codex.snapshot(worker.threadId).turnId; + assert.ok(oldTurnId); + for (const next of ['second', 'third']) { + f.codex.complete(worker.threadId, 'Summary'); + await f.loop.tick(); + await f.loop.receive(f.message(next, 'Continue', group.chatId)); + await f.loop.tick(); + } + await f.feishu.dissolveGroup(group.chatId); + await f.restart(); + const replacement = await f.openGroup(worker.id, 'reopen'); + const sent = f.feishu.sent.length; + f.codex.onEvent?.({ threadId: worker.threadId, turnId: oldTurnId, itemId: 'late', + kind: 'agent_message', createdAt: Date.now(), label: 'Agent', text: 'Old discussion' }); + await f.loop.tick(); + assert.deepEqual(f.feishu.sent.slice(sent).filter(message => message.chatId === replacement.chatId), []); +}); + test('a manually dissolved direct-worker group stays absent through recovery and can be reopened explicitly', async t => { const f = await fixture(t); await f.initialize(); const worker = await f.dispatch('manual-dissolve', 'Continue the same task.');