feat(assistant): add durable multi-agent collaboration and live task views (#4438)
* feat(assistant): add persistent multi-agent collaboration and live task views * fix(ci): wrap runtime notice message append * fix(agent): preserve collaboration results and prevent duplicate execution * fix(agent): fence panic followups and preserve approval timelines * test(frontend): stub connector labels in assistant refresh fixture * fix(migrations): avoid collaboration migration collision with main * fix(assistant): preserve child continuations and artifact access * fix(frontend): align artifact and icon checks with updated UI * fix: enforce child approvals and finalize interrupted collaboration runs * feat: support inherited temporary agent workers * docs: clarify inherited worker scope and lifecycle * fix: harden assistant retrieval and final delivery * fix(agent): keep closed child prompts continuable and renew active deadlines Expired child approvals were looked up by the child session, so the parent group stayed open and the run became needs_attention. Active collaborations also expired one hour after creation. * fix(lint): clear golangci-lint findings on the collaboration PR The previous CI run failed on line length, gofumpt, unchecked closes, and an unused dial parameter. * fix(ci): use the public npm registry for frontend dependencies * fix(agent): address collaboration review findings - keep ordinary fallbacks when a turn delegated no work - throttle lease/deadline heartbeats and drop duplicated child answers - force-close or compact aggregates that exceed the size limit - clamp completion budget to the model output limit - honor prompt_suspend for non-collaboration tools - clean up collaborations and child sessions on session delete, prune old rows - bound concurrent child executions globally - retry prompt classification and tolerate transient heartbeat errors - scope prompt history to listed messages, reject nil tenantsmain
parent
2c0d838439
commit
966d841d19
|
|
@ -297,9 +297,11 @@ builtin_agents:
|
|||
agent_type: "custom"
|
||||
system_prompt_id: "weknora_assistant"
|
||||
temperature: 0.3
|
||||
max_completion_tokens: 0
|
||||
max_iterations: 30
|
||||
kb_selection_mode: "selected"
|
||||
max_completion_tokens: 24576
|
||||
max_iterations: -1
|
||||
# The workspace assistant can read the caller's accessible bases. Explicit
|
||||
# mentions still narrow a turn; the current page is only contextual data.
|
||||
kb_selection_mode: "all"
|
||||
retrieve_kb_only_when_mentioned: false
|
||||
retain_retrieval_history: true
|
||||
# find_operations / run_operation and search_weknora_docs /
|
||||
|
|
|
|||
|
|
@ -160,7 +160,7 @@ templates:
|
|||
3. Change only what was asked. A request to fix one document does not cover others; a request to look does not cover changing. For anything that affects more than the target the user named, confirm the scope first with ask_user.
|
||||
4. Depending on the access level the user chose, a change may first show them a confirmation card; find_operations states the current policy. Run one at a time so each card is clear. If the user declines, do not retry it or route around it with another operation; ask what they want instead.
|
||||
5. Asynchronous work (reparse, URL import, move, delete) is accepted, not finished. Say so, and check progress with a read operation if the user wants to wait for the result.
|
||||
6. When the next step is the user's — reviewing a knowledge base, document, Wiki page or agent you created, changed or found, finishing a setting you cannot make, or finding where something is — give them a button with open_page rather than describing the way there. One per target, after the work it points to, and none for the page in page_context.
|
||||
6. When the next step is the user's — reviewing a knowledge base, document, Wiki page or agent you created, changed or found, finishing a setting you cannot make, or finding where something is — prepare a button with open_page after completing the relevant operations and before writing the final answer. Once the tool returns, give the complete answer or report with the page entry point; keep any text before the call to a brief progress update. Offer one button per target, and none for the page in page_context.
|
||||
Setting up agents:
|
||||
- Read an agent with agent.get before changing it. agent.update keeps every setting it is not given; to change the system prompt, send the whole new prompt, built from the current one.
|
||||
- Find models, knowledge bases and MCP services by name with model.list, knowledge_base.list and mcp_service.list, and use the ids they return. If several match or none does, ask instead of guessing.
|
||||
|
|
@ -185,7 +185,7 @@ templates:
|
|||
- Verify what you set up instead of leaving it to the user. After binding an MCP service to an agent, or when the user says one does not work, run mcp_service.test, then mcp_service.list_tools to confirm it offers the tools the agent needs.
|
||||
- When the user asks why something is not found, run knowledge_base.search with their wording: first without thresholds, then with the agent's vector_threshold and keyword_threshold. Say whether the document is missing, still parsing, or found but cut by a threshold or ranked too low, and propose the change that would fix it.
|
||||
- Probe operations change nothing, but a turn may run only a few. Check once, then report what you found.
|
||||
- After creating or reconfiguring an agent, offer to try it with try_agent before calling it done, using a question whose answer you know is in its knowledge bases. Judge the result from its answer, tool calls and references: an answer without references, a failed tool call, or a cited document other than the expected one shows what to fix. Report what you found rather than retrying the same question.
|
||||
- When delegating to existing reasoning agents, follow the runtime coordination instructions and available collaboration tool definitions.
|
||||
The user's past conversations:
|
||||
- You can read the user's own conversations and nobody else's, and you cannot change them. session.list shows recent ones or matches titles; message.search finds one by what was said; message.list reads one.
|
||||
- When the user refers to something from before ("last time", "what I asked about X"), search before saying it was never discussed. If message.search finds nothing, check message.chat_history_stats: without indexing it matches exact words only, so retry with the user's own wording and tell them search by meaning is off.
|
||||
|
|
|
|||
|
|
@ -0,0 +1,431 @@
|
|||
# Assistant 委派与子 Agent 协作
|
||||
|
||||
状态:六工具调度闭环、父等待点自动恢复及子任务审批转发已实现;剩余范围见下方交付边界。日期:2026-10-17。
|
||||
|
||||
## 0. 本批实现与交付边界
|
||||
|
||||
本批移除 `try_agent` 工具、临时试跑服务、注册、提示词和界面文案。保留且仅保留六个协作工具;不添加 `read_agent`、`close_agent`。
|
||||
|
||||
已接通:
|
||||
|
||||
- 有已登录 Web 用户身份的非共享 reasoning Agent 可作为父任务注册六工具,不限于助手。直属子实例仅注册 `send_message`,只能回报 `/root`。`spawn_agent` 省略 `agent_id` 时继承当前执行配置创建临时实例;提供时委派同工作区已有模板,保留原有模板资格限制。安装模式不开放协作。
|
||||
- 子实例的 `send_message` 使用独立说明与 schema,仅包含 `target`(枚举 `/root`)和 `message`;不向子实例描述父级的下发指令流程,也不暴露父级使用的 `expected_run_id`。工具由委派运行时注入,不要求 Agent 模板预先配置;普通独立运行满足父任务身份条件时也可拆分自己的任务。主动发送取决于模型调用;工具阶段自动记录、终态结果自动投递均由运行时另行负责。
|
||||
- `agent_collaborations` 有界聚合记录将任务、邮箱、结果与事件放在同一次 version CAS 内更新,兼容 PostgreSQL / SQLite。它替代下文完整目标设计的多张表,不依赖进程锁领取任务。正式迁移带活动父任务唯一索引。
|
||||
- 每个协作最多三个运行中的子轮次、16 个本轮使用的实例、每实例八轮记录(跨父轮次只保留上一终态作为续跑锚点)。排队不占执行槽位,空闲实例不驻留执行器。请求去重键来自真实 tool-call 元数据;累计输入与结果有大小限制。
|
||||
- `send_message` 不启动 idle;`followup_task` 在运行中作为邮件,只有未被该轮处理的追加要求才转成下一轮。结果先保存子会话的消息、工具步骤和引用,再发布事件。
|
||||
- 子邮箱在交给执行器前,以当前 run/owner 租约保护的 CAS 保存 `delivered_sequence`;消息正文仍保留供快照重建。执行器 panic、丢失返回值或审批恢复启动失败时,收尾使用持久游标,只为确实未投递的 followup 创建新轮次。投递不等于执行成功,失败任务仍由父级检查结果后决定下一步。
|
||||
- 引擎在轮次边界自动注入带来源的 assistant 消息;`wait_agent` 只返回通知,不消费正文。自然收尾必须等待子任务,且最新结果须参与一次模型调用;达到迭代上限时明确报错并取消剩余委派。
|
||||
- 中断、父任务取消、根会话停止接口、父任务挂起后被 supersede 均有持久取消路径。旧 run/owner、过期租约、旧父消息的停止指令不能覆盖新执行;迟到成功不会把已取消任务复活。
|
||||
- 父引擎在 `wait_agent` 与自然收尾等待子任务时保存安全快照、已观察游标和绝对截止时间。进程重启后,调度器扫描数据库中的结果/超时并通过 CAS 领取父租约,恢复原父消息;已完成工具不会重跑。等待超时不会因重启重新计时。运行中的父引擎仍在原等待处继续,不额外启动第二个父模型。
|
||||
- queued 子任务恢复;有持久审批快照的 waiting 子任务可恢复。普通 running 或已经消费审批并进入 executing 的不确定执行转为 `needs_attention`,不自动重放副作用。用户下一次继续对话也可接管未完成协作并读取持久结果。
|
||||
- 子任务审批/提问使用现有 HITL Broker,快照和当前 run 的审批关联先落库,再向父会话展示卡片。等待审批释放执行槽位;回答由后台队列消费,HTTP 不直接启动隐藏子会话。并发子任务的多个审批支持刷新恢复,保留原租户、用户、子会话和工具调用身份。
|
||||
- 取消优先写入协作聚合,随后收敛关闭审批并清理快照;关闭完成前保持 cancelling,重启仍会继续清理。迟到答案不能重新排队;恢复租约被撤销后,在消费审批和执行副作用前再次检查。Broker reaper 将尚未消费的子任务 answered 状态交回调度器,executing 状态仍禁止重放。
|
||||
- worker 每轮重新校验用户、当前工作空间成员资格和 Agent 可用性。默认确认/只读模式的子任务不能自行取得写授权;操作工具不被子任务继承。子会话及执行记录保留,不再像试跑一样删除。
|
||||
|
||||
页面事件与展示(已实现):
|
||||
|
||||
- 子任务状态独立于主模型文字:持久协作组提交后发布 `collaboration_status` 全量白名单投影,以数据库 CAS version 为 revision。lease 心跳不刷新 UI;同 group 旧 revision 被丢弃,同 run 终态不能回退。模板名称与 task/run 身份分离。
|
||||
- 状态包含当前任务名称、运行/等待输入/终态、工具阶段、最近主动消息及 prompt_id;不转发逐 token 思考或原始工具输入输出。主引擎 attach/recover 重放最新快照;消息历史 GET 从数据库补齐同形状的 `collaboration_status`,不依赖 Redis 存活。
|
||||
- `waiting` / `resumed` 在真实审批状态变化时各投递一次给父模型;恢复从 ParentWait.After 继续消费。工具阶段只更新 UI 投影,不逐次唤醒父模型。
|
||||
- 主助手中间说明使用独立 `progress` 事件,稳定事件 ID 与 `AgentStep.progress/progress_event_id` 支持持久恢复、回放去重;不写入最终正文或思考内容。
|
||||
- 页面按任务持续更新列表,`wait_agent` 多次轮询合并为一个等待指示;审批显示所属子任务与实际参数,长 MCP 工具文档可展开。执行记录保留查看入口,最终正文仍由父级统一汇总。
|
||||
- 审批恢复会重建 SSE 日志,其 `agent_query` 带 `resume_pending_id` 和 `resume_tool_call_id` 标识本次续跑。前端保留续跑前各 steer 分段的时间轴,重连时只重建本次续跑的后续事件;普通完整日志重放仍从空时间轴重建。
|
||||
- 实时 UI 通知为尽力投递,数据库状态是恢复依据;通知投递失败不会回滚已提交工具操作,也不会导致工具重跑。
|
||||
- 父 MCP 调用进入审批前检查本组当前活跃子任务已登记的审批:同服务、原生工具和语义 JSON 参数(含用户修改后的参数)返回 `delegated_call_in_progress`,不新建父审批、不调用 MCP、不借用子授权。直接与代理调用共用此检查;已结束/取消的子轮次不挡新的父调用。此保护不等于审批尚未登记时的跨进程原子防重,已有父审批恢复仍完成自身生命周期。
|
||||
- 对代码区域之外合法 nonce 的孤立 `</think:…>`,通过同 event ID 的 `answer.data.replace` 回收已误分类的思考前缀;普通答案保持即时流式,标准孤立结束标签与代码字面量保留。缺失开标签时,在结束标签到达前可能短暂显示前缀;确认后实时撤回,最终思考与正文完整分开归档。16 KiB 仅限制实时回收预览,不截断最终正文。
|
||||
- 2026-10-17 页面并发回归:红队评审、谜题工匠、热榜解读官三路运行;等待审批期间刷新后恢复;批准后子状态立即恢复,三份结果最终汇总且主任务结束。额外主动让父级重复调用热榜,确认命中防重、只保留子审批,日志仅一次实际 MCP 调用成功。重启、取消、迟到状态与审批恢复另由 race 回归覆盖。
|
||||
|
||||
|
||||
本批参数以 `internal/agent/tools/collaboration.go` 为准:`spawn_agent(task_name, message, agent_id?)`,`list_agents(path_prefix?)`,`send_message/followup_task(target, message, expected_run_id?)`,`interrupt_agent(target, expected_run_id?)`,`wait_agent(timeout_ms?)`。等待默认 30 秒,范围 1–60 秒,边界外拒绝。任务默认一小时期限。
|
||||
|
||||
提示词与消息边界(收敛后的实现):
|
||||
|
||||
- 角色提示词集中说明父子职责、进展与最终交付;工具说明仅定义调用语义与返回值。模板不再重复协作细则。
|
||||
- 父级角色提示词同时集中定义主动拆分策略:开始实质工作前判断独立范围,多个有实质工作量且并行有收益的部分默认创建临时子任务;简单请求、强依赖步骤、即时阻塞工作和冲突修改保留本地,用户要求本地完成时遵从。工具说明不重复该决策策略,运行时不按关键词或任务长度强制创建子任务。
|
||||
- 参考 Codex V2 的消息封装,在模型边界将持久化事件转换为 `Message Type / Sender / Run ID / Sequence / Status / Payload`。主动消息为 `MESSAGE`,追加任务为 `NEW_TASK`,子轮次结果为 `FINAL_ANSWER`(状态可能失败),恢复与审批/输入状态变更通知为 `<runtime_event>` 包裹的 JSON。审批通知携带 `type/source/task/run_id/sequence/prompt_id/prompt_kind/tool_call_id/service/tool/decision/execution_state`,工具身份和决定来自 broker 的白名单字段,不包含参数、完整请求或用户答案。`approval_resolved` 只表示审批已答复,`execution_state=queued` 只表示安排继续执行,不能视作工具成功或子任务完成;缺失/无效决定不推断。旧的纯文本通知封装为 `message` 保留,不补造审批信息。结果正文直接保留原文,不再要求模型解码嵌套 JSON;数据库事件结构不变,旧快照兼容。
|
||||
- 普通工具调用后的文字不再触发额外 system 提醒。只有已生成的答复被新输入或子任务结果续跑取代时,记录 `IntermediateAnswer` 并追加一条简短状态标记;重启时从该标志恢复同一边界。
|
||||
- 空响应重试和最终汇总的恢复通知通过 `Options.RuntimeNotice` 仅作用于当前模型请求,不追加到持久对话或检查点。通知位于序列尾部:Chat Completions 使用适配后的 system/developer,Responses 使用 input developer;Anthropic、Gemini、Ollama 使用明确标记来源的末尾输入,不把临时通知提升到全局系统前缀。既有系统指令、工具定义、历史和缓存断点不变;缓存命中率仍由服务端缓存寿命、路由与实际上下文决定。
|
||||
- 当前 `wait_agent` 等待复用时间轴底部的活动节点、图标对齐和光影效果,待审批显示“等待你处理”;等待结束后恢复正常推理展示,完成、取消或 steer 切段时移除。成功或超时返回的等待调用不渲染历史占位文案,真实等待错误保留普通工具行供检查。
|
||||
- 自然收尾仍由运行时检查活动子任务、未观察结果与取消状态;模型连续空答、重复响应或连续截断触发的协作退出返回错误,不走成功兜底,剩余子任务由运行时取消。提示词不承担审批判定、恢复资格或完成状态迁移。
|
||||
|
||||
本批未实现:跨子会话交付物发布、资源级共享写锁、临时模型覆盖和递归委派。只恢复明确的安全等待点,不声称恢复任意模型/工具执行点;已经发往外部系统的副作用不能通过取消撤回。没有增加模型可调用的读取、清理或审批工具。
|
||||
|
||||
验证:本轮补充原父消息自动恢复、已完成工具不重放、两个恢复器竞争领取、等待截止时间保留、取消与领取竞争、未消费审批跨重启、HTTP 不绕过子任务队列、旧轮次审批清理,以及父会话多审批刷新与去重测试。
|
||||
|
||||
验证:新增 runtime、工具、引擎和服务适配测试,覆盖双调度器并发领取、请求重放、追加消息与完成竞争、父子取消、迟到回调、过期所有权、父任务接管和权限范围。SQLite 迁移升级测试覆盖新表;PostgreSQL 提供 SQL 迁移但本机未运行 PostgreSQL 集成测试。
|
||||
|
||||
本轮验证记录:相关十个后端包的普通 `go test` 通过;六个包中的协作/恢复/审批定向 `-race -count=5` 通过;前端挂起恢复与审批 dock 测试 20 项通过。测试使用模拟模型和 SQLite;未运行真实模型或 PostgreSQL 实库联调。
|
||||
|
||||
第一阶段验证记录:相关七个包的普通 `go test` 通过;新调度 runtime 的 `-race -count=10` 及六工具/引擎/适配层定向 `-race` 重复测试通过;前端 `check-i18n` 15 项通过。测试时移除了环境里的 `LOG_FORMAT=json`(此项目将该值当作字面日志模板,否则原有日志断言读不到正文)。全 service 包 `-race` 仍有未改动测试的竞态失败:`TestTenantAPIKeyServiceAuthenticateThrottlesLastUsedUpdates`、`TestQueryTemplatesEnsureAndReplaceDoNotShareSingleflight`,以及 skill 安装相关的 `TestRegisterCatalogDoesNotMoveTheDefinitionWhenPinFails`、`TestRemovingThePinnedInstallReclaimsTheReplacedZip`、`TestUpgradeKeepsThePreviousVersionServingWhileItRuns`、`TestFailedUpgradeLeavesThePreviousVersionServing`;不能宣称全仓竞态检测通过。
|
||||
|
||||
### 0.1 实测问题修正(2026-10-17)
|
||||
|
||||
- 审批身份统一:协作记录的 `Scope.UserID` 是账户 ID,HITL 的 `UserID` 是 `Principal.StorageID()`(Web 用户为 `web_user:<ID>`)。审批登记、校验、刷新投影、重启恢复、reaper 接管及父审批关闭均在边界做显式转换,不能直接比较两个字段。旧测试手造裸 ID 掩盖了真实引擎的问题;新增测试使用真实 AgentEngine、MCPTool、Gate、SQLite prompt/snapshot 仓库及本地 HTTP MCP 服务。
|
||||
- `wait_agent` 和自然结束前的等待都检查未消费的 steer。返回 `interrupted=true` 区分用户输入与超时;读取不消费,仍由引擎持久化并作为 user 消息注入。正常数据库/队列延迟下按运行时 250 ms 轮询响应,不等待原定 60 秒窗口。恢复后的父执行重新创建 SteerSink,过期父租约的安全等待点也可因持久 steer 唤醒。
|
||||
- `list_agents` 增加有界 `progress`:最近工具名、调用 ID、轮次、阶段和更新时间,以及当前 `prompt_id`。工具进度覆盖保存,不累积到邮箱、不因每个工具唤醒模型;等待用户时由审批卡片展示,状态可通过 list_agents 查询,不投递模型邮箱。显式 `send_message` 继续用于中途发现和进展汇报。此处是工具可查询的运行状态,尚未增加完整子任务进度 UI。
|
||||
- 父任务完成后心跳正常退出,不再取消最终事件的发送。自动恢复时若引擎初始化失败、未发出完成事件,适配层会持久化错误并补一次完成事件,避免消息永久未结束。
|
||||
- 六工具定义补齐参数含义、模板查询入口、实例寻址、隔离上下文、等待/追加/取消语义和当前版本限制;不虚构 fork、模型覆盖或递归委派能力。仍未增加 read_agent、close_agent。
|
||||
|
||||
Codex V2 再核对:`multi_agents_v2/wait.rs` 用 input queue activity 同时监听 mailbox/steer,并在订阅时处理已存在输入;`agent/control.rs` 的 completion watcher 主要投递终态通知;`multi_agents_v2/list_agents.rs` 查询实时状态。这里对应实现为持久队列轮询、独立完成邮箱和进度快照,并未照抄其进程内通知机制。
|
||||
|
||||
本轮验证:十个相关后端包普通测试通过;六个包的协作/恢复定向 `-race -count=5` 通过(session 包在该筛选下无匹配用例);最后补充修改后重跑 agent/service 全包测试通过。新增 MCP 集成测试使用真实引擎、HTTP MCP 传输及 SQLite 审批/快照持久化,模型响应仍为脚本;未验证生产模型和 PostgreSQL 环境。
|
||||
|
||||
手工回归建议:
|
||||
|
||||
1. 在 WeKnora 助手中委派一个配置了需审批 MCP 工具的推理 Agent。审批卡出现后通过;应只执行一次 MCP 操作,子任务继续,父任务收到结果并结束。重复一次选择拒绝,确认 MCP 未执行。
|
||||
2. 让助手调用 `wait_agent` 等待 60 秒,在等待期间发送立即追加的 steer,确认很快进入下一轮且新输入只出现一次。另测自然收尾等待子任务期间的 steer。
|
||||
3. 子任务运行时要求助手 `list_agents`,观察 running/waiting 和 progress;等待审批不占并发槽位。
|
||||
4. 在审批挂起时重启后端,刷新主对话后审批;确认从原子轮次继续。另测父等待期间重启后发送 steer。
|
||||
5. 停止父任务或中断子任务,再提交旧审批/等待迟到结果;确认不会再次执行或唤醒。
|
||||
|
||||
### 0.2 实际运行日志复核(2026-10-17 14:02–14:05)
|
||||
|
||||
`km_hotlist_rerun` 本次实际完成,不能据等待阶段的文字判断父任务未收尾:14:02:57 第一次审批后的 hot-articles 成功;14:03:00 模型返回新的调用 ID,再次请求相同参数,触发第二次审批;14:03:13 第二次调用成功;14:04:45 子任务完成并更新消息;14:05:06 父任务记录 complete=true、更新消息;14:05:07 事件流记录 completed。两次审批是不同工具调用,未发现调度器重放同一调用的证据。第二次调用前的模型输入已包含第一次成功结果;不能把重复调用直接归因于审批未回传。
|
||||
|
||||
额外确认的恢复缺陷:此前同一轮已 describe 的 show-article 在审批恢复后不在可调用目录中,造成两次 tool_ref 参数校验失败;重新 describe 后才继续。原 RememberMCPHistory 只恢复已调用的工具,遗漏了“已描述、未调用”的工具。现增加快照字段 mcp_tool_refs,保存 schema hash 引用并在恢复时重新匹配当前目录与权限,不保存凭据、不跳过停用和 schema 变化检查;父等待快照也保存同样状态。新增直接/代理工具恢复与停用、schema 变化回归测试。旧快照缺少该字段时保持旧兼容行为,可能仍需重新 describe。
|
||||
|
||||
截图中的 authorized=false 标签片段来自父模型的普通文本输出,不是后端审批判定;waiting 阶段提前输出的长段文字会暂时像最终答复,实际是在等待子任务。该次日志核实了最终完成事件;未因此宣称已解决模型重复调用或所有等待阶段的展示问题。
|
||||
|
||||
### 0.3 交付流程与输出限制(2026-10-17,14:11 实测)
|
||||
|
||||
第二次运行的子会话 `a54e0ea4-73ac-4626-9e68-35e66845c018` 在 14:13:17 的第 7 轮返回 `finish_reason=length`,completion=4096,回答正文 7250 字节。是模型输出上限触发,并不能据此声称隐藏子会话里还有完整结尾。界面的 500K 是上下文容量,和本轮输出预算是两个设置。现有无 sandbox 的 smart-reasoning 默认输出预算是 4096;本批不擅自修改用户配置或把上下文容量用作输出预算。
|
||||
|
||||
此前还存在另一处独立问题:调度器把 Answer 裁到 4000 rune,附上“全文在子会话”,却没有展开全文的闭环。本批取消答案/证据的二次裁剪,按原文持久化及投递;聚合存储仍有 32 MiB 上限,不宣称无限容量。超大交付物的资源引用仍属于后续范围。
|
||||
|
||||
交付规则:
|
||||
|
||||
- 常规审批等待仅改变持久状态、投递 UI 卡片,不唤醒父模型。旧记录里的 waiting 事件也不会因重启重新唤醒或进入模型上下文。终态结果、显式消息、用户 steer、等待超时维持原来的唤醒机制。
|
||||
- 父轮次开始时如仍有活动子任务或未读结果,暂缓输出这一轮的推测性正文;通过结束屏障且无需继续处理新结果后才可交付。子结果已处理后的最终汇总仍可正常流式输出。中间步骤保留用于审计。
|
||||
- 根/子引擎在新执行和审批恢复时都有明确角色约束:交付实际内容,区分历史与当前运行,不复述旧审批状态,不重复已成功工具调用,不用执行清单替代正文。
|
||||
- 子回答达到输出上限时,仅在剩余轮数允许的情况下给一次无工具的精简重写机会,用已取到的证据覆盖各节;不提高用户预算,不循环续写,不重复副作用。这是 WeKnora 的受限恢复策略,不声称来自 Codex。重写仍截断或预算耗尽后的合成回答截断,结果带 `truncated=true`、终态 failed 和原因,保留已有正文,不冒充完整成功。父级可据此决定有针对性的 followup。
|
||||
|
||||
Codex 对照的具体边界:固定版本的 [session_prefix.rs](https://github.com/openai/codex/blob/3b8f43a06bb3105e81406b35ff69f94977d18ae4/codex-rs/core/src/session_prefix.rs#L20) 对 Completed(Some(message)) 直接复制回答,截断限额仅用于错误文本;[responses.rs](https://github.com/openai/codex/blob/3b8f43a06bb3105e81406b35ff69f94977d18ae4/codex-rs/codex-api/src/sse/responses.rs#L420) 将非 interrupted/content_filter 的 incomplete 转成 ResponseIncomplete 错误。不能由此推断所有提供商、上下文压缩或工具输出都完全不截断。
|
||||
|
||||
新增回归涵盖:超过 4000 字的答案经持久化/重建运行时后完整投递;旧 waiting 事件不会唤醒,真实完成事件仍唤醒;父任务在等待时不展示未确认正文;真实引擎 + 本地 HTTP MCP 的批准/拒绝/取消/重启,以及一次重写成功、再次截断、轮数耗尽合成截断,确保工具副作用不重复。
|
||||
|
||||
本批验证:相关 10 个后端包普通测试通过,runtime/engine/service 协作定向竞态测试重复 3 次通过。使用脚本模型与本地 HTTP MCP;没有用真实模型重新执行用户任务,未修改运行中服务或用户的输出预算配置。
|
||||
|
||||
### 0.4 中途报告与最终交付(2026-10-17,14:25 实测)
|
||||
|
||||
根消息 `8ab152d6-1e43-4502-bca8-610165da6b23` 在委派参数中自行要求「分两条消息」:子会话 `57403813-ca94-4840-a22e-1bdd48ee72bc` 第一轮返回榜单及前两篇,父任务第 6 轮复述正文并调用 followup_task;第二轮返回后两篇及结尾。主任务第 8 轮已有两份结果,无上下文压缩,finish=stop,completion=2210,却只交付后半段并称为完整结果。并非 4000 字裁剪或输出预算耗尽。
|
||||
|
||||
原因是 UI 将附带工具调用的正文重分类为中间步骤,而模型上下文没有明确说明这部分不属于最终交付。主 Agent 把自己前一轮的长篇正文当成用户已收到的「上一条」,最终答复依赖折叠步骤才能完整。
|
||||
|
||||
本批统一约定:执行中只给一两句进展,完整表格/章节留到最终正文;单个子执行轮次只产生一份最终答复,跨轮结果由父级合并。早期实现曾在附带正文的工具轮及续跑答复后注入 runtime delivery state;现已收敛为仅在答复被新输入续跑取代时追加简短状态标记。普通工具步骤通过原生 tool-call 结构区分,汇总规则仅保留在角色提示词。保留原 provider 消息、工具调用 ID 及 reasoning;快照根据 IntermediateAnswer 重建续跑边界,子结果通过独立消息封装交给父模型。没有通过重跑整个 Agent、裁剪正文或将工具步骤拼成最终回答来掩盖问题。
|
||||
|
||||
官方 [assistant phase 文档](https://developers.openai.com/api/docs/guides/deployment-checklist#set-up-the-assistant-phase-parameter) 区分 commentary 与 final_answer,并要求回传历史保留 phase;当前 Chat Completions 兼容链路未接通原生 phase,本批使用运行时语义标记与角色提示,不能宣称已经接入 Codex 的完整协议或强制保证模型语义质量。
|
||||
|
||||
子任务通过 send_message 主动报告关键发现/阻塞,父级等待立即收到通知、下一轮注入正文;自动工具进度仅更新 list_agents 查询状态,不逐步推送全部工具输出。回归验证关键消息在子任务仍 running 时可唤醒父级,取消后拒绝迟到消息。
|
||||
|
||||
新增测试覆盖两轮子结果同时保留在父上下文、正文与中间步骤的交付边界,以及快照恢复后该边界仍存在;使用脚本模型,不能替代真实模型对最终报告完整性的验收。
|
||||
|
||||
## 1. 核实结果与设计依据
|
||||
|
||||
用户提供的 `collaboration` 定义包含 `spawn_agent`、`list_agents`、`send_message`、`followup_task`、`interrupt_agent`、`wait_agent`。六个工具的名称、参数和核心语义与本次设计会话实际暴露的子 Agent 接口一致。可以确认这是本会话这一类子 Agent 协作接口的定义;无法仅凭文本确认导出来源、版本或其是否为所有 Codex 客户端的公开稳定 API。
|
||||
|
||||
进一步克隆官方仓库后,确认这六个工具对应 **MultiAgentV2** 的实现。检查仓库为 `https://github.com/openai/codex.git`,固定提交为 [`3b8f43a06bb3105e81406b35ff69f94977d18ae4`](https://github.com/openai/codex/commit/3b8f43a06bb3105e81406b35ff69f94977d18ae4),提交时间为 2026-10-17 02:27:35 UTC。本次只读检出的目录为 `/tmp/codex-source-audit.WNlDZa/codex`;临时目录不作为长期证据,以下链接均固定到该提交。实际工具暴露还受配置、模型元数据和版本影响,不声称文本逐字段适用于所有客户端。
|
||||
|
||||
官方 [Codex App Server 文档](https://learn.chatgpt.com/docs/app-server#api-overview) 另有 thread 创建、恢复、分叉、状态事件,以及 turn 启动、追加输入和中断接口。这支持“实例和执行轮次分离”的设计方向,但该文档不能证明用户提供的六个工具就是公开 App Server 协议。粘贴文本的 `encrypted`、`strict` 属于其 schema 元数据,本设计不据此推断加密方式,也不照搬。
|
||||
|
||||
当前仓库的基础:
|
||||
|
||||
| 已有实现 | 可以复用什么 | 尚需补充什么 |
|
||||
|---|---|---|
|
||||
| 原试跑入口(本批删除) | 解析 Agent、运行 AgentQA、收集结果的经验 | 由六工具和持久子会话统一替代,不再保留试跑用途 |
|
||||
| `internal/handler/session/qa.go`、`steer.go` | 后台运行、单会话执行互斥、停止、追加指令、后续轮次 | 提取不依赖 Gin/SSE 的统一运行入口 |
|
||||
| `internal/agent/hitl`、`internal/agent/resume.go` | 审批持久化、租约、快照、恢复 | 子任务审批的主对话展示;等待子 Agent 的独立恢复原因 |
|
||||
| `internal/types/interfaces/stream_manager.go` | 事件流、运行标记、用户消息投递 | 持久化的 Agent 邮箱与完成通知 |
|
||||
| `internal/types/message_artifact.go` | 交付物记录和下载入口 | 跨子会话的受控引用、结果版本关联 |
|
||||
| `internal/types/interfaces/task_queue.go`、`task_enqueuer.go` | 排队、领取、重试的已有基础设施 | Agent 执行的数据库所有权和不可盲目重放规则 |
|
||||
|
||||
现有 `Session.ParentSessionID` 表达会话分叉来源,不复用为委派关系;现有业务队列任务也不直接充当用户看到的子 Agent 实例。
|
||||
|
||||
### 1.1 Codex 源码对照结论
|
||||
|
||||
| 源码事实 | 固定版本证据 | 对本设计的影响 |
|
||||
|---|---|---|
|
||||
| V2 定义了上述六个工具;V1 另有关闭工具 | [multi_agents_spec.rs](https://github.com/openai/codex/blob/3b8f43a06bb3105e81406b35ff69f94977d18ae4/codex-rs/core/src/tools/handlers/multi_agents_spec.rs#L204) | 我们保留 V2 的六工具面;不能将“V2 不暴露关闭工具”说成“Codex 从未实现关闭工具” |
|
||||
| 消息区分 QueueOnly 与 TriggerTurn,followup 禁止指向 root | [control/api.rs](https://github.com/openai/codex/blob/3b8f43a06bb3105e81406b35ff69f94977d18ae4/codex-rs/core/src/agent/control/api.rs#L100) | 普通消息不启动空闲实例,返工启动子轮次;子 Agent 不能凭消息启动新的根任务 |
|
||||
| wait 订阅输入活动后检查已有输入;只接受 timeout_ms,返回 message/timed_out,不返回正文 | [v2/wait.rs](https://github.com/openai/codex/blob/3b8f43a06bb3105e81406b35ff69f94977d18ae4/codex-rs/core/src/tools/handlers/multi_agents_v2/wait.rs#L44)、[input_queue.rs](https://github.com/openai/codex/blob/3b8f43a06bb3105e81406b35ff69f94977d18ae4/codex-rs/core/src/session/input_queue.rs#L150) | 第一版 wait 同样仅保留 timeout_ms;游标由运行时管理,避免过滤和全局游标交错导致漏读 |
|
||||
| 子结果以 trigger_turn=false 投递给直接父级,投递代码明确为 best effort | [completion.rs](https://github.com/openai/codex/blob/3b8f43a06bb3105e81406b35ff69f94977d18ae4/codex-rs/core/src/agent/control/completion.rs#L1) | 数据库/outbox 可靠投递及根任务继续执行属于 WeKnora 的新增保证,不能宣称已由 Codex 源码验证 |
|
||||
| 空闲线程有 TriggerTurn 邮件才启动;存在 durable sleep 时,普通邮件也可唤醒 | [tasks/mod.rs](https://github.com/openai/codex/blob/3b8f43a06bb3105e81406b35ff69f94977d18ae4/codex-rs/core/src/tasks/mod.rs#L442) | 不能绝对化为“所有完成消息永不唤醒”;WeKnora 用明确的等待/继续执行记录决定是否唤醒 |
|
||||
| 中断拒绝 root/self,返回之前的状态;不会为中断而加载已卸载实例 | [interrupt.rs](https://github.com/openai/codex/blob/3b8f43a06bb3105e81406b35ff69f94977d18ae4/codex-rs/core/src/agent/control/interrupt.rs#L1) | 区分中断请求已接受和执行已退出;不靠读取旧状态判断已停止 |
|
||||
| 执行容量与驻留容量分开;空闲运行时可被卸载,保留/转移状态和邮箱 | [execution.rs](https://github.com/openai/codex/blob/3b8f43a06bb3105e81406b35ff69f94977d18ae4/codex-rs/core/src/agent/control/execution.rs#L1)、[residency.rs](https://github.com/openai/codex/blob/3b8f43a06bb3105e81406b35ff69f94977d18ae4/codex-rs/core/src/agent/control/residency.rs#L35) | 实例身份、驻留资源、执行槽位分别管理;WeKnora 的持久化恢复仍需自己实现 |
|
||||
| Agent 消息具有独立来源类型,呈现为 assistant 角色片段 | [inter_agent_message.rs](https://github.com/openai/codex/blob/3b8f43a06bb3105e81406b35ff69f94977d18ae4/codex-rs/core/src/context/inter_agent_message.rs#L46) | 不复用将内容视作用户授权的追加指令路径 |
|
||||
|
||||
已阅读相关测试而未执行 Rust 测试:`multi_agents_tests.rs` 中的 wait 只返回通知、已有邮件立即唤醒、followup 每轮通知、拒绝对 root followup、被中断轮次不发送完成通知;`core/tests/suite/agent_control_tests.rs` 的 `host_mailbox_notifies_waiting_agent_and_delivers_once` 验证正文独立投递且只出现一次。Codex 此版本的中断不产生完成通知,WeKnora 则明确增加独立的 `run.interrupted` 状态事件,以便持久任务管理不会一直等待成功结果。这是产品差异。
|
||||
|
||||
## 2. 目标与第一版边界
|
||||
|
||||
用户向 reasoning Agent 提出目标后,该 Agent 能创建继承自身能力的临时子任务,或选择已配置的 Agent 委派任务,并行分派工作,补充要求,等待结果,处理人工交互,要求返工,最终交付。刷新页面或恢复服务后,任务状态和已经完成的结果仍可查询。
|
||||
|
||||
当前采用一个父 Agent 协调多个直属子 Agent:
|
||||
|
||||
- 省略 `agent_id`:使用父任务当轮的生效配置快照,包括实际选用模型、提示词、知识库/文档/标签范围、MCP、Skills、沙箱配置和实际工具集合;不写入新的 `CustomAgent` 记录。
|
||||
- 提供 `agent_id`:使用已有 `CustomAgent` 模板快照,经授权范围裁剪后运行。
|
||||
- 只支持当前工作空间内可使用的 smart-reasoning Agent。共享跨租户执行不开放。模板模式保留内部管理模板限制;继承模式按父任务的运行权限工作,不因父任务是普通 Agent 或内置助手而增加专用分支。
|
||||
- 子 Agent 只能向父级回报,不再创建子 Agent,不直接指挥兄弟节点。后续可以在相同模型上开放层级和同级协作。
|
||||
- 面向模型只提供原来的六个协作工具;结果读取、上下文投递和实例清理由运行时负责,不增加读取或关闭实例的工具。
|
||||
- 默认最多 3 个子 Agent 同时执行,为协调者保留执行容量;等待审批或子任务时释放计算槽位。
|
||||
- 临时子任务不能自定义角色或覆盖模型,也不提供通用 DAG 编辑器、任意执行点无损恢复、定时调度。
|
||||
- 首版默认独立沙箱。共享知识库/Wiki 写入要有资源范围与冲突控制;不默认共享可写宿主项目目录。
|
||||
|
||||
### 临时子任务的持久化与范围
|
||||
|
||||
- 配置快照来自服务端运行上下文,工具调用不能提交模型、权限或配置快照。MCP 的 `all` 在父任务初始化时解析成具体服务集合;子执行注册的工具再与父任务实际工具集合取交集。
|
||||
- 用户、工作区成员身份和来源 Agent 在每轮重新授权;知识库读取权限、可写范围和工作区审批上限重新检查。Skills 只保存已授权名称,运行时重新加载可用内容和凭证,不持久化技能环境变量。
|
||||
- 临时子任务仍使用独立会话与沙箱,不复制父聊天历史、附件路径或未完成的调用。父级在 `message` 中提供完整任务与必要背景。`followup_task` 保留同一子会话和配置;审批恢复继续同一执行轮次。
|
||||
- 两种模式共用排队、邮箱、等待、取消、审批、结果和产物交接;临时任务界面显示 `task_name`,不把它伪装成一个新保存的模板。
|
||||
- 回归覆盖临时/模板三路混合并发、重启后配置恢复、同实例追加任务、普通父 Agent 唤醒、权限收紧和工具范围不扩张,以及两种模式下真实 MCP 审批的批准、拒绝、取消和重启恢复。
|
||||
|
||||
## 3. 三种身份与生命周期
|
||||
|
||||
必须区分:
|
||||
|
||||
1. **Agent 配置 `agent_id`**:模板委派时的现有 `CustomAgent` ID,可以同时实例化多次;临时实例的该字段为空,来源和生效配置保存在私有快照中。
|
||||
2. **协作实例 `member_id`**:某次用户任务里的子 Agent,拥有持久子会话和邮箱;一次工作完成后仍可接收返工。
|
||||
3. **执行轮次 `run_id`**:实例的一次执行。启动、返工会产生新轮次;审批恢复继续原轮次。
|
||||
|
||||
另建 `collaboration_id` 作为一次用户目标的边界,关联根会话和发起消息。同一根会话的不同任务不能仅凭 session ID 混在一起。
|
||||
|
||||
实例状态:`open → closed`,由运行时管理。执行情况由当前轮次表达;没有活跃轮次的 open 实例为 idle。单个子轮次结束后,实例仍可供 followup;整个协作结束或被取消后统一关闭。驻留状态 `loaded / unloaded` 独立于实例状态:unloaded 的 open 实例可在 followup 时重新加载,不能误判为 closed。
|
||||
|
||||
轮次状态:
|
||||
|
||||
```text
|
||||
queued → running → succeeded | failed | interrupted
|
||||
↘ awaiting_input → running
|
||||
↘ awaiting_children → running (协调者)
|
||||
queued/running/awaiting_* → cancelling → cancelled
|
||||
running → needs_attention (副作用结果未知等)
|
||||
```
|
||||
|
||||
- `succeeded` 只表示执行结束并保存结果,不等于交付质量已通过验收。第一版不引入机器可判定的 accepted/rejected 状态;父级依据结果决定返工或交付,运行时只记录结果版本、投递、参与处理的父轮次和返工关联。
|
||||
- `interrupt_agent` 停止当前轮次,保留实例及历史,可再 followup;拒绝 root/self 目标,对 idle 实例返回无活跃轮次而不重新加载。对挂起轮次也要取消其 prompt/wait 恢复资格,迟到审批不能复活被中断轮次。退出确认前不能在同一实例启动下一轮写操作。
|
||||
- 实例关闭和资源清理由运行时统一执行;关闭后不能再自动启动,仍在执行的轮次必须先取消并确认退出。实例关闭不删除历史和交付物。
|
||||
- 用户“停止整个任务”将协作置为 cancelling,取消所有排队/运行/挂起的轮次,关闭唤醒资格;不会回滚已经发生的修改。
|
||||
- 每个取消请求携带 generation。晚到的事件仍可记入审计,但不能重新启动已取消的任务。
|
||||
|
||||
## 4. 面向模型的工具
|
||||
|
||||
仅保留原定义的六个工具,不增加读取或关闭工具。以下是它们在 WeKnora 中的建议参数和语义,参数采用严格 schema 校验;参数适配不意味着与原定义逐字段兼容。
|
||||
|
||||
| 工具 | 主要参数 | 语义和返回 |
|
||||
|---|---|---|
|
||||
| `spawn_agent` | `agent_id, task_name, message, context_mode?, resource_refs?, expected_output?, limits?` | 创建实例、子会话、首轮和入队事件,立即返回 `member_id, run_id, task_path, status`;不等待完成 |
|
||||
| `list_agents` | `path_prefix?, include_closed?, cursor?` | 返回当前协作内实例和当前轮次摘要、阻塞原因、未读事件数、交付物摘要;不等于列出 Agent 配置 |
|
||||
| `send_message` | `target, message, expected_run_id?` | 持久投递消息;运行中在安全边界接收,idle 时保留在邮箱,不启动新轮次;返回 `event_id, delivery_state` |
|
||||
| `followup_task` | `target, message, expected_run_id?` | idle 时创建新轮次;running 时作为追加要求投递;挂起时保存要求但不自动批准审批。返工原因写在 message 中,运行时关联当时的结果版本;返回实际 `run_id` 和投递状态 |
|
||||
| `interrupt_agent` | `target, expected_run_id` | 中断指定轮次;返回原状态和 `interrupt_requested`,终止确认由后续事件表达 |
|
||||
| `wait_agent` | `timeout_ms?` | 等待当前协调者邮箱或输入变化,返回唤醒/超时/用户输入中断通知;不接受 targets 或模型提供的游标。正文及来源由运行时读取并投递 |
|
||||
|
||||
Agent 选择先复用 `agent.list / agent.get`,补充返回 `can_delegate`、不可运行原因及能力摘要;暂不新增单独的 Agent 搜索体系。
|
||||
|
||||
`target` 优先用 `member_id`,也可用同一协作内的路径。`task_name` 在同一父实例下唯一;相同请求重放返回原实例,不同请求使用重名则报冲突,不静默复用。所有工具的身份、租户、协作根、父实例均由运行上下文注入,模型不能指定。
|
||||
|
||||
保留原定义中 `wait_agent` 的职责:它负责等待并报告更新,正文由运行时从持久邮箱和结果记录读取,在安全边界另行投递。未调用 wait 时,运行中的父级也能收到结果。工具返回的更新标记不代表正文已被消费;只有正文及其来源已持久写入父级上下文,才推进投递游标。两条路径使用同一套去重记录。
|
||||
|
||||
wait 采用 wait-any 语义:任一相关实例有新消息、终态或待用户处理状态即返回;是否已经收齐所有结果由协调者判断。默认等待 30 秒,最小 10 秒、最大 1 小时,均为服务端配置;低于最小值钳制,高于最大值拒绝,不默认将 0 解释成立即读取。请求等待时长是此次 wait 的总截止时间,挂起和重启不能重置;超过运行时短等待阈值则写快照挂起,数据库定时扫描在 deadline 到达时也必须触发恢复,不能只靠子事件唤醒。超时不取消子任务。
|
||||
|
||||
示例:
|
||||
|
||||
```json
|
||||
{
|
||||
"agent_id": "existing-market-agent-id",
|
||||
"task_name": "market_analysis",
|
||||
"message": "分析提供的市场材料,区分事实、推断和缺失数据。",
|
||||
"context_mode": "brief",
|
||||
"resource_refs": [{"kind": "knowledge", "id": "authorized-document-id"}],
|
||||
"expected_output": "给出分析结论、证据引用和待核实事项;不修改原文。"
|
||||
}
|
||||
```
|
||||
|
||||
实例 ID 不混用现有 Agent 配置 ID。模型默认使用目标 Agent 保存的配置;第一版不提供任意模型 override。
|
||||
|
||||
## 5. 上下文、权限与人工交互
|
||||
|
||||
### 5.1 上下文传递
|
||||
|
||||
- 默认 `context_mode=brief`:任务说明、父级明确提供的必要背景、经检查的资源引用、交付要求。
|
||||
- `none`:只传任务与明确引用,不继承父历史。
|
||||
- `all`:后续版本开放授权范围内的父对话快照;不复制父级系统提示词、工具授权或未完成的 tool-call 配对。第一版遇到该参数应明确拒绝。
|
||||
- 创建时冻结历史边界和 Agent 配置版本/快照;快照保存凭证引用而非密钥正文。运行中修改配置不静默改变已有实例。授权撤回在每次恢复和敏感操作前重新检查。
|
||||
- 不透传过期 URL、父级 cN/dN 等临时引用句柄;转换为稳定资源 ID,在子会话重新解析。
|
||||
- 子结果通过 artifact/document ID 交接;父级显式选择再传给下一子 Agent,重新授权,不直接共享全部上下文或整个文件系统。
|
||||
|
||||
### 5.2 授权
|
||||
|
||||
有效资源/动作权限取“用户当前权限 ∩ 工作空间策略 ∩ 本次任务授权范围 ∩ 目标 Agent 允许范围”。父 assistant 自身未安装某个专业工具,不代表子 Agent 也不能使用;因此不能简单对父子工具名称取交集。
|
||||
|
||||
为子执行生成 DelegationContext,记录 root/member/run、用户、执行租户、资源范围、允许动作、审批策略和预算。所有工具入口、MCP 调用和沙箱能力由运行时执行约束,不能只写进提示词。范围未明确或无法执行约束的写能力不开放,标记需要授权/不支持。
|
||||
|
||||
第一版在注册时限制仅内置 assistant 能创建和控制子实例;子实例只有向父级发送消息的能力。不可通过子 Agent 获得管理目录、其他用户会话或宿主目录的额外权限。
|
||||
|
||||
Agent 消息保存 `source=agent`、发送者实例和轮次,是协作材料,不是用户授权。现有 `drainSteerMessages` 把内容写成 user 消息,不能直接原样复用于子 Agent 回报;新增专用 mailbox 注入路径和有来源的消息序列化,不能伪装成用户发言或提升为系统指令。
|
||||
|
||||
### 5.3 审批与提问
|
||||
|
||||
子 Agent 的 ask_user、工具审批、OAuth 仍复用 HITL Broker。请求归属保持在子会话/子消息,主对话只展示带 Agent 名称、任务与操作范围的代理卡片。回答通过服务端验证根任务到子 prompt 的归属、用户身份及当前状态后路由;不能为了方便把 prompt 的 session_id 改成父会话。
|
||||
|
||||
用户审批只允许该操作/明确范围,assistant 不能代批,也不能把拒绝转换为再次委派。其他子任务可以继续,父级能看到该任务在等待用户。停止根任务时同时关闭未决 prompt;晚到回答不能恢复任务。
|
||||
|
||||
## 6. 数据与执行架构
|
||||
|
||||
建议新增以下模型;JSON 字段保存可演进载荷,关系、状态、游标、版本与索引使用独立列:
|
||||
|
||||
| 模型 | 关键内容 |
|
||||
|---|---|
|
||||
| `agent_collaborations` | id、tenant/user、root_session、origin_message、status、generation、continuation_generation、pending_result_runs、预算和使用量 |
|
||||
| `agent_members` | id、collaboration、parent_member、agent_id、child_session、task_name/path、config_snapshot、授权范围、open/closed、current_run_id |
|
||||
| `agent_runs` | id、member、trigger_event、assistant_message、state、owner_token、lease、version、输入、结果引用、usage、error、latest_model_input_sequence |
|
||||
| `agent_mailbox_events` | recipient、sender、kind、sequence、run_id、payload、dedup_key、delivered_to_run、handled_by_run;关联持久消息/快照位置 |
|
||||
| `agent_waits` | run、cursor、deadline、snapshot_ref、恢复阶段、waiting/resuming 状态及版本 |
|
||||
| `agent_dispatch_outbox` | execute/resume/notify/cancel 事件、去重键、重试和已发送状态 |
|
||||
|
||||
关键约束:`(collaboration_id, parent_member_id, task_name)` 唯一;`(member_id, trigger_event_id)` 唯一;`(recipient_id, sequence)` 和投递 dedup_key 唯一;同一 run 只有一个有效 wait。根协调者同样有 member 记录,保证路径和邮箱一致。通过锁定 member 行并 CAS 更新 current_run_id,保证每个实例至多一个未结束轮次;根会话仍服从现有会话级互斥。所有约束须同时在 PostgreSQL 与 SQLite 实现,不能依赖只在 PostgreSQL 可用的锁语法。
|
||||
|
||||
子会话新增服务端专用 kind;普通会话列表默认不混入,任务卡可进入详情。用户可以查看其完整过程,执行完成不删除。删除根任务时先停止执行,再按会话/交付物保留规则清理。运行时关闭实例、释放资源与删除持久记录是不同操作。
|
||||
|
||||
```mermaid
|
||||
flowchart TD
|
||||
A[Assistant AgentEngine] --> T[Collaboration 工具]
|
||||
T --> C[CollaborationService]
|
||||
C --> D[(任务 / 轮次 / 邮箱 / Outbox)]
|
||||
D --> W[Dispatcher / Worker]
|
||||
W --> R[统一 AgentRunService]
|
||||
R --> E[子 AgentEngine]
|
||||
E --> H[HITL Broker]
|
||||
H --> U[主对话审批卡]
|
||||
E --> P[保存结果与交付物]
|
||||
P --> D
|
||||
D --> M[邮箱投递 / 等待恢复]
|
||||
M --> A
|
||||
```
|
||||
|
||||
从现有 session handler 中提取 `AgentRunService.Start/Resume/Interrupt` 及运行准备、结果持久化、交付物收集能力。HTTP handler、任务 worker、HITL 恢复共用服务;不在协作服务中模拟 HTTP 请求,也不只直接调用 AgentQA 而遗漏 handler 的结果处理。
|
||||
|
||||
任务创建、首轮、触发事件与 outbox 同一事务提交。Dispatcher 事务提交后入队;asynq/进程内 executor 只负责唤起执行,数据库 CAS、lease 和 owner token 决定谁能运行。无 Redis 模式也扫描未发送 outbox 和未领取工作,不能依赖进程内 goroutine 保证重启恢复。
|
||||
|
||||
## 7. 可靠投递与父级继续执行
|
||||
|
||||
### 7.1 消息不会自动变成新的任务
|
||||
|
||||
`send_message` 只写邮箱,不产生新轮次。运行中在下一轮模型调用前及自然结束前读取;idle 时留待下一次启动。`followup_task` 将“投递要求”和“确保有消费者”在事务中完成:要么交给当前轮次,要么在当前轮次结束后创建一个新轮次,不能落在退出竞态中丢失。
|
||||
|
||||
消息投递和 followup 路由在锁定 member/current_run 后确定。如果 `expected_run_id` 已变化,返回冲突,不把针对旧结果的返工投给新轮次。挂起期间只追加消息不等于恢复审批;排队、暂停和取消中的实例分别返回明确的 queued、paused 或 rejected 状态。
|
||||
|
||||
客户端请求 ID / 父工具调用 ID 映射为服务端去重键;模型重复输出同名工具但不同调用 ID 并不天然幂等,仍需重名、当前轮次和业务范围约束。`expected_run_id` 不匹配时返回冲突,不中断或覆盖后来的执行。
|
||||
|
||||
邮箱事件按接收者分配提交有序的序号,不用“全局自增 ID 大小”等同提交顺序。持久化上下文注入记录与游标推进应原子完成;刷新、崩溃后可回放相同事件,但不能重复写入模型历史。目标隔离在同一 collaboration,分页游标绑定接收者及筛选条件。
|
||||
|
||||
必须区分“进入持久上下文”和“父级已处理”:记录 `delivered_to_run` 后进程可能尚未调用模型。只有后续模型请求确实包含该事件,且父轮次完成或提交相关后续操作,才记录 `handled_by_run`。崩溃恢复时,未处理事件从持久消息或快照重新参与上下文构建,不能因投递游标已推进而丢弃。重新关联新父轮次不重复插入原消息。
|
||||
|
||||
### 7.2 等待是运行状态
|
||||
|
||||
短等待可在内存中等待事件;超过短等待阈值则写入 wait、引擎快照及已消费游标,置 `awaiting_children` 并释放计算资源。持久订阅先于再次检查事件,消除“检查后、订阅前完成”的丢唤醒窗口。
|
||||
|
||||
当前 `AgentEngine.Resume` 要求 answered AgentPrompt,`AgentRunSuspension` 也绑定 prompt_id。应抽出通用恢复载荷(`human_prompt / agent_wait`)及公共快照恢复逻辑,保留旧 HITL 数据兼容;不要创建伪造的“已批准 prompt”恢复 wait。wait 恢复时完成原 wait 工具调用并返回更新通知,运行时持久投递对应正文,再继续同一轮次。
|
||||
|
||||
快照必须同时覆盖 `pending_tool` 与 `between_rounds` 两种恢复阶段:显式 wait 恢复时补齐原工具结果;父级自然结束检查发现尚有子工作时,在轮次边界保存继续执行点,不伪造一个不存在的 wait 工具调用。现有 RunSnapshot 的 BlockedIndex/PendingRound 结构只覆盖前者,需要版本化扩展。等待阶段消息、步骤、事件游标和状态的提交要有一致的恢复协议,不能只保存一个 waiting 标记。
|
||||
|
||||
子轮次结果、交付物记录、终态、父邮箱事件及 outbox 在可提交的事务边界内发布;文件对象先写入,数据库引用后提交,孤立文件异步清理。只有可读取的结果提交后才通知“已完成”。
|
||||
|
||||
父级处理规则:
|
||||
|
||||
| 父级状态 | 子事件处理 |
|
||||
|---|---|
|
||||
| running | 写邮箱,在安全边界注入,不开第二个并行父轮次 |
|
||||
| awaiting_children | CAS 领取 wait,合并已到事件,恢复一次 |
|
||||
| awaiting_input | 保存事件,优先保留未决用户交互,不因子完成绕过它 |
|
||||
| active 但当前轮次已结束 | 仅运行时签发的完成/失败/中断/需用户输入事件,在匹配 continuation_generation 且关联 pending_result_runs 时可创建去重的协调后续轮次;普通 send_message 只排队 |
|
||||
| paused/needs_attention/failed/cancelling/cancelled/completed | 保存状态和结果,不自动唤醒 |
|
||||
|
||||
第一次 spawn 时,运行时为本次目标建立有限的继续执行资格;每次 spawn/followup 原子更新 pending_result_runs。资格受 generation、用户取消/暂停和总预算限制,只允许继续原目标,不允许子消息修改目标或额度。后台恢复由系统事件触发,不能通过在普通消息正文写“已完成”伪造。子审批首次进入待输入状态可通知父级一次,但不能因此反复启动父模型。
|
||||
|
||||
协作仍有未决子任务时,父级普通回复可结束当前轮次,但不能把整个目标标为完成。父级正常产生最终回答时,运行时在落库前进行终结检查:所有子轮次已退出、无未决 prompt/返工/待处理终态事件,且最后一次模型请求包含当前必需结果。若结果在模型请求之后到达,必须再给父级一轮处理机会;只“已经注入上下文”不够。检查通过后记录最终交付并统一关闭实例。这里判定的是执行流程结束,不是机器证明答案质量合格;失败分支仍需如实汇报。
|
||||
|
||||
父模型异常退出、被内容过滤、预算耗尽或用户中断不能走正常最终回答终结流程,分别保留 failed/needs_attention/paused/cancelled 等原因。与新子事件竞争时用协作锁和版本 CAS 决定继续或完成,不能先发布“任务已完成”再补查状态。流式文本可先展示,但最终完成标记必须等待该检查。
|
||||
|
||||
用户新消息、停止、回溯与系统唤醒共用会话互斥及 generation 检查。用户输入优先;新消息进入运行时更新上下文,回溯/删除使旧恢复资格失效。正常新消息不隐式取消所有旧任务;后台结果注入须标明目标,避免当作新问题的答案。
|
||||
|
||||
### 7.3 运行时读取与清理
|
||||
|
||||
结果读取使用内部服务接口,不注册为模型工具。子轮次完成后,运行时按 `member_id + run_id + result_version` 读取已提交结果、引用和交付物,生成带来源的父级上下文材料。短结果完整投递,长结果投递摘要、明确的截断标记及稳定资源引用;不能静默丢弃错误、阻塞或未完成项。完整文本可沿用已有的 `message.list` 操作读取所属子会话,文档/文件沿用现有资源读取能力;接入时必须验证新增子会话 kind 的授权与结果展开能力。不能只给出父级实际无工具可读的句柄;无法展开时应保留可交付原件并明确限制。用户查看完整过程沿用子会话详情。
|
||||
|
||||
清理遵循以下规则:
|
||||
|
||||
- 子轮次结束后释放执行槽位和临时执行资源,保留实例、会话及可恢复的工作区状态,允许后续返工。
|
||||
- 根任务完成时,在同一终结事务中校验 generation、无其他活跃/挂起轮次及未决交互、无待处理结果和 followup,并结束当前父轮次、保存最终交付与处理记录、关闭实例和唤醒资格。检查不能把即将结束的父轮次自身算成阻塞项。与并发 followup 争用同一协作状态锁,避免清理后仍入队。
|
||||
- 用户取消或删除时先进入 cancelling、阻止新工作并取消未决轮次和 prompt;待执行者退出后关闭实例。外部调用结果未知则保留待核实状态与审计信息,不宣称已回滚。
|
||||
- 沙箱、租约、临时文件的释放通过幂等清理任务完成;清理失败可重试,不重复运行 Agent。工作区需要恢复的内容先完成持久化,再释放资源。
|
||||
- 暂停不会关闭实例;恢复仍受当前权限和预算检查。关闭后的旧实例不能被消息或 followup 隐式重新打开。
|
||||
- 历史、结果和交付物按现有保留/删除规则处理,不随计算资源清理一并删除。
|
||||
|
||||
普通空闲卸载不同于根任务终结:卸载持有实例驻留租约,先禁止并发投递进入将被销毁的内存队列,再保存会话/工作区状态和未投递邮件,最后释放资源。send_message 可以直接写数据库邮箱而不加载实例;followup 先领取加载/执行资格再恢复。任务树关闭后不允许这种懒加载。分别配置最大实例数、最大驻留数和最大执行数,不能只限制并发模型请求而保留无限空闲沙箱。
|
||||
|
||||
## 8. 恢复、预算与写冲突
|
||||
|
||||
- 排队但未执行的轮次可以重新领取;审批/子任务等待可从已保存快照恢复。
|
||||
- 普通执行中进程崩溃不承诺任意点无损恢复。只读且可重放的轮次按策略重试;存在结果未知的写调用则置 `needs_attention`,保留证据并核实外部状态,不自动整轮重跑。
|
||||
- 租约过期后旧 owner 不得提交新结果或启动下一工具调用;外部写操作若不支持幂等键/版本条件,不能仅靠 fencing 保证恰好一次。
|
||||
- 同时限制工作空间、用户、整个协作和单轮次的执行并发、最大实例数、时间、token 与模型调用预算。创建时做准入,运行前预留额度,结束后结算;子调用必须汇总到根任务。
|
||||
- `max_completion_tokens` 只是单次模型输出限制,不能当作整个任务预算。供应商计费不精确或中断时,保留估算与实际值;预算不足不再分派新调用。
|
||||
- 并发槽位只计算实际执行,不让正在等待子任务的父级占满全部槽位。多租户公平排队,不在模型工具调用内无限阻塞等槽位。
|
||||
- 默认隔离沙箱。Wiki/文档写入按资源 ID 申请执行租约,并用版本条件/OCC 检测来自普通用户的并发编辑;仅有模型约定或协作内部锁不够。无法提供写入范围和冲突控制的能力暂不纳入并行委派。
|
||||
|
||||
## 9. 前端、结果与验收
|
||||
|
||||
主对话显示一组持久子任务卡片:Agent 名称、任务、运行状态、阻塞原因、结果摘要、交付物、查看过程、追加要求、停止。waiting 与 idle 区分,不能全部显示“运行中”。系统恢复产生的消息带“继续处理任务”来源,不伪造成用户消息。
|
||||
|
||||
结果建议结构:`run_id, result_version, status, summary, artifact_refs, evidence_refs, changes, unresolved_items, usage, error`。完整内容保存在子会话/交付物中,运行时负责读取并投递父级所需上下文。
|
||||
|
||||
assistant 检查运行时投递的结果与交付要求,不合格时用 followup 的 message 说明返工原因,运行时关联被修订的结果版本并产生新轮次。最终答案沿用现有普通模型输出,不要求额外的结构化“验收成功”协议,也不增加 acceptance 元数据或 review 参数。运行时记录哪些版本进入了最终父轮次及后续返工,但不自动推断语义验收通过。最终回复明确汇报交付物、实际修改、失败和未完成部分,不用“工具成功”替代任务验收。
|
||||
|
||||
## 10. 实施顺序与验收
|
||||
|
||||
1. **运行基础**:提取 AgentRunService,建立 collaboration/member/run、授权上下文、基本预算准入、数据库 CAS/outbox、子会话及结果持久化。验证单任务创建、执行、运行时读取、中断和返工;模型只注册六个协作工具。
|
||||
2. **协作闭环**:接入邮箱、增量游标、自然结束前检查、wait 挂起恢复、父级后续轮次、子审批转交、运行时终结/清理和主对话卡片。此阶段完成后才作为可用功能开放。
|
||||
3. **可靠性与并发**:完善预算结算、资源写冲突、失联回收、多副本/Lite 重启恢复及故障注入测试;通过对应验证后再开放并发写能力。
|
||||
4. **后续扩展**:共享 Agent、上下文 all、临时角色、多层委派和同级通信;每项独立设计授权与限额,不改变上述身份和生命周期。
|
||||
|
||||
核心验收场景:
|
||||
|
||||
- 同一 Agent 配置并行创建两个实例,历史、沙箱、结果互不混淆。
|
||||
- spawn 响应丢失后重试只产生一个实例;重复 followup 不产生两个轮次。
|
||||
- send_message 到 idle 不启动模型;followup 到 idle 恰好启动一次,到 finishing 的竞态也不丢消息。
|
||||
- 两个子任务完成事件同时到达、或事件早于 wait 注册,只恢复一个父轮次且不漏结果。
|
||||
- wait 在持久挂起后没有任何子事件也会按原 deadline 恢复并报告超时;重启不重置超时,也不取消仍在运行的子任务。
|
||||
- 主对话刷新、Redis 通知丢失后可从数据库恢复状态与消息;Lite 重启仍能领取待执行工作。
|
||||
- 子任务审批等待时另一个继续;主对话回答后恢复正确子轮次;重复/过期答案不执行写操作。
|
||||
- 运行中停止整个任务,迟到完成或审批不会重新唤醒;已发生修改被如实保留和展示。
|
||||
- 写操作后、结果落库前崩溃,标记结果待核实,不盲目重复执行。
|
||||
- 子消息不具备用户授权身份,跨租户/其他任务 target 被拒绝,授权撤回在恢复时生效。
|
||||
- 不合格交付物可以返工,运行时投递新版后父级再验收;最终可下载文件与验收结果一致。
|
||||
- 模型工具列表恰好包含六个协作工具;wait 仅通知更新,正文自动投递,wait 与后台投递不重复注入结果。
|
||||
- 子轮次结束后仍可 followup;根任务结束后运行时统一关闭,晚到 followup 不重新打开实例。
|
||||
- 清理与 followup 并发时只有一种合法结果;资源清理失败可幂等重试,历史与交付物仍可读取。
|
||||
- 普通消息发给 idle 父级不启动模型;系统终态事件仅在原任务仍有继续执行资格时唤醒,取消后不可复活。
|
||||
- 结果落库并推进投递游标后、模型请求前进程崩溃,恢复后结果仍参与父级处理,且不会重复写历史。
|
||||
- 子结果在父级最后一次模型请求之后到达,父级必须处理新版再终结;终结检查不会被父轮次自身阻塞。
|
||||
- 空闲卸载与消息/返工并发,消息不丢失,重新加载只发生一次;普通卸载保留返工能力,关闭后不能重新加载。
|
||||
- 父级对长结果有实际可用的完整读取路径;新增子会话 kind 不能绕过所有权检查或使引用不可读。
|
||||
|
||||
实现审查必须保持以下不变量:每个实例最多一个执行所有者;模型生成的消息不能伪造系统唤醒/用户授权;结果提交早于通知;投递不等于处理;终结时的输入版本覆盖必需结果;取消 generation 不可被迟到事件恢复;运行时卸载不等于关闭实例;wait 的截止时间可跨重启执行。数据库实现、快照恢复、资源读取与故障注入场景未通过前,不以“接口与 Codex 相似”作为发布依据。
|
||||
|
||||
本次完成了官方源码克隆、固定提交的实现/测试阅读,以及设计状态转换和竞态场景审查;没有实现新工具,没有编译运行 Codex 的 Rust 测试或 WeKnora 端到端测试。上述验收项是实现发布门槛,源码对照不等于证明多副本、恢复、预算或写入语义已经正确。
|
||||
|
||||
|
||||
### 跨父轮次续跑与产物读取(2026-10-18)
|
||||
|
||||
- 上一父轮次正常完成后,下一次用户输入创建新的协作组,并继承同账户、同空间、同主会话最近已完成组的空闲子实例标识。`list_agents` 通过 `previous_turn` 标识可继续的实例;`followup_task` 创建新子轮次但复用原子会话及其沙箱绑定。旧组仍保持完成状态,通过 CAS 记录唯一后继协作组,避免并发新请求克隆同一子会话;后继尚未创建时进程退出,下次请求复用该领取记录。旧邮箱、审批、租约、去重键和事件不继承。最近组若已取消,不跨过它继承更早实例。
|
||||
- 继承的实例在实际追加任务前不显示为本轮时间轴卡片,也不占用本轮 16 个实例额度。续跑卡片锚定 `followup_task` 所在位置。
|
||||
- 子轮次结果携带已持久化的文件元数据。父引擎从已投递事件账本恢复文件引用,完成时把文件绑定到父消息;普通 Markdown 链接与图片写法使用同一文件卡片和预览链路。同名文件按稳定资源引用区分,子文件来源路径按子会话隔离,避免误判版本。
|
||||
- 协作执行的 `read_file` 支持已交付文件的 `resource://` 引用,也支持无歧义的 `sandbox:<文件名>`。读取范围为当前会话产物与运行时绑定的已完成子轮次消息;校验空间、账户、消息及文件删除状态,按资源原存储后端读取,单文件读取上限 8 MiB,文本按现有行/字符游标分页。子沙箱目录不会暴露给父 Agent;需要继续编辑时仍委派原子 Agent。
|
||||
- 自动回归覆盖跨轮重启、同子会话复用、追加请求去重、旧组取消隔离、跨账户/会话拒绝、长行分页、同名文件歧义,以及续跑卡片的时间轴位置。
|
||||
|
||||
### 主子 Agent 的职责边界(2026-10-18)
|
||||
|
||||
- 用户要求已有智能体执行任务时,父 Agent 负责委派、沟通、读取交付产物、检查结果及最终汇总;子 Agent 使用自身模板、MCP、Skills 和工作区执行。配置查询是数据读取,不是角色切换,也不会转移工具、沙箱或审批授权。
|
||||
- 已委派工作不由父 Agent 重复调用 MCP 或重跑 Skill。补充要求和返工通过 `send_message` / `followup_task` 交回原实例;父 Agent 仍可使用自己的工具处理不重叠的工作。
|
||||
- 等待审批、失败、恢复不是自动接管信号。用户明确要求父 Agent 接管时,先中断仍活动的子任务并确认停止,检查已发生的效果,再按父 Agent 自身权限执行。
|
||||
- 这部分是集中在既有角色指导中的行为约定,不声称运行时能够判断所有语义重复。运行时继续维护独立权限、审批归属、取消与执行所有权,并保留匹配子审批调用的防重复检查;不以共享 MCP 服务为理由整体封禁父 Agent。
|
||||
File diff suppressed because it is too large
Load Diff
|
|
@ -0,0 +1,67 @@
|
|||
/** Current state of a delegated run, independent of its parent answer. */
|
||||
export interface CollaborationProgress {
|
||||
phase?: string
|
||||
tool_name?: string
|
||||
tool_call_id?: string
|
||||
iteration?: number
|
||||
updated_at?: string
|
||||
}
|
||||
|
||||
export interface CollaborationTaskStatus {
|
||||
id: string
|
||||
name: string
|
||||
display_name?: string
|
||||
agent_id: string
|
||||
session_id: string
|
||||
run_id: string
|
||||
status: string
|
||||
progress?: CollaborationProgress | null
|
||||
prompt_id?: string
|
||||
latest_message?: string
|
||||
}
|
||||
|
||||
export interface CollaborationStatus {
|
||||
group_id: string
|
||||
revision: number
|
||||
tasks: CollaborationTaskStatus[]
|
||||
}
|
||||
|
||||
export interface CollaborationStatusStreamEvent {
|
||||
response_type: 'collaboration_status'
|
||||
/** Parent request identifier; child run identifiers live in tasks. */
|
||||
id: string
|
||||
assistant_message_id?: string
|
||||
data: CollaborationStatus
|
||||
}
|
||||
|
||||
export interface ProgressStreamEvent {
|
||||
response_type: 'progress'
|
||||
id: string
|
||||
assistant_message_id?: string
|
||||
/** Cumulative visible progress text for this event, safe to replay. */
|
||||
content: string
|
||||
done: boolean
|
||||
data: { event_id: string; iteration?: number }
|
||||
}
|
||||
|
||||
/** Persisted agent step fields used when rebuilding the visible timeline. */
|
||||
export interface AgentStepRecord extends Record<string, unknown> {
|
||||
iteration?: number
|
||||
thought?: string
|
||||
reasoning_content?: string
|
||||
progress?: string
|
||||
progress_event_id?: string
|
||||
}
|
||||
|
||||
export interface ChatHistoryMessage extends Record<string, unknown> {
|
||||
collaboration_status?: CollaborationStatus
|
||||
agent_steps?: AgentStepRecord[]
|
||||
}
|
||||
|
||||
/** An explicit protocol correction replaces only this answer segment. */
|
||||
export interface AnswerStreamMetadata {
|
||||
event_id: string
|
||||
replace?: boolean
|
||||
truncated?: boolean
|
||||
is_fallback?: boolean
|
||||
}
|
||||
|
|
@ -4,6 +4,8 @@ import { generateRandomString } from '@/utils/index';
|
|||
import i18n from '@/i18n';
|
||||
import { getApiBaseUrl } from '@/utils/api-base';
|
||||
import type { AssistantAccessLevel } from '@/api/assistant';
|
||||
export type { CollaborationStatus, CollaborationTaskStatus, CollaborationProgress,
|
||||
CollaborationStatusStreamEvent, ProgressStreamEvent, AgentStepRecord, ChatHistoryMessage } from './streamTypes';
|
||||
import {
|
||||
sanitizeStreamRequestBody,
|
||||
type StreamRequestMeta,
|
||||
|
|
@ -107,6 +109,15 @@ export function useStream() {
|
|||
const sentAt = performance.now();
|
||||
const requestID = generateRandomString(12);
|
||||
let firstAnswerLogged = false;
|
||||
let receivedAssistantId = '';
|
||||
let receivedTerminal = false;
|
||||
let reconnectAttempts = 0;
|
||||
let streamMethod = params.method;
|
||||
// Never repeat an accepted POST: recovery attaches to its persisted message.
|
||||
const canReconnect = () => !embedToken && receivedAssistantId && !receivedTerminal &&
|
||||
(params.url === '/api/v1/agent-chat' || params.url === '/api/v1/sessions/continue-stream') &&
|
||||
myGeneration === streamGeneration && !streamAbort.signal.aborted;
|
||||
|
||||
|
||||
try {
|
||||
let url =
|
||||
|
|
@ -202,8 +213,25 @@ export function useStream() {
|
|||
// Wrapped so an expired access token can be refreshed and the request
|
||||
// replayed once. Nothing has been streamed to the UI yet when the
|
||||
// handshake 401s, so the replay is invisible to the user.
|
||||
const runStream = (authToken: string) => fetchEventSource(url, {
|
||||
method: params.method,
|
||||
const runStream = async (authToken: string) => {
|
||||
const connection = new AbortController();
|
||||
const abortConnection = () => connection.abort();
|
||||
streamAbort.signal.addEventListener('abort', abortConnection, { once: true });
|
||||
let idleTimer: ReturnType<typeof setTimeout>;
|
||||
let rejectIdle: (reason: Error) => void;
|
||||
const idle = new Promise<never>((_, reject) => { rejectIdle = reject; });
|
||||
const armIdle = () => {
|
||||
clearTimeout(idleTimer);
|
||||
if (!canReconnect()) return;
|
||||
idleTimer = setTimeout(() => {
|
||||
rejectIdle(new Error('stream heartbeat timed out'));
|
||||
connection.abort();
|
||||
}, 30000);
|
||||
};
|
||||
armIdle();
|
||||
try {
|
||||
await Promise.race([idle, fetchEventSource(url, {
|
||||
method: streamMethod,
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
"Authorization": embedToken ? `Embed ${embedToken}` : `Bearer ${authToken}`,
|
||||
|
|
@ -214,10 +242,10 @@ export function useStream() {
|
|||
...(params.embed_visitor_id ? { "X-Embed-Visitor": params.embed_visitor_id } : {}),
|
||||
},
|
||||
body:
|
||||
params.method == "POST"
|
||||
streamMethod == "POST"
|
||||
? JSON.stringify(postBody)
|
||||
: null,
|
||||
signal: streamAbort.signal,
|
||||
signal: connection.signal,
|
||||
openWhenHidden: true,
|
||||
|
||||
onopen: async (res) => {
|
||||
|
|
@ -225,12 +253,19 @@ export function useStream() {
|
|||
if (res.status === 401) throw new StreamAuthError(res.status);
|
||||
if (!res.ok) throw new Error(`HTTP ${res.status}`);
|
||||
console.log(`[TTFB] response:headers request_id=${requestID} elapsed_ms=${(performance.now() - sentAt).toFixed(1)}`);
|
||||
isLoading.value = false;
|
||||
if (myGeneration === streamGeneration) isLoading.value = false;
|
||||
},
|
||||
|
||||
onmessage: (ev) => {
|
||||
if (myGeneration !== streamGeneration) return
|
||||
const parsed = JSON.parse(ev.data);
|
||||
reconnectAttempts = 0;
|
||||
if (parsed?.response_type === 'agent_query' && typeof parsed.assistant_message_id === 'string') {
|
||||
receivedAssistantId = parsed.assistant_message_id;
|
||||
}
|
||||
if (['complete', 'stop', 'error'].includes(parsed?.response_type)) receivedTerminal = true;
|
||||
armIdle();
|
||||
if (parsed?.response_type === 'heartbeat') return;
|
||||
// Log first answer chunk for end-to-end TTFB measurement.
|
||||
// Filter by event type so non-answer events (references, tool
|
||||
// calls, etc.) don't count as the "first token" arrival.
|
||||
|
|
@ -255,23 +290,52 @@ export function useStream() {
|
|||
// POST may still be open waiting for the session title. Both share one
|
||||
// controller, so only the current stream may stop it; otherwise the
|
||||
// old connection closing cuts the follow-up off mid-answer.
|
||||
if (canReconnect()) throw new Error('stream closed before the turn completed');
|
||||
if (myGeneration === streamGeneration) stopStream();
|
||||
},
|
||||
});
|
||||
})]);
|
||||
} finally {
|
||||
clearTimeout(idleTimer!);
|
||||
streamAbort.signal.removeEventListener('abort', abortConnection);
|
||||
connection.abort();
|
||||
}
|
||||
};
|
||||
|
||||
await runStreamWithAuthRetry({
|
||||
run: runStream,
|
||||
initialToken: token,
|
||||
isEmbed: Boolean(embedToken),
|
||||
isCurrent: () => myGeneration === streamGeneration && !streamAbort.signal.aborted,
|
||||
refreshAccessToken: () => refreshAccessTokenShared({
|
||||
messages: {
|
||||
pleaseRelogin: i18n.global.t('error.pleaseRelogin'),
|
||||
tokenRefreshFailed: i18n.global.t('error.tokenRefreshFailed'),
|
||||
},
|
||||
}),
|
||||
reloginMessage: i18n.global.t('error.pleaseRelogin'),
|
||||
});
|
||||
while (myGeneration === streamGeneration && !streamAbort.signal.aborted) {
|
||||
try {
|
||||
await runStreamWithAuthRetry({
|
||||
run: runStream,
|
||||
initialToken: token,
|
||||
isEmbed: Boolean(embedToken),
|
||||
isCurrent: () => myGeneration === streamGeneration && !streamAbort.signal.aborted,
|
||||
refreshAccessToken: () => refreshAccessTokenShared({
|
||||
messages: {
|
||||
pleaseRelogin: i18n.global.t('error.pleaseRelogin'),
|
||||
tokenRefreshFailed: i18n.global.t('error.tokenRefreshFailed'),
|
||||
},
|
||||
}),
|
||||
reloginMessage: i18n.global.t('error.pleaseRelogin'),
|
||||
});
|
||||
break;
|
||||
} catch (err) {
|
||||
if (!canReconnect() || isStreamAuthError(err) || reconnectAttempts >= 8) throw err;
|
||||
reconnectAttempts++;
|
||||
// The server may still be restarting. A stop/new turn invalidates
|
||||
// this retry before it can attach or change visible state.
|
||||
await new Promise<void>((resolve) => {
|
||||
const done = () => {
|
||||
clearTimeout(timer);
|
||||
streamAbort.signal.removeEventListener('abort', done);
|
||||
resolve();
|
||||
};
|
||||
const timer = setTimeout(done, Math.min(1000 * 2 ** (reconnectAttempts - 1), 5000));
|
||||
streamAbort.signal.addEventListener('abort', done, { once: true });
|
||||
});
|
||||
if (myGeneration !== streamGeneration || streamAbort.signal.aborted) return;
|
||||
streamMethod = 'GET';
|
||||
url = `${apiUrl}/api/v1/sessions/continue-stream/${encodeURIComponent(params.session_id)}?message_id=${encodeURIComponent(receivedAssistantId)}`;
|
||||
}
|
||||
}
|
||||
} catch (err) {
|
||||
// A superseded stream failing must not surface as the current error or
|
||||
// abort the stream that replaced it (see onclose).
|
||||
|
|
|
|||
|
|
@ -118,3 +118,114 @@ test('the current stream failing still reports the error and stops', async () =>
|
|||
a.resolve()
|
||||
await first
|
||||
})
|
||||
|
||||
test('a disconnected accepted agent POST resumes by GET without executing the query twice', async () => {
|
||||
let stream!: ReturnType<typeof useStream>
|
||||
await renderToString(createSSRApp({ setup() { stream = useStream(); return () => null } }))
|
||||
const base = transport.calls.length
|
||||
const run = stream.startStream({ session_id: 'parent', query: 'spawn children', method: 'POST', url: '/api/v1/agent-chat' })
|
||||
const post = await nextCall(base + 1)
|
||||
post.options.onmessage({ data: JSON.stringify({ response_type: 'agent_query', id: 'r1', assistant_message_id: 'answer-1' }) })
|
||||
post.reject(new Error('server restarted'))
|
||||
await new Promise(r => setTimeout(r, 1050))
|
||||
const resumed = await nextCall(base + 2)
|
||||
assert.match(resumed.url, /\/sessions\/continue-stream\/parent\?message_id=answer-1$/)
|
||||
assert.equal((resumed.options as any).method, 'GET')
|
||||
assert.equal((resumed.options as any).body, null)
|
||||
assert.equal(stream.isStreaming.value, true)
|
||||
assert.equal(stream.error.value, null)
|
||||
resumed.options.onmessage({ data: JSON.stringify({ response_type: 'complete', id: 'r1' }) })
|
||||
resumed.options.onclose()
|
||||
resumed.resolve()
|
||||
await run
|
||||
assert.equal(stream.isStreaming.value, false)
|
||||
})
|
||||
|
||||
test('stop during reconnect backoff prevents the old parent from attaching again', async () => {
|
||||
let stream!: ReturnType<typeof useStream>
|
||||
await renderToString(createSSRApp({ setup() { stream = useStream(); return () => null } }))
|
||||
const base = transport.calls.length
|
||||
const run = stream.startStream({ session_id: 'parent', query: 'spawn children', method: 'POST', url: '/api/v1/agent-chat' })
|
||||
const post = await nextCall(base + 1)
|
||||
post.options.onmessage({ data: JSON.stringify({ response_type: 'agent_query', assistant_message_id: 'answer-1' }) })
|
||||
post.reject(new Error('connection reset'))
|
||||
await new Promise(r => setTimeout(r, 20))
|
||||
stream.stopStream()
|
||||
await run
|
||||
await new Promise(r => setTimeout(r, 1050))
|
||||
assert.equal(transport.calls.length, base + 1)
|
||||
assert.equal(stream.isStreaming.value, false)
|
||||
assert.equal(stream.error.value, null)
|
||||
})
|
||||
|
||||
test('EOF without complete attaches to the original message rather than declaring completion', async () => {
|
||||
let stream!: ReturnType<typeof useStream>
|
||||
await renderToString(createSSRApp({ setup() { stream = useStream(); return () => null } }))
|
||||
const base = transport.calls.length
|
||||
const run = stream.startStream({ session_id: 'parent', query: 'work', method: 'POST', url: '/api/v1/agent-chat' })
|
||||
const post = await nextCall(base + 1)
|
||||
post.options.onmessage({ data: JSON.stringify({ response_type: 'agent_query', assistant_message_id: 'answer-1' }) })
|
||||
try { post.options.onclose(); assert.fail('an incomplete EOF must request recovery') }
|
||||
catch (error) { post.reject(error) }
|
||||
await new Promise(r => setTimeout(r, 1050))
|
||||
const resumed = await nextCall(base + 2)
|
||||
assert.equal((resumed.options as any).method, 'GET')
|
||||
resumed.options.onmessage({ data: JSON.stringify({ response_type: 'complete' }) })
|
||||
resumed.options.onclose()
|
||||
resumed.resolve()
|
||||
await run
|
||||
assert.equal(stream.error.value, null)
|
||||
})
|
||||
|
||||
test('a new stream supersedes an old reconnect without being stopped or receiving old output', async () => {
|
||||
let stream!: ReturnType<typeof useStream>
|
||||
await renderToString(createSSRApp({ setup() { stream = useStream(); return () => null } }))
|
||||
const base = transport.calls.length
|
||||
const first = stream.startStream({ session_id: 'parent', query: 'old', method: 'POST', url: '/api/v1/agent-chat' })
|
||||
const post = await nextCall(base + 1)
|
||||
post.options.onmessage({ data: JSON.stringify({ response_type: 'agent_query', assistant_message_id: 'old-answer' }) })
|
||||
post.reject(new Error('server restarted'))
|
||||
await new Promise(r => setTimeout(r, 20))
|
||||
const second = stream.startStream({ session_id: 'another-session', query: 'new', method: 'POST', url: '/api/v1/agent-chat' })
|
||||
const current = await nextCall(base + 2)
|
||||
await first
|
||||
assert.equal(transport.calls.length, base + 2)
|
||||
assert.equal(current.options.signal.aborted, false)
|
||||
assert.equal(stream.isStreaming.value, true)
|
||||
assert.equal(stream.error.value, null)
|
||||
current.options.onmessage({ data: JSON.stringify({ response_type: 'complete' }) })
|
||||
current.options.onclose()
|
||||
current.resolve()
|
||||
await second
|
||||
})
|
||||
|
||||
test('a silent broken proxy connection times out and resumes by GET; heartbeats stay out of chat', async (t) => {
|
||||
let stream!: ReturnType<typeof useStream>
|
||||
await renderToString(createSSRApp({ setup() { stream = useStream(); return () => null } }))
|
||||
const chunks: unknown[] = []
|
||||
stream.onChunk(value => chunks.push(value))
|
||||
const base = transport.calls.length
|
||||
t.mock.timers.enable({ apis: ['setTimeout'] })
|
||||
const run = stream.startStream({ session_id: 'parent', query: 'work', method: 'POST', url: '/api/v1/agent-chat' })
|
||||
const post = transport.calls[base]
|
||||
post.options.onmessage({ data: JSON.stringify({ response_type: 'agent_query', assistant_message_id: 'answer-1' }) })
|
||||
t.mock.timers.tick(20000)
|
||||
post.options.onmessage({ data: JSON.stringify({ response_type: 'heartbeat' }) })
|
||||
assert.equal(chunks.length, 1)
|
||||
t.mock.timers.tick(20000)
|
||||
assert.equal(post.options.signal.aborted, false)
|
||||
t.mock.timers.tick(10001)
|
||||
for (let i = 0; i < 20; i++) await Promise.resolve()
|
||||
assert.equal(post.options.signal.aborted, true)
|
||||
t.mock.timers.tick(1000)
|
||||
for (let i = 0; i < 20; i++) await Promise.resolve()
|
||||
const resumed = transport.calls[base + 1]
|
||||
assert.ok(resumed)
|
||||
assert.equal((resumed.options as any).method, 'GET')
|
||||
resumed.options.onmessage({ data: JSON.stringify({ response_type: 'complete' }) })
|
||||
resumed.options.onclose()
|
||||
resumed.resolve()
|
||||
await run
|
||||
assert.equal(stream.isStreaming.value, false)
|
||||
assert.equal(stream.error.value, null)
|
||||
})
|
||||
|
|
|
|||
|
|
@ -8,6 +8,25 @@ const source = readFileSync(new URL('./Input-field.vue', import.meta.url), 'utf8
|
|||
const focusCode = source.slice(source.indexOf('const focusInput ='), source.indexOf('const onInput ='))
|
||||
const sendCode = source.slice(source.indexOf('const createSession ='), source.indexOf('const updateAgentModeDropdownPosition ='))
|
||||
|
||||
test('host page navigation preserves the assistant draft and uploads but clears the main chat composer', () => {
|
||||
const start = source.indexOf('onBeforeRouteUpdate(')
|
||||
const routeCode = source.slice(start, source.indexOf('defineExpose(', start))
|
||||
for (const embeddedMode of [true, false]) {
|
||||
const state = { draft: '还没有写完的问题', uploads: ['draft.pdf'], navigations: 0 }
|
||||
let beforeUpdate
|
||||
vm.runInNewContext(ts.transpile(routeCode), {
|
||||
props: { embeddedMode },
|
||||
onBeforeRouteUpdate: callback => { beforeUpdate = callback },
|
||||
clearvalue: () => { state.draft = '' },
|
||||
clearPendingUploads: () => { state.uploads = [] },
|
||||
})
|
||||
beforeUpdate({ params: { kbId: 'next' } }, { params: { kbId: 'previous' } }, () => { state.navigations++ })
|
||||
assert.equal(state.draft, embeddedMode ? '还没有写完的问题' : '')
|
||||
assert.deepEqual(state.uploads, embeddedMode ? ['draft.pdf'] : [])
|
||||
assert.equal(state.navigations, 1, 'preserving an assistant draft must not block page navigation')
|
||||
}
|
||||
})
|
||||
|
||||
for (const mode of ['normal', 'embedded', 'after', 'inject']) {
|
||||
test(`${mode} send clears the draft and restores focus after the DOM update`, async () => {
|
||||
const effects = [], ticks = []
|
||||
|
|
|
|||
|
|
@ -2745,8 +2745,12 @@ const handleStop = async () => {
|
|||
}
|
||||
|
||||
onBeforeRouteUpdate((to, from, next) => {
|
||||
clearvalue()
|
||||
clearPendingUploads()
|
||||
// The route belongs to the page behind an embedded assistant. Its draft
|
||||
// and uploads belong to the assistant session, which the host manages.
|
||||
if (!props.embeddedMode) {
|
||||
clearvalue()
|
||||
clearPendingUploads()
|
||||
}
|
||||
next()
|
||||
})
|
||||
|
||||
|
|
|
|||
|
|
@ -7,6 +7,7 @@ import { compileScript, parse } from '@vue/compiler-sfc'
|
|||
import * as vue from 'vue'
|
||||
import * as pinia from 'pinia'
|
||||
import ts from 'typescript'
|
||||
import * as childAgentTabs from '../../composables/useChildAgentTabs'
|
||||
|
||||
const filename = fileURLToPath(new URL('./AssistantPanel.vue', import.meta.url))
|
||||
const { descriptor } = parse(readFileSync(filename, 'utf8'), { filename })
|
||||
|
|
@ -94,6 +95,8 @@ async function fixture(
|
|||
DialogPlugin: { confirm: (options: any) => { dialogs.push(options); return { destroy() {} } } },
|
||||
},
|
||||
'@/views/chat/index.vue': ChatView,
|
||||
'@/views/chat/components/ChildAgentTabBar.vue': emptyComponent,
|
||||
'@/composables/useChildAgentTabs': childAgentTabs,
|
||||
'@/components/Input-field.vue': emptyComponent,
|
||||
'@/components/PanelResizeHandle.vue': emptyComponent,
|
||||
'./AssistantContextMenu.vue': emptyComponent,
|
||||
|
|
@ -479,6 +482,8 @@ test('the open dialog and the selection go with the message, the selection only
|
|||
f.assistant.setPageSelection({ text: 'Run setup.', field: 'Content', ref: 'e2', startLine: 7, endLine: 7 })
|
||||
f.assistant.open({ query: 'Polish this' })
|
||||
await flush()
|
||||
assert.deepEqual(Array.from(f.sent[0].scope.knowledgeBaseIds), [],
|
||||
'the current page must not become an explicit KB selection')
|
||||
assert.equal(JSON.stringify(f.sent[0].scope.pageContext), JSON.stringify({
|
||||
knowledge_base_id: 'kb-a', view: 'Edit Markdown',
|
||||
selection: { text: 'Run setup.', field: 'Content', ref: 'e2', start_line: 7, end_line: 7 },
|
||||
|
|
|
|||
|
|
@ -8,10 +8,14 @@
|
|||
@start="startResize" @resize="resize" @end="resizing = false" />
|
||||
|
||||
<header class="assistant-panel__header">
|
||||
<span class="assistant-panel__header-icon" aria-hidden="true">
|
||||
<t-icon name="compass" />
|
||||
</span>
|
||||
<span class="assistant-panel__title">{{ assistantName }}</span>
|
||||
<ChildAgentTabBar header-mode :tabs="childTabs.tabs.value"
|
||||
:active-id="childTabs.activeId.value" :attention="childTabs.attention.value"
|
||||
@select="selectConversationTab" @close="childTabs.close">
|
||||
<template #parent>
|
||||
<span class="assistant-panel__header-icon" aria-hidden="true"><t-icon name="compass" /></span>
|
||||
<span class="assistant-panel__title">{{ assistantName }}</span>
|
||||
</template>
|
||||
</ChildAgentTabBar>
|
||||
<t-tooltip :content="t('assistant.newConversation')" placement="bottom">
|
||||
<button type="button" class="assistant-panel__action" :disabled="!assistant.sessionId || starting"
|
||||
:aria-label="t('assistant.newConversation')" @click="startNewConversation">
|
||||
|
|
@ -121,10 +125,12 @@
|
|||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { computed, onMounted, onUnmounted, ref, watch } from 'vue'
|
||||
import { computed, onMounted, onUnmounted, provide, ref, watch } from 'vue'
|
||||
import { useI18n } from 'vue-i18n'
|
||||
import { DialogPlugin, MessagePlugin } from 'tdesign-vue-next'
|
||||
import ChatView from '@/views/chat/index.vue'
|
||||
import ChildAgentTabBar from '@/views/chat/components/ChildAgentTabBar.vue'
|
||||
import { createChildAgentTabs, childAgentTabsKey } from '@/composables/useChildAgentTabs'
|
||||
import InputField from '@/components/Input-field.vue'
|
||||
import PanelResizeHandle from '@/components/PanelResizeHandle.vue'
|
||||
import AssistantContextMenu from './AssistantContextMenu.vue'
|
||||
|
|
@ -147,6 +153,8 @@ import { removeSession, SESSION_MUTATION_EVENT, type SessionMutationDetail } fro
|
|||
import type { PageContextPayload } from '@/api/chat/streame'
|
||||
|
||||
const { t } = useI18n()
|
||||
const childTabs = createChildAgentTabs()
|
||||
provide(childAgentTabsKey, childTabs)
|
||||
const assistant = useAssistantStore()
|
||||
const auth = useAuthStore()
|
||||
useAssistantDataChange(() => { void auth.refreshFromAuthMe() }, { areas: ['workspace'] })
|
||||
|
|
@ -227,8 +235,8 @@ const starters = computed(() => {
|
|||
return [t('assistant.starters.agents'), t('assistant.starters.formats'), t('assistant.starters.createWiki')]
|
||||
})
|
||||
|
||||
// The backend only honours a page context inside the run's search scope, so
|
||||
// the page's knowledge base travels with it.
|
||||
// Page context is a hint, not an explicit retrieval selection. The backend
|
||||
// validates it against the agent's scope; only user selections narrow that scope.
|
||||
const hostScope = () => {
|
||||
const context = assistant.contextAttached ? assistant.pageContext : null
|
||||
const title = assistant.contextAttached ? assistant.pageTitle : ''
|
||||
|
|
@ -245,7 +253,7 @@ const hostScope = () => {
|
|||
if (view) pageContext.view = view
|
||||
if (selection) pageContext.selection = toPageSelectionPayload(selection)
|
||||
return {
|
||||
knowledgeBaseIds: context?.knowledgeBaseId ? [context.knowledgeBaseId] : [],
|
||||
knowledgeBaseIds: [],
|
||||
pageContext,
|
||||
assistantAccess,
|
||||
}
|
||||
|
|
@ -286,6 +294,7 @@ watch(() => [assistant.visible, assistant.pendingRequest] as const, ([visible, r
|
|||
}, { immediate: true })
|
||||
|
||||
const showHistory = ref(false)
|
||||
const selectConversationTab = (id: string) => { showHistory.value = false; childTabs.select(id) }
|
||||
const history = ref<SessionSummary[]>([])
|
||||
const historyPage = ref(0)
|
||||
const historyTotal = ref(0)
|
||||
|
|
@ -390,11 +399,13 @@ async function validateSession(id: string) {
|
|||
}
|
||||
|
||||
watch(() => assistant.sessionId, (id) => {
|
||||
childTabs.reset()
|
||||
if (id !== initialMessage.value?.sessionId) initialMessage.value = null
|
||||
void validateSession(id)
|
||||
}, { immediate: true })
|
||||
|
||||
watch(conversationOwner, () => {
|
||||
childTabs.reset()
|
||||
++historyGeneration
|
||||
history.value = []
|
||||
historyTotal.value = 0
|
||||
|
|
@ -713,13 +724,13 @@ onUnmounted(() => {
|
|||
|
||||
<style lang="less">
|
||||
html.has-assistant-dock {
|
||||
.t-drawer:not(.t-drawer--attach),
|
||||
.t-drawer:not(.t-drawer--attach):not(.chat-artifacts-drawer),
|
||||
.t-dialog__ctx--fixed .t-dialog__mask,
|
||||
.t-dialog__ctx--fixed .t-dialog__wrap {
|
||||
width: calc(100% - var(--assistant-dock-width));
|
||||
}
|
||||
|
||||
.t-drawer--right:not(.t-drawer--attach) {
|
||||
.t-drawer--right:not(.t-drawer--attach):not(.chat-artifacts-drawer) {
|
||||
right: var(--assistant-dock-width);
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -89,6 +89,7 @@
|
|||
}
|
||||
}
|
||||
|
||||
.answer-toolbar--persistent,
|
||||
.bot_msg:hover :deep(.answer-toolbar),
|
||||
.bot_msg:focus-within :deep(.answer-toolbar),
|
||||
.agent-stream-display:hover .answer-toolbar,
|
||||
|
|
|
|||
|
|
@ -0,0 +1,29 @@
|
|||
// Shared by the assistant conversation and child-agent detail viewport.
|
||||
.chat-scrollbar() {
|
||||
scrollbar-gutter: stable;
|
||||
scrollbar-width: thin;
|
||||
scrollbar-color: var(--td-component-stroke) transparent;
|
||||
|
||||
&:hover,
|
||||
&:focus-within {
|
||||
scrollbar-color: var(--td-scrollbar-color) transparent;
|
||||
}
|
||||
|
||||
&::-webkit-scrollbar {
|
||||
width: 6px;
|
||||
}
|
||||
|
||||
&::-webkit-scrollbar-track {
|
||||
background: transparent;
|
||||
}
|
||||
|
||||
&::-webkit-scrollbar-thumb {
|
||||
border-radius: var(--app-radius-sm);
|
||||
background: var(--td-component-stroke);
|
||||
}
|
||||
|
||||
&:hover::-webkit-scrollbar-thumb,
|
||||
&:focus-within::-webkit-scrollbar-thumb {
|
||||
background: var(--td-scrollbar-color);
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,19 @@
|
|||
import assert from 'node:assert/strict'
|
||||
import { readFileSync } from 'node:fs'
|
||||
import test from 'node:test'
|
||||
import vm from 'node:vm'
|
||||
|
||||
test('renderer mount failure becomes a visible preview error instead of a blank page', () => {
|
||||
const source = readFileSync(new URL('./document-preview.vue', import.meta.url), 'utf8')
|
||||
const hook = source.slice(source.indexOf('onErrorCaptured((err)'), source.indexOf("const previewType ="))
|
||||
assert.ok(hook.startsWith('onErrorCaptured('))
|
||||
const error = { value: '' }, loading = { value: true }
|
||||
let handler
|
||||
vm.runInNewContext(hook, {
|
||||
onErrorCaptured: callback => { handler = callback }, error, loading,
|
||||
t: key => key, console: { error() {} },
|
||||
})
|
||||
assert.equal(handler(new TypeError('Cannot read properties of null')), false)
|
||||
assert.equal(error.value, 'preview.loadFailed')
|
||||
assert.equal(loading.value, false)
|
||||
})
|
||||
|
|
@ -1,7 +1,7 @@
|
|||
// @ts-nocheck
|
||||
<script setup lang="ts">
|
||||
import { indexEmbeddedSourceImages } from '@/utils/sourceImage';
|
||||
import { ref, shallowRef, watch, onMounted, onUnmounted, nextTick, defineAsyncComponent } from 'vue';
|
||||
import { ref, shallowRef, watch, onMounted, onUnmounted, onErrorCaptured, nextTick, defineAsyncComponent } from 'vue';
|
||||
import { previewKnowledgeFile } from '@/api/knowledge-base/index';
|
||||
import { previewTemporaryAttachment } from '@/api/chat/temporary-attachments';
|
||||
import { downloadArtifact } from '@/api/chat';
|
||||
|
|
@ -79,6 +79,14 @@ const emit = defineEmits<{
|
|||
|
||||
const loading = ref(false);
|
||||
const error = ref('');
|
||||
// Async renderer setup/mount failures do not emit the renderer's `error` event.
|
||||
// Surface them in the preview instead of leaving an empty document area.
|
||||
onErrorCaptured((err) => {
|
||||
error.value = t('preview.loadFailed');
|
||||
loading.value = false;
|
||||
console.error('Document renderer failed:', err);
|
||||
return false;
|
||||
});
|
||||
const previewType = ref<FilePreviewKind>('unsupported');
|
||||
const blobUrl = ref('');
|
||||
const textContent = ref('');
|
||||
|
|
|
|||
|
|
@ -48,7 +48,7 @@ function loadComposable(name: string) {
|
|||
runInNewContext(transpile(readFileSync(join(srcDir, 'composables', `${file}.ts`), 'utf8')), {
|
||||
exports,
|
||||
require: (path: string) => {
|
||||
if (path === 'vue') return vue
|
||||
if (path === 'vue') return { ...vue, inject: (_key: unknown, fallback: unknown) => fallback }
|
||||
if (path.startsWith('./')) return load(path.slice(2))
|
||||
return stub
|
||||
},
|
||||
|
|
@ -65,7 +65,7 @@ function runSetup(file: string, props: Record<string, unknown>) {
|
|||
runInNewContext(transpile(script.content), {
|
||||
exports, console,
|
||||
require: (path: string) => {
|
||||
if (path === 'vue') return vue
|
||||
if (path === 'vue') return { ...vue, inject: (_key: unknown, fallback: unknown) => fallback }
|
||||
const name = composables.find(c => path.endsWith(`/composables/${c}`))
|
||||
return name ? loadComposable(name) : stub
|
||||
},
|
||||
|
|
|
|||
|
|
@ -0,0 +1,102 @@
|
|||
import assert from 'node:assert/strict'
|
||||
import test from 'node:test'
|
||||
import { createRenderer, nextTick, ref, shallowRef } from 'vue'
|
||||
import { useChatScrollFollow } from './useChatScrollFollow'
|
||||
|
||||
function mountViewport() {
|
||||
const listeners = new Map<string, EventListener>()
|
||||
let top = 1000
|
||||
const element = {
|
||||
firstElementChild: {}, scrollHeight: 1600, clientHeight: 600,
|
||||
get scrollTop() { return top },
|
||||
set scrollTop(value: number) { top = Math.max(0, Math.min(value, this.scrollHeight - this.clientHeight)) },
|
||||
addEventListener(name: string, handler: EventListener) { listeners.set(name, handler) },
|
||||
removeEventListener(name: string) { listeners.delete(name) },
|
||||
}
|
||||
const renderer = createRenderer<any, any>({
|
||||
patchProp() {}, insert() {}, remove() {}, setText() {}, setElementText() {},
|
||||
createElement: () => ({}), createText: () => ({}), createComment: () => ({}),
|
||||
parentNode: () => null, nextSibling: () => null,
|
||||
})
|
||||
const reading = ref(false), active = ref(true)
|
||||
let follow!: ReturnType<typeof useChatScrollFollow>
|
||||
const app = renderer.createApp({ setup() {
|
||||
follow = useChatScrollFollow(shallowRef(element as unknown as HTMLElement), reading, active)
|
||||
return () => null
|
||||
} })
|
||||
app.mount({})
|
||||
const wheel = (deltaY: number) => listeners.get('wheel')!({ deltaY } as unknown as Event)
|
||||
const scroll = (to: number) => { element.scrollTop = to; follow.onScroll() }
|
||||
return { app, element, reading, active, follow, listeners, wheel, scroll }
|
||||
}
|
||||
|
||||
test('parent and child follow policy respects upward intent, queued output, collapse and return to bottom', async () => {
|
||||
const original = globalThis.ResizeObserver
|
||||
let resize!: () => void
|
||||
globalThis.ResizeObserver = class {
|
||||
constructor(callback: () => void) { resize = callback }
|
||||
observe() {} disconnect() {}
|
||||
} as unknown as typeof ResizeObserver
|
||||
const chat = mountViewport()
|
||||
try {
|
||||
// A token queues a scroll, then the user scrolls up before Vue flushes.
|
||||
chat.follow.scrollToBottom()
|
||||
chat.wheel(-12)
|
||||
chat.scroll(988)
|
||||
await nextTick()
|
||||
assert.equal(chat.reading.value, true, 'even a small upward gesture leaves the live edge')
|
||||
assert.equal(chat.element.scrollTop, 988)
|
||||
chat.element.scrollHeight += 100
|
||||
chat.follow.scrollToBottom(true)
|
||||
resize()
|
||||
await nextTick()
|
||||
assert.equal(chat.element.scrollTop, 988, 'resumed runs and delayed rendering cannot force a jump')
|
||||
|
||||
// A collapse clamps the scrollbar to the bottom, but is not a user return.
|
||||
chat.element.scrollHeight = 1200
|
||||
chat.scroll(600)
|
||||
assert.equal(chat.reading.value, true)
|
||||
chat.element.scrollHeight += 200
|
||||
resize()
|
||||
assert.equal(chat.element.scrollTop, 600)
|
||||
chat.wheel(200)
|
||||
chat.scroll(800)
|
||||
assert.equal(chat.reading.value, false)
|
||||
chat.element.scrollHeight += 100
|
||||
resize()
|
||||
assert.equal(chat.element.scrollTop, 900, 'follow delayed content after returning to bottom')
|
||||
|
||||
chat.active.value = false
|
||||
chat.element.scrollHeight += 100
|
||||
chat.follow.scrollToBottom(true)
|
||||
resize()
|
||||
await nextTick()
|
||||
assert.equal(chat.element.scrollTop, 900, 'hidden tabs do not scroll')
|
||||
chat.active.value = true
|
||||
chat.reading.value = true
|
||||
chat.follow.resume()
|
||||
await nextTick()
|
||||
assert.equal(chat.reading.value, false)
|
||||
assert.equal(chat.element.scrollTop, 1000)
|
||||
} finally { chat.app.unmount(); globalThis.ResizeObserver = original }
|
||||
assert.equal(chat.listeners.size, 0)
|
||||
})
|
||||
|
||||
test('scrollbar and keyboard history navigation pause without requiring a wheel', async () => {
|
||||
const chat = mountViewport()
|
||||
try {
|
||||
chat.listeners.get('pointerdown')!({} as Event)
|
||||
chat.scroll(500)
|
||||
assert.equal(chat.reading.value, true)
|
||||
chat.follow.scrollToBottom(true)
|
||||
await nextTick()
|
||||
assert.equal(chat.element.scrollTop, 500)
|
||||
chat.follow.resume()
|
||||
await nextTick()
|
||||
chat.listeners.get('keydown')!({ key: 'PageUp' } as unknown as Event)
|
||||
assert.equal(chat.reading.value, true)
|
||||
chat.follow.scrollToBottom()
|
||||
await nextTick()
|
||||
assert.equal(chat.reading.value, true)
|
||||
} finally { chat.app.unmount() }
|
||||
})
|
||||
|
|
@ -0,0 +1,99 @@
|
|||
import { computed, nextTick, onMounted, onUnmounted, provide, ref, watch, type InjectionKey, type Ref } from 'vue'
|
||||
import { useStickyBottomOnResize } from './useStickyBottomOnResize'
|
||||
|
||||
export const chatReadingHistoryKey: InjectionKey<Readonly<Ref<boolean>>> = Symbol('chat-reading-history')
|
||||
|
||||
/** One follow policy for the parent conversation and each child viewport. */
|
||||
export function useChatScrollFollow(
|
||||
viewport: Ref<HTMLElement | null>,
|
||||
reading: Ref<boolean>,
|
||||
active: Readonly<Ref<boolean>> = computed(() => true),
|
||||
) {
|
||||
let lastTop = 0
|
||||
let lastHeight = 0
|
||||
let lastClientHeight = 0
|
||||
let gesture = false
|
||||
let touchY = 0
|
||||
let cleanup = () => {}
|
||||
const rememberPosition = () => {
|
||||
const el = viewport.value
|
||||
if (!el) return
|
||||
lastTop = el.scrollTop
|
||||
lastHeight = el.scrollHeight
|
||||
lastClientHeight = el.clientHeight
|
||||
}
|
||||
const atBottom = (el: HTMLElement) => el.scrollHeight - el.clientHeight - el.scrollTop <= 2
|
||||
const onScroll = () => {
|
||||
const el = viewport.value
|
||||
if (!el || !active.value) return
|
||||
const layoutChanged = el.scrollHeight !== lastHeight || el.clientHeight !== lastClientHeight
|
||||
// Resize, browser scroll anchoring and collapsing steps are not user input.
|
||||
// In particular, clamping to the bottom after a collapse must not reattach.
|
||||
if (gesture || !layoutChanged) {
|
||||
if (el.scrollTop < lastTop - 1) reading.value = true
|
||||
else if (el.scrollTop > lastTop + 1 && atBottom(el)) reading.value = false
|
||||
}
|
||||
gesture = false
|
||||
rememberPosition()
|
||||
}
|
||||
const scrollToBottom = (_force = false) => {
|
||||
// Stream callers historically pass force when a run starts/resumes. That
|
||||
// is not permission to override someone who is reading older messages.
|
||||
void nextTick(() => {
|
||||
if (!active.value || reading.value || !viewport.value) return
|
||||
viewport.value.scrollTop = viewport.value.scrollHeight
|
||||
rememberPosition()
|
||||
})
|
||||
}
|
||||
const resume = () => { reading.value = false; scrollToBottom() }
|
||||
const intent = (up: boolean) => {
|
||||
if (!active.value) return
|
||||
gesture = true
|
||||
if (up) reading.value = true
|
||||
else if (viewport.value && atBottom(viewport.value)) resume()
|
||||
}
|
||||
onMounted(() => {
|
||||
const el = viewport.value
|
||||
if (!el) return
|
||||
rememberPosition()
|
||||
const wheel = (e: WheelEvent) => { if (e.deltaY) intent(e.deltaY < 0) }
|
||||
const touchStart = (e: TouchEvent) => { touchY = e.touches[0]?.clientY || 0 }
|
||||
const touchMove = (e: TouchEvent) => {
|
||||
const y = e.touches[0]?.clientY ?? touchY
|
||||
if (y !== touchY) intent(y > touchY)
|
||||
touchY = y
|
||||
}
|
||||
const key = (e: KeyboardEvent) => {
|
||||
if ((e.target as HTMLElement)?.closest?.('input, textarea, [contenteditable="true"]')) return
|
||||
if (['ArrowUp', 'PageUp', 'Home'].includes(e.key) || (e.key === ' ' && e.shiftKey)) intent(true)
|
||||
else if (['ArrowDown', 'PageDown', 'End', ' '].includes(e.key)) intent(false)
|
||||
}
|
||||
const pointer = () => { gesture = true }
|
||||
el.addEventListener('wheel', wheel, { passive: true })
|
||||
el.addEventListener('touchstart', touchStart, { passive: true })
|
||||
el.addEventListener('touchmove', touchMove, { passive: true })
|
||||
el.addEventListener('keydown', key)
|
||||
el.addEventListener('pointerdown', pointer)
|
||||
cleanup = () => {
|
||||
el.removeEventListener('wheel', wheel)
|
||||
el.removeEventListener('touchstart', touchStart)
|
||||
el.removeEventListener('touchmove', touchMove)
|
||||
el.removeEventListener('keydown', key)
|
||||
el.removeEventListener('pointerdown', pointer)
|
||||
}
|
||||
})
|
||||
onUnmounted(() => cleanup())
|
||||
provide(chatReadingHistoryKey, computed(() => reading.value || !active.value))
|
||||
useStickyBottomOnResize(viewport, computed(() => reading.value || !active.value), rememberPosition)
|
||||
return { onScroll, scrollToBottom, resume, rememberPosition }
|
||||
}
|
||||
|
||||
/** Once folded, history stays folded when the user scrolls up later. */
|
||||
export function useDeferredTimelineCompletion(done: Readonly<Ref<boolean>>, reading: Readonly<Ref<boolean>>) {
|
||||
const settled = ref(done.value)
|
||||
watch([done, reading], ([complete, paused]) => {
|
||||
if (!complete) settled.value = false
|
||||
else if (!paused) settled.value = true
|
||||
}, { flush: 'sync' })
|
||||
return settled
|
||||
}
|
||||
|
|
@ -0,0 +1,332 @@
|
|||
import assert from 'node:assert/strict'
|
||||
import { readFileSync } from 'node:fs'
|
||||
import test from 'node:test'
|
||||
import vm from 'node:vm'
|
||||
import ts from 'typescript'
|
||||
import * as vue from 'vue'
|
||||
import * as finalContent from '../utils/finalArtifactContent.ts'
|
||||
import * as history from '../utils/rag-pipeline-history.ts'
|
||||
import * as timestamps from '../utils/messageTimestamp.ts'
|
||||
import * as steering from '../utils/steerStreamFork.ts'
|
||||
import * as dataChange from '../utils/assistantDataChange.ts'
|
||||
import type { useChatStreamHandler as StreamHandler } from './useChatStreamHandler.ts'
|
||||
|
||||
const source = readFileSync(new URL('./useChatStreamHandler.ts', import.meta.url), 'utf8')
|
||||
const compiled = ts.transpileModule(source, {
|
||||
compilerOptions: { module: ts.ModuleKind.CommonJS, target: ts.ScriptTarget.ES2022 },
|
||||
}).outputText
|
||||
const modules: Record<string, unknown> = {
|
||||
vue, 'vue-i18n': { useI18n: () => ({ t: (key: string) => key }) },
|
||||
'@/utils/finalArtifactContent': finalContent,
|
||||
'@/utils/rag-pipeline-history': history,
|
||||
'@/utils/messageTimestamp': timestamps,
|
||||
'@/utils/steerStreamFork': steering,
|
||||
'@/utils/assistantDataChange': dataChange,
|
||||
}
|
||||
const exports: { useChatStreamHandler?: typeof StreamHandler } = {}
|
||||
vm.runInNewContext(compiled, {
|
||||
exports, console,
|
||||
require: (id: string) => {
|
||||
assert.ok(id in modules, `unexpected import ${id}`)
|
||||
return modules[id]
|
||||
},
|
||||
})
|
||||
const useChatStreamHandler = exports.useChatStreamHandler!
|
||||
|
||||
function setup() {
|
||||
const messagesList = vue.reactive<Record<string, any>[]>([])
|
||||
const loading = vue.ref(false), isReplying = vue.ref(false)
|
||||
const currentAssistantMessageId = vue.ref(''), fullContent = vue.ref('')
|
||||
const turns: unknown[] = []
|
||||
const handler = useChatStreamHandler({
|
||||
messagesList, loading, isReplying, currentAssistantMessageId, fullContent,
|
||||
isAgentStreamSession: () => true, scrollToBottom() {},
|
||||
onTurnComplete: (m) => turns.push(m),
|
||||
preserveIncompleteStreamReactive: true,
|
||||
})
|
||||
return { handler, messagesList, isReplying, currentAssistantMessageId, turns, fullContent }
|
||||
}
|
||||
|
||||
const task = (status = 'running', run_id = 'child-run-1') => ({
|
||||
id: 'child', name: 'research', agent_id: 'agent', session_id: 'session', run_id, status,
|
||||
progress: { phase: 'tool', tool_name: 'search', iteration: 1 }, prompt_id: '',
|
||||
})
|
||||
|
||||
test('collaboration snapshots reject duplicate/late revisions without reviving terminal runs', () => {
|
||||
const { handler, messagesList, isReplying } = setup()
|
||||
isReplying.value = true
|
||||
handler.processStreamChunk({ response_type: 'agent_query', id: 'r1', assistant_message_id: 'a1' })
|
||||
const send = (revision: number, status: string, runId = 'child-run-1') => handler.processStreamChunk({
|
||||
response_type: 'collaboration_status', id: 'r1',
|
||||
data: { group_id: 'group', revision, tasks: [task(status, runId)] },
|
||||
})
|
||||
send(3, 'waiting')
|
||||
const waiting = messagesList[0].collaborationStatus
|
||||
send(2, 'running')
|
||||
send(3, 'running')
|
||||
assert.equal(messagesList[0].collaborationStatus, waiting)
|
||||
send(4, 'succeeded')
|
||||
send(5, 'running')
|
||||
assert.equal(messagesList[0].collaborationStatus.tasks[0].status, 'succeeded')
|
||||
assert.equal(messagesList[0].collaborationStatus.revision, 5)
|
||||
send(6, 'queued', 'child-run-2')
|
||||
assert.equal(messagesList[0].collaborationStatus.tasks[0].status, 'queued')
|
||||
assert.equal(messagesList[0].collaborationStatus.tasks[0].run_id, 'child-run-2')
|
||||
assert.equal(isReplying.value, true)
|
||||
assert.equal(messagesList[0].content, '')
|
||||
assert.equal(messagesList[0].is_completed, false)
|
||||
})
|
||||
|
||||
test('delayed collaboration updates bind to their parent request, not the latest active turn', () => {
|
||||
const { handler, messagesList } = setup()
|
||||
handler.processStreamChunk({ response_type: 'agent_query', id: 'r1', assistant_message_id: 'a1' })
|
||||
handler.processStreamChunk({ response_type: 'agent_query', id: 'r2', assistant_message_id: 'a2' })
|
||||
handler.processStreamChunk({ response_type: 'collaboration_status', id: 'r1',
|
||||
data: { group_id: 'g1', revision: 20, tasks: [task('succeeded')] } })
|
||||
handler.processStreamChunk({ response_type: 'collaboration_status', id: 'r2',
|
||||
data: { group_id: 'g2', revision: 1, tasks: [task('waiting')] } })
|
||||
handler.processStreamChunk({ response_type: 'collaboration_status', id: 'unknown-request',
|
||||
data: { group_id: 'g1', revision: 30, tasks: [task()] } })
|
||||
assert.equal(messagesList.length, 2)
|
||||
assert.equal(messagesList[0].collaborationStatus.group_id, 'g1')
|
||||
assert.equal(messagesList[0].collaborationStatus.tasks[0].status, 'succeeded')
|
||||
assert.equal(messagesList[1].collaborationStatus.group_id, 'g2')
|
||||
assert.equal(messagesList[1].collaborationStatus.revision, 1)
|
||||
assert.equal(messagesList[1].collaborationStatus.tasks[0].status, 'waiting')
|
||||
})
|
||||
|
||||
test('steering does not reset collaboration revision or terminal state', () => {
|
||||
const { handler, messagesList } = setup()
|
||||
handler.processStreamChunk({ response_type: 'agent_query', id: 'r1', assistant_message_id: 'a1' })
|
||||
const send = (revision: number, status: string) => handler.processStreamChunk({
|
||||
response_type: 'collaboration_status', id: 'r1',
|
||||
data: { group_id: 'g1', revision, tasks: [task(status)] },
|
||||
})
|
||||
send(5, 'failed')
|
||||
handler.processStreamChunk({ response_type: 'user_message_injected', id: 'r1',
|
||||
data: { steer_id: 's1', user_message_id: 'u1', content: 'continue' } })
|
||||
send(4, 'running')
|
||||
assert.equal(messagesList[2].collaborationStatus.revision, 5)
|
||||
assert.equal(messagesList[0].collaborationStatus, undefined)
|
||||
send(6, 'running')
|
||||
const updated = messagesList.at(-1)!
|
||||
assert.equal(updated.collaborationStatus.tasks[0].status, 'failed')
|
||||
assert.equal(messagesList.filter(m => m.collaborationStatus).length, 1)
|
||||
})
|
||||
|
||||
test('history hydrates collaboration status once on the last steer segment', async () => {
|
||||
const { handler, messagesList } = setup()
|
||||
await handler.handleMsgList([{
|
||||
id: 'a1', request_id: 'r1', role: 'assistant', content: 'Finished', is_completed: true,
|
||||
collaboration_status: { group_id: 'g1', revision: 9, tasks: [task('succeeded')] },
|
||||
agent_steps: [{ iteration: 0, progress: 'Checking', progress_event_id: 'p1' },
|
||||
{ iteration: 1, user_messages_before: ['u1'] }],
|
||||
}, { id: 'u1', request_id: 'r1', role: 'user', content: 'Continue', created_at: '2026-10-17T01:01:00Z' }])
|
||||
assert.equal(messagesList.length, 3)
|
||||
assert.equal(messagesList[0].collaborationStatus, undefined)
|
||||
assert.equal(messagesList[2].collaborationStatus.revision, 9)
|
||||
assert.equal(messagesList.filter(m => m.collaborationStatus).length, 1)
|
||||
handler.processStreamChunk({ response_type: 'collaboration_status', id: 'r1',
|
||||
data: { group_id: 'g1', revision: 8, tasks: [task('running')] } })
|
||||
assert.equal(messagesList[2].collaborationStatus.tasks[0].status, 'succeeded')
|
||||
})
|
||||
|
||||
test('progress snapshots replay idempotently and remain separate from reasoning and final answer', () => {
|
||||
const { handler, messagesList, fullContent } = setup()
|
||||
const query = { response_type: 'agent_query', id: 'r1', assistant_message_id: 'a1' }
|
||||
handler.processStreamChunk(query)
|
||||
const progress = { response_type: 'progress', id: 'r1', content: 'Searching sources', done: true,
|
||||
data: { event_id: 'progress-1', iteration: 0 } }
|
||||
handler.processStreamChunk(progress)
|
||||
handler.processStreamChunk(query)
|
||||
handler.processStreamChunk(progress)
|
||||
handler.processStreamChunk({ ...progress, content: 'Earlier partial text', done: false })
|
||||
handler.processStreamChunk({ ...progress, content: 'Checking the findings', data: { event_id: 'progress-2', iteration: 0 } })
|
||||
handler.processStreamChunk({ response_type: 'thinking', id: 'r1', content: 'Private reasoning', data: { event_id: 'reasoning-1' } })
|
||||
handler.processStreamChunk({ response_type: 'answer', id: 'r1', content: 'Final answer', data: { event_id: 'answer-1' } })
|
||||
const message = messagesList[0]
|
||||
const events = message.agentEventStream as Record<string, any>[]
|
||||
assert.equal(events.filter(e => e.type === 'progress').length, 2)
|
||||
assert.equal(events[0].content, 'Searching sources')
|
||||
assert.equal(events[1].content, 'Checking the findings')
|
||||
assert.equal(events.find(e => e.type === 'thinking')?.content, 'Private reasoning')
|
||||
assert.equal(message.content, 'Final answer')
|
||||
assert.ok(!fullContent.value.includes('Searching sources'))
|
||||
})
|
||||
|
||||
test('progress replay after steering does not duplicate an earlier segment', () => {
|
||||
const { handler, messagesList } = setup()
|
||||
handler.processStreamChunk({ response_type: 'agent_query', id: 'r1', assistant_message_id: 'a1' })
|
||||
const progress = { response_type: 'progress', id: 'r1', content: 'Working', done: true,
|
||||
data: { event_id: 'p1', iteration: 1 } }
|
||||
handler.processStreamChunk(progress)
|
||||
handler.processStreamChunk({ response_type: 'user_message_injected', id: 'r1',
|
||||
data: { steer_id: 's1', user_message_id: 'u1', content: 'more' } })
|
||||
handler.processStreamChunk(progress)
|
||||
handler.processStreamChunk({ ...progress, id: 'missing-request', data: { event_id: 'p2' } })
|
||||
const progressEvents = messagesList.flatMap(m => m.agentEventStream || []).filter(e => e.type === 'progress')
|
||||
assert.equal(progressEvents.length, 1)
|
||||
assert.equal(messagesList.length, 3)
|
||||
})
|
||||
|
||||
test('progress reclassifies a provisional answer with the same ID and ignores its replay', () => {
|
||||
const { handler, messagesList, fullContent } = setup()
|
||||
handler.processStreamChunk({ response_type: 'agent_query', id: 'r1', assistant_message_id: 'a1' })
|
||||
const provisional = { response_type: 'answer', id: 'r1', content: 'I will search', done: true, data: { event_id: 'p1' } }
|
||||
handler.processStreamChunk(provisional)
|
||||
handler.processStreamChunk({ ...provisional, response_type: 'progress', data: { event_id: 'p1', iteration: 1 } })
|
||||
handler.processStreamChunk(provisional)
|
||||
assert.equal(messagesList[0].agentEventStream.length, 1)
|
||||
assert.equal(messagesList[0].agentEventStream[0].type, 'progress')
|
||||
assert.equal(messagesList[0].agentEventStream[0].content, 'I will search')
|
||||
assert.equal(messagesList[0].content, '')
|
||||
assert.equal(fullContent.value, '')
|
||||
handler.processStreamChunk({ ...provisional, content: 'The result', data: { event_id: 'final' } })
|
||||
assert.equal(messagesList[0].content, 'The result')
|
||||
assert.equal(fullContent.value, 'The result')
|
||||
})
|
||||
|
||||
test('history restores step progress once, independently of reasoning and the final answer', async () => {
|
||||
const { handler, messagesList } = setup()
|
||||
await handler.handleMsgList([{
|
||||
id: 'a1', request_id: 'r1', role: 'assistant', content: 'Final answer', is_completed: true,
|
||||
agent_steps: [{ iteration: 0, reasoning_content: 'Private reasoning', thought: 'Checking sources',
|
||||
progress: 'Checking sources', progress_event_id: 'stable-progress-id', intermediate_answer: true,
|
||||
tool_calls: [{ id: 'call-1', name: 'search', args: {} }] }],
|
||||
}])
|
||||
const message = messagesList[0]
|
||||
const events = message.agentEventStream as Record<string, any>[]
|
||||
assert.equal(events.filter(e => e.content === 'Checking sources').length, 1)
|
||||
assert.equal(events.find(e => e.type === 'progress')?.content, 'Checking sources')
|
||||
assert.equal(events.find(e => e.type === 'thinking')?.content, 'Private reasoning')
|
||||
assert.equal(events.filter(e => e.type === 'answer').length, 1)
|
||||
assert.equal(message.content, 'Final answer')
|
||||
handler.processStreamChunk({ response_type: 'progress', id: 'r1', content: 'Checking sources', done: true,
|
||||
data: { event_id: 'stable-progress-id', iteration: 0 } })
|
||||
assert.equal(events.filter(e => e.type === 'progress').length, 1)
|
||||
})
|
||||
|
||||
test('a result with an unmatched call ID cannot complete another pending call with the same name', () => {
|
||||
const { handler, messagesList } = setup()
|
||||
handler.processStreamChunk({ response_type: 'agent_query', id: 'r1', assistant_message_id: 'a1' })
|
||||
for (const id of ['call-a', 'call-b']) handler.processStreamChunk({ response_type: 'tool_call', id: 'r1',
|
||||
data: { tool_call_id: id, tool_name: 'search', arguments: {} } })
|
||||
const result = (tool_call_id?: string) => handler.processStreamChunk({ response_type: 'tool_result', id: 'r1',
|
||||
data: { tool_call_id, tool_name: 'search', success: true, output: tool_call_id || 'legacy' } })
|
||||
result('missing')
|
||||
const calls = messagesList[0].agentEventStream as Record<string, any>[]
|
||||
assert.equal(calls[0].pending, true)
|
||||
assert.equal(calls[1].pending, true)
|
||||
result('call-b')
|
||||
result('call-b') // A replayed result must not consume the still-pending sibling.
|
||||
assert.equal(calls[0].pending, true)
|
||||
assert.equal(calls[1].pending, false)
|
||||
result()
|
||||
assert.equal(calls[0].pending, false)
|
||||
assert.equal(calls[0].output, 'legacy')
|
||||
})
|
||||
|
||||
|
||||
test('protocol answer replacement retracts only its event and never replays the prefix as progress', () => {
|
||||
const { handler, messagesList } = setup()
|
||||
handler.processStreamChunk({ response_type: 'agent_query', id: 'r1', assistant_message_id: 'a1' })
|
||||
const answer = (event_id: string, content: string, replace = false) => handler.processStreamChunk({ response_type: 'answer', id: 'r1', content, data: { event_id, replace } })
|
||||
answer('prior', 'Earlier legitimate result.')
|
||||
answer('bad', 'refs\nprivate planning')
|
||||
answer('bad', '', true)
|
||||
answer('bad', '## 进展\nComplete report')
|
||||
const stream = messagesList[0].agentEventStream
|
||||
assert.equal(stream.find((e: any) => e.event_id === 'prior').content, 'Earlier legitimate result.')
|
||||
assert.equal(stream.find((e: any) => e.event_id === 'bad').content, '## 进展\nComplete report')
|
||||
assert.doesNotMatch(messagesList[0].content, /private planning|refs/)
|
||||
assert.equal(stream.some((e: any) => e.type === 'progress'), false)
|
||||
})
|
||||
|
||||
test('protocol replacement clears matching progress across steer rows', () => {
|
||||
const { handler, messagesList } = setup()
|
||||
handler.processStreamChunk({ response_type: 'agent_query', id: 'r1', assistant_message_id: 'a1' })
|
||||
handler.processStreamChunk({ response_type: 'progress', id: 'r1', content: 'private provisional prefix', done: true, data: { event_id: 'bad' } })
|
||||
handler.processStreamChunk({ response_type: 'user_message_injected', id: 'r1', data: { steer_id: 'st1', message_id: 'u1', content: 'Continue' } })
|
||||
handler.processStreamChunk({ response_type: 'answer', id: 'r1', content: '', data: { event_id: 'bad', replace: true } })
|
||||
handler.processStreamChunk({ response_type: 'answer', id: 'r1', content: 'Clean final answer', data: { event_id: 'bad' } })
|
||||
const events = messagesList.flatMap(m => m.agentEventStream || [])
|
||||
assert.equal(events.filter(e => e.event_id === 'bad').length, 1)
|
||||
assert.equal(events.find(e => e.event_id === 'bad').type, 'answer')
|
||||
assert.equal(events.find(e => e.event_id === 'bad').content, 'Clean final answer')
|
||||
assert.doesNotMatch(JSON.stringify(events), /private provisional prefix/)
|
||||
})
|
||||
|
||||
|
||||
test('corrected archived answer keeps complete reasoning in its own channel', async () => {
|
||||
const { handler, messagesList } = setup()
|
||||
await handler.handleMsgList([{ id: 'a1', request_id: 'r1', role: 'assistant', content: '## 进展\nComplete report', is_completed: true,
|
||||
agent_steps: [{ iteration: 0, reasoning_content: 'refs\nprivate planning', thought: '## 进展\nComplete report', tool_calls: [] }] }])
|
||||
const stream = messagesList[0].agentEventStream
|
||||
assert.equal(stream.find((e: any) => e.type === 'thinking').content, 'refs\nprivate planning')
|
||||
assert.equal(stream.filter((e: any) => e.type === 'answer').length, 1)
|
||||
assert.equal(stream.find((e: any) => e.type === 'answer').content, '## 进展\nComplete report')
|
||||
assert.equal(stream.some((e: any) => e.type === 'progress'), false)
|
||||
})
|
||||
|
||||
test('protocol replacement of current progress reuses its event for later chunks', () => {
|
||||
const { handler, messagesList } = setup()
|
||||
handler.processStreamChunk({ response_type: 'agent_query', id: 'r1', assistant_message_id: 'a1' })
|
||||
handler.processStreamChunk({ response_type: 'progress', id: 'r1', content: 'private prefix', done: true, data: { event_id: 'bad' } })
|
||||
handler.processStreamChunk({ response_type: 'answer', id: 'r1', content: '', data: { event_id: 'bad', replace: true } })
|
||||
handler.processStreamChunk({ response_type: 'answer', id: 'r1', content: 'Clean final', data: { event_id: 'bad' } })
|
||||
assert.equal(messagesList[0].agentEventStream.length, 1)
|
||||
assert.equal(messagesList[0].agentEventStream[0].content, 'Clean final')
|
||||
assert.equal(messagesList[0].content, 'Clean final')
|
||||
})
|
||||
|
||||
|
||||
test('ordinary stream reconnect rebuilds answer, reasoning and tools without duplication', () => {
|
||||
const { handler, messagesList } = setup()
|
||||
const replay = () => {
|
||||
handler.processStreamChunk({ response_type: 'agent_query', id: 'r1', assistant_message_id: 'a1' })
|
||||
handler.processStreamChunk({ response_type: 'thinking', id: 'r1', content: 'reasoning', data: { event_id: 'thought' } })
|
||||
handler.processStreamChunk({ response_type: 'tool_call', id: 'r1', data: { tool_call_id: 'call', tool_name: 'search', arguments: {} } })
|
||||
handler.processStreamChunk({ response_type: 'tool_result', id: 'r1', data: { tool_call_id: 'call', tool_name: 'search', success: true, output: 'found' } })
|
||||
handler.processStreamChunk({ response_type: 'answer', id: 'r1', content: 'first part', data: { event_id: 'answer' }, done: false })
|
||||
}
|
||||
replay()
|
||||
const row = messagesList[0]
|
||||
replay()
|
||||
replay()
|
||||
assert.equal(messagesList.length, 1)
|
||||
assert.equal(messagesList[0], row)
|
||||
assert.equal(row.content, 'first part')
|
||||
assert.equal(row.agentEventStream.filter((e: Record<string, any>) => e.type === 'thinking').length, 1)
|
||||
assert.equal(row.agentEventStream.find((e: Record<string, any>) => e.type === 'thinking').content, 'reasoning')
|
||||
assert.equal(row.agentEventStream.filter((e: Record<string, any>) => e.type === 'tool_call').length, 1)
|
||||
handler.processStreamChunk({ response_type: 'answer', id: 'r1', content: ' continued', data: { event_id: 'answer' }, done: false })
|
||||
assert.equal(row.content, 'first part continued')
|
||||
})
|
||||
|
||||
import { createChildAgentTabs, findChildAgentTask } from './useChildAgentTabs'
|
||||
import { collaborationTasks } from '../utils/collaborationDisplay'
|
||||
|
||||
test('open child tab follows steering, approval, completion and subsequent runs', () => {
|
||||
const { handler, messagesList } = setup()
|
||||
handler.processStreamChunk({ response_type: 'agent_query', id: 'r1', assistant_message_id: 'a1' })
|
||||
const update = (revision: number, status: string, runId = 'child-run-1') => handler.processStreamChunk({
|
||||
response_type: 'collaboration_status', id: 'r1', data: { group_id: 'group', revision, tasks: [task(status, runId)] },
|
||||
})
|
||||
update(1, 'running')
|
||||
const original = messagesList[0]
|
||||
const child = collaborationTasks(original.collaborationStatus)[0]
|
||||
const tabs = createChildAgentTabs()
|
||||
tabs.open(child, () => findChildAgentTask(messagesList, child))
|
||||
handler.processStreamChunk({ response_type: 'user_message_injected', id: 'r1', data: { steer_id: 's1', user_message_id: 'u1', content: 'Current progress?' } })
|
||||
assert.equal(original.collaborationStatus, undefined)
|
||||
update(2, 'waiting')
|
||||
assert.equal(tabs.tabs.value[0].task.status, 'waiting')
|
||||
update(3, 'succeeded')
|
||||
assert.equal(tabs.tabs.value[0].task.status, 'succeeded')
|
||||
update(4, 'running', 'child-run-2')
|
||||
assert.equal(tabs.tabs.value[0].task.runId, 'child-run-2')
|
||||
assert.equal(tabs.tabs.value[0].task.status, 'running')
|
||||
// Another conversation with a matching display ID must not hijack the tab.
|
||||
messagesList.push({ collaborationStatus: { tasks: [{ ...task('failed'), session_id: 'other-session' }] } })
|
||||
assert.equal(tabs.tabs.value[0].task.status, 'running')
|
||||
})
|
||||
|
|
@ -201,3 +201,244 @@ test('a prompt without display steps remains answerable after orphan recovery',
|
|||
assert.equal(cards(message).length, 1)
|
||||
assert.equal(cards(message)[0].pending_id, 'p1')
|
||||
})
|
||||
|
||||
test('parallel child approvals reload on a running parent without suspending it', async () => {
|
||||
const { handler, messagesList } = setup()
|
||||
const base = awaitingRow() as Record<string, any>
|
||||
base.run_state = ''
|
||||
base.is_completed = false
|
||||
const prompt = base.pending_prompt
|
||||
delete base.pending_prompt
|
||||
base.delegated_prompts = [
|
||||
{ ...prompt, id: 'child-1', delegated_task: 'research' },
|
||||
{ ...prompt, id: 'child-2', delegated_task: 'writer' },
|
||||
]
|
||||
await handler.handleMsgList([base])
|
||||
const m = messagesList[0]
|
||||
assert.equal(m.run_state, '')
|
||||
assert.equal(m.is_completed, false)
|
||||
assert.deepEqual(Array.from(cards(m), (p) => p.pending_id), ['child-1', 'child-2'])
|
||||
assert.equal(cards(m)[0].delegated_task, 'research')
|
||||
handler.processStreamChunk({ response_type: 'tool_approval_required', id: 'r1', data: {
|
||||
pending_id: 'child-1', suspended: true, suspendable: true,
|
||||
} })
|
||||
assert.equal(cards(m).length, 2)
|
||||
})
|
||||
|
||||
test('forwarded live approval is parked while parent keeps streaming', () => {
|
||||
const { handler, messagesList, isReplying } = setup()
|
||||
isReplying.value = true
|
||||
handler.processStreamChunk({ response_type: 'agent_query', id: 'r1', assistant_message_id: 'a1' })
|
||||
handler.processStreamChunk({ response_type: 'tool_approval_required', id: 'r1', data: {
|
||||
pending_id: 'child', suspended: true, suspendable: true, description: 'writer: change a page',
|
||||
} })
|
||||
assert.equal(cards(messagesList[0])[0].suspended, true)
|
||||
assert.equal(isReplying.value, true)
|
||||
assert.notEqual(messagesList[0].run_state, 'awaiting_input')
|
||||
})
|
||||
|
||||
test('child approval resolutions after steering update the original segment and not another turn', () => {
|
||||
const { handler, messagesList } = setup()
|
||||
handler.processStreamChunk({ response_type: 'agent_query', id: 'r1', assistant_message_id: 'a1' })
|
||||
for (const pending_id of ['child-a', 'child-b']) {
|
||||
handler.processStreamChunk({ response_type: 'tool_approval_required', id: 'r1', data: { pending_id } })
|
||||
}
|
||||
handler.processStreamChunk({ response_type: 'agent_prompt_required', id: 'r1', data: { pending_id: 'child-question', kind: 'ask_user' } })
|
||||
const original = messagesList[0]
|
||||
handler.processStreamChunk({ response_type: 'user_message_injected', id: 'r1', data: {
|
||||
steer_id: 's1', user_message_id: 'u1', content: 'cancel child-a only',
|
||||
} })
|
||||
assert.equal(original.steerForked, true)
|
||||
// Replaying a required event after a segment split must not clone its card.
|
||||
handler.processStreamChunk({ response_type: 'tool_approval_required', id: 'r1', data: { pending_id: 'child-a' } })
|
||||
const foreign = { id: 'another-turn', role: 'assistant', is_completed: true, agentEventStream: [
|
||||
{ type: 'tool_approval_required', pending_id: 'child-a', resolved: false },
|
||||
] }
|
||||
messagesList.unshift(foreign)
|
||||
handler.processStreamChunk({ response_type: 'tool_approval_resolved', id: 'r1', data: { pending_id: 'child-a', approved: false, canceled: true } })
|
||||
assert.equal(cards(original)[0].resolved, true)
|
||||
assert.equal(cards(original)[0].canceled, true)
|
||||
assert.equal(cards(original)[1].resolved, false)
|
||||
handler.processStreamChunk({ response_type: 'agent_prompt_resolved', id: 'r1', data: { pending_id: 'child-question', answered: true } })
|
||||
assert.equal(original.agentEventStream.find((e: any) => e.pending_id === 'child-question').resolved, true)
|
||||
handler.processStreamChunk({ response_type: 'tool_approval_resolved', id: 'r1', data: { pending_id: 'child-b', approved: true } })
|
||||
assert.equal(cards(original)[1].approved, true)
|
||||
assert.equal(messagesList.length, 4)
|
||||
assert.equal(cards(messagesList[3]).length, 0)
|
||||
assert.equal(cards(foreign)[0].resolved, false)
|
||||
})
|
||||
|
||||
test('stopping a suspended turn closes its cards even when its display row is completed', async () => {
|
||||
const { handler, messagesList } = setup()
|
||||
await handler.handleMsgList([awaitingRow()])
|
||||
handler.markInFlightAssistantStopped('a1')
|
||||
assert.equal(messagesList[0].run_state, '')
|
||||
assert.equal(cards(messagesList[0])[0].resolved, true)
|
||||
assert.equal(cards(messagesList[0])[0].canceled, true)
|
||||
assert.equal(messagesList[0].is_completed, true)
|
||||
})
|
||||
|
||||
|
||||
test('stop still clears cards after a stream watcher has already settled the row', () => {
|
||||
const { handler, messagesList } = setup()
|
||||
messagesList.push({ id: 'a1', role: 'assistant', is_completed: true, run_state: '',
|
||||
agentEventStream: [{type: 'tool_approval_required', pending_id: 'p1', suspended: true}, {type: 'tool_call', pending: true}] })
|
||||
handler.markInFlightAssistantStopped()
|
||||
assert.equal(messagesList[0].agentEventStream[1].pending, false)
|
||||
assert.equal(cards(messagesList[0])[0].resolved, true)
|
||||
assert.equal(cards(messagesList[0])[0].canceled, true)
|
||||
})
|
||||
|
||||
test('rehydrated in-flight steps remain reactive while tools and thinking stream in', async () => {
|
||||
const { handler, messagesList, currentAssistantMessageId } = setup()
|
||||
const row = awaitingRow()
|
||||
row.run_state = ''
|
||||
await handler.handleMsgList([row])
|
||||
currentAssistantMessageId.value = 'a1'
|
||||
const m = messagesList[0]
|
||||
const observed = vue.computed(() => (m.agentEventStream as any[]).map(e =>
|
||||
`${e.type}:${e.content || ''}:${e.pending}:${e.success}`).join('|'))
|
||||
const before = observed.value
|
||||
assert.doesNotMatch(before, /agent_complete/, 'an elapsed duration must not settle a running timeline')
|
||||
handler.processStreamChunk({ response_type: 'thinking', id: 'r1', content: 'new thought',
|
||||
done: false, data: { event_id: 'thinking-2' } })
|
||||
assert.notEqual(observed.value, before, 'new timeline rows must invalidate the render')
|
||||
handler.processStreamChunk({ response_type: 'thinking', id: 'r1', content: ' continues',
|
||||
done: false, data: { event_id: 'thinking-2' } })
|
||||
assert.match(observed.value, /new thought continues/)
|
||||
handler.processStreamChunk({ response_type: 'tool_call', id: 'r1',
|
||||
data: { tool_call_id: 'call-2', tool_name: 'search', arguments: {} } })
|
||||
assert.match(observed.value, /tool_call::true/)
|
||||
handler.processStreamChunk({ response_type: 'tool_result', id: 'r1',
|
||||
data: { tool_call_id: 'call-2', tool_name: 'search', success: true, output: 'found' } })
|
||||
assert.match(observed.value, /tool_call::false:true/)
|
||||
})
|
||||
|
||||
|
||||
test('resolved approvals reload once in timeline order before completion and never become pending', async () => {
|
||||
const { handler, messagesList } = setup()
|
||||
const prompt = { id: 'approved', kind: 'tool_approval', status: 'done',
|
||||
tool_call_id: 'call-1', created_at: '2026-10-13T08:00:01Z',
|
||||
request: { service_name: 'KM', mcp_tool_name: 'hot-articles', args: { limit: 1 } },
|
||||
response: { approved: true, modified_args: { limit: 2 } } }
|
||||
await handler.handleMsgList([{ id: 'a', role: 'assistant', is_completed: true,
|
||||
content: 'final', agent_duration_ms: 5000,
|
||||
agent_steps: [{ iteration: 0, timestamp: '2026-10-13T08:00:00Z', thought: 'starting',
|
||||
tool_calls: [{ id: 'call-1', name: 'mcp_x', args: {}, result: { success: true } }] }],
|
||||
prompt_history: [prompt], delegated_prompts: [prompt,
|
||||
{ ...prompt, id: 'rejected', delegated_task: 'child', response: { approved: false } },
|
||||
{ ...prompt, id: 'canceled', delegated_task: 'child', status: 'canceled', response: {} }],
|
||||
}])
|
||||
const m = messagesList[0]
|
||||
assert.equal(cards(m).length, 3)
|
||||
assert.ok(cards(m).every(c => c.resolved && !c.suspended))
|
||||
assert.equal(cards(m)[0].approved, true)
|
||||
assert.equal(cards(m)[0].args_json, '{"limit":2}')
|
||||
assert.equal(cards(m)[1].approved, false)
|
||||
assert.equal(cards(m)[2].canceled, true)
|
||||
const events = m.agentEventStream as Record<string, any>[]
|
||||
assert.ok(events.findIndex(e => e.pending_id === 'approved') < events.findIndex(e => e.type === 'tool_call'))
|
||||
assert.ok(events.findIndex(e => e.pending_id === 'canceled') < events.findIndex(e => e.type === 'agent_complete'))
|
||||
assert.equal(events.at(-1)?.content, 'final')
|
||||
})
|
||||
|
||||
for (const prepared of [false, true]) {
|
||||
test(`same-request approval resume and reconnect retain the timeline (prepared=${prepared})`, async () => {
|
||||
const { handler, messagesList } = setup()
|
||||
await handler.handleMsgList([awaitingRow()])
|
||||
const m = messagesList[0]
|
||||
if (prepared) handler.prepareResumedMessage(m, 'p1')
|
||||
const resume = () => {
|
||||
handler.processStreamChunk({ response_type: 'agent_query', id: 'r1', assistant_message_id: 'a1',
|
||||
data: { resume_pending_id: 'p1', resume_tool_call_id: 'call-1' } })
|
||||
handler.processStreamChunk({ response_type: 'tool_approval_resolved', id: 'r1',
|
||||
data: { pending_id: 'p1', approved: true } })
|
||||
handler.processStreamChunk({ response_type: 'tool_call', id: 'r1',
|
||||
data: { tool_call_id: 'call-1', tool_name: 'mcp_x', arguments: {} } })
|
||||
handler.processStreamChunk({ response_type: 'tool_result', id: 'r1',
|
||||
data: { tool_call_id: 'call-1', tool_name: 'mcp_x', success: true, output: 'approved result' } })
|
||||
handler.processStreamChunk({ response_type: 'answer', id: 'r1', content: 'after approval',
|
||||
data: { event_id: 'resume-progress' }, done: false })
|
||||
}
|
||||
resume()
|
||||
resume()
|
||||
resume()
|
||||
assert.equal(messagesList.length, 1)
|
||||
const events = m.agentEventStream as Record<string, any>[]
|
||||
assert.equal(events.filter(e => e.content === 'checking').length, 1)
|
||||
assert.equal(events.filter(e => e.type === 'tool_call' && e.tool_call_id === 'call-1').length, 1)
|
||||
assert.equal(events.filter(e => e.type === 'answer' && e.content === 'after approval').length, 1)
|
||||
assert.equal(cards(m).length, 1)
|
||||
assert.equal(cards(m)[0].approved, true)
|
||||
assert.equal(m.content, 'after approval')
|
||||
|
||||
// A second approval creates a new suffix, retaining the first one's history.
|
||||
handler.processStreamChunk({ response_type: 'tool_approval_required', id: 'r1',
|
||||
data: { pending_id: 'p2', tool_call_id: 'call-2' } })
|
||||
handler.prepareResumedMessage(m, 'p2')
|
||||
const secondResume = () => {
|
||||
handler.processStreamChunk({ response_type: 'agent_query', id: 'r1', assistant_message_id: 'a1',
|
||||
data: { resume_pending_id: 'p2', resume_tool_call_id: 'call-2' } })
|
||||
handler.processStreamChunk({ response_type: 'tool_approval_resolved', id: 'r1',
|
||||
data: { pending_id: 'p2', approved: true } })
|
||||
}
|
||||
secondResume()
|
||||
secondResume()
|
||||
assert.equal(cards(m).length, 2)
|
||||
assert.ok(cards(m).every(e => e.approved))
|
||||
assert.equal(m.agentEventStream.filter((e: any) => e.content === 'checking').length, 1)
|
||||
assert.equal(m.agentEventStream.filter((e: any) => e.content === 'after approval').length, 1)
|
||||
})
|
||||
}
|
||||
|
||||
test('approval suffix replay preserves steer boundaries before and after suspension', async () => {
|
||||
const { handler, messagesList } = setup()
|
||||
const query = { response_type: 'agent_query', id: 'r1', assistant_message_id: 'a1' }
|
||||
const steer = (id: string) => handler.processStreamChunk({ response_type: 'user_message_injected', id: 'r1',
|
||||
data: { steer_id: id, user_message_id: id, content: id } })
|
||||
const answer = (text: string) => handler.processStreamChunk({ response_type: 'answer', id: 'r1',
|
||||
data: { event_id: text }, content: text, done: false })
|
||||
handler.processStreamChunk(query)
|
||||
answer('before-steer')
|
||||
steer('u-before')
|
||||
answer('before-approval')
|
||||
const replay = () => {
|
||||
handler.processStreamChunk({ ...query, data: { resume_pending_id: 'p1', resume_tool_call_id: 'c1' } })
|
||||
answer('after-approval')
|
||||
steer('u-after')
|
||||
answer('after-steer')
|
||||
}
|
||||
replay()
|
||||
replay()
|
||||
const assistants = messagesList.filter(m => m.role === 'assistant')
|
||||
assert.equal(assistants.length, 3)
|
||||
const texts = assistants.map(m => m.agentEventStream.filter((e: any) => e.type === 'answer').map((e: any) => e.content))
|
||||
assert.deepEqual(JSON.parse(JSON.stringify(texts)), [['before-steer'], ['before-approval', 'after-approval'], ['after-steer']])
|
||||
})
|
||||
|
||||
|
||||
test('reloaded history containing a later checkpoint does not duplicate the resumed suffix', async () => {
|
||||
const { handler, messagesList } = setup()
|
||||
await handler.handleMsgList([awaitingRow()])
|
||||
const m = messagesList[0]
|
||||
m.agentEventStream.push({ type: 'answer', content: 'persisted suffix', event_id: 'suffix', done: true })
|
||||
handler.processStreamChunk({ response_type: 'agent_query', id: 'r1', assistant_message_id: 'a1',
|
||||
data: { resume_pending_id: 'p1', resume_tool_call_id: 'call-1' } })
|
||||
handler.processStreamChunk({ response_type: 'answer', id: 'r1', content: 'persisted suffix',
|
||||
data: { event_id: 'suffix' }, done: false })
|
||||
assert.equal(m.agentEventStream.filter((e: any) => e.content === 'checking').length, 1)
|
||||
assert.equal(m.agentEventStream.filter((e: any) => e.content === 'persisted suffix').length, 1)
|
||||
assert.equal(cards(m).length, 1)
|
||||
})
|
||||
|
||||
|
||||
test('approval resume keeps updates that arrived while approval was pending', async () => {
|
||||
const { handler, messagesList } = setup()
|
||||
await handler.handleMsgList([awaitingRow()])
|
||||
const m = messagesList[0]
|
||||
handler.prepareResumedMessage(m, 'p1')
|
||||
m.agentEventStream.push({ type: 'answer', content: 'another child finished', event_id: 'child-progress', done: true })
|
||||
handler.processStreamChunk({ response_type: 'agent_query', id: 'r1', assistant_message_id: 'a1',
|
||||
data: { resume_pending_id: 'p1', resume_tool_call_id: 'call-1' } })
|
||||
assert.equal(m.agentEventStream.filter((e: any) => e.content === 'another child finished').length, 1)
|
||||
})
|
||||
|
|
|
|||
|
|
@ -174,7 +174,7 @@ const runAnswerCase = () => {
|
|||
}
|
||||
const state = { fullContent: { value: '' }, doneCount: 0 }
|
||||
const process = vm.runInNewContext(
|
||||
ts.transpile(`(message, data, dataPayload) => { switch ('answer') { ${chunk} } }`),
|
||||
ts.transpile(`(message, data, dataPayload) => { const turnPromptEvents = () => message.agentEventStream || []; switch ('answer') { ${chunk} } }`),
|
||||
{
|
||||
...state,
|
||||
recomposeAgentAnswer: recompose,
|
||||
|
|
@ -274,7 +274,7 @@ test('the live answer path carries truncated onto the event and the message', ()
|
|||
const chunk = source.slice(chunkStart, source.indexOf("case 'artifacts_pending'", chunkStart))
|
||||
const state = { fullContent: { value: '' } }
|
||||
const process = vm.runInNewContext(
|
||||
ts.transpile(`(message, data, dataPayload) => { switch ('answer') { ${chunk} } }`),
|
||||
ts.transpile(`(message, data, dataPayload) => { const turnPromptEvents = () => message.agentEventStream || []; switch ('answer') { ${chunk} } }`),
|
||||
{
|
||||
...state,
|
||||
recomposeAgentAnswer: (m) =>
|
||||
|
|
|
|||
|
|
@ -4,9 +4,16 @@ import { markRaw, nextTick, type Ref } from 'vue'
|
|||
import { useI18n } from 'vue-i18n'
|
||||
import { ensureRagPipelineHistoryStream } from '@/utils/rag-pipeline-history'
|
||||
import { applyMessageCreatedAt, bindServerTurnTimestamps, ensureMessageCreatedAt } from '@/utils/messageTimestamp'
|
||||
import { expandSteerForksInHistory, forkAfterInjectedUser, steerStepEvents, resetSteerTurnForReplay } from '@/utils/steerStreamFork'
|
||||
import { expandSteerForksInHistory, forkAfterInjectedUser, persistedAssistantId, steerStepEvents, resetSteerTurnForReplay } from '@/utils/steerStreamFork'
|
||||
import type { CollaborationStatus, CollaborationTaskStatus } from '@/api/chat/streamTypes'
|
||||
|
||||
export type ChatMessage = Record<string, unknown>
|
||||
export type { CollaborationStatus, CollaborationTaskStatus } from '@/api/chat/streamTypes'
|
||||
export type ChatMessage = Record<string, unknown> & {
|
||||
collaborationStatus?: CollaborationStatus
|
||||
collaboration_status?: CollaborationStatus
|
||||
}
|
||||
|
||||
const TERMINAL_COLLABORATION_STATES = new Set(['succeeded', 'completed', 'failed', 'interrupted', 'cancelled', 'canceled'])
|
||||
|
||||
// Tools whose results tell open pages what changed (see dataChangeTools on
|
||||
// the server).
|
||||
|
|
@ -72,25 +79,39 @@ export function isAwaitingInput(message: ChatMessage | undefined): boolean {
|
|||
return message?.run_state === AWAITING_INPUT
|
||||
}
|
||||
|
||||
/** Rebuilds the card of the prompt a suspended run waits on, from history. */
|
||||
/** Rebuilds open and resolved prompt cards from durable history. */
|
||||
export function pendingPromptEvents(prompt: unknown): ChatMessage[] {
|
||||
const p = prompt as Record<string, any> | undefined
|
||||
if (!p?.id) return []
|
||||
const request = (p.request || {}) as Record<string, any>
|
||||
const createdAt = Date.parse(String(p.created_at || ''))
|
||||
const requestedAt = Number.isNaN(createdAt) ? undefined : Math.floor(createdAt / 1000)
|
||||
const response = p.response || {}
|
||||
const resolved = Boolean(p.status && !['pending', 'suspended'].includes(p.status))
|
||||
const state = {
|
||||
resolved,
|
||||
timestamp: Number.isNaN(createdAt) ? undefined : createdAt,
|
||||
canceled: p.status === 'canceled',
|
||||
abandoned: ['expired', 'superseded'].includes(p.status),
|
||||
resolve_reason: p.close_reason || response.reason,
|
||||
suspended: !resolved,
|
||||
}
|
||||
if (p.kind === 'ask_user') {
|
||||
return [{
|
||||
type: 'agent_prompt_required',
|
||||
pending_id: p.id,
|
||||
kind: p.kind,
|
||||
request,
|
||||
delegated_task: p.delegated_task,
|
||||
request: p.delegated_task ? { ...request, question: `${p.delegated_task}: ${request.question || ""}` } : request,
|
||||
tool_call_id: p.tool_call_id,
|
||||
requested_at: requestedAt,
|
||||
suspendable: true,
|
||||
suspended: true,
|
||||
expires_at: p.expires_at,
|
||||
resolved: false,
|
||||
...state,
|
||||
answered: resolved && Boolean(p.response) && !response.declined,
|
||||
response,
|
||||
resolve_reason: response.declined ? 'declined' : state.resolve_reason,
|
||||
timed_out: p.status === 'expired',
|
||||
}]
|
||||
}
|
||||
if (p.kind !== 'tool_approval') return []
|
||||
|
|
@ -99,15 +120,18 @@ export function pendingPromptEvents(prompt: unknown): ChatMessage[] {
|
|||
pending_id: p.id,
|
||||
service_name: request.service_name,
|
||||
mcp_tool_name: request.mcp_tool_name,
|
||||
delegated_task: p.delegated_task,
|
||||
description: request.description,
|
||||
args_json: request.args === undefined ? '' : JSON.stringify(request.args),
|
||||
args_json: response.approved && response.modified_args !== undefined
|
||||
? JSON.stringify(response.modified_args)
|
||||
: request.args === undefined ? '' : JSON.stringify(request.args),
|
||||
grant_scope: request.grant_scope,
|
||||
tool_call_id: p.tool_call_id,
|
||||
requested_at: requestedAt,
|
||||
suspendable: true,
|
||||
suspended: true,
|
||||
expires_at: p.expires_at,
|
||||
resolved: false,
|
||||
...state,
|
||||
approved: Boolean(response.approved),
|
||||
}]
|
||||
}
|
||||
|
||||
|
|
@ -187,7 +211,8 @@ export function useChatStreamHandler(options: UseChatStreamHandlerOptions) {
|
|||
}
|
||||
|
||||
const markAssistantStopped = (message: ChatMessage) => {
|
||||
if (!message || message.is_completed) return
|
||||
if (!message) return
|
||||
message.run_state = ''
|
||||
message.is_completed = true
|
||||
if (message.isAgentMode) {
|
||||
if (!message.agentEventStream) message.agentEventStream = []
|
||||
|
|
@ -230,14 +255,24 @@ export function useChatStreamHandler(options: UseChatStreamHandlerOptions) {
|
|||
target = messagesList.find(
|
||||
(m) =>
|
||||
m.role === 'assistant' &&
|
||||
!m.is_completed &&
|
||||
(m.id === messageId ||
|
||||
m.assistant_message_id === messageId ||
|
||||
m.request_id === messageId),
|
||||
)
|
||||
}
|
||||
if (!target) target = getTrailingIncompleteAssistant()
|
||||
if (target) markAssistantStopped(target)
|
||||
if (!target) target = getTrailingIncompleteAssistant() || findLastMessage(m => m.role === 'assistant')
|
||||
if (target) {
|
||||
const turnId = persistedAssistantId(target)
|
||||
for (const row of messagesList) {
|
||||
if (row.role !== 'assistant' || persistedAssistantId(row) !== turnId) continue
|
||||
row.run_state = ''
|
||||
for (const e of (row.agentEventStream as ChatMessage[] | undefined) || []) {
|
||||
if (isPromptCard(e) && !e.resolved) Object.assign(e, { resolved: true, canceled: true })
|
||||
if (e.pending) Object.assign(e, { pending: false, canceled: true })
|
||||
}
|
||||
}
|
||||
markAssistantStopped(target)
|
||||
}
|
||||
fullContent.value = ''
|
||||
}
|
||||
|
||||
|
|
@ -263,6 +298,14 @@ export function useChatStreamHandler(options: UseChatStreamHandlerOptions) {
|
|||
|
||||
if (dataId && replaySegments.has(dataId)) return replaySegments.get(dataId)
|
||||
|
||||
// A delayed event from an earlier request must not bind to the current
|
||||
// assistant merely because it appears later in the transcript.
|
||||
if (dataId) {
|
||||
const requestMatch = findLastMessage(item => item.role === 'assistant' &&
|
||||
(item.request_id === dataId || item.id === dataId))
|
||||
if (requestMatch) return requestMatch
|
||||
}
|
||||
|
||||
const matched = findLastMessage((item) => {
|
||||
if (item.role !== 'assistant') return false
|
||||
if (dataId && (item.request_id === dataId || item.id === dataId)) return true
|
||||
|
|
@ -346,6 +389,7 @@ export function useChatStreamHandler(options: UseChatStreamHandlerOptions) {
|
|||
const shouldRenderAssistantMessage = (session: ChatMessage) => {
|
||||
if (!session?.isAgentMode) return true
|
||||
if (!session.is_completed) return true
|
||||
if (session.collaborationStatus?.tasks.length) return true
|
||||
const stream = session.agentEventStream
|
||||
if (Array.isArray(stream) && stream.length > 0) return true
|
||||
if (Array.isArray(session.knowledge_references) && session.knowledge_references.length > 0) {
|
||||
|
|
@ -409,6 +453,26 @@ export function useChatStreamHandler(options: UseChatStreamHandlerOptions) {
|
|||
Array.isArray(agentSteps) &&
|
||||
agentSteps.some((step) => (step as ChatMessage | undefined)?.truncated === true)
|
||||
|
||||
// Steering splits presentation, not the collaboration group. Its current
|
||||
// snapshot appears only on the last assistant segment of the parent turn.
|
||||
const consolidateCollaborationStatus = () => {
|
||||
const turns = new Map<string, { last: ChatMessage; snapshot?: CollaborationStatus }>()
|
||||
for (const row of messagesList) {
|
||||
if (row.role !== 'assistant') continue
|
||||
const id = persistedAssistantId(row)
|
||||
if (!id) continue
|
||||
const prior = turns.get(id)?.snapshot
|
||||
const incoming = row.collaborationStatus
|
||||
const snapshot = !incoming || (prior?.group_id === incoming.group_id && prior.revision > incoming.revision)
|
||||
? prior : incoming
|
||||
turns.set(id, { last: row, snapshot })
|
||||
delete row.collaborationStatus
|
||||
}
|
||||
for (const { last, snapshot } of turns.values()) {
|
||||
if (snapshot) last.collaborationStatus = snapshot
|
||||
}
|
||||
}
|
||||
|
||||
const reconstructEventStreamFromSteps = (
|
||||
agentSteps: unknown[],
|
||||
messageContent: string,
|
||||
|
|
@ -442,12 +506,17 @@ export function useChatStreamHandler(options: UseChatStreamHandlerOptions) {
|
|||
duration_ms: step.duration || undefined,
|
||||
})
|
||||
}
|
||||
const progressText = step.progress && String(step.progress).trim() ? String(step.progress) : ''
|
||||
const preambleText = step.thought && String(step.thought).trim() ? String(step.thought) : ''
|
||||
if (preambleText && step.intermediate_answer) {
|
||||
if (progressText) {
|
||||
events.push({ type: 'progress', event_id: step.progress_event_id || `step-${step.iteration}-progress`,
|
||||
content: progressText, done: true, iteration: step.iteration, timestamp: stepTimestamp || undefined })
|
||||
}
|
||||
if (!progressText && preambleText && step.intermediate_answer) {
|
||||
events.push({ type: 'answer', event_id: `step-${step.iteration}-answer`,
|
||||
content: preambleText, done: true, intermediate_answer: true, timestamp: stepTimestamp || undefined })
|
||||
}
|
||||
if (preambleText && hasToolCalls) {
|
||||
if (!progressText && preambleText && hasToolCalls) {
|
||||
events.push({
|
||||
type: 'answer',
|
||||
event_id: `step-${step.iteration}-preamble`,
|
||||
|
|
@ -488,7 +557,7 @@ export function useChatStreamHandler(options: UseChatStreamHandlerOptions) {
|
|||
})
|
||||
}
|
||||
|
||||
if (agentDurationMs > 0 || usage) {
|
||||
if (isCompleted && (agentDurationMs > 0 || usage)) {
|
||||
events.push({
|
||||
type: 'agent_complete',
|
||||
total_duration_ms: agentDurationMs,
|
||||
|
|
@ -551,14 +620,19 @@ export function useChatStreamHandler(options: UseChatStreamHandlerOptions) {
|
|||
|
||||
for (const raw of chatlist) {
|
||||
const item = preserveIncompleteStreamReactive ? raw : { ...raw }
|
||||
if (item.collaboration_status) item.collaborationStatus = item.collaboration_status
|
||||
if (item.id && existingIds.has(item.id)) continue
|
||||
if (item.id) existingIds.add(item.id)
|
||||
|
||||
item.isAgentMode = false
|
||||
if (item.collaborationStatus) {
|
||||
item.isAgentMode = true
|
||||
item.hideContent = true
|
||||
}
|
||||
// A run awaiting input has ended for now: nothing streams until its
|
||||
// prompt is answered, so it renders as settled.
|
||||
const awaiting = isAwaitingInput(item)
|
||||
const willContinueStream = preserveIncompleteStreamReactive && !item.is_completed
|
||||
const willContinueStream = preserveIncompleteStreamReactive && (!item.is_completed || awaiting)
|
||||
if (willContinueStream) {
|
||||
item.agentEventStream = item.agentEventStream || []
|
||||
item._eventMap = new Map()
|
||||
|
|
@ -572,16 +646,15 @@ export function useChatStreamHandler(options: UseChatStreamHandlerOptions) {
|
|||
|
||||
if (item.agent_steps && Array.isArray(item.agent_steps) && item.agent_steps.length > 0) {
|
||||
item.isAgentMode = true
|
||||
item.agentEventStream = markRaw(
|
||||
reconstructEventStreamFromSteps(
|
||||
item.agent_steps as unknown[],
|
||||
String(item.content || ''),
|
||||
Boolean(item.is_completed),
|
||||
Boolean(item.is_fallback),
|
||||
Number(item.agent_duration_ms) || 0,
|
||||
item.usage,
|
||||
),
|
||||
const restoredEvents = reconstructEventStreamFromSteps(
|
||||
item.agent_steps as unknown[],
|
||||
String(item.content || ''),
|
||||
Boolean(item.is_completed),
|
||||
Boolean(item.is_fallback),
|
||||
Number(item.agent_duration_ms) || 0,
|
||||
item.usage,
|
||||
)
|
||||
item.agentEventStream = willContinueStream ? restoredEvents : markRaw(restoredEvents)
|
||||
item.hideContent = true
|
||||
if (agentStepsAreTruncated(item.agent_steps as unknown[])) item.truncated = true
|
||||
}
|
||||
|
|
@ -589,13 +662,35 @@ export function useChatStreamHandler(options: UseChatStreamHandlerOptions) {
|
|||
if (awaiting) {
|
||||
item.isAgentMode = true
|
||||
item.hideContent = true
|
||||
item.agentEventStream = markRaw(
|
||||
(item.agentEventStream as ChatMessage[])
|
||||
.filter((e) => e.type !== 'agent_complete')
|
||||
.concat(pendingPromptEvents(item.pending_prompt)),
|
||||
)
|
||||
const awaitingEvents = (item.agentEventStream as ChatMessage[])
|
||||
.filter((e) => e.type !== 'agent_complete')
|
||||
|
||||
item.agentEventStream = willContinueStream ? awaitingEvents : markRaw(awaitingEvents)
|
||||
item.is_completed = true
|
||||
}
|
||||
const promptCards = [
|
||||
...(Array.isArray(item.prompt_history) ? item.prompt_history : []),
|
||||
...(Array.isArray(item.delegated_prompts) ? item.delegated_prompts : []),
|
||||
...(item.pending_prompt ? [item.pending_prompt] : []),
|
||||
].flatMap(pendingPromptEvents)
|
||||
if (promptCards.length) {
|
||||
item.isAgentMode = true
|
||||
item.hideContent = true
|
||||
const events = [...(item.agentEventStream as ChatMessage[])]
|
||||
promptCards.sort((a, b) => Number(a.timestamp || 0) - Number(b.timestamp || 0))
|
||||
for (const card of promptCards) {
|
||||
if (events.some(e => isPromptCard(e) && e.pending_id === card.pending_id)) continue
|
||||
// Replace ask_user's tool-result fallback with the authoritative row.
|
||||
const fallback = events.findIndex(e => e.pending_id === `history-${card.tool_call_id}` && !card.delegated_task)
|
||||
if (fallback >= 0) events.splice(fallback, 1)
|
||||
const at = events.findIndex(e =>
|
||||
(!card.delegated_task && e.type === 'tool_call' && e.tool_call_id === card.tool_call_id) ||
|
||||
(card.timestamp && e.timestamp && Number(e.timestamp) > Number(card.timestamp)) ||
|
||||
e.type === 'agent_complete' || (e.type === 'answer' && !e.event_id))
|
||||
events.splice(at < 0 ? events.length : at, 0, card)
|
||||
}
|
||||
item.agentEventStream = willContinueStream ? events : markRaw(events)
|
||||
}
|
||||
restoreQuickAnswerFlags(item)
|
||||
|
||||
if (item.content) {
|
||||
|
|
@ -632,6 +727,7 @@ export function useChatStreamHandler(options: UseChatStreamHandlerOptions) {
|
|||
} else {
|
||||
messagesList.push(...expandSteerForksInHistory(processed))
|
||||
}
|
||||
consolidateCollaborationStatus()
|
||||
}
|
||||
|
||||
if (isFirstEnter?.value) {
|
||||
|
|
@ -688,6 +784,16 @@ export function useChatStreamHandler(options: UseChatStreamHandlerOptions) {
|
|||
let message = resolveActiveAssistantMessage(data)
|
||||
let created = false
|
||||
|
||||
if (data.response_type === 'collaboration_status' || data.response_type === 'progress') {
|
||||
// These updates describe an existing parent run. Never create a new
|
||||
// bubble or attach an unknown/old request to an unrelated active turn.
|
||||
const matchesRequest = message && dataId && (message.request_id === dataId || message.id === dataId)
|
||||
const matchesAssistant = message && data.assistant_message_id &&
|
||||
persistedAssistantId(message) === data.assistant_message_id &&
|
||||
(!dataId || !message.request_id || message.request_id === dataId)
|
||||
if (!matchesRequest && !matchesAssistant) return
|
||||
}
|
||||
|
||||
if (message?.role === 'user') {
|
||||
message = undefined
|
||||
}
|
||||
|
|
@ -724,6 +830,7 @@ export function useChatStreamHandler(options: UseChatStreamHandlerOptions) {
|
|||
if (
|
||||
loading.value &&
|
||||
(data.response_type === 'thinking' ||
|
||||
data.response_type === 'progress' ||
|
||||
data.response_type === 'answer' ||
|
||||
data.response_type === 'tool_call' ||
|
||||
data.response_type === 'tool_approval_required' ||
|
||||
|
|
@ -735,8 +842,69 @@ export function useChatStreamHandler(options: UseChatStreamHandlerOptions) {
|
|||
|
||||
const responseType = data.response_type as string
|
||||
const dataPayload = data.data as ChatMessage | undefined
|
||||
// Child prompts can predate a steer boundary. Their resolution still
|
||||
// belongs to the same persisted turn, even when the active bubble changed.
|
||||
const turnPromptEvents = () => {
|
||||
const turnID = persistedAssistantId(message)
|
||||
return messagesList
|
||||
.filter(m => m.role === 'assistant' && (m === message || (turnID && persistedAssistantId(m) === turnID)))
|
||||
.flatMap(m => (m.agentEventStream as ChatMessage[] | undefined) || [])
|
||||
}
|
||||
|
||||
switch (responseType) {
|
||||
case 'collaboration_status': {
|
||||
const snapshot = dataPayload as unknown as CollaborationStatus | undefined
|
||||
if (!snapshot?.group_id || !Number.isSafeInteger(snapshot.revision) || !Array.isArray(snapshot.tasks)) break
|
||||
const turnID = persistedAssistantId(message)
|
||||
const previous = messagesList
|
||||
.filter(m => m.role === 'assistant' && persistedAssistantId(m) === turnID)
|
||||
.map(m => m.collaborationStatus)
|
||||
.filter((s): s is CollaborationStatus => s?.group_id === snapshot.group_id)
|
||||
.sort((a, b) => b.revision - a.revision)[0]
|
||||
if (previous && snapshot.revision <= previous.revision) break
|
||||
const tasks = snapshot.tasks.map((task): CollaborationTaskStatus => {
|
||||
const prior = previous?.tasks.find(t => t.id === task.id && t.run_id === task.run_id)
|
||||
// A follow-up has a new run_id and can become queued/running again;
|
||||
// late updates to a completed run cannot undo its terminal state.
|
||||
return prior && TERMINAL_COLLABORATION_STATES.has(prior.status)
|
||||
? { ...prior }
|
||||
: { ...task, progress: task.progress ? { ...task.progress } : task.progress }
|
||||
})
|
||||
message.collaborationStatus = { group_id: snapshot.group_id, revision: snapshot.revision, tasks }
|
||||
consolidateCollaborationStatus()
|
||||
break
|
||||
}
|
||||
case 'progress': {
|
||||
const eventId = String(dataPayload?.event_id || dataPayload?.id || '')
|
||||
if (!eventId) break
|
||||
const previous = turnPromptEvents().find(e => (e.type === 'progress' || e.type === 'answer') && e.event_id === eventId)
|
||||
if (previous?.type === 'progress' && previous.done) break
|
||||
if (previous) {
|
||||
const wasAnswer = previous.type === 'answer'
|
||||
previous.type = 'progress'
|
||||
delete previous.superseded
|
||||
if (typeof data.content === 'string') previous.content = data.content
|
||||
previous.done = Boolean(data.done)
|
||||
previous.iteration = dataPayload?.iteration
|
||||
if (wasAnswer) {
|
||||
// Older streams can emit the provisional text as answer first.
|
||||
// Reclassify that same event rather than displaying it twice or
|
||||
// seeding the final answer with the progress text.
|
||||
for (const row of messagesList) {
|
||||
if ((row.agentEventStream as ChatMessage[] | undefined)?.includes(previous)) {
|
||||
row.content = recomposeAgentAnswer(row)
|
||||
if (row === message) fullContent.value = String(row.content || '')
|
||||
}
|
||||
}
|
||||
}
|
||||
} else {
|
||||
;(message.agentEventStream as ChatMessage[]).push({
|
||||
type: 'progress', event_id: eventId, content: String(data.content || ''),
|
||||
done: Boolean(data.done), iteration: dataPayload?.iteration,
|
||||
})
|
||||
}
|
||||
break
|
||||
}
|
||||
case 'thinking': {
|
||||
const eventId = dataPayload?.event_id as string | undefined
|
||||
log('[Thinking Event]', {
|
||||
|
|
@ -807,17 +975,21 @@ export function useChatStreamHandler(options: UseChatStreamHandlerOptions) {
|
|||
case 'tool_approval_required': {
|
||||
if (!message.agentEventStream) message.agentEventStream = []
|
||||
const d = dataPayload || {}
|
||||
if (turnPromptEvents().some(e => e.pending_id === d.pending_id)) break
|
||||
;(message.agentEventStream as ChatMessage[]).push({
|
||||
type: 'tool_approval_required',
|
||||
pending_id: d.pending_id,
|
||||
service_name: d.service_name,
|
||||
mcp_tool_name: d.mcp_tool_name,
|
||||
description: d.description,
|
||||
delegated_task: d.delegated_task,
|
||||
args_json: d.args_json,
|
||||
grant_scope: d.grant_scope,
|
||||
timeout_seconds: d.timeout_seconds,
|
||||
hot_wait_seconds: d.hot_wait_seconds,
|
||||
suspendable: d.suspendable,
|
||||
suspended: d.suspended,
|
||||
expires_at: d.expires_at,
|
||||
requested_at: d.requested_at,
|
||||
tool_call_id: d.tool_call_id,
|
||||
resolved: false,
|
||||
|
|
@ -831,14 +1003,18 @@ export function useChatStreamHandler(options: UseChatStreamHandlerOptions) {
|
|||
break
|
||||
}
|
||||
if (!message.agentEventStream) message.agentEventStream = []
|
||||
if (turnPromptEvents().some(e => e.pending_id === d.pending_id)) break
|
||||
;(message.agentEventStream as ChatMessage[]).push({
|
||||
type: 'agent_prompt_required',
|
||||
pending_id: d.pending_id,
|
||||
kind: d.kind,
|
||||
delegated_task: d.delegated_task,
|
||||
request: d.request,
|
||||
timeout_seconds: d.timeout_seconds,
|
||||
hot_wait_seconds: d.hot_wait_seconds,
|
||||
suspendable: d.suspendable,
|
||||
suspended: d.suspended,
|
||||
expires_at: d.expires_at,
|
||||
requested_at: d.requested_at,
|
||||
tool_call_id: d.tool_call_id,
|
||||
resolved: false,
|
||||
|
|
@ -847,7 +1023,7 @@ export function useChatStreamHandler(options: UseChatStreamHandlerOptions) {
|
|||
}
|
||||
case 'agent_prompt_resolved': {
|
||||
const d = dataPayload || {}
|
||||
const ev = (message.agentEventStream as ChatMessage[] | undefined)?.find(
|
||||
const ev = turnPromptEvents().find(
|
||||
(e) => e.type === 'agent_prompt_required' && e.pending_id === d.pending_id,
|
||||
)
|
||||
if (ev) {
|
||||
|
|
@ -881,7 +1057,7 @@ export function useChatStreamHandler(options: UseChatStreamHandlerOptions) {
|
|||
case 'tool_approval_resolved': {
|
||||
const d = dataPayload || {}
|
||||
const pid = d.pending_id
|
||||
const ev = (message.agentEventStream as ChatMessage[] | undefined)?.find(
|
||||
const ev = turnPromptEvents().find(
|
||||
(e) => e.type === 'tool_approval_required' && e.pending_id === pid,
|
||||
)
|
||||
if (ev) {
|
||||
|
|
@ -913,7 +1089,7 @@ export function useChatStreamHandler(options: UseChatStreamHandlerOptions) {
|
|||
const d = dataPayload || {}
|
||||
const pid = d.pending_id
|
||||
const sid = d.service_id
|
||||
const list = message.agentEventStream as ChatMessage[] | undefined
|
||||
const list = turnPromptEvents()
|
||||
// Resolve the matching card; also clear any other still-pending cards
|
||||
// for the same service (parallel tool calls dedup to a single auth).
|
||||
list?.forEach((e) => {
|
||||
|
|
@ -1036,7 +1212,7 @@ export function useChatStreamHandler(options: UseChatStreamHandlerOptions) {
|
|||
if (toolCallId && pending.has(toolCallId)) {
|
||||
toolCallEvent = pending.get(toolCallId)
|
||||
pending.delete(toolCallId)
|
||||
} else {
|
||||
} else if (!toolCallId) {
|
||||
Array.from(pending.entries()).some(([key, value]) => {
|
||||
if (value.tool_name === toolName) {
|
||||
toolCallEvent = value
|
||||
|
|
@ -1100,12 +1276,44 @@ export function useChatStreamHandler(options: UseChatStreamHandlerOptions) {
|
|||
let answerEvent = eventId
|
||||
? eventMap.get(eventId)
|
||||
: stream.find((e) => e.type === 'answer' && !e.event_id)
|
||||
const replaceAnswer = dataPayload?.replace === true
|
||||
if (replaceAnswer && eventId) {
|
||||
const turnID = persistedAssistantId(message)
|
||||
// A protocol correction can arrive after a steer boundary or after
|
||||
// that provisional event was reclassified as progress. Retract only
|
||||
// this ID, never another round's legitimate answer.
|
||||
for (const row of messagesList) {
|
||||
if (row.role !== 'assistant' || (row !== message && persistedAssistantId(row) !== turnID)) continue
|
||||
const events = (row.agentEventStream as ChatMessage[] | undefined) || []
|
||||
for (const prior of events) {
|
||||
if (prior.event_id !== eventId || !['answer', 'progress'].includes(String(prior.type))) continue
|
||||
prior.content = ''
|
||||
prior.done = true
|
||||
}
|
||||
if (row !== message) {
|
||||
row.agentEventStream = events.filter(e => e.event_id !== eventId || !['answer', 'progress'].includes(String(e.type)))
|
||||
;(row._eventMap as Map<string, ChatMessage> | undefined)?.delete(eventId)
|
||||
}
|
||||
row.content = recomposeAgentAnswer(row)
|
||||
}
|
||||
answerEvent = eventMap.get(eventId) || stream.find(e => e.event_id === eventId)
|
||||
if (answerEvent) {
|
||||
Object.assign(answerEvent, { type: 'answer', content: '', done: false, superseded: false })
|
||||
eventMap.set(eventId, answerEvent)
|
||||
}
|
||||
}
|
||||
// Replayed provisional answer chunks may follow a progress snapshot
|
||||
// for the same event. They must not append to or revive that answer.
|
||||
if (!replaceAnswer && (answerEvent?.type === 'progress' || (eventId && turnPromptEvents().some(
|
||||
e => e.type === 'progress' && e.event_id === eventId,
|
||||
)))) break
|
||||
if (!answerEvent) {
|
||||
answerEvent = { type: 'answer', event_id: eventId, content: '', done: false }
|
||||
stream.push(answerEvent)
|
||||
if (eventId) eventMap.set(eventId, answerEvent)
|
||||
}
|
||||
if (!answerEvent.content && message.content && String(message.content).trim()) {
|
||||
if (replaceAnswer) answerEvent.protocol_replaced = true
|
||||
if (!replaceAnswer && !answerEvent.protocol_replaced && !answerEvent.content && message.content && String(message.content).trim()) {
|
||||
// Seeding exists for resume paths where message.content holds text no
|
||||
// stream event carries. When a live prior answer event exists, its
|
||||
// text is already counted by recomposeAgentAnswer, so seeding the new
|
||||
|
|
@ -1122,8 +1330,8 @@ export function useChatStreamHandler(options: UseChatStreamHandlerOptions) {
|
|||
answerEvent.content = message.content
|
||||
}
|
||||
}
|
||||
if (data.content) {
|
||||
answerEvent.content = String(answerEvent.content || '') + String(data.content)
|
||||
if (data.content || replaceAnswer) {
|
||||
answerEvent.content = replaceAnswer ? String(data.content || '') : String(answerEvent.content || '') + String(data.content)
|
||||
message.content = recomposeAgentAnswer(message)
|
||||
fullContent.value = String(message.content || '')
|
||||
}
|
||||
|
|
@ -1197,6 +1405,7 @@ export function useChatStreamHandler(options: UseChatStreamHandlerOptions) {
|
|||
injectedUser,
|
||||
steerId,
|
||||
)
|
||||
consolidateCollaborationStatus()
|
||||
if (dataId && replaySegments.has(dataId)) replaySegments.set(dataId, continuation)
|
||||
if (!alreadyInList) emitMessageCreated(injectedUser)
|
||||
if (continuation !== message) {
|
||||
|
|
@ -1251,6 +1460,7 @@ export function useChatStreamHandler(options: UseChatStreamHandlerOptions) {
|
|||
timestamp: Date.now(),
|
||||
reason: dataPayload?.reason || 'user_requested',
|
||||
})
|
||||
markInFlightAssistantStopped(persistedAssistantId(message))
|
||||
message.is_completed = true
|
||||
loading.value = false
|
||||
isReplying.value = false
|
||||
|
|
@ -1300,7 +1510,9 @@ export function useChatStreamHandler(options: UseChatStreamHandlerOptions) {
|
|||
|
||||
if (data.response_type === 'agent_query') {
|
||||
if (data.id) replaySegments.delete(String(data.id))
|
||||
const replay = resetSteerTurnForReplay(messagesList, String(data.id || ''))
|
||||
const resumeData = (data.data || {}) as ChatMessage
|
||||
const replay = resetSteerTurnForReplay(messagesList, String(data.id || ''),
|
||||
String(resumeData.resume_pending_id || ''), String(resumeData.resume_tool_call_id || ''))
|
||||
if (replay) replaySegments.set(String(data.id), replay)
|
||||
if (data.id) {
|
||||
const earlyMsg = getTrailingIncompleteAssistant()
|
||||
|
|
@ -1370,6 +1582,8 @@ export function useChatStreamHandler(options: UseChatStreamHandlerOptions) {
|
|||
|
||||
const isAgentOnlyResponse =
|
||||
data.response_type === 'thinking' ||
|
||||
data.response_type === 'progress' ||
|
||||
data.response_type === 'collaboration_status' ||
|
||||
data.response_type === 'tool_call' ||
|
||||
data.response_type === 'tool_result' ||
|
||||
data.response_type === 'command_output' ||
|
||||
|
|
|
|||
|
|
@ -0,0 +1,138 @@
|
|||
import assert from 'node:assert/strict'
|
||||
import { readFileSync } from 'node:fs'
|
||||
import test from 'node:test'
|
||||
import { parse } from '@vue/compiler-sfc'
|
||||
import vm from 'node:vm'
|
||||
import ts from 'typescript'
|
||||
import * as vue from 'vue'
|
||||
import * as finalContent from '../utils/finalArtifactContent.ts'
|
||||
import * as history from '../utils/rag-pipeline-history.ts'
|
||||
import * as timestamps from '../utils/messageTimestamp.ts'
|
||||
import * as steering from '../utils/steerStreamFork.ts'
|
||||
import * as dataChange from '../utils/assistantDataChange.ts'
|
||||
import type { useChatStreamHandler as StreamHandler } from './useChatStreamHandler.ts'
|
||||
|
||||
const source = readFileSync(new URL('./useChatStreamHandler.ts', import.meta.url), 'utf8')
|
||||
const compiled = ts.transpileModule(source, {
|
||||
compilerOptions: { module: ts.ModuleKind.CommonJS, target: ts.ScriptTarget.ES2022 },
|
||||
}).outputText
|
||||
const modules: Record<string, unknown> = {
|
||||
vue, 'vue-i18n': { useI18n: () => ({ t: (key: string) => key }) },
|
||||
'@/utils/finalArtifactContent': finalContent,
|
||||
'@/utils/rag-pipeline-history': history,
|
||||
'@/utils/messageTimestamp': timestamps,
|
||||
'@/utils/steerStreamFork': steering,
|
||||
'@/utils/assistantDataChange': dataChange,
|
||||
}
|
||||
const exports: { useChatStreamHandler?: typeof StreamHandler } = {}
|
||||
vm.runInNewContext(compiled, {
|
||||
exports, console,
|
||||
require: (id: string) => {
|
||||
assert.ok(id in modules, `unexpected import ${id}`)
|
||||
return modules[id]
|
||||
},
|
||||
})
|
||||
const useChatStreamHandler = exports.useChatStreamHandler!
|
||||
|
||||
const component = parse(readFileSync(new URL('../views/chat/components/ChildAgentStream.vue', import.meta.url), 'utf8')).descriptor.scriptSetup!.content
|
||||
const childCode = ts.transpileModule(component + '\nexports.state = { messages, refresh, viewport, onScroll, scrollToBottom, scrollFollow };', {
|
||||
compilerOptions: { module: ts.ModuleKind.CommonJS, target: ts.ScriptTarget.ES2022 },
|
||||
}).outputText
|
||||
|
||||
async function flushUntil(predicate: () => boolean) {
|
||||
for (let n = 0; n < 20 && !predicate(); n++) {
|
||||
await new Promise(resolve => setImmediate(resolve))
|
||||
}
|
||||
assert.ok(predicate(), 'expected async subscription transition')
|
||||
}
|
||||
|
||||
test('open suspended child resumes GET subscription and live timeline after parent approval', async () => {
|
||||
const props = vue.reactive({ task: { sessionId: 'child-session', status: 'waiting' }, active: true })
|
||||
const requests: any[] = []
|
||||
let deliver: (chunk: any) => void = () => {}
|
||||
let finish: () => void = () => {}
|
||||
let mounted: () => Promise<void> = async () => {}
|
||||
let unmounted: () => void = () => {}
|
||||
let stopped = false
|
||||
const stream = {
|
||||
isStreaming: vue.ref(false), error: vue.ref(''),
|
||||
onChunk: (fn: typeof deliver) => { deliver = fn },
|
||||
startStream: async (args: any) => {
|
||||
requests.push(args)
|
||||
stream.isStreaming.value = true
|
||||
await new Promise<void>(resolve => { finish = resolve })
|
||||
stream.isStreaming.value = false
|
||||
},
|
||||
stopStream: () => { stopped = true; finish() },
|
||||
}
|
||||
const childExports: any = {}
|
||||
const scope = vue.effectScope()
|
||||
scope.run(() => vm.runInNewContext(childCode, {
|
||||
exports: childExports, console, defineProps: () => props,
|
||||
setTimeout: () => 1, clearTimeout() {},
|
||||
require: (id: string) => {
|
||||
if (id === 'vue') return { ...vue, onMounted: (fn: typeof mounted) => { mounted = fn }, onUnmounted: (fn: typeof unmounted) => { unmounted = fn } }
|
||||
if (id === '@/composables/useChatScrollFollow') {
|
||||
const exported: any = {}
|
||||
const scrollCode = ts.transpileModule(readFileSync(new URL('./useChatScrollFollow.ts', import.meta.url), 'utf8'), {
|
||||
compilerOptions: { module: ts.ModuleKind.CommonJS, target: ts.ScriptTarget.ES2022 },
|
||||
}).outputText
|
||||
vm.runInNewContext(scrollCode, { exports: exported, require: (name: string) => name === 'vue'
|
||||
? { ...vue, provide() {}, onMounted() {}, onUnmounted() {} }
|
||||
: { useStickyBottomOnResize() {} } })
|
||||
return exported
|
||||
}
|
||||
if (id === '@/api/chat') return { getMessageList: async () => ({ data: [{
|
||||
id: 'child-answer', request_id: 'child-run', role: 'assistant', content: '',
|
||||
is_completed: false, run_state: 'awaiting_input', agent_duration_ms: 100,
|
||||
agent_steps: [{ iteration: 0, reasoning_content: 'before approval', tool_calls: [{ id: 'call-1', name: 'mcp_read', args: {} }] }],
|
||||
pending_prompt: { id: 'approval', kind: 'tool_approval', tool_call_id: 'call-1', request: {} },
|
||||
}] }) }
|
||||
if (id === '@/api/chat/streame') return { useStream: () => stream }
|
||||
if (id === '@/composables/useChatStreamHandler') return { useChatStreamHandler, isAwaitingInput: (m: any) => m?.run_state === 'awaiting_input' }
|
||||
if (id === '@/utils/collaborationDisplay') return { isCollaborationTaskActive: (s: string) => ['running', 'waiting'].includes(s) }
|
||||
assert.ok(id in modules, `unexpected component import ${id}`)
|
||||
return modules[id]
|
||||
},
|
||||
}))
|
||||
await mounted()
|
||||
assert.equal(requests.length, 0, 'approval wait should not keep replaying the suspended stream')
|
||||
assert.equal(childExports.state.messages[0].is_completed, true, 'history is settled for presentation')
|
||||
props.task.status = 'running'
|
||||
await flushUntil(() => requests.length === 1)
|
||||
assert.equal(requests[0].method, 'GET')
|
||||
assert.equal(requests[0].query, 'child-answer')
|
||||
const message = childExports.state.messages[0]
|
||||
assert.equal(message.is_completed, false)
|
||||
assert.ok(!message.agentEventStream.some((e: any) => e.tool_call_id === 'call-1' && e.type === 'tool_call'))
|
||||
const visible = vue.computed(() => message.agentEventStream.map((e: any) => `${e.type}:${e.content || ''}:${e.pending}`).join('|'))
|
||||
assert.doesNotMatch(visible.value, /after approval/)
|
||||
deliver({ response_type: 'thinking', id: 'child-run', content: 'after approval', done: false, data: { event_id: 't2' } })
|
||||
assert.match(visible.value, /after approval/)
|
||||
deliver({ response_type: 'tool_call', id: 'child-run', data: { tool_call_id: 'call-2', tool_name: 'mcp_read', arguments: {} } })
|
||||
assert.match(visible.value, /tool_call::true/)
|
||||
assert.equal(message.is_completed, false, 'timeline updates before completion')
|
||||
childExports.state.viewport.value = { scrollTop: 400, scrollHeight: 2000, clientHeight: 400 }
|
||||
childExports.state.scrollFollow.rememberPosition()
|
||||
childExports.state.viewport.value.scrollTop = 240
|
||||
childExports.state.onScroll()
|
||||
props.active = false
|
||||
await vue.nextTick()
|
||||
childExports.state.viewport.value.scrollTop = 0
|
||||
deliver({ response_type: 'thinking', id: 'child-run', content: 'hidden-tab-update', done: false, data: { event_id: 't3' } })
|
||||
childExports.state.scrollToBottom()
|
||||
await vue.nextTick()
|
||||
assert.match(visible.value, /hidden-tab-update/, 'hidden tabs still receive stream updates')
|
||||
assert.equal(childExports.state.viewport.value.scrollTop, 0, 'hidden streams must not move the viewport')
|
||||
assert.equal(stopped, false, 'switching tabs must not disconnect the stream')
|
||||
props.active = true
|
||||
await vue.nextTick()
|
||||
await vue.nextTick()
|
||||
assert.equal(childExports.state.viewport.value.scrollTop, 240, 'returning to a scrolled-up tab restores its position')
|
||||
unmounted()
|
||||
scope.stop()
|
||||
assert.equal(stopped, true)
|
||||
const before = visible.value
|
||||
deliver({ response_type: 'thinking', id: 'child-run', content: 'late', done: false, data: { event_id: 't2' } })
|
||||
assert.equal(visible.value, before, 'late stream frames cannot update a closed viewer')
|
||||
})
|
||||
|
|
@ -0,0 +1,42 @@
|
|||
import assert from 'node:assert/strict'
|
||||
import { test } from 'node:test'
|
||||
import { ref } from 'vue'
|
||||
import { createChildAgentTabs } from './useChildAgentTabs'
|
||||
import type { CollaborationTaskView } from '../utils/collaborationDisplay'
|
||||
const task = (id: string, status = 'running'): CollaborationTaskView => ({ id, sessionId: `session-${id}`, runId: 'r1', name: id, displayName: id, status, latestMessage: '' })
|
||||
|
||||
test('tabs deduplicate child entries, retain live status and return to main when the selected tab closes', () => {
|
||||
const state = createChildAgentTabs()
|
||||
const a = ref(task('a')), b = ref(task('b'))
|
||||
state.open(a.value, () => a.value)
|
||||
const aId = state.activeId.value
|
||||
state.open(b.value, () => b.value)
|
||||
const bId = state.activeId.value
|
||||
state.open(a.value, () => a.value)
|
||||
assert.equal(state.tabs.value.length, 2)
|
||||
assert.equal(state.activeId.value, aId)
|
||||
a.value = { ...a.value, status: 'waiting' }
|
||||
assert.equal(state.tabs.value[0].task.status, 'waiting')
|
||||
a.value = { ...a.value, runId: 'r2', status: 'running' }
|
||||
assert.equal(state.tabs.value[0].task.runId, 'r2')
|
||||
state.select('')
|
||||
assert.equal(state.tabs.value.length, 2)
|
||||
state.select(aId)
|
||||
state.close(bId)
|
||||
assert.equal(state.activeId.value, aId)
|
||||
state.close(aId)
|
||||
assert.equal(state.activeId.value, '')
|
||||
assert.deepEqual(state.tabs.value, [])
|
||||
})
|
||||
|
||||
test('tab state is scoped to a chat and reset releases previous session entries', () => {
|
||||
const first = createChildAgentTabs(), second = createChildAgentTabs()
|
||||
first.open(task('a'), () => undefined)
|
||||
assert.equal(first.tabs.value[0].task.displayName, 'a')
|
||||
assert.equal(second.tabs.value.length, 0)
|
||||
first.select('missing')
|
||||
assert.notEqual(first.activeId.value, 'missing')
|
||||
first.reset()
|
||||
assert.equal(first.activeId.value, '')
|
||||
assert.equal(first.tabs.value.length, 0)
|
||||
})
|
||||
|
|
@ -0,0 +1,38 @@
|
|||
import { computed, shallowRef, type InjectionKey } from 'vue'
|
||||
import { collaborationTasks, type CollaborationTaskView } from '../utils/collaborationDisplay'
|
||||
|
||||
export function createChildAgentTabs() {
|
||||
const entries = shallowRef<Array<{ id: string; initial: CollaborationTaskView; latest: () => CollaborationTaskView | undefined }>>([])
|
||||
const activeId = shallowRef('')
|
||||
const attention = shallowRef(false)
|
||||
const tabs = computed(() => entries.value.map(entry => ({ id: entry.id, task: entry.latest() || entry.initial })))
|
||||
function open(task: CollaborationTaskView, latest: () => CollaborationTaskView | undefined) {
|
||||
const id = `${task.sessionId}:${task.id}`
|
||||
const entry = { id, initial: task, latest }
|
||||
const index = entries.value.findIndex(item => item.id === id)
|
||||
if (index < 0) entries.value = [...entries.value, entry]
|
||||
else entries.value = entries.value.map(item => item.id === id ? entry : item)
|
||||
activeId.value = id
|
||||
}
|
||||
function select(id: string) {
|
||||
if (!id || entries.value.some(entry => entry.id === id)) activeId.value = id
|
||||
}
|
||||
function close(id: string) {
|
||||
entries.value = entries.value.filter(entry => entry.id !== id)
|
||||
if (activeId.value === id) activeId.value = ''
|
||||
}
|
||||
function reset() { entries.value = []; activeId.value = ''; attention.value = false }
|
||||
return { tabs, activeId, attention, open, select, close, reset }
|
||||
}
|
||||
export const childAgentTabsKey: InjectionKey<ReturnType<typeof createChildAgentTabs>> = Symbol('child-agent-tabs')
|
||||
|
||||
// Steering moves the current snapshot between presentation segments. Resolve
|
||||
// by durable child identity across the conversation, never by the opened row.
|
||||
export function findChildAgentTask(messages: readonly { collaborationStatus?: unknown }[], task: CollaborationTaskView) {
|
||||
for (let i = messages.length - 1; i >= 0; i--) {
|
||||
const current = collaborationTasks(messages[i].collaborationStatus)
|
||||
.find(item => item.id === task.id && item.sessionId === task.sessionId)
|
||||
if (current) return current
|
||||
}
|
||||
}
|
||||
export const childAgentTaskLookupKey: InjectionKey<(task: CollaborationTaskView) => CollaborationTaskView | undefined> = Symbol('child-agent-task-lookup')
|
||||
|
|
@ -0,0 +1,21 @@
|
|||
import assert from 'node:assert/strict'
|
||||
import { test } from 'node:test'
|
||||
import { effectScope } from 'vue'
|
||||
import { useChildAgentViewer } from './useChildAgentViewer'
|
||||
|
||||
test('opening a child in another message closes the previous viewer without a stale close clearing the new one', () => {
|
||||
const first = effectScope()
|
||||
const second = effectScope()
|
||||
const a = first.run(useChildAgentViewer)!
|
||||
const b = second.run(useChildAgentViewer)!
|
||||
a.value = 'a'
|
||||
assert.equal(a.value, 'a')
|
||||
assert.equal(b.value, '')
|
||||
b.value = 'b'
|
||||
assert.equal(a.value, '')
|
||||
assert.equal(b.value, 'b')
|
||||
first.stop()
|
||||
assert.equal(b.value, 'b')
|
||||
second.stop()
|
||||
assert.equal(b.value, '')
|
||||
})
|
||||
|
|
@ -0,0 +1,17 @@
|
|||
import { computed, onScopeDispose, shallowRef } from 'vue'
|
||||
|
||||
// Multiple assistant messages can contain child entry points, but the page has
|
||||
// one detail viewer. Opening another entry releases the previous subscription.
|
||||
const active = shallowRef<{ owner: symbol; taskId: string } | null>(null)
|
||||
export function useChildAgentViewer() {
|
||||
const owner = Symbol('child-viewer')
|
||||
const selectedTaskId = computed({
|
||||
get: () => active.value?.owner === owner ? active.value.taskId : '',
|
||||
set: (taskId: string) => {
|
||||
if (taskId) active.value = { owner, taskId }
|
||||
else if (active.value?.owner === owner) active.value = null
|
||||
},
|
||||
})
|
||||
onScopeDispose(() => { selectedTaskId.value = '' })
|
||||
return selectedTaskId
|
||||
}
|
||||
|
|
@ -4,6 +4,7 @@ import test from 'node:test'
|
|||
import vm from 'node:vm'
|
||||
import ts from 'typescript'
|
||||
import * as vue from 'vue'
|
||||
import * as steering from '../utils/steerStreamFork.ts'
|
||||
import { isSubmitKey, optionIndexForKey, optionKey } from '../utils/promptKeys.ts'
|
||||
|
||||
const source = readFileSync(new URL('./usePromptDock.ts', import.meta.url), 'utf8')
|
||||
|
|
@ -12,6 +13,7 @@ const compiled = ts.transpileModule(source, {
|
|||
}).outputText
|
||||
const modules = {
|
||||
vue,
|
||||
'@/utils/steerStreamFork': steering,
|
||||
'@/composables/useChatStreamHandler': {
|
||||
isAwaitingInput: (m) => m?.run_state === 'awaiting_input',
|
||||
},
|
||||
|
|
@ -176,3 +178,20 @@ test('Enter on an unselected option selects it instead of submitting the previou
|
|||
assert.deepEqual(submitted, [['B']])
|
||||
}
|
||||
})
|
||||
|
||||
test('steering keeps earlier child approvals docked only while the same turn is active', () => {
|
||||
const messages = vue.reactive([
|
||||
{ id: 'parent', role: 'assistant', is_completed: true, steerForked: true, agentEventStream: [approval('child-a'), approval('child-b')] },
|
||||
{ id: 'steer-user', role: 'user' },
|
||||
{ id: 'continuation', assistant_message_id: 'parent', role: 'assistant', is_completed: false, agentEventStream: [] },
|
||||
{ id: 'other-turn', role: 'assistant', is_completed: true, agentEventStream: [approval('old')] },
|
||||
])
|
||||
assert.deepEqual(ids(pendingPrompts(messages)), ['child-a', 'child-b'])
|
||||
messages[0].agentEventStream[0].resolved = true
|
||||
assert.deepEqual(ids(pendingPrompts(messages)), ['child-b'])
|
||||
messages[2].is_completed = true
|
||||
assert.deepEqual(ids(pendingPrompts(messages)), [])
|
||||
// A new turn must never revive the old approval cards.
|
||||
messages.push({ id: 'new-turn', role: 'assistant', is_completed: false, agentEventStream: [] })
|
||||
assert.deepEqual(ids(pendingPrompts(messages)), [])
|
||||
})
|
||||
|
|
|
|||
|
|
@ -1,5 +1,6 @@
|
|||
import { computed, inject, provide, reactive, ref, type ComputedRef, type InjectionKey, type Ref } from 'vue'
|
||||
import { isAwaitingInput } from '@/composables/useChatStreamHandler'
|
||||
import { persistedAssistantId } from '@/utils/steerStreamFork'
|
||||
|
||||
type PromptEvent = Record<string, any>
|
||||
type ChatRow = Record<string, unknown>
|
||||
|
|
@ -38,11 +39,21 @@ function isDockable(e: PromptEvent): boolean {
|
|||
*/
|
||||
export function pendingPrompts(messages: ChatRow[]): PromptEvent[] {
|
||||
const out: PromptEvent[] = []
|
||||
const liveTurns = new Set(messages
|
||||
.filter(m => m.role === 'assistant' && (!m.is_completed || isAwaitingInput(m)))
|
||||
.map(persistedAssistantId).filter(Boolean))
|
||||
const seen = new Set<string>()
|
||||
for (const message of messages) {
|
||||
if (message.role !== 'assistant') continue
|
||||
if (message.is_completed && !isAwaitingInput(message)) continue
|
||||
// Steering seals a display segment, not the parent run or its children.
|
||||
// Keep that segment's cards actionable while its continuation is live.
|
||||
if (message.is_completed && !isAwaitingInput(message) &&
|
||||
!(message.steerForked && liveTurns.has(persistedAssistantId(message)))) continue
|
||||
for (const e of (message.agentEventStream as PromptEvent[] | undefined) || []) {
|
||||
if (isDockable(e)) out.push(e)
|
||||
if (isDockable(e) && !seen.has(e.pending_id)) {
|
||||
seen.add(e.pending_id)
|
||||
out.push(e)
|
||||
}
|
||||
}
|
||||
}
|
||||
return out
|
||||
|
|
|
|||
|
|
@ -12,6 +12,7 @@ import { onMounted, onUnmounted, type Ref } from 'vue'
|
|||
export function useStickyBottomOnResize(
|
||||
scrollContainer: Ref<HTMLElement | null>,
|
||||
userHasScrolledUp: Ref<boolean>,
|
||||
onFollow?: () => void,
|
||||
): void {
|
||||
let resizeObserver: ResizeObserver | null = null
|
||||
|
||||
|
|
@ -25,6 +26,7 @@ export function useStickyBottomOnResize(
|
|||
// answer, then snaps it back on the next frame. Correct the scroll offset
|
||||
// now; changing scrollTop does not resize the observed content wrapper.
|
||||
container.scrollTop = container.scrollHeight
|
||||
onFollow?.()
|
||||
}
|
||||
|
||||
onMounted(() => {
|
||||
|
|
|
|||
|
|
@ -6461,6 +6461,9 @@ export default {
|
|||
expand: 'Expand'
|
||||
},
|
||||
toolApproval: {
|
||||
title: 'Approval',
|
||||
toolDescription: 'Tool description',
|
||||
delegatedTask: 'Delegated task',
|
||||
waiting: 'Awaiting review · {target}',
|
||||
waitingStatus: 'Awaiting review',
|
||||
targetWithTool: '{service} › {tool}',
|
||||
|
|
@ -6482,6 +6485,7 @@ export default {
|
|||
parked: 'Waiting in the background — answer any time',
|
||||
parkedUntil: 'Waiting in the background — answer before {time}',
|
||||
abandonedTag: 'Abandoned',
|
||||
canceledTag: 'Canceled',
|
||||
invalidJson: 'Arguments must be valid JSON',
|
||||
submitted: 'Submitted',
|
||||
submitFailed: 'Submit failed',
|
||||
|
|
@ -6591,7 +6595,12 @@ export default {
|
|||
databaseQuery: 'Database Query',
|
||||
findOperations: 'Find operations',
|
||||
runOperation: 'Run operation',
|
||||
tryAgent: 'Try agent',
|
||||
spawn_agent: 'Start agent',
|
||||
list_agents: 'List agents',
|
||||
send_message: 'Send message',
|
||||
followup_task: 'Continue task',
|
||||
interrupt_agent: 'Interrupt agent',
|
||||
wait_agent: 'Wait for agent',
|
||||
openPage: 'Open page',
|
||||
searchWeKnoraDocs: 'Search product docs',
|
||||
readWeKnoraDoc: 'Read product doc',
|
||||
|
|
@ -6599,6 +6608,33 @@ export default {
|
|||
selectTab: 'Select tab',
|
||||
fillPage: 'Fill page'
|
||||
},
|
||||
collaboration: {
|
||||
tabs: 'Task tabs',
|
||||
mainConversation: 'Main chat',
|
||||
recentProgress: 'Recent progress',
|
||||
waitFailed: 'Could not wait for task updates',
|
||||
assignment: 'View assignment',
|
||||
"title": "Tasks",
|
||||
"unnamed": "Unnamed task",
|
||||
"waiting": "Waiting for task updates…",
|
||||
"status": {
|
||||
"queued": "Queued",
|
||||
"running": "Running",
|
||||
"waiting": "Waiting for your input",
|
||||
"succeeded": "Completed",
|
||||
"failed": "Failed",
|
||||
"interrupted": "Interrupted",
|
||||
"cancelled": "Cancelled",
|
||||
"needs_attention": "Needs attention",
|
||||
"cancelling": "Cancelling",
|
||||
"unknown": "Unknown status"
|
||||
},
|
||||
"phase": {
|
||||
"tool_running": "Using tool",
|
||||
"tool_succeeded": "Tool completed",
|
||||
"tool_failed": "Tool failed"
|
||||
}
|
||||
},
|
||||
pageAccess: {
|
||||
viewed: 'Viewed the current page: {location}'
|
||||
},
|
||||
|
|
@ -7038,7 +7074,7 @@ export default {
|
|||
model: 'Select the LLM used by the agent',
|
||||
temperature: 'Control output randomness, 0 is most deterministic, 1 is most random',
|
||||
maxTokens: 'Maximum tokens for the model reply. Default is 2048. Custom values are saved as entered.',
|
||||
maxTokensAgent: 'Maximum tokens generated in each reasoning round, including tool-call JSON. Default is 4096 without a sandbox, or 24576 when a sandbox can write or edit files. A custom value is saved as entered and is not changed later.',
|
||||
maxTokensAgent: 'Maximum tokens generated in each reasoning round, including tool-call JSON. Defaults to 24576. A custom value is saved as entered.',
|
||||
thinking: 'Enable extended thinking capability (requires model support)',
|
||||
conversationSection: 'Configure multi-turn conversation and query rewriting parameters',
|
||||
conversationSectionAgent: 'Smart reasoning is always multi-turn. Earlier conversation is kept up to the model context window, and older turns are summarized automatically once it fills',
|
||||
|
|
|
|||
|
|
@ -6461,6 +6461,9 @@ export default {
|
|||
expand: '展開'
|
||||
},
|
||||
toolApproval: {
|
||||
title: '承認',
|
||||
toolDescription: 'ツールの説明',
|
||||
delegatedTask: '委任されたタスク',
|
||||
waiting: '承認待ち · {target}',
|
||||
waitingStatus: '承認待ち',
|
||||
targetWithTool: '{service} › {tool}',
|
||||
|
|
@ -6482,6 +6485,7 @@ export default {
|
|||
parked: 'バックグラウンドで待機中。後で対応できます',
|
||||
parkedUntil: 'バックグラウンドで待機中。{time} までに対応してください',
|
||||
abandonedTag: '破棄済み',
|
||||
canceledTag: 'キャンセル済み',
|
||||
invalidJson: '引数は有効なJSONである必要があります',
|
||||
submitted: '送信しました',
|
||||
submitFailed: '送信に失敗しました',
|
||||
|
|
@ -6591,7 +6595,12 @@ export default {
|
|||
databaseQuery: 'データベース照会',
|
||||
findOperations: '操作を検索',
|
||||
runOperation: '操作を実行',
|
||||
tryAgent: 'エージェントを試す',
|
||||
spawn_agent: 'エージェントを起動',
|
||||
list_agents: 'エージェント一覧',
|
||||
send_message: 'メッセージを送信',
|
||||
followup_task: 'タスクを続行',
|
||||
interrupt_agent: 'エージェントを中断',
|
||||
wait_agent: 'エージェントを待機',
|
||||
openPage: 'ページを開く',
|
||||
searchWeKnoraDocs: '製品ドキュメントを検索',
|
||||
readWeKnoraDoc: '製品ドキュメントを読む',
|
||||
|
|
@ -6599,6 +6608,33 @@ export default {
|
|||
selectTab: 'タブを選択',
|
||||
fillPage: 'ページに入力'
|
||||
},
|
||||
collaboration: {
|
||||
tabs: 'タスクタブ',
|
||||
mainConversation: 'メインチャット',
|
||||
recentProgress: '最近の進捗',
|
||||
waitFailed: 'タスク更新の待機に失敗しました',
|
||||
assignment: '担当内容を表示',
|
||||
"title": "サブタスク",
|
||||
"unnamed": "無名のタスク",
|
||||
"waiting": "タスクの更新を待機中…",
|
||||
"status": {
|
||||
"queued": "待機中",
|
||||
"running": "実行中",
|
||||
"waiting": "入力待ち",
|
||||
"succeeded": "完了",
|
||||
"failed": "失敗",
|
||||
"interrupted": "中断",
|
||||
"cancelled": "キャンセル済み",
|
||||
"needs_attention": "対応が必要",
|
||||
"cancelling": "キャンセル中",
|
||||
"unknown": "不明"
|
||||
},
|
||||
"phase": {
|
||||
"tool_running": "ツールを使用中",
|
||||
"tool_succeeded": "ツール完了",
|
||||
"tool_failed": "ツール失敗"
|
||||
}
|
||||
},
|
||||
pageAccess: {
|
||||
viewed: '現在のページを確認しました:{location}'
|
||||
},
|
||||
|
|
@ -7038,7 +7074,7 @@ export default {
|
|||
model: 'エージェントが使用するLLMを選択します',
|
||||
temperature: '出力のランダム性を制御します。0が最も決定的、1が最もランダムです',
|
||||
maxTokens: 'モデルの応答の最大トークン数。デフォルトは2048です。カスタム値は入力したとおりに保存されます。',
|
||||
maxTokensAgent: '推論の各ラウンドで生成される最大トークン数(ツール呼び出しのJSONを含む)。デフォルトは、サンドボックスなしの場合4096、サンドボックスがファイルの書き込みや編集を行える場合は24576です。カスタム値は入力したとおりに保存され、以降変更されません。',
|
||||
maxTokensAgent: '推論の各ラウンドで生成される最大トークン数(ツール呼び出しのJSONを含む)。デフォルトは24576です。カスタム値は入力したとおりに保存されます。',
|
||||
thinking: '拡張思考機能を有効にします(モデルの対応が必要)',
|
||||
conversationSection: 'マルチターン会話とクエリのリライトに関するパラメータを設定します',
|
||||
conversationSectionAgent: 'スマート推論は常にマルチターンです。過去の会話はモデルのコンテキストウィンドウに収まる範囲で保持され、超えると古い部分が自動的に要約されます',
|
||||
|
|
|
|||
|
|
@ -1586,7 +1586,7 @@ export default {
|
|||
model: '에이전트가 사용할 대규모 언어 모델을 선택하세요',
|
||||
temperature: '출력의 무작위성을 제어합니다. 0이 가장 확정적, 1이 가장 무작위',
|
||||
maxTokens: '모델 응답의 최대 토큰 수. 「기본값」은 2048입니다. 「사용자 지정」은 입력한 값을 그대로 저장합니다.',
|
||||
maxTokensAgent: '각 추론 라운드에서 생성할 최대 토큰 수(도구 호출 JSON 포함). 「기본값」은 샌드박스 없으면 4096, 파일 쓰기/편집이 가능하면 24576입니다. 「사용자 지정」은 입력한 값을 그대로 저장합니다.',
|
||||
maxTokensAgent: '각 추론 라운드에서 생성할 최대 토큰 수(도구 호출 JSON 포함). 기본값은 24576입니다. 사용자 지정 값은 입력한 대로 저장됩니다.',
|
||||
thinking: '모델의 확장 사고 기능 활성화 (모델 지원 필요)',
|
||||
conversationSection: '다중 턴 대화 및 질문 재작성 관련 매개변수 설정',
|
||||
conversationSectionAgent: '스마트 추론은 항상 다중 턴입니다. 이전 대화는 모델의 컨텍스트 창 범위까지 유지되며, 초과하면 오래된 내용이 자동으로 요약됩니다',
|
||||
|
|
@ -1838,7 +1838,12 @@ export default {
|
|||
databaseQuery: '데이터베이스 조회',
|
||||
findOperations: '작업 찾기',
|
||||
runOperation: '작업 실행',
|
||||
tryAgent: '에이전트 시험 실행',
|
||||
spawn_agent: '에이전트 시작',
|
||||
list_agents: '에이전트 목록',
|
||||
send_message: '메시지 보내기',
|
||||
followup_task: '작업 계속',
|
||||
interrupt_agent: '에이전트 중단',
|
||||
wait_agent: '에이전트 대기',
|
||||
openPage: '페이지 열기',
|
||||
searchWeKnoraDocs: '제품 문서 검색',
|
||||
readWeKnoraDoc: '제품 문서 읽기',
|
||||
|
|
@ -1846,6 +1851,33 @@ export default {
|
|||
selectTab: '탭 선택',
|
||||
fillPage: '페이지 입력'
|
||||
},
|
||||
collaboration: {
|
||||
tabs: '작업 탭',
|
||||
mainConversation: '기본 대화',
|
||||
recentProgress: '최근 진행 상황',
|
||||
waitFailed: '작업 업데이트 대기 실패',
|
||||
assignment: '작업 내용 보기',
|
||||
"title": "하위 작업",
|
||||
"unnamed": "이름 없는 작업",
|
||||
"waiting": "작업 업데이트 기다리는 중…",
|
||||
"status": {
|
||||
"queued": "대기 중",
|
||||
"running": "진행 중",
|
||||
"waiting": "입력 대기 중",
|
||||
"succeeded": "완료",
|
||||
"failed": "실패",
|
||||
"interrupted": "중단됨",
|
||||
"cancelled": "취소됨",
|
||||
"needs_attention": "확인 필요",
|
||||
"cancelling": "취소 중",
|
||||
"unknown": "알 수 없음"
|
||||
},
|
||||
"phase": {
|
||||
"tool_running": "도구 사용 중",
|
||||
"tool_succeeded": "도구 완료",
|
||||
"tool_failed": "도구 실패"
|
||||
}
|
||||
},
|
||||
pageAccess: {
|
||||
viewed: '현재 페이지를 확인했습니다: {location}'
|
||||
},
|
||||
|
|
@ -2133,6 +2165,9 @@ export default {
|
|||
expand: '펼치기'
|
||||
},
|
||||
toolApproval: {
|
||||
title: '승인',
|
||||
toolDescription: '도구 설명',
|
||||
delegatedTask: '위임된 작업',
|
||||
waiting: '승인 대기 · {target}',
|
||||
waitingStatus: '승인 대기',
|
||||
targetWithTool: '{service} › {tool}',
|
||||
|
|
@ -2154,6 +2189,7 @@ export default {
|
|||
parked: '백그라운드에서 대기 중 — 나중에 처리할 수 있습니다',
|
||||
parkedUntil: '백그라운드에서 대기 중 — {time} 전에 처리하세요',
|
||||
abandonedTag: '포기됨',
|
||||
canceledTag: '취소됨',
|
||||
invalidJson: '유효한 JSON이 아닙니다',
|
||||
submitted: '제출됨',
|
||||
submitFailed: '제출 실패',
|
||||
|
|
|
|||
|
|
@ -1586,7 +1586,7 @@ export default {
|
|||
model: 'Выберите LLM, используемую агентом',
|
||||
temperature: 'Контроль случайности выхода: 0 — наиболее детерминированный, 1 — наиболее случайный',
|
||||
maxTokens: 'Максимум токенов в ответе. «По умолчанию» — 2048. «Своё» сохраняет введённое число.',
|
||||
maxTokensAgent: 'Максимум токенов за один раунд рассуждения, включая JSON вызовов инструментов. «По умолчанию»: 4096 без песочницы, 24576 с записью/правкой файлов. «Своё» сохраняет введённое число и больше не меняется.',
|
||||
maxTokensAgent: 'Максимум токенов за один раунд рассуждения, включая JSON вызовов инструментов. По умолчанию — 24576. Пользовательское значение сохраняется как введено.',
|
||||
thinking: 'Включить расширенное мышление модели (требуется поддержка модели)',
|
||||
conversationSection: 'Настройка параметров многооборотного диалога и перефразирования вопросов',
|
||||
conversationSectionAgent: 'Умные рассуждения всегда многооборотные. Предыдущий диалог хранится в пределах контекстного окна модели, а при его заполнении ранние ходы автоматически сжимаются в сводку',
|
||||
|
|
@ -1838,7 +1838,12 @@ export default {
|
|||
databaseQuery: 'Запрос к базе данных',
|
||||
findOperations: 'Поиск операций',
|
||||
runOperation: 'Выполнение операции',
|
||||
tryAgent: 'Пробный запуск агента',
|
||||
spawn_agent: 'Запустить агента',
|
||||
list_agents: 'Список агентов',
|
||||
send_message: 'Отправить сообщение',
|
||||
followup_task: 'Продолжить задачу',
|
||||
interrupt_agent: 'Прервать агента',
|
||||
wait_agent: 'Ожидать агента',
|
||||
openPage: 'Открыть страницу',
|
||||
searchWeKnoraDocs: 'Поиск в документации',
|
||||
readWeKnoraDoc: 'Чтение документации',
|
||||
|
|
@ -1846,6 +1851,33 @@ export default {
|
|||
selectTab: 'Выбор вкладки',
|
||||
fillPage: 'Заполнение страницы'
|
||||
},
|
||||
collaboration: {
|
||||
tabs: 'Вкладки задач',
|
||||
mainConversation: 'Основной чат',
|
||||
recentProgress: 'Последние обновления',
|
||||
waitFailed: 'Не удалось дождаться обновлений задач',
|
||||
assignment: 'Показать задание',
|
||||
"title": "Подзадачи",
|
||||
"unnamed": "Задача без названия",
|
||||
"waiting": "Ожидание обновлений задач…",
|
||||
"status": {
|
||||
"queued": "В очереди",
|
||||
"running": "Выполняется",
|
||||
"waiting": "Ожидает вашего ввода",
|
||||
"succeeded": "Завершена",
|
||||
"failed": "Ошибка",
|
||||
"interrupted": "Прервана",
|
||||
"cancelled": "Отменена",
|
||||
"needs_attention": "Требует внимания",
|
||||
"cancelling": "Отменяется",
|
||||
"unknown": "Статус неизвестен"
|
||||
},
|
||||
"phase": {
|
||||
"tool_running": "Использует инструмент",
|
||||
"tool_succeeded": "Инструмент завершён",
|
||||
"tool_failed": "Ошибка инструмента"
|
||||
}
|
||||
},
|
||||
pageAccess: {
|
||||
viewed: 'Просмотрена текущая страница: {location}'
|
||||
},
|
||||
|
|
@ -2133,6 +2165,9 @@ export default {
|
|||
expand: 'Развернуть'
|
||||
},
|
||||
toolApproval: {
|
||||
title: 'Подтверждение',
|
||||
toolDescription: 'Описание инструмента',
|
||||
delegatedTask: 'Делегированная задача',
|
||||
waiting: 'Ожидание проверки · {target}',
|
||||
waitingStatus: 'Ожидание проверки',
|
||||
targetWithTool: '{service} › {tool}',
|
||||
|
|
@ -2154,6 +2189,7 @@ export default {
|
|||
parked: 'Ожидает в фоне — можно ответить позже',
|
||||
parkedUntil: 'Ожидает в фоне — ответьте до {time}',
|
||||
abandonedTag: 'Отменено',
|
||||
canceledTag: 'Отменено',
|
||||
invalidJson: 'Некорректный JSON',
|
||||
submitted: 'Отправлено',
|
||||
submitFailed: 'Ошибка отправки',
|
||||
|
|
|
|||
|
|
@ -1588,7 +1588,7 @@ export default {
|
|||
model: '选择智能体使用的大语言模型',
|
||||
temperature: '控制输出的随机性,0 最确定,1 最随机',
|
||||
maxTokens: '模型生成回复的最大 Token 数。选「默认」时为 2048;选「自定义」后按你填的数保存。',
|
||||
maxTokensAgent: '每一轮推理的最大生成 Token(含工具调用 JSON)。选「默认」时,未绑沙箱为 4096,绑了沙箱(可写/改文件)为 24576。选「自定义」后按你填的数保存,不再自动改。',
|
||||
maxTokensAgent: '每一轮推理的最大生成 Token(含工具调用 JSON)。默认 24576。选「自定义」后按你填的数保存。',
|
||||
thinking: '启用模型的扩展思考能力(需要模型支持)',
|
||||
conversationSection: '配置多轮对话开关与问题改写开关(改写提示词见「提示词」)',
|
||||
conversationSectionAgent: '智能推理始终为多轮模式:按模型上下文窗口保留历史对话,超出时自动把较早的内容压缩成摘要。',
|
||||
|
|
@ -1840,7 +1840,12 @@ export default {
|
|||
databaseQuery: '数据库查询',
|
||||
findOperations: '查找操作',
|
||||
runOperation: '执行操作',
|
||||
tryAgent: '试跑智能体',
|
||||
spawn_agent: '启动智能体',
|
||||
list_agents: '查看智能体',
|
||||
send_message: '发送消息',
|
||||
followup_task: '继续任务',
|
||||
interrupt_agent: '中断智能体',
|
||||
wait_agent: '等待智能体',
|
||||
openPage: '打开页面',
|
||||
searchWeKnoraDocs: '搜索产品文档',
|
||||
readWeKnoraDoc: '阅读产品文档',
|
||||
|
|
@ -1848,6 +1853,33 @@ export default {
|
|||
selectTab: '切换标签',
|
||||
fillPage: '填写页面'
|
||||
},
|
||||
collaboration: {
|
||||
tabs: '任务标签页',
|
||||
mainConversation: '主对话',
|
||||
recentProgress: '最近进展',
|
||||
waitFailed: '等待子任务更新失败',
|
||||
assignment: '查看任务分工',
|
||||
"title": "子任务",
|
||||
"unnamed": "未命名任务",
|
||||
"waiting": "等待子任务更新…",
|
||||
"status": {
|
||||
"queued": "排队中",
|
||||
"running": "进行中",
|
||||
"waiting": "等待你处理",
|
||||
"succeeded": "已完成",
|
||||
"failed": "失败",
|
||||
"interrupted": "已中断",
|
||||
"cancelled": "已取消",
|
||||
"needs_attention": "需要处理",
|
||||
"cancelling": "正在取消",
|
||||
"unknown": "状态未知"
|
||||
},
|
||||
"phase": {
|
||||
"tool_running": "正在使用工具",
|
||||
"tool_succeeded": "工具已完成",
|
||||
"tool_failed": "工具失败"
|
||||
}
|
||||
},
|
||||
pageAccess: {
|
||||
viewed: '已查看当前页面:{location}'
|
||||
},
|
||||
|
|
@ -2135,6 +2167,9 @@ export default {
|
|||
expand: '展开'
|
||||
},
|
||||
toolApproval: {
|
||||
title: '人工审核',
|
||||
toolDescription: '工具说明',
|
||||
delegatedTask: '子任务',
|
||||
waiting: '等待审核 · {target}',
|
||||
waitingStatus: '等待审核',
|
||||
targetWithTool: '{service} › {tool}',
|
||||
|
|
@ -2156,6 +2191,7 @@ export default {
|
|||
parked: '已转入后台等待,可稍后处理',
|
||||
parkedUntil: '已转入后台等待,{time} 前可处理',
|
||||
abandonedTag: '已放弃',
|
||||
canceledTag: '已取消',
|
||||
invalidJson: '参数不是合法 JSON',
|
||||
submitted: '已提交',
|
||||
submitFailed: '提交失败',
|
||||
|
|
|
|||
|
|
@ -1588,7 +1588,7 @@ export default {
|
|||
model: '選擇智慧代理使用的大型語言模型',
|
||||
temperature: '控制輸出的隨機性,0 最確定,1 最隨機',
|
||||
maxTokens: '模型生成回覆的最大 Token 數。選「預設」時為 2048;選「自定義」後按你填的數儲存。',
|
||||
maxTokensAgent: '每一輪推論的最大生成 Token(含工具呼叫 JSON)。選「預設」時,未綁沙箱為 4096,綁了沙箱(可寫/改檔案)為 24576。選「自定義」後按你填的數儲存,不再自動改。',
|
||||
maxTokensAgent: '每一輪推論的最大生成 Token(含工具呼叫 JSON)。預設為 24576。選「自訂」後按你填的數儲存。',
|
||||
thinking: '啟用模型的擴展思考能力(需要模型支持)',
|
||||
conversationSection: '設定多輪對話開關與問題改寫開關(改寫提示語見「提示語」)',
|
||||
conversationSectionAgent: '智慧推論始終為多輪模式:按模型脈絡視窗保留歷史對話,超出時自動把較早的內容壓縮成摘要。',
|
||||
|
|
@ -1840,7 +1840,12 @@ export default {
|
|||
databaseQuery: '資料庫查詢',
|
||||
findOperations: '查找操作',
|
||||
runOperation: '執行操作',
|
||||
tryAgent: '試跑智能體',
|
||||
spawn_agent: '啟動智慧體',
|
||||
list_agents: '查看智慧體',
|
||||
send_message: '傳送訊息',
|
||||
followup_task: '繼續任務',
|
||||
interrupt_agent: '中斷智慧體',
|
||||
wait_agent: '等待智慧體',
|
||||
openPage: '開啟頁面',
|
||||
searchWeKnoraDocs: '搜尋產品文件',
|
||||
readWeKnoraDoc: '閱讀產品文件',
|
||||
|
|
@ -1848,6 +1853,33 @@ export default {
|
|||
selectTab: '切換標籤',
|
||||
fillPage: '填寫頁面'
|
||||
},
|
||||
collaboration: {
|
||||
tabs: '任務分頁',
|
||||
mainConversation: '主對話',
|
||||
recentProgress: '最近進展',
|
||||
waitFailed: '等待子任務更新失敗',
|
||||
assignment: '查看任務分工',
|
||||
"title": "子任務",
|
||||
"unnamed": "未命名任務",
|
||||
"waiting": "等待子任務更新…",
|
||||
"status": {
|
||||
"queued": "排隊中",
|
||||
"running": "進行中",
|
||||
"waiting": "等待你處理",
|
||||
"succeeded": "已完成",
|
||||
"failed": "失敗",
|
||||
"interrupted": "已中斷",
|
||||
"cancelled": "已取消",
|
||||
"needs_attention": "需要處理",
|
||||
"cancelling": "正在取消",
|
||||
"unknown": "狀態未知"
|
||||
},
|
||||
"phase": {
|
||||
"tool_running": "正在使用工具",
|
||||
"tool_succeeded": "工具已完成",
|
||||
"tool_failed": "工具失敗"
|
||||
}
|
||||
},
|
||||
pageAccess: {
|
||||
viewed: '已查看目前頁面:{location}'
|
||||
},
|
||||
|
|
@ -2135,6 +2167,9 @@ export default {
|
|||
expand: '展開'
|
||||
},
|
||||
toolApproval: {
|
||||
title: '人工審核',
|
||||
toolDescription: '工具說明',
|
||||
delegatedTask: '子任務',
|
||||
waiting: '等待審核 · {target}',
|
||||
waitingStatus: '等待審核',
|
||||
targetWithTool: '{service} › {tool}',
|
||||
|
|
@ -2156,6 +2191,7 @@ export default {
|
|||
parked: '已轉入背景等待,可稍後處理',
|
||||
parkedUntil: '已轉入背景等待,{time} 前可處理',
|
||||
abandonedTag: '已放棄',
|
||||
canceledTag: '已取消',
|
||||
invalidJson: '參數不是合法 JSON',
|
||||
submitted: '已提交',
|
||||
submitFailed: '提交失敗',
|
||||
|
|
|
|||
|
|
@ -68,7 +68,7 @@ export function getAgentToolIconName(
|
|||
if (toolName === 'run_operation') {
|
||||
return 'terminal'
|
||||
}
|
||||
if (toolName === 'try_agent') {
|
||||
if (['spawn_agent', 'list_agents', 'send_message', 'followup_task', 'interrupt_agent', 'wait_agent'].includes(toolName)) {
|
||||
return 'chat'
|
||||
}
|
||||
if (toolName === 'open_page') {
|
||||
|
|
|
|||
|
|
@ -0,0 +1,81 @@
|
|||
import assert from 'node:assert/strict'
|
||||
import { test } from 'node:test'
|
||||
import { foldProgressIntoThinking } from './agentTimelinePresentation'
|
||||
import { withoutCollaborationWaits } from './collaborationDisplay'
|
||||
|
||||
test('live and recovered progress label the preceding reasoning without changing stored events', () => {
|
||||
for (const done of [false, true]) {
|
||||
const thought = Object.freeze({ type: 'thinking', event_id: 'r1', content: 'Check the agents', done })
|
||||
for (const update of [
|
||||
{ type: 'progress', event_id: 'p1', content: '我先查看智能体。', iteration: 1 },
|
||||
{ type: 'answer', event_id: 'p1', content: '我先查看智能体。', superseded: true },
|
||||
]) {
|
||||
const input = Object.freeze([thought, Object.freeze(update)])
|
||||
const output = foldProgressIntoThinking([...input])
|
||||
assert.deepEqual(output, [{ ...thought, title: update.content }])
|
||||
assert.equal(output[0].event_id, 'r1') // Preserve expansion identity.
|
||||
assert.equal('title' in thought, false)
|
||||
assert.equal(input[1].type, update.type)
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
test('tools, approvals and user messages prevent cross-round association even when hidden', () => {
|
||||
for (const boundary of [
|
||||
{ type: 'tool_call', tool_name: 'wait_agent' },
|
||||
{ type: 'tool_call', tool_name: 'spawn_agent' },
|
||||
{ type: 'tool_approval_required' },
|
||||
{ type: 'user_message_injected' },
|
||||
]) {
|
||||
const events = [{ type: 'thinking', content: 'Earlier reasoning' }, boundary,
|
||||
{ type: 'progress', content: 'New update' }]
|
||||
const projected = withoutCollaborationWaits(foldProgressIntoThinking(events))
|
||||
assert.equal(projected[0].title, undefined)
|
||||
assert.equal(projected.at(-1)?.type, 'progress')
|
||||
}
|
||||
})
|
||||
|
||||
test('final answers, standalone progress, different rounds and subsequent updates remain separate', () => {
|
||||
const events = [
|
||||
{ type: 'progress', content: 'Starting' },
|
||||
{ type: 'thinking', content: 'Reasoning', iteration: 1 },
|
||||
{ type: 'progress', content: 'Different round', iteration: 2 },
|
||||
{ type: 'thinking', content: 'More reasoning' },
|
||||
{ type: 'progress', content: 'First update' },
|
||||
{ type: 'progress', content: 'Second update' },
|
||||
{ type: 'answer', content: 'Complete deliverable' },
|
||||
]
|
||||
const output = foldProgressIntoThinking(events)
|
||||
assert.equal(output.length, 6)
|
||||
assert.equal(output[1].title, undefined)
|
||||
assert.equal(output[3].title, 'First update')
|
||||
assert.deepEqual(output.at(-1), events.at(-1))
|
||||
assert.equal(output[4].content, 'Second update')
|
||||
})
|
||||
|
||||
test('adjacent visible progress keeps only the latest summary and preserves earlier updates for expansion', async () => {
|
||||
const { groupProgressUpdates } = await import('./agentTimelinePresentation')
|
||||
const { collaborationTimeline } = await import('./collaborationDisplay')
|
||||
const first = Object.freeze({ type: 'progress', event_id: 'p1', content: '等待审批', timestamp: 1 })
|
||||
const second = Object.freeze({ type: 'progress', event_id: 'p2', content: '正在读取全文', timestamp: 2 })
|
||||
const third = Object.freeze({ type: 'progress', event_id: 'p3', content: '正在整理结果', timestamp: 3 })
|
||||
const events = [first, { type: 'tool_call', tool_name: 'wait_agent', success: true }, second, third]
|
||||
const projected = groupProgressUpdates(collaborationTimeline(events, undefined))
|
||||
assert.equal(projected.length, 1)
|
||||
assert.equal(projected[0].event_id, 'p1')
|
||||
assert.equal(projected[0].content, third.content)
|
||||
assert.deepEqual(projected[0].progress_history, [first.content, second.content])
|
||||
assert.equal(first.content, '等待审批')
|
||||
assert.equal('progress_history' in third, false)
|
||||
const appended = groupProgressUpdates([...projected, { type: 'progress', event_id: 'p4', content: '即将完成' }])
|
||||
assert.equal(appended[0].event_id, 'p1')
|
||||
assert.deepEqual(appended[0].progress_history, [first.content, second.content, third.content])
|
||||
})
|
||||
|
||||
test('progress grouping preserves approval, reasoning, tool, user input and final answer boundaries', async () => {
|
||||
const { groupProgressUpdates } = await import('./agentTimelinePresentation')
|
||||
for (const type of ['tool_approval_required', 'agent_prompt_required', 'thinking', 'tool_call', 'user_message_injected', 'answer', 'stop']) {
|
||||
const events = [{ type: 'progress', content: 'Before' }, { type, content: 'Boundary' }, { type: 'progress', content: 'After' }]
|
||||
assert.deepEqual(groupProgressUpdates(events), events)
|
||||
}
|
||||
})
|
||||
|
|
@ -0,0 +1,43 @@
|
|||
/** Presentation only: keep reasoning and progress separate in the stored stream. */
|
||||
export function foldProgressIntoThinking(events: any[]): any[] {
|
||||
const result: any[] = []
|
||||
for (const event of events) {
|
||||
const progress = event.type === 'progress' || (event.type === 'answer' && event.superseded)
|
||||
if (!progress || typeof event.content !== 'string' || !event.content.trim()) {
|
||||
result.push(event)
|
||||
continue
|
||||
}
|
||||
const previous = result[result.length - 1]
|
||||
// Only adjacent events belong together. Tools, approvals and user input
|
||||
// remain boundaries, even when a later presentation filter hides them.
|
||||
const sameRound = previous?.iteration == null || event.iteration == null
|
||||
|| previous.iteration === event.iteration
|
||||
if (previous?.type === 'thinking' && !previous.title && sameRound) {
|
||||
result[result.length - 1] = { ...previous, title: event.content }
|
||||
} else {
|
||||
result.push(event.type === 'progress' ? event : { ...event, type: 'progress', done: true })
|
||||
}
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
/** Compact adjacent visible updates without crossing tools, prompts or answers. */
|
||||
export function groupProgressUpdates(events: any[]): any[] {
|
||||
const result: any[] = []
|
||||
for (const event of events) {
|
||||
const previous = result.at(-1)
|
||||
if (event.type === 'progress' && typeof event.content === 'string' && event.content.trim()
|
||||
&& previous?.type === 'progress' && typeof previous.content === 'string' && previous.content.trim()) {
|
||||
result[result.length - 1] = {
|
||||
...event,
|
||||
// Keep the first row's identity so expansion survives streamed updates.
|
||||
event_id: previous.event_id,
|
||||
timestamp: previous.timestamp,
|
||||
progress_history: [...(previous.progress_history || []), previous.content],
|
||||
}
|
||||
} else {
|
||||
result.push(event)
|
||||
}
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
|
@ -0,0 +1,127 @@
|
|||
import assert from 'node:assert/strict'
|
||||
import { test } from 'node:test'
|
||||
import { collaborationTimeline, collaborationTasks, collaborationWaitState, withoutCollaborationWaits } from './collaborationDisplay'
|
||||
|
||||
test('parallel tasks retain separate identities and readable latest messages', () => {
|
||||
const tasks = collaborationTasks({ tasks: [
|
||||
{ id: 'a', name: 'research', status: 'running', latest_message: { content: 'Found evidence' }, progress: { phase: 'tool_running', tool_name: 'web_search' } },
|
||||
{ member_id: 'b', task_name: 'review', status: 'waiting', latest_message: { arbitrary: 'do not render JSON' } },
|
||||
] })
|
||||
assert.deepEqual(tasks.map(t => [t.id, t.name, t.status, t.latestMessage]), [['a','research','running','Found evidence'], ['b','review','waiting','']])
|
||||
assert.equal(tasks[0].progress?.tool_name, 'web_search')
|
||||
})
|
||||
test('wait polls fold without hiding actual progress or losing active wait', () => {
|
||||
const events = [
|
||||
{ type: 'tool_call', tool_name: 'wait_agent', pending: false, output: '{"timed_out":true}' },
|
||||
{ type: 'progress', content: 'Review is still running' },
|
||||
{ type: 'tool_call', tool_name: 'wait_agent', pending: true },
|
||||
]
|
||||
assert.equal(collaborationWaitState(events), 'waiting')
|
||||
assert.equal(collaborationWaitState(events, true), 'finished')
|
||||
assert.deepEqual(withoutCollaborationWaits(events), [events[1]])
|
||||
assert.equal(collaborationWaitState([]), undefined)
|
||||
})
|
||||
test('cancellation and missing snapshots do not claim task completion', () => {
|
||||
assert.deepEqual(collaborationTasks(undefined), [])
|
||||
const tasks = collaborationTasks({ tasks: [{ id: 'a', status: 'running', cancel_requested: true }, { id: 'b', status: 'future-status' }] })
|
||||
assert.deepEqual(tasks.map(t => t.status), ['cancelling', 'unknown'])
|
||||
})
|
||||
|
||||
test('failed wait remains visible instead of becoming a successful wait summary', () => {
|
||||
assert.equal(collaborationWaitState([{ type: 'tool_call', tool_name: 'wait_agent', pending: false, success: false }]), 'failed')
|
||||
})
|
||||
|
||||
test('tool counts include calls represented by the task panel without mutating history', async () => {
|
||||
const { countToolCalls } = await import('./collaborationDisplay')
|
||||
const events = [
|
||||
{ type: 'tool_call', tool_name: 'spawn_agent', tool_call_id: 'spawn' },
|
||||
{ type: 'thinking', content: 'private reasoning' },
|
||||
{ type: 'progress', content: 'First progress' },
|
||||
{ type: 'tool_call', tool_name: 'list_agents', tool_call_id: 'list' },
|
||||
{ type: 'tool_call', tool_name: 'wait_agent', tool_call_id: 'wait-1' },
|
||||
{ type: 'progress', content: 'Latest progress' },
|
||||
{ type: 'tool_call', tool_name: 'wait_agent', tool_call_id: 'wait-2' },
|
||||
{ type: 'tool_approval_required', pending_id: 'one', resolved: false },
|
||||
{ type: 'agent_prompt_required', pending_id: 'two', resolved: false },
|
||||
{ type: 'tool_approval_required', pending_id: 'old', resolved: true },
|
||||
{ type: 'answer', content: 'Result' },
|
||||
]
|
||||
assert.equal(countToolCalls(events), 4)
|
||||
assert.equal(countToolCalls([...events, events[0]]), 4)
|
||||
assert.equal(events.filter(e => e.type === 'progress').length, 2, 'full history is untouched')
|
||||
})
|
||||
test('display name is distinct from the logical assignment name', () => {
|
||||
const [task] = collaborationTasks({ tasks: [{ id: 'id', name: 'review', display_name: '质量审核员', status: 'succeeded' }] })
|
||||
assert.equal(task.displayName, '质量审核员')
|
||||
assert.equal(task.name, 'review')
|
||||
})
|
||||
|
||||
test('child rows stay at spawn position and concurrent waits share one row', async () => {
|
||||
const { collaborationTimeline } = await import('./collaborationDisplay')
|
||||
const events = [
|
||||
{ type: 'progress', content: 'Starting' },
|
||||
{ type: 'tool_call', tool_name: 'spawn_agent', arguments: { task_name: 'a' } },
|
||||
{ type: 'tool_call', tool_name: 'spawn_agent', arguments: { task_name: 'b' } },
|
||||
{ type: 'tool_call', tool_name: 'wait_agent', pending: false },
|
||||
{ type: 'progress', content: 'Checking' },
|
||||
{ type: 'tool_call', tool_name: 'wait_agent', pending: true },
|
||||
]
|
||||
const snapshot = { tasks: [{ id: 'a', name: 'a', session_id: 'sa', run_id: 'ra', status: 'running' },
|
||||
{ id: 'b', name: 'b', session_id: 'sb', run_id: 'rb', status: 'waiting' }] }
|
||||
const result = collaborationTimeline(events, snapshot)
|
||||
assert.deepEqual(result.map(e => e.type), ['progress', 'child_task', 'child_task', 'progress'])
|
||||
assert.equal(result[1].task.sessionId, 'sa')
|
||||
assert.equal(result[2].task.sessionId, 'sb')
|
||||
assert.equal(result.filter(e => e.type === 'child_wait').length, 0, 'live waiting belongs at the response tail')
|
||||
const restored = collaborationTimeline([{ type: 'answer', content: 'Result' }], snapshot, true)
|
||||
assert.deepEqual(restored.map(e => e.type), ['child_task', 'child_task', 'answer'])
|
||||
})
|
||||
|
||||
|
||||
test('live waiting follows approval state and stops on cancellation, completion, or parent resumption', async () => {
|
||||
const { collaborationActivity, collaborationTimeline } = await import('./collaborationDisplay')
|
||||
const wait = { type: 'tool_call', tool_name: 'wait_agent', pending: true }
|
||||
const events: any[] = [{ ...wait, pending: false }, ...Array.from({ length: 60 }, () => ({ type: 'progress', content: 'progress' })), wait]
|
||||
const snapshot = { tasks: [{ id: 'a', status: 'running' }, { id: 'b', status: 'running' }] }
|
||||
assert.equal(collaborationActivity(events, snapshot), 'waiting')
|
||||
const prompt = { type: 'tool_approval_required', resolved: false }
|
||||
events.push(prompt)
|
||||
assert.equal(collaborationActivity(events, snapshot), 'approval')
|
||||
prompt.resolved = true
|
||||
assert.equal(collaborationActivity(events, snapshot), 'waiting')
|
||||
assert.equal(collaborationActivity(events, snapshot, true), undefined)
|
||||
assert.equal(collaborationActivity([...events, { type: 'stop' }], snapshot), undefined)
|
||||
assert.equal(collaborationActivity([...events, { type: 'agent_complete' }], snapshot), undefined)
|
||||
wait.pending = false
|
||||
assert.equal(collaborationActivity(events, snapshot), undefined, 'a running child alone does not mean its parent is waiting')
|
||||
const history = collaborationTimeline(events, snapshot, true)
|
||||
assert.equal(history.filter(e => e.type === 'child_wait' || e.tool_name === 'wait_agent').length, 0, 'completed polls are not user-facing milestones')
|
||||
})
|
||||
|
||||
|
||||
test('successful and timed-out waits disappear from history while real errors remain inspectable', async () => {
|
||||
const { collaborationTimeline } = await import('./collaborationDisplay')
|
||||
const completed = { type: 'tool_call', tool_name: 'wait_agent', pending: false, success: true, tool_data: { timed_out: true } }
|
||||
const failure = { ...completed, success: false, output: 'Connection failed' }
|
||||
assert.deepEqual(collaborationTimeline([completed], undefined, true), [])
|
||||
assert.deepEqual(collaborationTimeline([completed, failure], undefined, true), [failure])
|
||||
})
|
||||
|
||||
test('a continued child stays at its followup position in the new parent turn', () => {
|
||||
for (const target of ['child-id', 'novelist', '/root/novelist']) {
|
||||
const snapshot = { tasks: [{ id: 'child-id', name: 'novelist', session_id: 'original-session', run_id: 'new-run', status: 'running' }] }
|
||||
const events = [
|
||||
{ type: 'progress', content: '继续写第一章' },
|
||||
{ type: 'tool_call', tool_name: 'followup_task', arguments: { target }, success: true, timestamp: 'now' },
|
||||
{ type: 'thinking', content: 'Waiting for the chapter' },
|
||||
{ type: 'tool_call', tool_name: 'wait_agent', success: true },
|
||||
]
|
||||
const rows = collaborationTimeline(events, snapshot)
|
||||
assert.deepEqual(rows.map(row => row.type), ['progress', 'child_task', 'thinking'])
|
||||
assert.equal(rows[1].task.sessionId, 'original-session')
|
||||
assert.equal(rows[1].task.runId, 'new-run')
|
||||
assert.equal(rows[1].timestamp, 'now')
|
||||
events[1].success = false
|
||||
assert.ok(collaborationTimeline(events, snapshot).some(row => row.tool_name === 'followup_task'), 'failed continuation remains visible')
|
||||
}
|
||||
})
|
||||
|
|
@ -0,0 +1,100 @@
|
|||
/** Presentation projection; never expose runtime IDs or raw tool payloads. */
|
||||
export interface CollaborationTaskView {
|
||||
id: string
|
||||
name: string
|
||||
sessionId: string
|
||||
runId: string
|
||||
displayName: string
|
||||
status: string
|
||||
progress?: { phase?: string; tool_name?: string; iteration?: number }
|
||||
latestMessage: string
|
||||
}
|
||||
const statuses = new Set(['queued', 'running', 'waiting', 'succeeded', 'failed', 'interrupted', 'cancelled', 'cancelling', 'needs_attention'])
|
||||
export function collaborationTasks(snapshot: unknown): CollaborationTaskView[] {
|
||||
const tasks = (snapshot as any)?.tasks
|
||||
if (!Array.isArray(tasks)) return []
|
||||
return tasks.filter((task: any) => task && typeof task === 'object').map((task: any, index: number) => {
|
||||
const latest = task.latest_message
|
||||
const message = typeof latest === 'string' ? latest : latest?.content ?? latest?.message
|
||||
return {
|
||||
id: String(task.id || task.member_id || task.name || task.task_name || index),
|
||||
name: String(task.name || task.task_name || ''),
|
||||
sessionId: String(task.session_id || ''),
|
||||
runId: String(task.run_id || ''),
|
||||
displayName: String(task.display_name || task.name || task.task_name || ''),
|
||||
status: task.cancel_requested && ['queued', 'running', 'waiting'].includes(task.status)
|
||||
? 'cancelling' : statuses.has(task.status) ? task.status : 'unknown',
|
||||
progress: task.progress && typeof task.progress === 'object' ? task.progress : undefined,
|
||||
latestMessage: typeof message === 'string' ? message : '',
|
||||
}
|
||||
})
|
||||
}
|
||||
export function collaborationWaitState(events: any[] = [], settled = false): 'waiting' | 'finished' | 'failed' | undefined {
|
||||
const waits = events.filter(event => event?.type === 'tool_call' && event.tool_name === 'wait_agent')
|
||||
if (!waits.length) return undefined
|
||||
if (!settled && waits.some(event => event.pending && !event.canceled)) return 'waiting'
|
||||
return waits[waits.length - 1].success === false ? 'failed' : 'finished'
|
||||
}
|
||||
/** Current activity belongs at the live response tail, not the first wait call. */
|
||||
export function collaborationActivity(events: any[], snapshot: unknown, settled = false): 'waiting' | 'approval' | undefined {
|
||||
if (settled || events.some(event => event?.type === 'stop' || event?.type === 'agent_complete')) return undefined
|
||||
if (collaborationWaitState(events) !== 'waiting') return undefined
|
||||
return events.some(isUnresolvedCollaborationPrompt) || collaborationTasks(snapshot).some(task => task.status === 'waiting')
|
||||
? 'approval' : 'waiting'
|
||||
}
|
||||
/** All wait polls share the task panel; they must not multiply timeline rows. */
|
||||
export function withoutCollaborationWaits(events: any[]): any[] {
|
||||
return events.filter(event => !(event?.type === 'tool_call' && event.tool_name === 'wait_agent'))
|
||||
}
|
||||
|
||||
export function isCollaborationTaskActive(status: string): boolean {
|
||||
return ['queued', 'running', 'waiting', 'cancelling'].includes(status)
|
||||
}
|
||||
export function isUnresolvedCollaborationPrompt(event: any): boolean {
|
||||
return ['tool_approval_required', 'agent_prompt_required', 'mcp_oauth_required'].includes(event?.type)
|
||||
&& !event.resolved && !event.canceled && !event.abandoned
|
||||
}
|
||||
/** Count the actual calls, including calls represented by the task panel. */
|
||||
export function countToolCalls(events: any[]): number {
|
||||
const calls = events.filter(event => event?.type === 'tool_call')
|
||||
const ids = new Set(calls.map(event => event.tool_call_id).filter(Boolean))
|
||||
return ids.size + calls.filter(event => !event.tool_call_id).length
|
||||
}
|
||||
|
||||
/** Keep child rows at their spawn/continuation location, including restored snapshots. */
|
||||
export function collaborationTimeline(events: any[], snapshot: unknown, settled = false): any[] {
|
||||
const tasks = collaborationTasks(snapshot)
|
||||
const seen = new Set<string>()
|
||||
const result: any[] = []
|
||||
const waitState = collaborationWaitState(events, settled)
|
||||
const lastWait = events.filter(event => event?.type === 'tool_call' && event.tool_name === 'wait_agent').at(-1)
|
||||
for (const event of events) {
|
||||
if (event.type === 'tool_call' && (event.tool_name === 'spawn_agent'
|
||||
|| (event.tool_name === 'followup_task' && event.success !== false && !event.canceled))) {
|
||||
const target = event.arguments?.target
|
||||
const task = tasks.find(t => event.tool_name === 'followup_task'
|
||||
? t.id === target || t.name === target || `/root/${t.name}` === target
|
||||
: t.id === event.tool_data?.member_id
|
||||
|| t.name === event.arguments?.task_name || t.name === event.arguments?.name)
|
||||
if (task) {
|
||||
if (!seen.has(task.id)) result.push({ type: 'child_task', event_id: `child-${task.id}`, task, timestamp: event.timestamp })
|
||||
seen.add(task.id)
|
||||
continue
|
||||
}
|
||||
}
|
||||
if (tasks.length && event.type === 'tool_call' && event.tool_name === 'list_agents') continue
|
||||
if (event.type === 'tool_call' && event.tool_name === 'wait_agent') {
|
||||
// Successful polls (including timeouts) are plumbing, not milestones.
|
||||
// Preserve an actual failure in the normal tool row for inspection.
|
||||
if (event === lastWait && waitState === 'failed') result.push(event)
|
||||
continue
|
||||
}
|
||||
result.push(event)
|
||||
}
|
||||
// A restored segment may lack the original spawn calls. Keep orphan rows in
|
||||
// the transcript before its answer, never in a separate top status panel.
|
||||
const missing = tasks.filter(t => !seen.has(t.id)).map(task => ({ type: 'child_task', event_id: `child-${task.id}`, task }))
|
||||
const answer = result.findIndex(e => e.type === 'answer' && !e.superseded)
|
||||
result.splice(answer < 0 ? result.length : answer, 0, ...missing)
|
||||
return result
|
||||
}
|
||||
|
|
@ -0,0 +1,23 @@
|
|||
import assert from 'node:assert/strict'
|
||||
import test from 'node:test'
|
||||
import { loadConfigFromFile } from 'vite'
|
||||
import { build } from 'esbuild'
|
||||
import { fileURLToPath } from 'node:url'
|
||||
|
||||
test('PPTX preview bundles the ESM renderer with one shared Vue runtime', async () => {
|
||||
const root = fileURLToPath(new URL('../../', import.meta.url))
|
||||
const loaded = await loadConfigFromFile({ command: 'serve', mode: 'development' }, `${root}vite.config.ts`)
|
||||
const aliases = loaded!.config.resolve!.alias as Record<string, string>
|
||||
const entry = aliases['@vue-office/pptx']
|
||||
assert.match(entry, /\/v3\/vue-office-pptx\.mjs$/)
|
||||
const result = await build({
|
||||
stdin: { contents: `export { createApp } from 'vue'; export { default as Pptx } from ${JSON.stringify(entry)}`,
|
||||
resolveDir: root },
|
||||
bundle: true, write: false, metafile: true, format: 'esm', platform: 'browser',
|
||||
})
|
||||
// Mixing require('vue') from the UMD renderer with the app's ESM import
|
||||
// previously detached template refs and threw during the mounted hook.
|
||||
const inputs = Object.keys(result.metafile!.inputs)
|
||||
assert.equal(inputs.filter(path => path.includes('@vue/runtime-core/dist/')).length, 1)
|
||||
assert.ok(!inputs.some(path => /vue\/(?:index\.js|dist\/vue\.cjs)/.test(path)))
|
||||
})
|
||||
|
|
@ -1,8 +1,11 @@
|
|||
import assert from 'node:assert/strict'
|
||||
import test from 'node:test'
|
||||
import { marked } from 'marked'
|
||||
import { renderChatMarkdown } from './chatMarkdownRenderer.ts'
|
||||
import { renderArtifactFileIcon } from './artifactFileIcon'
|
||||
|
||||
import {
|
||||
installArtifactLinkRenderer,
|
||||
isArtifactRefHref,
|
||||
normalizeSandboxArtifactRefs,
|
||||
renderArtifactReference,
|
||||
|
|
@ -256,3 +259,31 @@ test('a deleted artifact is not mistaken for a foreign handle', () => {
|
|||
const live = artifacts.filter((_, i) => i !== 0)
|
||||
assert.equal(renderArtifactReference({ href: refFor(0), artifacts: live, labels }), null)
|
||||
})
|
||||
|
||||
|
||||
test('parent Markdown links render as file cards with exact child indices, including refreshed metadata', () => {
|
||||
const renderer = new marked.Renderer()
|
||||
let files: ArtifactRefMeta[] = []
|
||||
installArtifactLinkRenderer(renderer, () => ({ artifacts: files, labels }))
|
||||
const body = `[开书设定](${refFor(0)})\n\n[文件](${refFor(1)})\n\n[网页](https://example.com)`
|
||||
const render = () => renderChatMarkdown(body, {
|
||||
renderer, escapeMarkdown: text => text, sanitizeHtml: html => html,
|
||||
})
|
||||
assert.doesNotMatch(render(), /data-artifact-index/)
|
||||
files = [
|
||||
{ index: 0, handle: refFor(0), file_name: '开书设定.md', file_type: '.md' },
|
||||
{ index: 1, handle: refFor(1), file_name: '开书设定.md', file_type: '.md' },
|
||||
]
|
||||
const html = render()
|
||||
assert.match(html, /data-artifact-index="0"/)
|
||||
assert.match(html, /data-artifact-index="1"/)
|
||||
assert.equal((html.match(/点击预览/g) || []).length, 2)
|
||||
assert.match(html, /href="https:\/\/example.com"/)
|
||||
assert.doesNotMatch(html, /href="resource:/)
|
||||
files = files.map(({ handle, ...file }) => ({ ...file, url: handle }))
|
||||
assert.equal(render(), html, 'history URL metadata and live handle metadata render identically')
|
||||
files[0].deleted_at = '2026-10-18'
|
||||
assert.match(render(), /文件已删除/)
|
||||
assert.doesNotMatch(render(), /data-artifact-index="0"/)
|
||||
assert.match(render(), /data-artifact-index="1"/)
|
||||
})
|
||||
|
|
|
|||
|
|
@ -22,6 +22,8 @@
|
|||
* 会被当成知识库图片走受保护图片渲染,最终显示成一张拉不出来的裂图。
|
||||
*/
|
||||
|
||||
import type { Renderer } from 'marked';
|
||||
|
||||
import { escapeHTML } from './security.ts';
|
||||
import { renderArtifactFileIcon } from './artifactFileIcon';
|
||||
|
||||
|
|
@ -421,3 +423,16 @@ export function artifactIndexFromEventTarget(target: EventTarget | null): number
|
|||
const index = Number(card.getAttribute('data-artifact-index'));
|
||||
return Number.isInteger(index) && index >= 0 ? index : null;
|
||||
}
|
||||
|
||||
/** Links and images referencing a generated file must share its authorized
|
||||
* preview path. Leave unrelated links to the original Markdown renderer. */
|
||||
export function installArtifactLinkRenderer(
|
||||
renderer: Renderer,
|
||||
options: () => Omit<Parameters<typeof renderArtifactReference>[0], 'href' | 'alt'>,
|
||||
): void {
|
||||
const defaultLink = renderer.link;
|
||||
renderer.link = function (token) {
|
||||
const artifact = renderArtifactReference({ ...options(), href: token.href, alt: token.text });
|
||||
return artifact ?? defaultLink.call(this, token);
|
||||
};
|
||||
}
|
||||
|
|
|
|||
|
|
@ -291,23 +291,54 @@ export function steerStepEvents(step: ChatMessage): ChatMessage[] {
|
|||
return events
|
||||
}
|
||||
|
||||
/** A continue-stream replays from offset zero. Keep row identities, but rebuild
|
||||
* every segment from that log rather than appending old events onto the tail. */
|
||||
export function resetSteerTurnForReplay(list: ChatMessage[], requestId: string): ChatMessage | undefined {
|
||||
/** Rebuild the current stream generation. Approval continuations replay only
|
||||
* their suffix, so retain an immutable baseline for each presentation segment. */
|
||||
export function resetSteerTurnForReplay(
|
||||
list: ChatMessage[], requestId: string, resumeId = '', blockedCallId = '',
|
||||
): ChatMessage | undefined {
|
||||
const segments = list.filter(m => m.role === 'assistant' && m.request_id === requestId)
|
||||
if (!segments.some(m => m.steerForked)) return undefined
|
||||
for (const segment of segments) {
|
||||
if (!requestId || segments.length === 0) return undefined
|
||||
const sameResume = resumeId && segments.some(m => m._resumeReplayId === resumeId)
|
||||
const boundary = resumeId ? segments.findIndex(m =>
|
||||
((m.agentEventStream || []) as ChatMessage[]).some(e =>
|
||||
e.type === 'tool_call' && e.tool_call_id === blockedCallId)) : -1
|
||||
let active = segments[0]
|
||||
for (const [index, segment] of segments.entries()) {
|
||||
if (resumeId && !sameResume) {
|
||||
delete segment._resumeReplayId
|
||||
delete segment._resumeReplayEvents
|
||||
}
|
||||
if (resumeId && !sameResume && (boundary < 0 || index <= boundary)) {
|
||||
segment._resumeReplayId = resumeId
|
||||
const events = (segment.agentEventStream || []) as ChatMessage[]
|
||||
const blocked = events.findIndex(e => e.type === 'tool_call' && e.tool_call_id === blockedCallId)
|
||||
// The resumed call starts the suffix in reloaded history. Events arriving
|
||||
// while approval was pending still belong to the prefix and must survive.
|
||||
segment._resumeReplayEvents = (blocked < 0 ? events : events.slice(0, blocked))
|
||||
.filter(e => e.type !== 'agent_complete' && e.type !== 'stop' &&
|
||||
!(blockedCallId && e.type === 'tool_call' && e.tool_call_id === blockedCallId))
|
||||
.map(e => ({ ...e }))
|
||||
}
|
||||
const hasBaseline = resumeId && segment._resumeReplayId === resumeId
|
||||
segment.content = ''
|
||||
segment.agentEventStream = []
|
||||
segment.agentEventStream = hasBaseline
|
||||
? (segment._resumeReplayEvents as ChatMessage[]).map(e => ({ ...e })) : []
|
||||
segment._eventMap = new Map()
|
||||
segment._pendingToolCalls = new Map()
|
||||
segment.is_completed = true
|
||||
segment._steerReplayPending = true
|
||||
if (hasBaseline) {
|
||||
active = segment
|
||||
delete segment._steerReplayPending
|
||||
} else if (!resumeId) {
|
||||
delete segment._resumeReplayId
|
||||
delete segment._resumeReplayEvents
|
||||
}
|
||||
}
|
||||
segments[0].is_completed = false
|
||||
segments[0].steerForked = false
|
||||
delete segments[0]._steerReplayPending
|
||||
return segments[0]
|
||||
active.is_completed = false
|
||||
active.steerForked = false
|
||||
delete active._steerReplayPending
|
||||
return active
|
||||
}
|
||||
|
||||
/** Individual answer.done events close a message, not the running task. */
|
||||
|
|
|
|||
|
|
@ -2468,7 +2468,7 @@ const defaultVectorThreshold = ref(0.5);
|
|||
const defaultRerankTopK = ref(5);
|
||||
const defaultRerankThreshold = ref(0.5);
|
||||
const defaultQuickAnswerMaxCompletionTokens = 2048;
|
||||
const defaultSmartReasoningMaxCompletionTokens = 4096;
|
||||
const defaultSmartReasoningMaxCompletionTokens = 24576;
|
||||
const defaultSandboxWriteMaxCompletionTokens = 24576;
|
||||
const defaultTemperature = ref(0.7);
|
||||
|
||||
|
|
@ -3692,6 +3692,7 @@ watch(() => props.visible, async (val) => {
|
|||
newFormData.config.rerank_top_k = defaultRerankTopK.value;
|
||||
newFormData.config.rerank_threshold = defaultRerankThreshold.value;
|
||||
newFormData.config.max_completion_tokens = 0;
|
||||
newFormData.config.max_iterations = -1;
|
||||
newFormData.config.temperature = defaultTemperature.value;
|
||||
// 应用系统默认提示词(根据模式填充)
|
||||
const isAgent = newFormData.config.agent_mode === 'smart-reasoning';
|
||||
|
|
@ -3948,7 +3949,7 @@ watch(agentMode, (val, _oldVal) => {
|
|||
formData.value.config.allowed_tools = tools;
|
||||
}
|
||||
if (formData.value.config.max_iterations >= 0 && formData.value.config.max_iterations <= 1) {
|
||||
formData.value.config.max_iterations = 10;
|
||||
formData.value.config.max_iterations = -1;
|
||||
}
|
||||
// 切换到 Agent 模式时,如果系统提示词是快速问答的默认值或为空,替换为 Agent 默认提示词
|
||||
if (defaultAgentSystemPrompt.value) {
|
||||
|
|
|
|||
|
|
@ -0,0 +1,104 @@
|
|||
import assert from 'node:assert/strict'
|
||||
import { readFileSync } from 'node:fs'
|
||||
import test from 'node:test'
|
||||
import vm from 'node:vm'
|
||||
import ts from 'typescript'
|
||||
import { parse } from '@vue/compiler-sfc'
|
||||
import { computed, reactive, ref } from 'vue'
|
||||
import { persistedAssistantId } from '../../../utils/steerStreamFork.ts'
|
||||
|
||||
const source = readFileSync(new URL('./AgentStreamDisplay.vue', import.meta.url), 'utf8')
|
||||
const child = parse(readFileSync(new URL('./ChildAgentStream.vue', import.meta.url), 'utf8')).descriptor
|
||||
const start = source.indexOf('const showArtifactDrawer = ')
|
||||
const end = source.indexOf('\nconst artifactRefContext = ', start)
|
||||
assert.ok(start >= 0 && end > start)
|
||||
const code = ts.transpile(source.slice(start, end))
|
||||
|
||||
function setup(overrides = {}, withPanel = true) {
|
||||
const calls = []
|
||||
const props = reactive({
|
||||
sessionId: 'child-session',
|
||||
session: { id: 'child-message', artifacts: [
|
||||
{ file_name: 'deleted.md', deleted_at: '2026-10-18' },
|
||||
{ file_name: 'slides.pptx' },
|
||||
{ file_name: 'notes.md' },
|
||||
] },
|
||||
...overrides,
|
||||
})
|
||||
const state = vm.runInNewContext(`${code}; ({
|
||||
openArtifactDrawer, showArtifactDrawer, artifactPreviewIndex, useArtifactDrawer,
|
||||
sessionIdForArtifacts, messageIdForArtifacts, liveArtifacts,
|
||||
})`, {
|
||||
props, computed, ref,
|
||||
useChatSandboxPanel: () => withPanel ? {
|
||||
toggleArtifacts: id => calls.push(['toggle', id]),
|
||||
open: (tab, focus) => calls.push(['open', tab, focus.messageId, focus.previewIndex]),
|
||||
} : null,
|
||||
persistedAssistantId,
|
||||
useArtifactArriveMotion: () => ({}),
|
||||
isCollectingSkillArtifacts: () => false,
|
||||
})
|
||||
return { ...state, props, calls }
|
||||
}
|
||||
|
||||
test('child viewer explicitly routes artifacts locally while retaining the child session', () => {
|
||||
const stream = child.template.ast.children[0].children[0].children
|
||||
.find(node => node.tag === 'template').children.find(node => node.tag === 'AgentStreamDisplay')
|
||||
assert.ok(stream.props.some(prop => prop.type === 6 && prop.name === 'artifacts-in-drawer'))
|
||||
assert.ok(stream.props.some(prop => prop.arg?.content === 'session-id' && prop.exp?.content === 'task.sessionId'))
|
||||
// Rendering and click routing must agree; otherwise clicks only toggle invisible state.
|
||||
const drawer = parse(source).descriptor.template.ast.children.find(node => node.tag === 'ChatArtifactsDrawer')
|
||||
for (const [attribute, expression] of [
|
||||
['session-id', 'sessionIdForArtifacts'], ['message-id', 'messageIdForArtifacts'],
|
||||
['artifacts', 'liveArtifacts'], ['preview-index', 'artifactPreviewIndex'],
|
||||
]) {
|
||||
assert.ok(drawer.props.some(prop => prop.arg?.content === attribute && prop.exp?.content === expression))
|
||||
}
|
||||
const condition = drawer.props.find(prop => prop.name === 'if').exp.content
|
||||
const ctx = setup({ artifactsInDrawer: true })
|
||||
assert.equal(vm.runInNewContext(condition, {
|
||||
hasArtifacts: true, embeddedMode: false, useArtifactDrawer: ctx.useArtifactDrawer.value,
|
||||
sessionIdForArtifacts: ctx.sessionIdForArtifacts.value,
|
||||
messageIdForArtifacts: ctx.messageIdForArtifacts.value,
|
||||
}), 'child-message')
|
||||
})
|
||||
|
||||
test('child inline cards and folder use the same local drawer, preserving original file indexes', () => {
|
||||
const ctx = setup({ artifactsInDrawer: true })
|
||||
for (const index of [1, 2]) {
|
||||
ctx.openArtifactDrawer(index)
|
||||
assert.equal(ctx.showArtifactDrawer.value, true)
|
||||
assert.equal(ctx.artifactPreviewIndex.value, index)
|
||||
assert.equal(ctx.liveArtifacts.value.find(file => file.index === index).file_name,
|
||||
index === 1 ? 'slides.pptx' : 'notes.md')
|
||||
assert.equal(ctx.sessionIdForArtifacts.value, 'child-session')
|
||||
assert.equal(ctx.messageIdForArtifacts.value, 'child-message')
|
||||
ctx.showArtifactDrawer.value = false
|
||||
}
|
||||
ctx.openArtifactDrawer()
|
||||
assert.equal(ctx.showArtifactDrawer.value, true)
|
||||
assert.equal(ctx.artifactPreviewIndex.value, null)
|
||||
assert.deepEqual(ctx.calls, [], 'must not send child message IDs to the parent panel')
|
||||
})
|
||||
|
||||
test('main conversation retains panel routing; embedded and standalone viewers have a visible fallback', () => {
|
||||
const main = setup({ sessionId: 'main-session', session: { id: 'main-message', artifacts: [{}] } })
|
||||
main.openArtifactDrawer()
|
||||
main.openArtifactDrawer(0)
|
||||
assert.equal(main.useArtifactDrawer.value, false)
|
||||
assert.equal(main.showArtifactDrawer.value, false)
|
||||
assert.deepEqual(main.calls, [['toggle', 'main-message'], ['open', 'artifacts', 'main-message', 0]])
|
||||
for (const ctx of [setup({ embeddedMode: true }), setup({}, false)]) {
|
||||
ctx.openArtifactDrawer(1)
|
||||
assert.equal(ctx.useArtifactDrawer.value, true)
|
||||
assert.equal(ctx.showArtifactDrawer.value, true)
|
||||
assert.deepEqual(ctx.calls, [])
|
||||
}
|
||||
})
|
||||
|
||||
test('messages without live artifacts do not open either surface', () => {
|
||||
const ctx = setup({ artifactsInDrawer: true, session: { id: 'empty', artifacts: [] } })
|
||||
ctx.openArtifactDrawer()
|
||||
assert.equal(ctx.showArtifactDrawer.value, false)
|
||||
assert.deepEqual(ctx.calls, [])
|
||||
})
|
||||
|
|
@ -0,0 +1,110 @@
|
|||
import assert from 'node:assert/strict'
|
||||
import { readFileSync } from 'node:fs'
|
||||
import { test } from 'node:test'
|
||||
import vm from 'node:vm'
|
||||
import ts from 'typescript'
|
||||
import { computed, ref } from 'vue'
|
||||
import { useDeferredTimelineCompletion } from '../../../composables/useChatScrollFollow'
|
||||
import { foldProgressIntoThinking } from '../../../utils/agentTimelinePresentation'
|
||||
|
||||
const source = readFileSync(new URL('./AgentStreamDisplay.vue', import.meta.url), 'utf8')
|
||||
|
||||
test('delegated work keeps progress and approvals in one chronological stream and restores the completed steps fold without duplicating child entry points', () => {
|
||||
const collapse = source.slice(source.indexOf('const shouldShowCollapsedSteps ='), source.indexOf('// Once the steps collapse'))
|
||||
const display = source.slice(source.indexOf('const displayEvents ='), source.indexOf('const isPageLinkEvent ='))
|
||||
const done = ref(false)
|
||||
const delegated = ref(false)
|
||||
const expanded = ref(false)
|
||||
const readingHistory = ref(false)
|
||||
const stream = ref<any[]>([
|
||||
{ type: 'thinking', event_id: 'r1', content: 'Check agents' },
|
||||
{ type: 'progress', event_id: 'p1', content: '两个智能体已经并行开工了。' },
|
||||
{ type: 'tool_approval_required', pending_id: 'approval', resolved: false },
|
||||
])
|
||||
const code = ts.transpileModule(`${collapse}\n${display}\n({ shouldShowCollapsedSteps, displayEvents })`, {
|
||||
compilerOptions: { target: ts.ScriptTarget.ES2022, module: ts.ModuleKind.CommonJS },
|
||||
}).outputText
|
||||
const state = vm.runInNewContext(code, {
|
||||
computed, props: { ragMode: false }, hasCollaborationTasks: delegated, showIntermediateSteps: expanded,
|
||||
eventStream: stream, isConversationDone: done, intermediateStepsCount: ref(2), readingHistory, timelineCompleted: useDeferredTimelineCompletion(done, readingHistory),
|
||||
buildFullEventList: foldProgressIntoThinking, finalContent: ref(null),
|
||||
})
|
||||
for (const hasChildren of [false, true]) {
|
||||
delegated.value = hasChildren
|
||||
assert.equal(state.shouldShowCollapsedSteps.value, false)
|
||||
assert.deepEqual(Array.from(state.displayEvents.value, (e: any) => e.type), ['thinking', 'tool_approval_required'])
|
||||
assert.equal(state.displayEvents.value[0].title, '两个智能体已经并行开工了。')
|
||||
assert.equal(state.displayEvents.value[1].resolved, false)
|
||||
}
|
||||
stream.value[2].resolved = true
|
||||
assert.equal(state.displayEvents.value[1].resolved, true)
|
||||
stream.value.push({ type: 'answer', content: '完整结果' })
|
||||
stream.value.splice(2, 0, { type: 'child_task', event_id: 'child-a', task: { id: 'a' } })
|
||||
readingHistory.value = true
|
||||
done.value = true
|
||||
assert.equal(state.shouldShowCollapsedSteps.value, false, 'completion must not fold history under the reader')
|
||||
assert.ok(state.displayEvents.value.some((event: any) => event.type === 'thinking'))
|
||||
readingHistory.value = false
|
||||
assert.equal(state.shouldShowCollapsedSteps.value, true)
|
||||
assert.deepEqual(Array.from(state.displayEvents.value, (e: any) => e.type), ['answer'])
|
||||
readingHistory.value = true
|
||||
assert.equal(state.shouldShowCollapsedSteps.value, true, 'older completed timelines stay folded when reading history')
|
||||
readingHistory.value = false
|
||||
expanded.value = true
|
||||
assert.deepEqual(Array.from(state.displayEvents.value, (e: any) => e.type), ['answer'])
|
||||
expanded.value = false
|
||||
stream.value = stream.value.filter(e => e.type !== 'answer')
|
||||
assert.equal(state.displayEvents.value.length, 0)
|
||||
expanded.value = true
|
||||
assert.equal(state.displayEvents.value.length, 0)
|
||||
stream.value = [{ type: 'answer', content: '完整结果' }]
|
||||
delegated.value = false
|
||||
assert.equal(state.shouldShowCollapsedSteps.value, true)
|
||||
assert.deepEqual(Array.from(state.displayEvents.value, (e: any) => e.content), ['完整结果'])
|
||||
})
|
||||
|
||||
test('the template has no second latest-progress outlet above the timeline', () => {
|
||||
assert.doesNotMatch(source, /CollaborationProgress|latestParentProgress/)
|
||||
})
|
||||
|
||||
|
||||
test('live child waiting uses the timeline tail icon and existing pending shimmer', () => {
|
||||
const template = source.slice(0, source.indexOf('</template>\n\n<script'))
|
||||
const tail = template.slice(template.indexOf('<!-- One live tail node'), template.indexOf('<!-- 引用 hover'))
|
||||
assert.match(tail, /v-if="showAgentActivityIndicator \|\| childActivity"/)
|
||||
assert.match(tail, /class="tree-child tree-child-last streaming-loading-node"/)
|
||||
assert.match(tail, /role="status" aria-live="polite"/)
|
||||
assert.match(tail, /class="action-card action-pending"/)
|
||||
assert.match(tail, /class="action-title-icon icon-mask"/)
|
||||
assert.match(tail, /class="action-name"/)
|
||||
assert.match(template, /!showAgentActivityIndicator && !childActivity && index === lastStreamingTimelineEventIndex/)
|
||||
assert.doesNotMatch(template, /agent-child-activity|child-wait-spinner|child_wait/)
|
||||
})
|
||||
|
||||
test('thinking resumes after child waiting and resolved approval', () => {
|
||||
const snippet = source.slice(source.indexOf('const hasPendingStreamingActivity ='), source.indexOf('const isStreamingTimelineEvent ='))
|
||||
const events = ref<any[]>([]), done = ref(false), wait = ref('finished'), answering = ref(false)
|
||||
const code = ts.transpileModule(`${snippet}\n({ showAgentActivityIndicator })`, {
|
||||
compilerOptions: { target: ts.ScriptTarget.ES2022, module: ts.ModuleKind.CommonJS },
|
||||
}).outputText
|
||||
const state = vm.runInNewContext(code, {
|
||||
computed, displayEvents: events, isSegmentDone: done, hasCollaborationTasks: ref(true),
|
||||
props: { ragMode: false }, hasAnswerStarted: answering, collaborationWait: wait,
|
||||
isThinkingActive: () => false,
|
||||
isUnresolvedCollaborationPrompt: (event: any) => event.type === 'tool_approval_required' && !event.resolved,
|
||||
})
|
||||
assert.equal(state.showAgentActivityIndicator.value, true)
|
||||
events.value = [{ type: 'tool_approval_required', resolved: true }]
|
||||
assert.equal(state.showAgentActivityIndicator.value, true)
|
||||
events.value[0].resolved = false
|
||||
assert.equal(state.showAgentActivityIndicator.value, false)
|
||||
events.value = []
|
||||
wait.value = 'waiting'
|
||||
assert.equal(state.showAgentActivityIndicator.value, false)
|
||||
wait.value = 'finished'
|
||||
answering.value = true
|
||||
assert.equal(state.showAgentActivityIndicator.value, false)
|
||||
answering.value = false
|
||||
done.value = true
|
||||
assert.equal(state.showAgentActivityIndicator.value, false)
|
||||
})
|
||||
|
|
@ -4,9 +4,12 @@ import { dirname, join } from 'node:path'
|
|||
import { fileURLToPath } from 'node:url'
|
||||
import test from 'node:test'
|
||||
import vm from 'node:vm'
|
||||
import { computed, reactive } from 'vue'
|
||||
import { computed, reactive, ref } from 'vue'
|
||||
import { isAssistantTurnComplete } from '../../../utils/steerStreamFork.ts'
|
||||
|
||||
import { useDeferredTimelineCompletion } from '../../../composables/useChatScrollFollow.ts'
|
||||
import { collaborationWaitState, collaborationActivity } from '../../../utils/collaborationDisplay.ts'
|
||||
|
||||
const here = dirname(fileURLToPath(import.meta.url))
|
||||
const source = readFileSync(join(here, 'AgentStreamDisplay.vue'), 'utf8')
|
||||
|
||||
|
|
@ -20,6 +23,8 @@ test('steer seals animation while keeping the preceding timeline open without co
|
|||
const props = reactive({ ragMode: false, session: { steerForked: true, is_completed: true } })
|
||||
const state = vm.runInNewContext(`${stateBlock}\n${collapseBlock}\n({ isConversationDone, isSegmentDone, shouldShowCollapsedSteps })`, {
|
||||
props, computed, isAssistantTurnComplete, intermediateStepsCount: { value: 2 },
|
||||
useDeferredTimelineCompletion, readingHistory: ref(false), eventStream: ref([]),
|
||||
collaborationWaitState, collaborationActivity,
|
||||
isAwaitingInput: (m) => m?.run_state === 'awaiting_input',
|
||||
})
|
||||
assert.equal(state.isSegmentDone.value, true)
|
||||
|
|
@ -52,7 +57,7 @@ test('expanded agent step log keeps model thinking in the tool timeline', () =>
|
|||
})
|
||||
|
||||
test('streaming log renders reasoning alongside tool calls', () => {
|
||||
assert.match(source, /if \(!isConversationDone\.value\)\s*\{\s*return result;\s*\}/)
|
||||
assert.match(source, /if \(!timelineCompleted\.value\)\s*\{\s*return result;\s*\}/)
|
||||
})
|
||||
|
||||
test('expanded model reasoning stays inline without a separate thinking title', () => {
|
||||
|
|
@ -74,7 +79,7 @@ test('streaming tool log uses the same timeline structure', () => {
|
|||
})
|
||||
|
||||
test('final done row uses an existing common translation key', () => {
|
||||
assert.match(source, /t\('common\.finish'\)/)
|
||||
assert.match(source, /t\(wasUserStopped \? 'input\.messages\.stopSuccess' : 'common\.finish'\)/)
|
||||
assert.doesNotMatch(source, /\$t\('common\.done'\)/)
|
||||
assert.match(source, /'tree-child-last': !isSegmentDone && index === visibleIntermediateEvents\.length - 1/)
|
||||
})
|
||||
|
|
@ -97,7 +102,7 @@ test('tool rows use line icon names instead of legacy asset masks', () => {
|
|||
|
||||
test('rag mode delegates pre-answer loading to pipeline and adds no row after answer starts', () => {
|
||||
assert.match(source, /if \(props\.ragMode \|\| hasAnswerStarted\.value\) return false/)
|
||||
assert.match(source, /v-if="displayEvents\.length > 0 \|\| showMemoryRow \|\| showAgentActivityIndicator"/)
|
||||
assert.match(source, /v-if="displayEvents\.length > 0 \|\| showMemoryRow \|\| showAgentActivityIndicator \|\| childActivity"/)
|
||||
assert.doesNotMatch(source, /ChatActivityIndicator/)
|
||||
})
|
||||
|
||||
|
|
@ -151,9 +156,9 @@ test('agent mode shows a native placeholder before answer whenever nothing is pe
|
|||
assert.match(source, /event\.thinking === true \|\| isThinkingActive\(event\.event_id\)/)
|
||||
assert.match(
|
||||
source,
|
||||
/event\.type === 'tool_approval_required' \|\|\s*event\.type === 'mcp_oauth_required' \|\|\s*event\.type === 'agent_prompt_required'/,
|
||||
/return isUnresolvedCollaborationPrompt\(event\)/,
|
||||
)
|
||||
assert.match(source, /class="action-card action-pending"/)
|
||||
assert.match(source, /t\('chat\.thinkingAlt'\)/)
|
||||
assert.match(source, /childActivity \? 'agentStream\.collaboration\.waiting' : 'chat\.thinkingAlt'/)
|
||||
assert.match(source, /chat-timeline-loading\.less/)
|
||||
})
|
||||
|
|
|
|||
|
|
@ -1,6 +1,10 @@
|
|||
<template>
|
||||
<div ref="rootElement" class="agent-stream-display" :class="{ 'is-embedded': embeddedMode, 'is-rag-mode': ragMode, 'is-steer-prefix': session?.steerForked }">
|
||||
|
||||
<t-drawer v-if="selectedChild && !childAgentTabs" attach="body" :close-btn="true" :z-index="2000" :visible="true" :header="selectedChild.displayName" size="min(680px, 95vw)" :footer="false" @close="selectedChildId = ''">
|
||||
<ChildAgentStream :key="selectedChild.id + ':' + selectedChild.runId" :task="selectedChild" />
|
||||
</t-drawer>
|
||||
|
||||
<!-- Collapsed intermediate steps (tree root) -->
|
||||
<div v-if="shouldShowCollapsedSteps" class="tree-container">
|
||||
<div class="tool-event">
|
||||
|
|
@ -28,9 +32,11 @@
|
|||
/>
|
||||
<template v-for="(event, index) in visibleIntermediateEvents" :key="getEventKey(event, index)">
|
||||
<div v-if="event && event.type" class="tree-child"
|
||||
:class="{ 'tree-child-last': !isSegmentDone && index === visibleIntermediateEvents.length - 1 }">
|
||||
:class="{ 'tree-child-last': !isSegmentDone && index === visibleIntermediateEvents.length - 1, 'tree-child-progress': event.type === 'child_task' }">
|
||||
<div class="tree-branch"></div>
|
||||
<div class="tree-child-content">
|
||||
<CollaborationTasks v-if="event.type === 'child_task'" :task="event.task" :disabled="!!embedToken" :tool-label="getLocalizedToolName" @open="openChildTask" />
|
||||
|
||||
<!-- Plan Task Change Event -->
|
||||
<div v-if="event.type === 'plan_task_change'" class="plan-task-change-event">
|
||||
<div class="plan-task-change-card">
|
||||
|
|
@ -62,6 +68,9 @@
|
|||
<!-- Thinking Event (streaming / merged). When a round's retracted
|
||||
preamble was folded in, it becomes the card title and the
|
||||
reasoning is the expandable body. -->
|
||||
<ProgressUpdates v-if="event.type === 'progress' && event.content"
|
||||
:content="event.content" :history="event.progress_history" />
|
||||
|
||||
<div v-if="event.type === 'thinking'" class="tool-event">
|
||||
<div class="action-card thinking-event-card"
|
||||
:class="{ 'action-pending': isThinkingActive(event.event_id) }">
|
||||
|
|
@ -113,10 +122,10 @@
|
|||
|
||||
<!-- MCP tool human approval (issue #1173) -->
|
||||
<div v-else-if="event.type === 'tool_approval_required'" class="tool-event">
|
||||
<ToolApprovalCard :pending-id="event.pending_id" :service-name="event.service_name || ''"
|
||||
<ToolApprovalCard :pending-id="event.pending_id" :delegated-task="event.delegated_task" :service-name="event.service_name || ''"
|
||||
:mcp-tool-name="event.mcp_tool_name || ''" :description="event.description"
|
||||
:args-json="event.args_json" :grant-scope="event.grant_scope" :timeout-seconds="event.timeout_seconds"
|
||||
:requested-at="event.requested_at" :resolved="event.resolved" :approved="event.approved"
|
||||
:requested-at="event.requested_at" :resolved="event.resolved" :approved="event.approved" :canceled="event.canceled"
|
||||
:resolve-reason="event.resolve_reason" :suspendable="event.suspendable"
|
||||
:hot-wait-seconds="event.hot_wait_seconds" :suspended="event.suspended"
|
||||
:expires-at="event.expires_at" :abandoned="event.abandoned" v-bind="embedAuthProps" />
|
||||
|
|
@ -261,7 +270,7 @@
|
|||
<div class="action-header no-results">
|
||||
<div class="action-title">
|
||||
<t-icon class="action-title-icon" name="check-circle" />
|
||||
<span class="action-name">{{ t('common.finish') }}</span>
|
||||
<span class="action-name">{{ t(wasUserStopped ? 'input.messages.stopSuccess' : 'common.finish') }}</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
|
@ -271,9 +280,8 @@
|
|||
</div>
|
||||
|
||||
<!-- Event Stream (non-tree mode: before answer starts, or answer events) -->
|
||||
<div v-if="displayEvents.length > 0 || showMemoryRow || showAgentActivityIndicator" ref="streamingStepsContainer"
|
||||
<div v-if="displayEvents.length > 0 || showMemoryRow || showAgentActivityIndicator || childActivity"
|
||||
class="streaming-steps-container" :class="{
|
||||
'streaming-steps-constrained': !answerEverStarted && !isSegmentDone,
|
||||
'is-streaming-timeline': showStreamingTimeline
|
||||
}">
|
||||
<!-- Recalled memory leads the timeline: it is what the turn knew before it
|
||||
|
|
@ -293,12 +301,15 @@
|
|||
<div v-if="event && event.type" class="event-item" :class="{
|
||||
'event-answer': event.type === 'answer',
|
||||
'tree-child': isStreamingTimelineEvent(event),
|
||||
'tree-child-last': isStreamingTimelineEvent(event) && !showAgentActivityIndicator && index === lastStreamingTimelineEventIndex
|
||||
'tree-child-progress': event.type === 'child_task',
|
||||
'tree-child-last': isStreamingTimelineEvent(event) && !showAgentActivityIndicator && !childActivity && index === lastStreamingTimelineEventIndex
|
||||
}">
|
||||
<div v-if="isStreamingTimelineEvent(event)" class="tree-branch"></div>
|
||||
<div :class="{ 'tree-child-content': isStreamingTimelineEvent(event) }">
|
||||
|
||||
<!-- Plan Task Change Event -->
|
||||
<CollaborationTasks v-if="event.type === 'child_task'" :task="event.task" :disabled="!!embedToken" :tool-label="getLocalizedToolName" @open="openChildTask" />
|
||||
|
||||
<!-- Plan Task Change Event -->
|
||||
<div v-if="event.type === 'plan_task_change'" class="plan-task-change-event">
|
||||
<div class="plan-task-change-card">
|
||||
<div class="plan-task-change-content">
|
||||
|
|
@ -329,6 +340,9 @@
|
|||
<!-- Thinking Event (streaming / merged). A folded preamble (retracted
|
||||
from the answer area) is shown as the card title; the reasoning is
|
||||
the expandable body. -->
|
||||
<ProgressUpdates v-if="event.type === 'progress' && event.content"
|
||||
:content="event.content" :history="event.progress_history" />
|
||||
|
||||
<div v-if="event.type === 'thinking'" class="tool-event">
|
||||
<div class="action-card thinking-event-card"
|
||||
:class="{ 'action-pending': isThinkingActive(event.event_id) }">
|
||||
|
|
@ -356,10 +370,10 @@
|
|||
|
||||
<!-- MCP tool human approval -->
|
||||
<div v-else-if="event.type === 'tool_approval_required'" class="tool-event">
|
||||
<ToolApprovalCard :pending-id="event.pending_id" :service-name="event.service_name || ''"
|
||||
<ToolApprovalCard :pending-id="event.pending_id" :delegated-task="event.delegated_task" :service-name="event.service_name || ''"
|
||||
:mcp-tool-name="event.mcp_tool_name || ''" :description="event.description" :args-json="event.args_json"
|
||||
:grant-scope="event.grant_scope" :timeout-seconds="event.timeout_seconds" :requested-at="event.requested_at" :resolved="event.resolved"
|
||||
:approved="event.approved" :resolve-reason="event.resolve_reason" :suspendable="event.suspendable"
|
||||
:approved="event.approved" :canceled="event.canceled" :resolve-reason="event.resolve_reason" :suspendable="event.suspendable"
|
||||
:hot-wait-seconds="event.hot_wait_seconds" :suspended="event.suspended" :expires-at="event.expires_at"
|
||||
:abandoned="event.abandoned" v-bind="embedAuthProps" />
|
||||
</div>
|
||||
|
|
@ -419,7 +433,7 @@
|
|||
:tool-call-id="edit.tool_call_id" />
|
||||
</div>
|
||||
<div v-if="answerFullyRendered && event.done && event.content && event.content.trim()"
|
||||
class="answer-toolbar">
|
||||
class="answer-toolbar" :class="{ 'answer-toolbar--persistent': hasArtifacts || artifactsCollecting }">
|
||||
<t-tooltip v-if="canFork" :content="forkTooltip">
|
||||
<t-button size="small" variant="outline" shape="round" @click.stop="emitFork">
|
||||
<ChatActionIcon name="git-branch" />
|
||||
|
|
@ -453,16 +467,15 @@
|
|||
:title="$t('agent.addToKnowledgeBase')">
|
||||
<ChatActionIcon name="bookmark-add" />
|
||||
</t-button>
|
||||
<!-- Skill artifact download: only shown when the persisted
|
||||
assistant message recorded any generated files. Agent
|
||||
mode is the primary path for skills, so this is where
|
||||
the button is most likely to appear. -->
|
||||
<span v-if="!embeddedMode && (hasArtifacts || artifactsCollecting)" class="answer-toolbar__artifact"
|
||||
<!-- Includes files delivered by child agents. Embedded assistants
|
||||
use the same entry and open the artifact drawer. -->
|
||||
<span v-if="hasArtifacts || artifactsCollecting" class="answer-toolbar__artifact"
|
||||
:class="{ 'is-collecting': artifactButtonCollecting, 'is-arrived': artifactArrived }"
|
||||
@animationend="onArtifactArriveEnd">
|
||||
<t-button size="small" variant="outline" shape="round"
|
||||
:disabled="artifactButtonCollecting"
|
||||
:title="hasArtifacts ? $t('agent.artifactDrawer.buttonTitle') : $t('agent.artifactDrawer.collecting')"
|
||||
:aria-label="hasArtifacts ? $t('agent.artifactDrawer.buttonTitle') : $t('agent.artifactDrawer.collecting')"
|
||||
@click.stop="openArtifactDrawer()">
|
||||
<t-icon v-if="artifactButtonCollecting" name="loading" class="answer-toolbar__artifact-spinner" />
|
||||
<ChatActionIcon v-else name="folder" />
|
||||
|
|
@ -609,27 +622,28 @@
|
|||
<div v-if="showRequestInfo && isConversationDone && !hasDoneAnswerContent" class="answer-toolbar">
|
||||
<ChatRequestInfoButton :session="session" :session-id="sessionId" />
|
||||
</div>
|
||||
<!-- Loading Indicator (inside container so it scrolls into view) -->
|
||||
<div v-if="showAgentActivityIndicator" class="tree-child tree-child-last streaming-loading-node">
|
||||
<!-- One live tail node shares the timeline trunk, icon alignment and shimmer. -->
|
||||
<div v-if="showAgentActivityIndicator || childActivity" class="tree-child tree-child-last streaming-loading-node" role="status" aria-live="polite">
|
||||
<div class="tree-branch"></div>
|
||||
<div class="tree-child-content">
|
||||
<div class="action-card action-pending">
|
||||
<div class="action-header no-results">
|
||||
<div class="action-title">
|
||||
<t-icon class="action-title-icon" name="lightbulb" />
|
||||
<span class="action-name">{{ t('chat.thinkingAlt') }}</span>
|
||||
<span class="action-title-icon icon-mask" :style="maskIconStyle(thinkingIcon)" aria-hidden="true" />
|
||||
<span class="action-name">{{ t(childActivity === 'approval' ? 'agentStream.collaboration.status.waiting' : childActivity ? 'agentStream.collaboration.waiting' : 'chat.thinkingAlt') }}</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
</div>
|
||||
<!-- 引用 hover 浮层(与历史消息共用同一组件) -->
|
||||
<ChatCitationFloat :float="citationFloat" :on-enter="cancelCitationClose" :on-leave="scheduleCitationClose" />
|
||||
|
||||
<!-- Image Preview -->
|
||||
<picturePreview :reviewImg="imagePreviewVisible" :reviewUrl="imagePreviewUrl" @closePreImg="closeImagePreview" />
|
||||
<picturePreview v-if="imagePreviewVisible" :reviewImg="imagePreviewVisible" :reviewUrl="imagePreviewUrl" @closePreImg="closeImagePreview" />
|
||||
|
||||
<!-- Wiki Page Detail Drawer -->
|
||||
<!-- Mount on demand: a hidden TDesign drawer steals focus when each response mounts. -->
|
||||
|
|
@ -664,7 +678,7 @@
|
|||
</template>
|
||||
</t-drawer>
|
||||
<ChatArtifactsDrawer
|
||||
v-if="hasArtifacts && embeddedMode && sessionIdForArtifacts && messageIdForArtifacts"
|
||||
v-if="hasArtifacts && useArtifactDrawer && sessionIdForArtifacts && messageIdForArtifacts"
|
||||
v-model:visible="showArtifactDrawer"
|
||||
:session-id="sessionIdForArtifacts"
|
||||
:message-id="messageIdForArtifacts"
|
||||
|
|
@ -677,12 +691,21 @@
|
|||
import { readDocumentReferences } from '@/utils/readDocumentReferences';
|
||||
import { isAssistantTurnComplete } from '@/utils/steerStreamFork';
|
||||
import { isAwaitingInput } from '@/composables/useChatStreamHandler';
|
||||
import { ref, computed, watch, onMounted, onBeforeUnmount, onUpdated, nextTick } from 'vue';
|
||||
import { inject, ref, computed, watch, onMounted, onBeforeUnmount, onUpdated, nextTick } from 'vue';
|
||||
import { chatReadingHistoryKey, useDeferredTimelineCompletion } from '@/composables/useChatScrollFollow';
|
||||
import { useRouter, useRoute } from 'vue-router';
|
||||
import { marked } from 'marked';
|
||||
import 'katex/dist/katex.min.css';
|
||||
import SandboxCommandProgress from '@/components/SandboxCommandProgress.vue';
|
||||
import ToolResultRenderer from './ToolResultRenderer.vue';
|
||||
import CollaborationTasks from './CollaborationTasks.vue';
|
||||
import { childAgentTabsKey, childAgentTaskLookupKey } from '@/composables/useChildAgentTabs';
|
||||
import { useChildAgentViewer } from '@/composables/useChildAgentViewer';
|
||||
import { defineAsyncComponent } from 'vue';
|
||||
const ChildAgentStream = defineAsyncComponent(() => import('./ChildAgentStream.vue'));
|
||||
import ProgressUpdates from './ProgressUpdates.vue';
|
||||
import { foldProgressIntoThinking, groupProgressUpdates } from '@/utils/agentTimelinePresentation';
|
||||
import { isUnresolvedCollaborationPrompt, collaborationActivity, collaborationWaitState, collaborationTimeline, collaborationTasks, countToolCalls } from '@/utils/collaborationDisplay';
|
||||
import ToolApprovalCard from './ToolApprovalCard.vue';
|
||||
import McpOAuthCard from './McpOAuthCard.vue';
|
||||
import OpenPageCard from './OpenPageCard.vue';
|
||||
|
|
@ -721,6 +744,7 @@ import {
|
|||
artifactIndexFromEventTarget,
|
||||
hydrateArtifactImages,
|
||||
renderArtifactReference,
|
||||
installArtifactLinkRenderer,
|
||||
} from '@/utils/sandboxArtifactRefs';
|
||||
import type { ProtectedFileAccessContext } from '@/utils/protectedFileAccess';
|
||||
import { unwrapFinalAnswerWrappers, thinkingEqualsAnswer } from '@/utils/finalAnswer';
|
||||
|
|
@ -772,6 +796,7 @@ import { browserToolTitle } from '@/utils/browserToolDisplay';
|
|||
import BrowserIcon from '@/components/icons/BrowserIcon.vue';
|
||||
const getToolIconName = getAgentToolIconName;
|
||||
|
||||
const readingHistory = inject(chatReadingHistoryKey, ref(false));
|
||||
const router = useRouter();
|
||||
const route = useRoute();
|
||||
const uiStore = useUIStore();
|
||||
|
|
@ -828,7 +853,12 @@ const TOOL_NAME_KEYS: Record<string, string> = {
|
|||
database_query: 'agentStream.tools.databaseQuery',
|
||||
find_operations: 'agentStream.tools.findOperations',
|
||||
run_operation: 'agentStream.tools.runOperation',
|
||||
try_agent: 'agentStream.tools.tryAgent',
|
||||
spawn_agent: 'agentStream.tools.spawn_agent',
|
||||
list_agents: 'agentStream.tools.list_agents',
|
||||
send_message: 'agentStream.tools.send_message',
|
||||
followup_task: 'agentStream.tools.followup_task',
|
||||
interrupt_agent: 'agentStream.tools.interrupt_agent',
|
||||
wait_agent: 'agentStream.tools.wait_agent',
|
||||
open_page: 'agentStream.tools.openPage',
|
||||
read_page: 'agentStream.tools.readPage',
|
||||
select_tab: 'agentStream.tools.selectTab',
|
||||
|
|
@ -909,7 +939,6 @@ function escapeHtml(value: string): string {
|
|||
.replace(/'/g, ''');
|
||||
}
|
||||
|
||||
const streamingStepsContainer = ref<HTMLElement | null>(null);
|
||||
|
||||
// 图片预览状态
|
||||
const imagePreviewVisible = ref(false);
|
||||
|
|
@ -1051,6 +1080,7 @@ const props = defineProps<{
|
|||
sessionId?: string;
|
||||
userQuery?: string;
|
||||
embeddedMode?: boolean;
|
||||
artifactsInDrawer?: boolean;
|
||||
embedChannelId?: string;
|
||||
embedToken?: string;
|
||||
embedSessionSig?: string;
|
||||
|
|
@ -1125,9 +1155,12 @@ const protectedFileAccess = computed<ProtectedFileAccessContext | undefined>(()
|
|||
// -----------------------------------------------------------------------------
|
||||
// Same contract as botmsg.vue: only render the button when the persisted
|
||||
// assistant message actually recorded files, then open the sandbox panel's
|
||||
// artifacts tab (or ChatArtifactsDrawer in embedded mode).
|
||||
// artifacts tab, or a session-local drawer for embedded/child conversations.
|
||||
const showArtifactDrawer = ref(false);
|
||||
const sandboxPanel = useChatSandboxPanel();
|
||||
// A child inherits the parent's injection, but that panel belongs to a different
|
||||
// session. Use the same routing condition for opening and rendering the drawer.
|
||||
const useArtifactDrawer = computed(() => props.artifactsInDrawer || props.embeddedMode || !sandboxPanel);
|
||||
const artifactList = computed(() => {
|
||||
const list = ((props.session?.artifacts as any[]) || []);
|
||||
return list.map((a, i) => ({ index: i, ...a }));
|
||||
|
|
@ -1151,7 +1184,7 @@ const messageIdForArtifacts = computed(() =>
|
|||
const artifactPreviewIndex = ref<number | null>(null);
|
||||
function openArtifactDrawer(previewIndex: number | null = null) {
|
||||
if (!hasArtifacts.value) return;
|
||||
if (sandboxPanel && !props.embeddedMode) {
|
||||
if (sandboxPanel && !useArtifactDrawer.value) {
|
||||
if (previewIndex == null) {
|
||||
sandboxPanel.toggleArtifacts(messageIdForArtifacts.value);
|
||||
} else {
|
||||
|
|
@ -1512,6 +1545,17 @@ configureMarkedForChatMarkdown();
|
|||
|
||||
// Event stream
|
||||
const eventStream = computed(() => props.session?.agentEventStream || []);
|
||||
const childAgentTabs = inject(childAgentTabsKey, null);
|
||||
const lookupChildTask = inject(childAgentTaskLookupKey, null);
|
||||
const openChildTask = (task: ReturnType<typeof collaborationTasks>[number]) => {
|
||||
if (childAgentTabs) childAgentTabs.open(task, () => lookupChildTask
|
||||
? lookupChildTask(task)
|
||||
: collaborationTasks(props.session.collaborationStatus).find(item => item.id === task.id));
|
||||
else selectedChildId.value = task.id;
|
||||
};
|
||||
const selectedChildId = useChildAgentViewer();
|
||||
const selectedChild = computed(() => collaborationTasks(props.session.collaborationStatus).find(task => task.id === selectedChildId.value));
|
||||
const hasCollaborationTasks = computed(() => !props.ragMode && collaborationTasks(props.session.collaborationStatus).length > 0);
|
||||
|
||||
// Expanded events tracking (for tool calls and thinking events)
|
||||
const expandedEvents = ref<Set<string>>(new Set());
|
||||
|
|
@ -1527,8 +1571,10 @@ const isThinkingActive = (eventId: string): boolean => {
|
|||
return activeThinkingIds.value.has(eventId);
|
||||
};
|
||||
|
||||
const deferredThinkingFolds = new Set<string>();
|
||||
|
||||
// Watch event stream to auto-expand thinking events and auto-collapse when non-thinking follows
|
||||
watch(eventStream, (stream) => {
|
||||
watch([eventStream, readingHistory], ([stream]) => {
|
||||
if (!stream || !Array.isArray(stream)) return;
|
||||
|
||||
// Scan stream to find thinking events to expand and collapse
|
||||
|
|
@ -1555,36 +1601,20 @@ watch(eventStream, (stream) => {
|
|||
|
||||
// Collapse thinking events that were active before but are no longer trailing
|
||||
for (const oldId of activeThinkingIds.value) {
|
||||
if (!newActiveIds.has(oldId)) {
|
||||
expandedEvents.value.delete(oldId);
|
||||
}
|
||||
if (!newActiveIds.has(oldId)) deferredThinkingFolds.add(oldId);
|
||||
}
|
||||
if (!readingHistory.value) {
|
||||
for (const id of deferredThinkingFolds) {
|
||||
if (!newActiveIds.has(id)) expandedEvents.value.delete(id);
|
||||
}
|
||||
deferredThinkingFolds.clear();
|
||||
}
|
||||
|
||||
activeThinkingIds.value = newActiveIds;
|
||||
activeThinkingVersion.value++;
|
||||
|
||||
nextTick(async () => {
|
||||
await hydrateProtectedFileImages(rootElement.value, protectedFileAccess.value);
|
||||
await enhanceMarkdownContainer(rootElement.value);
|
||||
// Auto-scroll thinking detail content to bottom during streaming
|
||||
if (newActiveIds.size > 0 && rootElement.value) {
|
||||
const els = rootElement.value.querySelectorAll('.thinking-detail-content');
|
||||
els.forEach((el: Element) => {
|
||||
const htmlEl = el as HTMLElement;
|
||||
if (htmlEl.scrollHeight > htmlEl.clientHeight) {
|
||||
htmlEl.scrollTop = htmlEl.scrollHeight;
|
||||
}
|
||||
});
|
||||
}
|
||||
// Auto-scroll the steps container to the bottom while it is still height-
|
||||
// capped (steps-only phase). Once answer text appears the cap is released
|
||||
// and the container grows with the page, so internal scrolling is moot.
|
||||
if (!answerEverStarted.value && streamingStepsContainer.value) {
|
||||
const el = streamingStepsContainer.value;
|
||||
if (el.scrollHeight > el.clientHeight) {
|
||||
el.scrollTop = el.scrollHeight;
|
||||
}
|
||||
}
|
||||
});
|
||||
}, { immediate: true, deep: true });
|
||||
|
||||
|
|
@ -1603,18 +1633,6 @@ const hasAnswerStarted = computed(() => {
|
|||
return stream.some((e: any) => e.type === 'answer' && !e.superseded && e.content && e.content.trim());
|
||||
});
|
||||
|
||||
// Whether ANY answer text has ever appeared this turn — including a preamble
|
||||
// that was later superseded (its content stays in the stream). Used to release
|
||||
// the live container's height cap. Unlike hasAnswerStarted this is monotonic:
|
||||
// it does not flip back when a preamble is retracted, so the container does not
|
||||
// shrink back to the capped height (which would look like a jump). Once the
|
||||
// model starts producing answer-style text, give it full height to breathe.
|
||||
const answerEverStarted = computed(() => {
|
||||
const stream = eventStream.value;
|
||||
if (!stream || !Array.isArray(stream)) return false;
|
||||
return stream.some((e: any) => e.type === 'answer' && e.content && e.content.trim());
|
||||
});
|
||||
|
||||
const agentDurationMs = ref<number>(0);
|
||||
watch(eventStream, (stream) => {
|
||||
if (!stream || !Array.isArray(stream)) return;
|
||||
|
|
@ -1635,7 +1653,10 @@ watch(eventStream, (stream) => {
|
|||
const isConversationDone = computed(
|
||||
() => isAssistantTurnComplete(props.session) && !isAwaitingInput(props.session),
|
||||
);
|
||||
const timelineCompleted = useDeferredTimelineCompletion(isConversationDone, readingHistory);
|
||||
const isSegmentDone = computed(() => Boolean(props.session?.steerForked) || isConversationDone.value);
|
||||
const collaborationWait = computed(() => collaborationWaitState(eventStream.value, isSegmentDone.value));
|
||||
const childActivity = computed(() => props.ragMode ? undefined : collaborationActivity(eventStream.value, props.session.collaborationStatus, isSegmentDone.value));
|
||||
|
||||
const streamingMermaidSvgCache = ref<string[]>([]);
|
||||
let streamingMermaidRenderTask: Promise<void> | null = null;
|
||||
|
|
@ -1728,6 +1749,8 @@ watch(answerFullyRendered, (ready) => {
|
|||
});
|
||||
}, { immediate: true });
|
||||
|
||||
const wasUserStopped = computed(() => eventStream.value.some((e: any) => e.type === 'stop'));
|
||||
|
||||
// Whether any currently visible step is actively pending (a running tool, or a
|
||||
// blocking approval/OAuth prompt). A pending step shimmers on its own, so we
|
||||
// don't stack a placeholder on top of it.
|
||||
|
|
@ -1741,11 +1764,7 @@ const hasPendingStreamingActivity = computed(() => {
|
|||
) {
|
||||
return true;
|
||||
}
|
||||
return (
|
||||
event.type === 'tool_approval_required' ||
|
||||
event.type === 'mcp_oauth_required' ||
|
||||
event.type === 'agent_prompt_required'
|
||||
);
|
||||
return isUnresolvedCollaborationPrompt(event);
|
||||
});
|
||||
});
|
||||
|
||||
|
|
@ -1758,6 +1777,7 @@ const hasPendingStreamingActivity = computed(() => {
|
|||
const showAgentActivityIndicator = computed(() => {
|
||||
if (isSegmentDone.value) return false;
|
||||
if (props.ragMode || hasAnswerStarted.value) return false;
|
||||
if (collaborationWait.value === 'waiting') return false;
|
||||
return !hasPendingStreamingActivity.value;
|
||||
});
|
||||
|
||||
|
|
@ -1766,7 +1786,7 @@ const isStreamingTimelineEvent = (event: any): boolean => {
|
|||
};
|
||||
|
||||
const showStreamingTimeline = computed(() => {
|
||||
return displayEvents.value.some((event: any) => isStreamingTimelineEvent(event)) || showAgentActivityIndicator.value;
|
||||
return displayEvents.value.some((event: any) => isStreamingTimelineEvent(event)) || showAgentActivityIndicator.value || Boolean(childActivity.value);
|
||||
});
|
||||
|
||||
const lastStreamingTimelineEventIndex = computed(() => {
|
||||
|
|
@ -1839,11 +1859,11 @@ const finalContent = computed(() => {
|
|||
|
||||
// Count intermediate steps (after merging consecutive thinking events, matching what user sees in tree)
|
||||
const intermediateStepsCount = computed(() => {
|
||||
if (!hasAnswerStarted.value && !isSegmentDone.value) return 0;
|
||||
if (!hasAnswerStarted.value && !isSegmentDone.value && !hasCollaborationTasks.value) return 0;
|
||||
// Count only thinking and tool_call events (exclude plan_task_change, etc.);
|
||||
// a question card stands in for its ask_user call.
|
||||
return intermediateEvents.value.filter(
|
||||
(e: any) => e.type === 'thinking' || e.type === 'tool_call' || e.type === 'agent_prompt_required'
|
||||
(e: any) => e.type === 'thinking' || e.type === 'progress' || e.type === 'tool_call' || e.type === 'child_task' || e.type === 'agent_prompt_required'
|
||||
).length;
|
||||
});
|
||||
|
||||
|
|
@ -1852,15 +1872,13 @@ const intermediateStepsCount = computed(() => {
|
|||
// over-counts what the user perceives as agent loops (a single loop emits one
|
||||
// thinking card plus its tool calls).
|
||||
const reasoningRoundsCount = computed(() => {
|
||||
if (!hasAnswerStarted.value && !isSegmentDone.value) return 0;
|
||||
if (!hasAnswerStarted.value && !isSegmentDone.value && !hasCollaborationTasks.value) return 0;
|
||||
return intermediateEvents.value.filter((e: any) => e.type === 'thinking').length;
|
||||
});
|
||||
|
||||
const toolCallsCount = computed(() => {
|
||||
if (!hasAnswerStarted.value && !isSegmentDone.value) return 0;
|
||||
return intermediateEvents.value.filter(
|
||||
(e: any) => e.type === 'tool_call' || e.type === 'agent_prompt_required'
|
||||
).length;
|
||||
if (!hasAnswerStarted.value && !isSegmentDone.value && !hasCollaborationTasks.value) return 0;
|
||||
return countToolCalls(eventStream.value);
|
||||
});
|
||||
|
||||
const intermediateStepsSummary = computed(() => {
|
||||
|
|
@ -1904,7 +1922,7 @@ const intermediateStepsSummaryHtml = computed(() => {
|
|||
const shouldShowCollapsedSteps = computed(() => {
|
||||
if (props.ragMode) return false
|
||||
const hasSteps = intermediateStepsCount.value > 0;
|
||||
return hasSteps && isConversationDone.value;
|
||||
return hasSteps && timelineCompleted.value;
|
||||
});
|
||||
|
||||
// Once the steps collapse, the memory row travels with them into the tree —
|
||||
|
|
@ -1917,7 +1935,7 @@ const showMemoryRow = computed(
|
|||
// Memory leads the timeline, so it is only the last node while nothing has
|
||||
// followed it yet — and a lone node has no trunk line to draw below it.
|
||||
const memoryIsLast = computed(
|
||||
() => lastStreamingTimelineEventIndex.value === -1 && !showAgentActivityIndicator.value,
|
||||
() => lastStreamingTimelineEventIndex.value === -1 && !showAgentActivityIndicator.value && !childActivity.value,
|
||||
);
|
||||
|
||||
// Check if event is a "deep thinking" type (either streaming thinking or thinking tool call)
|
||||
|
|
@ -1959,11 +1977,8 @@ const buildFullEventList = (stream: any[]) => {
|
|||
.filter((e: any) => e?.type === 'agent_prompt_required' && e.tool_call_id)
|
||||
.map((e: any) => e.tool_call_id),
|
||||
);
|
||||
const validStream = stream.filter(
|
||||
(e: any) =>
|
||||
e && typeof e === 'object' && e.type &&
|
||||
!(e.type === 'tool_call' && askedCalls.has(e.tool_call_id)),
|
||||
);
|
||||
// Retain tool boundaries until reasoning and progress have been associated.
|
||||
const validStream = stream.filter((e: any) => e && typeof e === 'object' && e.type);
|
||||
let lastTask: string | null = null;
|
||||
const result: any[] = [];
|
||||
|
||||
|
|
@ -2024,47 +2039,24 @@ const buildFullEventList = (stream: any[]) => {
|
|||
result.push(event);
|
||||
}
|
||||
|
||||
// Relocate each retracted (superseded) answer — a tool round's optimistic
|
||||
// preamble that was pulled out of the answer area — into that round's
|
||||
// thinking card as its TITLE, with the reasoning as the body (one card per
|
||||
// round). A lone preamble (model has no separate reasoning channel) becomes a
|
||||
// title-only thinking card. Non-superseded answers stay as `answer` and are
|
||||
// rendered in the answer area, never here.
|
||||
const folded: any[] = [];
|
||||
for (const e of result) {
|
||||
if (e.type === 'answer' && e.superseded) {
|
||||
const preambleText = typeof e.content === 'string' ? e.content : '';
|
||||
const prev = folded[folded.length - 1];
|
||||
if (prev && prev.type === 'thinking' && !prev.title) {
|
||||
folded[folded.length - 1] = { ...prev, title: preambleText };
|
||||
continue;
|
||||
}
|
||||
// No reasoning channel: title-only thinking card (same chrome as merged
|
||||
// rounds). Rounds with reasoning_content merge preamble into prev.title.
|
||||
folded.push({
|
||||
type: 'thinking',
|
||||
event_id: e.event_id,
|
||||
title: preambleText,
|
||||
content: '',
|
||||
thinking: false,
|
||||
timestamp: e.timestamp,
|
||||
});
|
||||
continue;
|
||||
}
|
||||
folded.push(e);
|
||||
}
|
||||
// Progress is the visible label; the preceding reasoning remains expandable.
|
||||
// This projection never changes the stored event types or final answers.
|
||||
const folded = collaborationTimeline(foldProgressIntoThinking(result), props.session.collaborationStatus, isSegmentDone.value).filter(
|
||||
(e: any) =>
|
||||
!(e.type === 'tool_call' && askedCalls.has(e.tool_call_id)),
|
||||
);
|
||||
|
||||
// Drop thinking cards that are entirely empty (no title and no body). Some
|
||||
// models emit "\n\n" before a tool call (e.g. qwen3 blank lines between
|
||||
// [assistant] and tool_calls), which would otherwise show an empty "思考"
|
||||
// card. Keep cards that carry a title (a relocated preamble) even with no
|
||||
// reasoning body.
|
||||
return folded.filter((e: any) => {
|
||||
return groupProgressUpdates(folded.filter((e: any) => {
|
||||
if (e.type !== 'thinking') return true;
|
||||
const content = typeof e.content === 'string' ? e.content : '';
|
||||
const title = typeof e.title === 'string' ? e.title : '';
|
||||
return content.trim().length > 0 || title.trim().length > 0;
|
||||
});
|
||||
}));
|
||||
};
|
||||
|
||||
// IDs of thinking events that should NOT be rendered in the intermediate-
|
||||
|
|
@ -2168,14 +2160,15 @@ const displayEvents = computed(() => {
|
|||
|
||||
// Keep the active reasoning event inline with tool activity. It uses the same
|
||||
// compact timeline card and is auto-collapsed when a tool or answer follows.
|
||||
if (!isConversationDone.value) {
|
||||
if (!timelineCompleted.value) {
|
||||
return result;
|
||||
}
|
||||
|
||||
// Done: the steps live in the collapsed tree; show only the answer here.
|
||||
const answerEvents = result.filter((e: any) => e.type === 'answer');
|
||||
if (answerEvents.length > 0) {
|
||||
return answerEvents;
|
||||
// All completed steps, including child task entry points, belong to the
|
||||
// collapsible timeline. Only the final answer remains outside it.
|
||||
const foregroundEvents = result.filter((e: any) => e.type === 'answer');
|
||||
if (foregroundEvents.length > 0) {
|
||||
return foregroundEvents;
|
||||
}
|
||||
|
||||
// If the intermediate-steps tree is active, all thinking/tool_call events
|
||||
|
|
@ -2681,6 +2674,13 @@ agentRenderer.image = function agentImageRenderer(token) {
|
|||
return defaultImageRenderer.call(this, token);
|
||||
};
|
||||
|
||||
installArtifactLinkRenderer(agentRenderer, () => ({
|
||||
artifacts: artifactList.value,
|
||||
labels: artifactRefLabels.value,
|
||||
context: artifactRefContext.value,
|
||||
streaming: !isSegmentDone.value,
|
||||
}));
|
||||
|
||||
const hasCachedMermaidSvg = (cached: CachedMermaidSvgHtml): boolean => {
|
||||
if (!cached) return false;
|
||||
if (typeof cached === 'string') return cached.length > 0;
|
||||
|
|
@ -3285,6 +3285,8 @@ const handleAddToKnowledge = (answerEvent: any) => {
|
|||
</script>
|
||||
|
||||
<style lang="less" scoped>
|
||||
|
||||
|
||||
@import '../../../components/css/chat-markdown.less';
|
||||
@import '../../../components/css/chat-message-shared.less';
|
||||
@import '../../../components/css/chat-citations.less';
|
||||
|
|
@ -3325,35 +3327,14 @@ const handleAddToKnowledge = (answerEvent: any) => {
|
|||
}
|
||||
}
|
||||
|
||||
// Streaming steps container
|
||||
// Keep one outer scroll viewport through reasoning, progress and answer phases.
|
||||
// A height cap here would release on the first answer token and jump the page.
|
||||
.streaming-steps-container {
|
||||
position: relative;
|
||||
|
||||
&.is-streaming-timeline {
|
||||
margin-top: 8px;
|
||||
}
|
||||
|
||||
&.streaming-steps-constrained {
|
||||
max-height: 400px;
|
||||
overflow-y: auto;
|
||||
|
||||
&::-webkit-scrollbar {
|
||||
width: 4px;
|
||||
}
|
||||
|
||||
&::-webkit-scrollbar-track {
|
||||
background: transparent;
|
||||
}
|
||||
|
||||
&::-webkit-scrollbar-thumb {
|
||||
background: var(--td-bg-color-component-disabled);
|
||||
border-radius: 2px;
|
||||
|
||||
&:hover {
|
||||
background: var(--td-text-color-placeholder);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Event items (flat, no timeline)
|
||||
|
|
@ -3432,6 +3413,9 @@ const handleAddToKnowledge = (answerEvent: any) => {
|
|||
border-left: 1px solid var(--agent-step-line-color);
|
||||
}
|
||||
|
||||
// Narration has no icon, so its trunk must cover the usual icon gap.
|
||||
&.tree-child-progress::before { top: 0; }
|
||||
|
||||
// horizontal branch connector
|
||||
.tree-branch {
|
||||
display: none;
|
||||
|
|
|
|||
|
|
@ -13,13 +13,23 @@
|
|||
</div>
|
||||
|
||||
<div v-for="field in fields" :key="field.name" class="ask-field">
|
||||
<label class="ask-field-label">
|
||||
<label :id="`${pendingId}-${field.name}-label`" class="ask-field-label">
|
||||
{{ field.label || field.name }}<span v-if="field.required" class="ask-required">*</span>
|
||||
</label>
|
||||
<t-input-number v-if="field.type === 'number'" v-model="values[field.name]" :disabled="submitting"
|
||||
theme="normal" size="small" class="ask-number" />
|
||||
<t-select v-else-if="field.type === 'select' || field.type === 'multiselect'" v-model="values[field.name]"
|
||||
:multiple="field.type === 'multiselect'" :disabled="submitting" size="small" clearable
|
||||
<div v-else-if="field.type === 'multiselect'" class="ask-field-options" role="group"
|
||||
:aria-labelledby="`${pendingId}-${field.name}-label`">
|
||||
<label v-for="option in field.options || []" :key="option" class="ask-field-option"
|
||||
:class="{ 'is-selected': fieldHasOption(field.name, option), 'is-disabled': submitting }">
|
||||
<input type="checkbox" :checked="fieldHasOption(field.name, option)" :disabled="submitting"
|
||||
@change="toggleFieldOption(field.name, option)" />
|
||||
<span class="ask-field-option-mark" aria-hidden="true"><CheckIcon size="12px" /></span>
|
||||
<span class="ask-field-option-text">{{ option }}</span>
|
||||
</label>
|
||||
</div>
|
||||
<t-select v-else-if="field.type === 'select'" v-model="values[field.name]"
|
||||
:disabled="submitting" size="small" clearable
|
||||
:popup-props="{ overlayClassName: 'wk-popover' }"
|
||||
:placeholder="$t('agentStream.askUser.selectPlaceholder')">
|
||||
<t-option v-for="option in field.options || []" :key="option" :value="option" :label="option" />
|
||||
|
|
@ -73,6 +83,7 @@
|
|||
<script setup lang="ts">
|
||||
import { computed, inject, reactive, ref } from 'vue'
|
||||
import { MessagePlugin } from 'tdesign-vue-next'
|
||||
import { CheckIcon } from 'tdesign-icons-vue-next'
|
||||
import { useI18n } from 'vue-i18n'
|
||||
import { resolveAgentPrompt } from '@/api/mcp-service'
|
||||
import { resolveEmbedAgentPrompt } from '@/api/embed'
|
||||
|
|
@ -133,6 +144,17 @@ const values = reactive<Record<string, unknown>>({})
|
|||
const text = ref('')
|
||||
const submitting = ref(false)
|
||||
|
||||
const fieldHasOption = (name: string, option: string) =>
|
||||
Array.isArray(values[name]) && (values[name] as string[]).includes(option)
|
||||
|
||||
const toggleFieldOption = (name: string, option: string) => {
|
||||
if (submitting.value) return
|
||||
const selected = Array.isArray(values[name]) ? values[name] as string[] : []
|
||||
values[name] = selected.includes(option)
|
||||
? selected.filter(value => value !== option)
|
||||
: [...selected, option]
|
||||
}
|
||||
|
||||
const isSelected = (option: string) =>
|
||||
multiSelect.value ? selectedMany.value.includes(option) : selectedOne.value === option
|
||||
|
||||
|
|
@ -276,6 +298,60 @@ defineExpose({ handleKey })
|
|||
width: 100%;
|
||||
}
|
||||
|
||||
.ask-field-options {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(auto-fit, minmax(min(100%, 150px), 1fr));
|
||||
gap: 6px;
|
||||
max-height: 200px;
|
||||
overflow-y: auto;
|
||||
overscroll-behavior: contain;
|
||||
padding: 2px;
|
||||
}
|
||||
|
||||
.ask-field-option {
|
||||
position: relative;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
min-width: 0;
|
||||
padding: 9px 10px;
|
||||
border: 1px solid var(--td-component-stroke);
|
||||
border-radius: var(--app-radius-md);
|
||||
background: var(--td-bg-color-container);
|
||||
color: var(--td-text-color-primary);
|
||||
font-size: var(--agent-step-summary-size, 13px);
|
||||
line-height: 1.5;
|
||||
cursor: pointer;
|
||||
transition: background var(--app-motion-fast) ease, border-color var(--app-motion-fast) ease;
|
||||
|
||||
&:hover:not(.is-disabled) { background: var(--td-bg-color-container-hover); }
|
||||
&.is-selected {
|
||||
background: var(--td-bg-color-secondarycontainer);
|
||||
border-color: var(--td-component-border);
|
||||
}
|
||||
&:has(input:focus-visible) { outline: 2px solid var(--td-brand-color); outline-offset: 1px; }
|
||||
&.is-disabled { opacity: .5; cursor: not-allowed; }
|
||||
input { position: absolute; width: 1px; height: 1px; opacity: 0; }
|
||||
}
|
||||
|
||||
.ask-field-option-text { min-width: 0; overflow-wrap: anywhere; }
|
||||
.ask-field-option-mark {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
flex-shrink: 0;
|
||||
width: 15px;
|
||||
height: 15px;
|
||||
border: 1px solid var(--td-component-border);
|
||||
border-radius: var(--app-radius-xs, 3px);
|
||||
color: transparent;
|
||||
}
|
||||
.is-selected .ask-field-option-mark {
|
||||
background: var(--td-brand-color);
|
||||
border-color: var(--td-brand-color);
|
||||
color: var(--td-text-color-anti);
|
||||
}
|
||||
|
||||
// Filled, borderless fields, like the option rows and argument editor of the
|
||||
// other prompts in the dock.
|
||||
.ask-field :deep(.t-input),
|
||||
|
|
|
|||
|
|
@ -23,7 +23,7 @@
|
|||
v-if="internalVisible && previewItem"
|
||||
class="artifact-preview-resize-handle"
|
||||
:class="{ 'artifact-preview-resize-handle--active': previewResizing }"
|
||||
:style="{ right: `${previewWidth}px` }"
|
||||
:style="{ right: drawerSize }"
|
||||
role="separator"
|
||||
aria-orientation="vertical"
|
||||
@mousedown.prevent="onPreviewResizeStart"
|
||||
|
|
@ -38,9 +38,10 @@
|
|||
:class="{ 'chat-artifacts-drawer--preview': !!previewItem, 'chat-artifacts-drawer--resizing': previewResizing }"
|
||||
placement="right"
|
||||
:size="drawerSize"
|
||||
:z-index="previewItem ? 2000 : 1500"
|
||||
:z-index="2000"
|
||||
attach="body"
|
||||
:footer="false"
|
||||
:close-btn="true"
|
||||
:close-on-overlay-click="true"
|
||||
:close-on-esc-keydown="true"
|
||||
:destroy-on-close="false"
|
||||
|
|
@ -248,7 +249,7 @@ const previewFileType = computed(() => {
|
|||
})
|
||||
|
||||
const drawerSize = computed(() => (
|
||||
previewItem.value ? `${previewWidth.value}px` : `${LIST_WIDTH}px`
|
||||
`min(${previewItem.value ? previewWidth.value : LIST_WIDTH}px, 100%)`
|
||||
))
|
||||
|
||||
function previewMaxWidth() {
|
||||
|
|
@ -444,7 +445,7 @@ onUnmounted(() => {
|
|||
}
|
||||
|
||||
.artifact-drawer-header--preview {
|
||||
padding-right: 8px;
|
||||
padding-right: 32px;
|
||||
}
|
||||
|
||||
.artifact-back {
|
||||
|
|
@ -602,8 +603,7 @@ onUnmounted(() => {
|
|||
bottom: 0;
|
||||
width: 12px;
|
||||
margin-left: -6px;
|
||||
// Its inline right is the drawer width; a docked assistant panel adds to it.
|
||||
margin-right: var(--assistant-dock-width, 0px);
|
||||
// This drawer belongs to the conversation and overlays the assistant too.
|
||||
z-index: 2002;
|
||||
cursor: col-resize;
|
||||
display: flex;
|
||||
|
|
|
|||
|
|
@ -0,0 +1,166 @@
|
|||
<template>
|
||||
<div ref="viewport" class="child-stream" @scroll="onScroll">
|
||||
<div class="child-stream-content">
|
||||
<p v-if="loading && !messages.length">{{ t('common.loading') }}</p>
|
||||
<div v-if="failure" class="child-stream-error" role="alert">
|
||||
{{ failure }} <button type="button" @click="refresh">{{ t('common.retry') }}</button>
|
||||
</div>
|
||||
<template v-for="message in messages" :key="String(message.id)">
|
||||
<details v-if="message.role === 'user'" class="child-assignment">
|
||||
<summary>
|
||||
<span class="child-assignment-label">
|
||||
<TaskIcon class="child-assignment-icon" size="18px" aria-hidden="true" />
|
||||
{{ t('agentStream.collaboration.assignment') }}
|
||||
</span>
|
||||
<span v-if="message === latestAssignment" class="child-assignment-status" :class="task.status" role="status">
|
||||
{{ t(`agentStream.collaboration.status.${task.status}`) }}
|
||||
</span>
|
||||
<ChevronRightIcon class="child-assignment-chevron" size="16px" aria-hidden="true" />
|
||||
</summary>
|
||||
<div class="child-assignment-body">{{ message.content }}</div>
|
||||
</details>
|
||||
<AgentStreamDisplay v-else-if="message.role === 'assistant'" :session="message" :session-id="task.sessionId" artifacts-in-drawer />
|
||||
</template>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
<script setup lang="ts">
|
||||
import { computed, defineAsyncComponent, nextTick, onMounted, onUnmounted, reactive, ref, watch } from 'vue'
|
||||
import { useI18n } from 'vue-i18n'
|
||||
import { ChevronRightIcon, TaskIcon } from 'tdesign-icons-vue-next'
|
||||
import { useChatScrollFollow } from '@/composables/useChatScrollFollow'
|
||||
import { getMessageList } from '@/api/chat'
|
||||
import { useStream } from '@/api/chat/streame'
|
||||
import { isAwaitingInput, useChatStreamHandler, type ChatMessage } from '@/composables/useChatStreamHandler'
|
||||
import { isCollaborationTaskActive, type CollaborationTaskView } from '@/utils/collaborationDisplay'
|
||||
const AgentStreamDisplay = defineAsyncComponent(() => import('./AgentStreamDisplay.vue'))
|
||||
const props = defineProps<{ task: CollaborationTaskView; active?: boolean }>()
|
||||
const { t } = useI18n()
|
||||
const messages = reactive<ChatMessage[]>([])
|
||||
const latestAssignment = computed(() => [...messages].reverse().find(message => message.role === 'user'))
|
||||
const viewport = ref<HTMLElement | null>(null)
|
||||
const loading = ref(false)
|
||||
const isReplying = ref(false)
|
||||
const currentAssistantMessageId = ref('')
|
||||
const fullContent = ref('')
|
||||
const failure = ref('')
|
||||
let closed = false
|
||||
let refreshing = false
|
||||
let refreshRequested = false
|
||||
let timer: ReturnType<typeof setTimeout> | undefined
|
||||
const readingHistory = ref(false)
|
||||
let historySignature = ''
|
||||
const scrollFollow = useChatScrollFollow(viewport, readingHistory, computed(() => props.active !== false))
|
||||
const { onScroll, scrollToBottom } = scrollFollow
|
||||
let savedScrollTop = 0
|
||||
watch(() => props.active, active => {
|
||||
if (active === false) savedScrollTop = viewport.value?.scrollTop || 0
|
||||
else void nextTick(() => {
|
||||
if (viewport.value) {
|
||||
viewport.value.scrollTop = readingHistory.value ? savedScrollTop : viewport.value.scrollHeight
|
||||
scrollFollow.rememberPosition()
|
||||
}
|
||||
})
|
||||
})
|
||||
const stream = useStream()
|
||||
const handler = useChatStreamHandler({ messagesList: messages, loading, isReplying,
|
||||
currentAssistantMessageId, fullContent, isAgentStreamSession: () => true, scrollToBottom,
|
||||
preserveIncompleteStreamReactive: true })
|
||||
stream.onChunk(data => { if (!closed) handler.processStreamChunk(data) })
|
||||
async function refresh() {
|
||||
if (closed || refreshing || stream.isStreaming.value) return
|
||||
clearTimeout(timer)
|
||||
refreshing = true
|
||||
loading.value = true
|
||||
try {
|
||||
const response = await getMessageList({ session_id: props.task.sessionId, limit: 100, created_at: '' })
|
||||
if (closed) return
|
||||
const rows = (response?.data || []) as ChatMessage[]
|
||||
const signature = JSON.stringify(rows)
|
||||
if (signature !== historySignature) {
|
||||
messages.splice(0)
|
||||
await handler.handleMsgList(rows)
|
||||
historySignature = signature
|
||||
}
|
||||
failure.value = ''
|
||||
// Suspended messages are settled for rendering, but may resume on the same
|
||||
// message ID. Never mistake that presentation flag for a terminal task.
|
||||
const latest = [...messages].reverse().find(m => m.role === 'assistant')
|
||||
const waiting = isAwaitingInput(latest)
|
||||
const pending = latest && (!latest.is_completed || waiting) ? latest : undefined
|
||||
if (pending && (!waiting || props.task.status === 'running')) {
|
||||
currentAssistantMessageId.value = String(pending.id)
|
||||
if (waiting) handler.prepareResumedMessage(pending, String((pending.pending_prompt as any)?.id || ''))
|
||||
await stream.startStream({ session_id: props.task.sessionId, query: String(pending.id),
|
||||
method: 'GET', url: '/api/v1/sessions/continue-stream' })
|
||||
if (!closed && stream.error.value) failure.value = stream.error.value
|
||||
}
|
||||
} catch (error: any) {
|
||||
if (!closed) failure.value = error?.message || t('common.error')
|
||||
} finally {
|
||||
refreshing = false
|
||||
loading.value = false
|
||||
// Poll only while disconnected; token updates use the child SSE stream.
|
||||
if (!closed && (refreshRequested || isCollaborationTaskActive(props.task.status))) {
|
||||
timer = setTimeout(refresh, refreshRequested ? 0 : 2000)
|
||||
}
|
||||
refreshRequested = false
|
||||
}
|
||||
}
|
||||
watch(() => props.task.status, () => {
|
||||
if (refreshing) refreshRequested = true
|
||||
else if (!stream.isStreaming.value) void refresh()
|
||||
})
|
||||
onMounted(refresh)
|
||||
onUnmounted(() => { closed = true; clearTimeout(timer); stream.stopStream() })
|
||||
</script>
|
||||
<style scoped lang="less">
|
||||
@import '../../../components/css/chat-scrollbar.less';
|
||||
.child-stream { height: 100%; box-sizing: border-box; overflow-y: auto; overscroll-behavior-y: contain; padding: 18px 16px 24px; font-size: var(--app-text-base); .chat-scrollbar(); }
|
||||
.child-assignment {
|
||||
margin: 0 0 20px;
|
||||
border: 1px solid var(--td-component-border);
|
||||
border-radius: var(--app-radius-md);
|
||||
background: var(--td-bg-color-container);
|
||||
}
|
||||
.child-assignment summary {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 10px;
|
||||
min-height: 46px;
|
||||
padding: 10px 12px;
|
||||
box-sizing: border-box;
|
||||
border-radius: var(--app-radius-md);
|
||||
color: var(--td-text-color-primary);
|
||||
font-size: var(--app-text-base);
|
||||
line-height: 1.5;
|
||||
list-style: none;
|
||||
cursor: pointer;
|
||||
transition: background-color var(--app-motion-fast) ease;
|
||||
}
|
||||
.child-assignment summary::-webkit-details-marker { display: none; }
|
||||
.child-assignment summary:hover { background: var(--td-bg-color-container-hover); }
|
||||
.child-assignment summary:focus-visible { outline: 2px solid var(--td-brand-color); outline-offset: 2px; }
|
||||
.child-assignment-label { display: inline-flex; align-items: center; gap: 8px; font-weight: 500; }
|
||||
.child-assignment-icon { flex-shrink: 0; color: var(--td-text-color-secondary); }
|
||||
.child-assignment-chevron { margin-left: auto; flex-shrink: 0; color: var(--td-text-color-secondary); transition: transform var(--app-motion-fast) ease; }
|
||||
.child-assignment[open] .child-assignment-chevron { transform: rotate(90deg); }
|
||||
.child-assignment-status { flex-shrink: 0; padding: 2px 7px; border-radius: var(--app-radius-xs); background: var(--td-bg-color-secondarycontainer); color: var(--td-text-color-secondary); font-size: var(--app-text-md); line-height: 1.5; }
|
||||
.child-assignment-status.running { color: var(--td-brand-color); background: var(--td-brand-color-light); }
|
||||
.child-assignment-status.waiting, .child-assignment-status.needs_attention { color: var(--td-warning-color); }
|
||||
.child-assignment-status.failed { color: var(--td-error-color); }
|
||||
.child-assignment-body {
|
||||
margin: 0;
|
||||
padding: 12px 16px;
|
||||
border-top: 1px solid var(--td-component-border);
|
||||
white-space: pre-wrap;
|
||||
overflow-wrap: anywhere;
|
||||
color: var(--td-text-color-secondary);
|
||||
font-size: var(--app-text-base);
|
||||
line-height: 1.7;
|
||||
}
|
||||
@media (prefers-reduced-motion: reduce) {
|
||||
.child-assignment-chevron, .child-assignment summary { transition: none; }
|
||||
}
|
||||
.child-stream-error { color: var(--td-error-color); margin: 12px 0; }
|
||||
</style>
|
||||
|
|
@ -0,0 +1,75 @@
|
|||
<template>
|
||||
<div ref="bar" class="child-agent-tabs" :class="{ 'in-header': headerMode }" role="tablist" :aria-label="t('agentStream.collaboration.tabs')">
|
||||
<button type="button" role="tab" class="child-agent-tab child-agent-tab-parent" :class="{ 'is-active': !activeId }"
|
||||
:aria-selected="!activeId" :tabindex="!activeId ? 0 : -1" @click="$emit('select', '')"
|
||||
@keydown="navigate($event, 0)">
|
||||
<span v-if="attention" class="child-agent-tab-dot waiting" :title="t('agentStream.collaboration.status.waiting')" />
|
||||
<slot name="parent">{{ t('agentStream.collaboration.mainConversation') }}</slot>
|
||||
</button>
|
||||
<div class="child-agent-tabs-scroll">
|
||||
<div v-for="(tab, index) in tabs" :key="tab.id" class="child-agent-tab-entry" :class="{ 'is-active': activeId === tab.id }">
|
||||
<button type="button" role="tab" class="child-agent-tab" :aria-selected="activeId === tab.id"
|
||||
:tabindex="activeId === tab.id ? 0 : -1" :title="`${tab.task.displayName} · ${t(`agentStream.collaboration.status.${tab.task.status}`)}`"
|
||||
@click="$emit('select', tab.id)" @keydown="navigate($event, index + 1)">
|
||||
<span class="child-agent-tab-dot" :class="tab.task.status" aria-hidden="true" />
|
||||
<span class="child-agent-tab-name">{{ tab.task.displayName || t('agentStream.collaboration.unnamed') }}</span>
|
||||
</button>
|
||||
<button type="button" class="child-agent-tab-close" :aria-label="`${t('common.close')} ${tab.task.displayName}`"
|
||||
@click="closeTab(tab.id)"><CloseIcon aria-hidden="true" /></button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
<script setup lang="ts">
|
||||
import { nextTick, ref, watch } from 'vue'
|
||||
import { useI18n } from 'vue-i18n'
|
||||
import { CloseIcon } from 'tdesign-icons-vue-next'
|
||||
import type { CollaborationTaskView } from '@/utils/collaborationDisplay'
|
||||
const props = defineProps<{ tabs: Array<{ id: string; task: CollaborationTaskView }>; activeId: string; attention?: boolean; headerMode?: boolean }>()
|
||||
const emit = defineEmits<{ select: [id: string]; close: [id: string] }>()
|
||||
const { t } = useI18n()
|
||||
const bar = ref<HTMLElement>()
|
||||
function closeTab(id: string) {
|
||||
emit('close', id)
|
||||
void nextTick(() => bar.value?.querySelector<HTMLButtonElement>('[aria-selected="true"]')?.focus())
|
||||
}
|
||||
function navigate(event: KeyboardEvent, index: number) {
|
||||
const count = props.tabs.length + 1
|
||||
let target: number
|
||||
if (event.key === 'ArrowRight') target = (index + 1) % count
|
||||
else if (event.key === 'ArrowLeft') target = (index + count - 1) % count
|
||||
else if (event.key === 'Home') target = 0
|
||||
else if (event.key === 'End') target = count - 1
|
||||
else return
|
||||
event.preventDefault()
|
||||
emit('select', target === 0 ? '' : props.tabs[target - 1].id)
|
||||
bar.value?.querySelectorAll<HTMLButtonElement>('[role="tab"]')[target]?.focus()
|
||||
}
|
||||
watch(() => props.activeId, () => nextTick(() => {
|
||||
if (props.activeId) bar.value?.querySelector('.child-agent-tabs-scroll [aria-selected="true"]')?.scrollIntoView({ block: 'nearest', inline: 'nearest' })
|
||||
}))
|
||||
</script>
|
||||
<style scoped lang="less">
|
||||
.child-agent-tabs { display: flex; align-items: center; flex-shrink: 0; gap: 4px; padding: 6px 12px; border-bottom: 1px solid var(--td-component-border); min-width: 0; }
|
||||
.child-agent-tabs-scroll { display: flex; align-items: center; gap: 4px; min-width: 0; overflow-x: auto; scrollbar-width: none; }
|
||||
.child-agent-tabs-scroll::-webkit-scrollbar { display: none; }
|
||||
.child-agent-tab-entry { display: flex; align-items: center; flex-shrink: 0; border-radius: var(--app-radius-sm); }
|
||||
.child-agent-tab { display: flex; align-items: center; gap: 7px; padding: 7px 10px; border: 0; border-radius: var(--app-radius-sm); background: transparent; color: var(--td-text-color-secondary); font: inherit; font-size: var(--app-text-md); line-height: 1.4; white-space: nowrap; cursor: pointer; flex-shrink: 0; }
|
||||
.child-agent-tabs.in-header { flex: 1; min-width: 0; border: 0; padding: 0; gap: 4px; }
|
||||
.in-header .child-agent-tab { padding: 6px 8px; font-size: var(--app-text-sm, 13px); }
|
||||
.in-header .child-agent-tab-name { max-width: 130px; }
|
||||
.child-agent-tab-name { max-width: 160px; overflow: hidden; text-overflow: ellipsis; }
|
||||
.child-agent-tab.is-active, .child-agent-tab-entry.is-active { background: var(--td-bg-color-secondarycontainer); }
|
||||
.child-agent-tab.is-active, .is-active .child-agent-tab { color: var(--td-text-color-primary); }
|
||||
.child-agent-tab-entry { transition: background-color var(--app-motion-fast) ease; }
|
||||
.child-agent-tab-entry:hover, .child-agent-tab-parent:hover { background: var(--td-bg-color-container-hover); }
|
||||
.child-agent-tab-entry:hover .child-agent-tab, .child-agent-tab-close:hover { color: var(--td-text-color-primary); }
|
||||
.in-header .child-agent-tab-parent { position: relative; padding: 0; gap: 4px; margin-right: 8px; background: transparent; color: var(--td-text-color-primary); }
|
||||
.in-header .child-agent-tab-parent > .child-agent-tab-dot { position: absolute; right: 0; top: 0; }
|
||||
.child-agent-tab:focus-visible, .child-agent-tab-close:focus-visible { outline: 2px solid var(--td-brand-color); outline-offset: -2px; }
|
||||
.child-agent-tab-close { display: flex; align-items: center; justify-content: center; width: 22px; height: 22px; margin-right: 5px; padding: 0; border: 0; border-radius: var(--app-radius-xs); background: transparent; color: var(--td-text-color-placeholder); cursor: pointer; font-size: var(--app-text-sm); }
|
||||
.child-agent-tab-dot { width: 5px; height: 5px; border-radius: 50%; background: var(--td-text-color-placeholder); flex-shrink: 0; }
|
||||
.child-agent-tab-dot.running { background: var(--td-brand-color); }
|
||||
.child-agent-tab-dot.waiting, .child-agent-tab-dot.needs_attention { background: var(--td-warning-color); }
|
||||
.child-agent-tab-dot.failed { background: var(--td-error-color); }
|
||||
</style>
|
||||
|
|
@ -0,0 +1,42 @@
|
|||
import assert from 'node:assert/strict'
|
||||
import { readFileSync } from 'node:fs'
|
||||
import { parse, compileTemplate } from '@vue/compiler-sfc'
|
||||
import { after, before, test } from 'node:test'
|
||||
import { fileURLToPath } from 'node:url'
|
||||
import { createServer, type ViteDevServer } from 'vite'
|
||||
import vue from '@vitejs/plugin-vue'
|
||||
import { createSSRApp, h, type Component } from 'vue'
|
||||
import { renderToString } from 'vue/server-renderer'
|
||||
import { createI18n } from 'vue-i18n'
|
||||
import zh from '../../../i18n/locales/zh-CN'
|
||||
let server: ViteDevServer
|
||||
let Card: Component
|
||||
before(async () => {
|
||||
server = await createServer({ configFile: false, optimizeDeps: { noDiscovery: true, entries: [] }, plugins: [vue()],
|
||||
resolve: { alias: { '@': fileURLToPath(new URL('../../../', import.meta.url)) } },
|
||||
server: { middlewareMode: true, hmr: false }, appType: 'custom' })
|
||||
Card = (await server.ssrLoadModule('/src/views/chat/components/CollaborationTasks.vue')).default
|
||||
// Compile the integration component as well: both timeline branches render progress.
|
||||
const source = readFileSync(new URL('./AgentStreamDisplay.vue', import.meta.url), 'utf8')
|
||||
const { descriptor } = parse(source)
|
||||
const compiled = compileTemplate({ source: descriptor.template!.content, filename: 'AgentStreamDisplay.vue', id: 'test' })
|
||||
assert.deepEqual(compiled.errors, [])
|
||||
})
|
||||
after(async () => { await server?.close() })
|
||||
async function render(props: Record<string, unknown>) {
|
||||
const app = createSSRApp({ render: () => h(Card, { toolLabel: () => '搜索网页', ...props }) })
|
||||
app.use(createI18n({ legacy: false, locale: 'zh-CN', messages: { 'zh-CN': zh } }))
|
||||
return renderToString(app)
|
||||
}
|
||||
test('child rows expose a readable task name and current tool without a top summary', async () => {
|
||||
const html = await render({ task: { id: 'private-id', name: 'review', displayName: '审核任务',
|
||||
sessionId: 's', runId: 'r', status: 'running', progress: { tool_name: 'web_search' } } })
|
||||
assert.match(html, /审核任务/)
|
||||
assert.match(html, /正在使用工具 · 搜索网页/)
|
||||
assert.doesNotMatch(html, /collaboration-summary|private-id|<details/)
|
||||
})
|
||||
test('completed child rows hide obsolete running tool progress', async () => {
|
||||
const html = await render({ task: { id: 'a', displayName: '检索', sessionId: 's', status: 'succeeded', progress: { tool_name: 'web_search' } } })
|
||||
assert.match(html, /已完成/)
|
||||
assert.doesNotMatch(html, /正在使用工具/)
|
||||
})
|
||||
|
|
@ -0,0 +1,101 @@
|
|||
<template>
|
||||
<button class="child-task-row" :class="{ 'is-running': task.status === 'running' }" type="button" :disabled="!task.sessionId || disabled" @click="$emit('open', task)">
|
||||
<span class="child-task-icon" :style="iconStyle" aria-hidden="true" />
|
||||
<span class="child-task-body">
|
||||
<span class="child-task-name">{{ task.displayName || t('agentStream.collaboration.unnamed') }}</span>
|
||||
<span class="child-task-activity" :class="task.status">{{ activity }}</span>
|
||||
</span>
|
||||
<ChevronRightIcon class="child-task-chevron" aria-hidden="true" />
|
||||
</button>
|
||||
</template>
|
||||
<script setup lang="ts">
|
||||
import { computed } from 'vue'
|
||||
import { useI18n } from 'vue-i18n'
|
||||
import { ChevronRightIcon } from 'tdesign-icons-vue-next'
|
||||
import agentIcon from '@/assets/img/agent.svg'
|
||||
import type { CollaborationTaskView } from '@/utils/collaborationDisplay'
|
||||
const iconStyle = { maskImage: `url("${agentIcon}")`, WebkitMaskImage: `url("${agentIcon}")` }
|
||||
const props = defineProps<{ task: CollaborationTaskView; disabled?: boolean; toolLabel: (name: string) => string }>()
|
||||
defineEmits<{ open: [task: CollaborationTaskView] }>()
|
||||
const { t } = useI18n()
|
||||
const activity = computed(() => {
|
||||
if (props.task.status === 'running' && props.task.progress?.tool_name) {
|
||||
const phase = props.task.progress.phase
|
||||
const key = ['tool_running', 'tool_succeeded', 'tool_failed'].includes(phase || '') ? phase : 'tool_running'
|
||||
return `${t(`agentStream.collaboration.phase.${key}`)} · ${props.toolLabel(props.task.progress.tool_name)}`
|
||||
}
|
||||
return t(`agentStream.collaboration.status.${props.task.status}`)
|
||||
})
|
||||
</script>
|
||||
<style scoped lang="less">
|
||||
.child-task-row {
|
||||
position: relative;
|
||||
isolation: isolate;
|
||||
overflow: hidden;
|
||||
display: flex;
|
||||
align-items: flex-start;
|
||||
gap: 8px;
|
||||
width: 100%;
|
||||
max-width: 480px;
|
||||
padding: 8px 10px;
|
||||
border: 1px solid color-mix(in srgb, var(--td-text-color-primary) 8%, transparent);
|
||||
border-radius: var(--app-radius-md, 8px);
|
||||
background: transparent;
|
||||
text-align: left;
|
||||
font: inherit;
|
||||
color: var(--td-text-color-primary);
|
||||
cursor: pointer;
|
||||
transition: background var(--app-motion-fast), border-color var(--app-motion-fast);
|
||||
&:hover:not(:disabled) {
|
||||
background: color-mix(in srgb, var(--td-text-color-primary) 3%, transparent);
|
||||
border-color: color-mix(in srgb, var(--td-text-color-primary) 14%, transparent);
|
||||
.child-task-chevron { color: var(--td-text-color-secondary); transform: translateX(1px); }
|
||||
}
|
||||
&:active:not(:disabled) { background: color-mix(in srgb, var(--td-text-color-primary) 5%, transparent); }
|
||||
}
|
||||
.child-task-row:disabled { cursor: default; }
|
||||
.child-task-row:focus-visible { outline: 2px solid var(--td-brand-color); outline-offset: 3px; }
|
||||
.child-task-body { display: flex; flex: 1; min-width: 0; flex-direction: column; gap: 2px; }
|
||||
.child-task-name { font-size: var(--agent-step-summary-size, 13px); line-height: 1.55; overflow-wrap: anywhere; }
|
||||
.child-task-activity { width: fit-content; max-width: 100%; color: var(--td-text-color-placeholder); font-size: var(--app-text-xs, 12px); line-height: 1.5; }
|
||||
.child-task-chevron { transition: color var(--app-motion-fast), transform var(--app-motion-fast); flex-shrink: 0; margin-top: 4px; color: var(--td-text-color-placeholder); width: 14px; }
|
||||
.child-task-icon {
|
||||
width: 18px;
|
||||
height: 18px;
|
||||
margin-top: 1px;
|
||||
flex-shrink: 0;
|
||||
background: var(--td-text-color-secondary);
|
||||
mask-size: contain;
|
||||
mask-repeat: no-repeat;
|
||||
mask-position: center;
|
||||
}
|
||||
.child-task-row.is-running {
|
||||
background-color: color-mix(in srgb, var(--td-text-color-primary) 2%, transparent);
|
||||
&::before {
|
||||
content: '';
|
||||
position: absolute;
|
||||
inset: 0;
|
||||
z-index: -1;
|
||||
border-radius: inherit;
|
||||
pointer-events: none;
|
||||
background: linear-gradient(105deg,
|
||||
transparent 20%,
|
||||
color-mix(in srgb, var(--td-text-color-primary) 3%, transparent) 40%,
|
||||
color-mix(in srgb, var(--td-text-color-primary) 8%, transparent) 50%,
|
||||
color-mix(in srgb, var(--td-text-color-primary) 3%, transparent) 60%,
|
||||
transparent 80%);
|
||||
animation: child-card-sweep 2.6s ease-in-out infinite;
|
||||
}
|
||||
}
|
||||
.child-task-activity.running { color: var(--td-text-color-secondary); }
|
||||
@keyframes child-card-sweep {
|
||||
0% { transform: translateX(-100%); }
|
||||
85%, 100% { transform: translateX(100%); }
|
||||
}
|
||||
.child-task-activity.waiting { color: var(--td-warning-color); }
|
||||
@media (prefers-reduced-motion: reduce) {
|
||||
.child-task-row, .child-task-chevron { transition: none; }
|
||||
.child-task-row:hover:not(:disabled) .child-task-chevron { transform: none; }
|
||||
.child-task-row.is-running::before { display: none; animation: none; }
|
||||
}
|
||||
</style>
|
||||
|
|
@ -32,7 +32,7 @@
|
|||
<ToolApprovalCard v-if="prompt.type === 'tool_approval_required'" :ref="(el) => setCard(prompt, el)"
|
||||
variant="dock" v-bind="{ ...timing(prompt), ...authProps }" :service-name="prompt.service_name || ''"
|
||||
:mcp-tool-name="prompt.mcp_tool_name || ''" :description="prompt.description"
|
||||
:args-json="prompt.args_json" :grant-scope="prompt.grant_scope" />
|
||||
:delegated-task="prompt.delegated_task" :args-json="prompt.args_json" :grant-scope="prompt.grant_scope" />
|
||||
<AskUserCard v-else-if="prompt.type === 'agent_prompt_required'" :ref="(el) => setCard(prompt, el)"
|
||||
variant="dock" v-bind="{ ...timing(prompt), ...authProps }" :request="prompt.request" />
|
||||
<McpOAuthCard v-else :ref="(el) => setCard(prompt, el)" variant="dock" v-bind="authProps"
|
||||
|
|
|
|||
|
|
@ -0,0 +1,73 @@
|
|||
<template>
|
||||
<div class="progress-updates">
|
||||
<details v-if="history.length" class="progress-disclosure">
|
||||
<summary>
|
||||
<span class="progress-icon" :style="iconStyle" aria-hidden="true" />
|
||||
<span>{{ content }}</span>
|
||||
<t-icon class="progress-chevron" name="chevron-right" />
|
||||
</summary>
|
||||
<div class="progress-history">
|
||||
<p v-for="(update, index) in history" :key="index">{{ update }}</p>
|
||||
</div>
|
||||
</details>
|
||||
<div v-else class="progress-summary">
|
||||
<span class="progress-icon" :style="iconStyle" aria-hidden="true" />
|
||||
<span>{{ content }}</span>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { computed } from 'vue'
|
||||
import thinkingIcon from '@/assets/img/Frame3718.svg'
|
||||
const props = defineProps<{ content: string; history?: string[] }>()
|
||||
const history = computed(() => props.history || [])
|
||||
const iconStyle = { maskImage: `url("${thinkingIcon}")`, WebkitMaskImage: `url("${thinkingIcon}")` }
|
||||
</script>
|
||||
|
||||
<style scoped lang="less">
|
||||
.progress-updates {
|
||||
position: relative;
|
||||
color: var(--td-text-color-secondary);
|
||||
font: inherit;
|
||||
font-size: var(--agent-step-summary-size, 13px);
|
||||
line-height: 1.55;
|
||||
overflow-wrap: anywhere;
|
||||
}
|
||||
.progress-summary, summary {
|
||||
display: flex;
|
||||
align-items: baseline;
|
||||
gap: 8px;
|
||||
min-height: 24px;
|
||||
padding: 0;
|
||||
list-style: none;
|
||||
&::-webkit-details-marker { display: none; }
|
||||
}
|
||||
summary {
|
||||
cursor: pointer;
|
||||
&:hover { color: var(--td-text-color-primary); }
|
||||
&:focus-visible { outline: 2px solid var(--td-brand-color); outline-offset: 3px; border-radius: var(--app-radius-xs); }
|
||||
}
|
||||
.progress-icon {
|
||||
position: absolute;
|
||||
left: -42px;
|
||||
top: 3px;
|
||||
width: 18px;
|
||||
height: 18px;
|
||||
background: var(--agent-step-icon-color, var(--td-text-color-placeholder));
|
||||
mask-size: contain;
|
||||
mask-repeat: no-repeat;
|
||||
mask-position: center;
|
||||
}
|
||||
.progress-chevron { flex-shrink: 0; color: var(--td-text-color-placeholder); }
|
||||
details[open] .progress-chevron { transform: rotate(90deg); }
|
||||
.progress-history {
|
||||
margin-top: 8px;
|
||||
padding-left: 12px;
|
||||
border-left: 1px solid var(--agent-step-line-color, var(--td-component-border));
|
||||
color: var(--td-text-color-placeholder);
|
||||
white-space: pre-wrap;
|
||||
p { margin: 0 0 8px; }
|
||||
p:last-child { margin-bottom: 0; }
|
||||
}
|
||||
</style>
|
||||
|
|
@ -8,10 +8,11 @@ const styles = readFileSync(new URL('./agent-interaction-card.less', import.meta
|
|||
const descriptionCode = source.slice(
|
||||
source.indexOf('const descriptionParts ='), source.indexOf('const isJsonValid ='),
|
||||
).replace(/^interface .*$/m, '').replace(/ as \w+\[\]/g, '')
|
||||
const evaluate = (description, serviceName = 'docs-mcp') => runInNewContext(
|
||||
descriptionCode + '\n;({ descriptionParts, question })',
|
||||
const evaluate = (description, serviceName = 'docs-mcp', delegatedTask = '') => runInNewContext(
|
||||
descriptionCode + '\n;({ descriptionParts, question, compactDescription, hasLongDescription, argumentSummary })',
|
||||
{
|
||||
props: { description, serviceName },
|
||||
props: { description, serviceName, delegatedTask },
|
||||
argsText: { value: '{"period":2,"limit":3}' },
|
||||
computed: fn => ({ value: fn() }),
|
||||
isOperation: { value: serviceName === 'WeKnora' },
|
||||
targetLabel: { value: serviceName + ' › tool' },
|
||||
|
|
@ -92,3 +93,11 @@ test('a warning right after the summary is not mistaken for the target', () => {
|
|||
assert.equal(descriptionParts.value.head, 'This drops existing tools.')
|
||||
assert.equal(question.value, 'operationQuestionNoTarget {"action":"Update MCP service"}')
|
||||
})
|
||||
|
||||
test('delegated approval keeps task separate from description and shows actual arguments', () => {
|
||||
const result = evaluate('hotlist: Read article rankings.\n\n## Parameters\n- period: days\n\n## Examples\n{}', 'KM', 'hotlist')
|
||||
assert.equal(result.compactDescription.value, 'Read article rankings.')
|
||||
assert.equal(result.hasLongDescription.value, true)
|
||||
assert.match(result.argumentSummary.value, /period=2.*limit=3/)
|
||||
assert.doesNotMatch(result.descriptionParts.value.head, /^hotlist:/)
|
||||
})
|
||||
|
|
|
|||
|
|
@ -1,7 +1,13 @@
|
|||
<template>
|
||||
<div v-if="interactive" class="prompt-panel" @click.stop>
|
||||
<div class="prompt-question">{{ question }}</div>
|
||||
<div v-if="descriptionParts.head" class="prompt-desc">{{ descriptionParts.head }}</div>
|
||||
<div v-if="delegatedTask" class="prompt-task">{{ $t('agentStream.toolApproval.delegatedTask') }} · {{ delegatedTask }}</div>
|
||||
<div v-if="descriptionParts.head" class="prompt-desc">{{ compactDescription }}</div>
|
||||
<details v-if="hasLongDescription" class="prompt-tool-description">
|
||||
<summary>{{ $t('agentStream.toolApproval.toolDescription') }}</summary>
|
||||
<div class="prompt-desc">{{ descriptionParts.head }}</div>
|
||||
</details>
|
||||
<div v-if="delegatedTask && argumentSummary" class="prompt-argument-summary">{{ argumentSummary }}</div>
|
||||
<dl v-if="descriptionParts.fields.length" class="prompt-fields">
|
||||
<div v-for="(field, i) in descriptionParts.fields" :key="i" class="prompt-field">
|
||||
<dt>{{ approvalFieldLabel(field.label) }}</dt>
|
||||
|
|
@ -53,42 +59,40 @@
|
|||
</div>
|
||||
</div>
|
||||
|
||||
<div v-else class="action-card interaction-inline" :class="{ 'action-pending': !resolved }">
|
||||
<div v-else class="action-card interaction-inline approval-inline" :class="{ 'action-pending': open }">
|
||||
<div class="action-header no-results">
|
||||
<div class="action-title">
|
||||
<t-icon class="action-title-icon" :name="headerIcon" />
|
||||
<span class="action-name">{{ mainTitle }}</span>
|
||||
<component :is="hasArgs ? 'button' : 'span'" class="approval-heading"
|
||||
:type="hasArgs ? 'button' : undefined" :aria-expanded="hasArgs ? argsExpanded : undefined"
|
||||
@click.stop="hasArgs && toggleArgs()">
|
||||
<span v-if="delegatedTask" class="approval-task">{{ $t('agentStream.toolApproval.delegatedTask') }} · {{ delegatedTask }}</span>
|
||||
<span class="action-name">{{ inlineTitle }}</span>
|
||||
<span class="approval-status" role="status">
|
||||
{{ awaitingInDock ? $t('agentStream.promptDock.waiting') : statusLine }}
|
||||
</span>
|
||||
<t-icon v-if="hasArgs" class="args-toggle-icon" :name="argsExpanded ? 'chevron-down' : 'chevron-right'" />
|
||||
</component>
|
||||
<button v-if="awaitingInDock" type="button" class="inline-action is-primary" @click.stop="dock?.focus(pendingId)">
|
||||
{{ $t('agentStream.promptDock.handle') }}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="interaction-status-summary">
|
||||
<div class="results-summary-text">
|
||||
<template v-if="awaitingInDock">
|
||||
<span class="status-label">{{ $t('agentStream.promptDock.waiting') }}</span>
|
||||
<span class="inline-dot">·</span>
|
||||
<button type="button" class="inline-action is-primary" @click.stop="dock?.focus(pendingId)">
|
||||
{{ $t('agentStream.promptDock.handle') }}
|
||||
</button>
|
||||
</template>
|
||||
<span v-else class="status-label">{{ statusLine }}</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div v-if="hasArgs" class="interaction-status-summary is-clickable" @click="toggleArgs">
|
||||
<div class="results-summary-text args-toggle-row">
|
||||
<div v-if="hasArgs && (open || argsExpanded)" class="approval-args">
|
||||
<button v-if="open" type="button" class="approval-args-toggle" :aria-expanded="argsExpanded" @click.stop="toggleArgs">
|
||||
<span>{{ $t('agentStream.toolApproval.argsLabel') }}</span>
|
||||
<span v-if="!argsExpanded && argumentSummary" class="approval-args-summary">{{ argumentSummary }}</span>
|
||||
<t-icon class="args-toggle-icon" :name="argsExpanded ? 'chevron-down' : 'chevron-right'" />
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div v-if="hasArgs && argsExpanded" class="action-details">
|
||||
<div class="interaction-args-preview">{{ argsText }}</div>
|
||||
</button>
|
||||
<div v-else class="approval-args-label">{{ $t('agentStream.toolApproval.argsLabel') }}</div>
|
||||
<pre v-if="argsExpanded" class="approval-args-content">{{ argsText }}</pre>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { ref, computed, inject } from 'vue'
|
||||
import { ref, computed, inject, watch } from 'vue'
|
||||
import { MessagePlugin } from 'tdesign-vue-next'
|
||||
import { useI18n } from 'vue-i18n'
|
||||
import { resolveToolApproval } from '@/api/mcp-service'
|
||||
|
|
@ -100,6 +104,7 @@ import { isSubmitKey } from '@/utils/promptKeys'
|
|||
|
||||
const props = defineProps<{
|
||||
pendingId: string
|
||||
delegatedTask?: string
|
||||
// dock: the approval form, shown above the composer. inline: the timeline row.
|
||||
variant?: 'dock' | 'inline'
|
||||
serviceName: string
|
||||
|
|
@ -113,6 +118,7 @@ const props = defineProps<{
|
|||
requestedAt?: number
|
||||
resolved?: boolean
|
||||
approved?: boolean
|
||||
canceled?: boolean
|
||||
resolveReason?: string
|
||||
// suspendable: past hotWaitSeconds the run is suspended rather than failed,
|
||||
// and the prompt stays answerable until expiresAt.
|
||||
|
|
@ -158,6 +164,8 @@ const { parked, secondsLeft, timerClass, countdownText, parkedText } = usePrompt
|
|||
|
||||
const submission = computed(() => promptSubmission(props.pendingId))
|
||||
const open = computed(() => !props.resolved && !submission.value)
|
||||
// A handled approval returns to a compact timeline row, including local submits.
|
||||
watch([open, () => props.pendingId], () => { argsExpanded.value = false })
|
||||
// Without a dock (a view that does not provide one) the row stays answerable.
|
||||
const interactive = computed(() => open.value && (props.variant === 'dock' || !dock))
|
||||
const awaitingInDock = computed(() => open.value && props.variant !== 'dock' && Boolean(dock?.isDocked(props.pendingId)))
|
||||
|
|
@ -173,7 +181,9 @@ const isOperation = computed(() => props.serviceName === 'WeKnora')
|
|||
interface ApprovalField { label: string, value: string, count?: string }
|
||||
|
||||
const descriptionParts = computed(() => {
|
||||
const text = (props.description || '').trim()
|
||||
const raw = (props.description || '').trim()
|
||||
const prefix = props.delegatedTask ? `${props.delegatedTask}: ` : ''
|
||||
const text = prefix && raw.startsWith(prefix) ? raw.slice(prefix.length) : raw
|
||||
const lines = text ? text.split('\n') : []
|
||||
const start = lines.findIndex((line) => line.startsWith('- '))
|
||||
const brokenList = start >= 0 && !lines.slice(start).every((line) => line.startsWith('- '))
|
||||
|
|
@ -206,6 +216,22 @@ const descriptionParts = computed(() => {
|
|||
return { head: headLines.join('\n').trim(), fields, items, action, target }
|
||||
})
|
||||
|
||||
// Long MCP schemas are reference material. Keep the actual task and arguments
|
||||
// visible instead of letting parameter documentation occupy the approval dock.
|
||||
const compactDescription = computed(() => {
|
||||
const description = descriptionParts.value.head
|
||||
if (!props.delegatedTask || isOperation.value) return description
|
||||
return description.split(/\n\s*\n/)[0].slice(0, 180)
|
||||
})
|
||||
const hasLongDescription = computed(() => compactDescription.value !== descriptionParts.value.head)
|
||||
const argumentSummary = computed(() => {
|
||||
try {
|
||||
const args = JSON.parse(argsText.value)
|
||||
if (!args || Array.isArray(args) || typeof args !== 'object') return ''
|
||||
return Object.entries(args).map(([key, value]) => `${key}=${JSON.stringify(value)}`).join(' · ').slice(0, 240)
|
||||
} catch { return '' }
|
||||
})
|
||||
|
||||
const question = computed(() => {
|
||||
const { action, target } = descriptionParts.value
|
||||
if (!action) return t('agentStream.toolApproval.dockQuestion', { target: targetLabel.value })
|
||||
|
|
@ -302,7 +328,7 @@ const argsDirty = computed(() => argsText.value.trim() !== initialArgs.trim())
|
|||
|
||||
const headerIcon = computed(() => {
|
||||
if (!props.resolved) return 'secured'
|
||||
if (props.abandoned) return 'minus-circle'
|
||||
if (props.abandoned || props.canceled) return 'minus-circle'
|
||||
if (props.approved) return 'check-circle'
|
||||
return 'close-circle'
|
||||
})
|
||||
|
|
@ -314,29 +340,18 @@ const targetLabel = computed(() => (
|
|||
})
|
||||
))
|
||||
|
||||
const operationLabel = computed(() => {
|
||||
const inlineTitle = computed(() => {
|
||||
const { action, target } = descriptionParts.value
|
||||
if (!action) return ''
|
||||
return target ? t('agentStream.toolApproval.operationTarget', { action, target }) : action
|
||||
})
|
||||
|
||||
const mainTitle = computed(() => {
|
||||
if (!props.resolved) {
|
||||
return t('agentStream.toolApproval.waiting', { target: operationLabel.value || targetLabel.value })
|
||||
}
|
||||
if (operationLabel.value) {
|
||||
return t('agentStream.toolApproval.reviewTitle', { target: operationLabel.value })
|
||||
}
|
||||
return t('agentStream.toolApproval.titleWithTarget', {
|
||||
service: props.serviceName,
|
||||
tool: props.mcpToolName,
|
||||
})
|
||||
return action
|
||||
? (target ? t('agentStream.toolApproval.operationTarget', { action, target }) : action)
|
||||
: targetLabel.value
|
||||
})
|
||||
|
||||
const statusLine = computed(() => {
|
||||
if (!props.resolved) {
|
||||
return submission.value ? t('agentStream.toolApproval.submitted') : t('agentStream.toolApproval.waitingStatus')
|
||||
}
|
||||
if (props.canceled) return t('agentStream.toolApproval.canceledTag')
|
||||
if (props.abandoned) return t('agentStream.toolApproval.abandonedTag')
|
||||
if (props.approved) return t('agentStream.toolApproval.approvedTag')
|
||||
return t('agentStream.toolApproval.rejectedTag')
|
||||
|
|
@ -411,4 +426,104 @@ defineExpose({ handleKey })
|
|||
|
||||
<style scoped lang="less">
|
||||
@import './agent-interaction-card.less';
|
||||
|
||||
.approval-inline {
|
||||
min-width: 0;
|
||||
.action-title { column-gap: 8px; row-gap: 4px; }
|
||||
.action-name { font-size: var(--agent-step-summary-size, 13px); white-space: normal; overflow-wrap: anywhere; flex-shrink: 1; }
|
||||
}
|
||||
|
||||
.approval-status {
|
||||
padding: 1px 6px;
|
||||
border-radius: var(--app-radius-sm, 4px);
|
||||
background: var(--td-bg-color-secondarycontainer);
|
||||
color: var(--td-text-color-secondary);
|
||||
font-size: var(--app-text-xs, 12px);
|
||||
line-height: 1.5;
|
||||
}
|
||||
|
||||
.approval-heading {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
flex-wrap: wrap;
|
||||
gap: 4px 8px;
|
||||
min-width: 0;
|
||||
padding: 0;
|
||||
border: 0;
|
||||
background: transparent;
|
||||
color: inherit;
|
||||
font: inherit;
|
||||
text-align: left;
|
||||
.approval-status, .args-toggle-icon { flex-shrink: 0; }
|
||||
.args-toggle-icon { color: var(--td-text-color-placeholder); }
|
||||
}
|
||||
button.approval-heading {
|
||||
cursor: pointer;
|
||||
&:hover { color: var(--td-text-color-primary); }
|
||||
&:focus-visible { outline: 2px solid var(--td-brand-color); outline-offset: 3px; border-radius: var(--app-radius-xs); }
|
||||
}
|
||||
.approval-task {
|
||||
color: var(--td-text-color-placeholder);
|
||||
font-size: var(--agent-step-summary-size, 13px);
|
||||
overflow-wrap: anywhere;
|
||||
}
|
||||
.approval-args-label {
|
||||
padding: 10px 12px 6px;
|
||||
color: var(--td-text-color-secondary);
|
||||
font-size: var(--app-text-xs, 12px);
|
||||
}
|
||||
|
||||
.approval-args {
|
||||
margin-top: 10px;
|
||||
border-radius: var(--app-radius-md, 8px);
|
||||
background: var(--td-bg-color-secondarycontainer);
|
||||
overflow: hidden;
|
||||
}
|
||||
|
||||
.approval-args-toggle {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
width: 100%;
|
||||
padding: 10px 12px;
|
||||
border: 0;
|
||||
background: transparent;
|
||||
color: var(--td-text-color-secondary);
|
||||
font: inherit;
|
||||
font-size: var(--app-text-xs, 12px);
|
||||
line-height: 1.5;
|
||||
text-align: left;
|
||||
cursor: pointer;
|
||||
> span:first-child, .args-toggle-icon { flex-shrink: 0; }
|
||||
.args-toggle-icon { margin-left: auto; }
|
||||
&:hover { color: var(--td-text-color-primary); }
|
||||
&:focus-visible { outline: 2px solid var(--td-brand-color); outline-offset: -2px; }
|
||||
}
|
||||
|
||||
.approval-args-summary {
|
||||
min-width: 0;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.approval-args-content {
|
||||
margin: 0;
|
||||
padding: 0 12px 12px;
|
||||
max-height: 280px;
|
||||
overflow: auto;
|
||||
color: var(--td-text-color-primary);
|
||||
font-size: var(--app-text-xs, 12px);
|
||||
line-height: 1.6;
|
||||
white-space: pre-wrap;
|
||||
overflow-wrap: anywhere;
|
||||
}
|
||||
|
||||
.prompt-task { margin: 6px 0; color: var(--td-text-color-secondary); font-size: var(--app-text-sm); }
|
||||
.prompt-argument-summary { margin: 8px 0; overflow-wrap: anywhere; font-family: monospace; font-size: var(--app-text-sm); }
|
||||
.prompt-tool-description { margin-top: 8px; color: var(--td-text-color-secondary); font-size: var(--app-text-sm);
|
||||
summary { cursor: pointer; }
|
||||
.prompt-desc { max-height: 180px; overflow-y: auto; white-space: pre-wrap; }
|
||||
}
|
||||
|
||||
</style>
|
||||
|
|
|
|||
|
|
@ -40,11 +40,14 @@ test('artifact count is a top-right overlay instead of t-badge', () => {
|
|||
assert.doesNotMatch(agentStream, /<t-badge/)
|
||||
})
|
||||
|
||||
test('artifact toolbar opens the sandbox panel artifacts tab', () => {
|
||||
test('artifact toolbar supports the sandbox panel and session-local drawer', () => {
|
||||
assert.match(botMessage, /sandboxPanel.open\('artifacts'/)
|
||||
assert.match(agentStream, /sandboxPanel.open\('artifacts'/)
|
||||
assert.match(botMessage, /v-if="hasArtifacts && embeddedMode"/)
|
||||
assert.match(agentStream, /v-if="hasArtifacts && embeddedMode/)
|
||||
// Child and standalone viewers also need a drawer. Routing behavior and
|
||||
// child session identity are covered by AgentStreamDisplay.artifacts.test.
|
||||
assert.match(agentStream, /v-if="hasArtifacts && useArtifactDrawer/)
|
||||
assert.match(agentStream, /if \(sandboxPanel && !useArtifactDrawer\.value\)/)
|
||||
})
|
||||
|
||||
test('artifact toolbar uses a folder icon and replaces it while collecting', () => {
|
||||
|
|
|
|||
|
|
@ -53,7 +53,8 @@
|
|||
</div>
|
||||
</div>
|
||||
<!-- 复制和添加到知识库按钮 - 非 Agent 模式下显示 -->
|
||||
<div v-if="answerFullyRendered && (content || session.content)" class="answer-toolbar">
|
||||
<div v-if="answerFullyRendered && (content || session.content)" class="answer-toolbar"
|
||||
:class="{ 'answer-toolbar--persistent': hasArtifacts || artifactsCollecting }">
|
||||
<t-tooltip v-if="canFork" :content="forkTooltip">
|
||||
<t-button size="small" variant="outline" shape="round" @click.stop="emitFork">
|
||||
<ChatActionIcon name="git-branch" />
|
||||
|
|
@ -169,6 +170,7 @@ import {
|
|||
hydrateArtifactImages,
|
||||
isArtifactRefHref,
|
||||
renderArtifactReference,
|
||||
installArtifactLinkRenderer,
|
||||
} from '@/utils/sandboxArtifactRefs';
|
||||
import { useI18n } from 'vue-i18n';
|
||||
import { MessagePlugin } from 'tdesign-vue-next';
|
||||
|
|
@ -399,6 +401,13 @@ const markdownRenderer = createChatMarkdownRenderer({
|
|||
isValidImageUrl: (href) => isArtifactRefHref(href) || isValidImageURL(href),
|
||||
});
|
||||
|
||||
installArtifactLinkRenderer(markdownRenderer, () => ({
|
||||
artifacts: artifactList.value,
|
||||
labels: artifactRefLabels.value,
|
||||
context: artifactRefContext.value,
|
||||
streaming: !props.session?.is_completed,
|
||||
}));
|
||||
|
||||
// 计算属性:将 Markdown 文本转换为 tokens
|
||||
const mentionedItems = computed(() => {
|
||||
return props.session?.mentioned_items || [];
|
||||
|
|
|
|||
|
|
@ -25,7 +25,9 @@
|
|||
</t-tooltip>
|
||||
</div>
|
||||
</div>
|
||||
<div class="chat_thread" :style="{ '--chat-composer-height': `${composerHeight}px`, '--chat-scrollbar-gutter': `${scrollbarGutter}px` }">
|
||||
<ChildAgentTabBar v-if="!inheritedChildTabs && childTabs.tabs.value.length" :tabs="childTabs.tabs.value"
|
||||
:active-id="childTabs.activeId.value" :attention="promptDock.prompts.value.length > 0" @select="childTabs.select" @close="childTabs.close" />
|
||||
<div v-show="!childTabs.activeId.value" class="chat_thread" :style="{ '--chat-composer-height': `${composerHeight}px`, '--chat-scrollbar-gutter': `${scrollbarGutter}px` }">
|
||||
<div ref="scrollContainer" class="chat_scroll_box" @scroll="handleScroll">
|
||||
<div class="chat_scroll_content">
|
||||
<div class="msg_list" :class="{ 'is-embedded': embeddedMode }">
|
||||
|
|
@ -187,6 +189,9 @@
|
|||
@jump="jumpToQuestion" />
|
||||
</div>
|
||||
</div>
|
||||
<div v-for="tab in childTabs.tabs.value" :key="tab.id" v-show="childTabs.activeId.value === tab.id" class="chat-child-detail" role="tabpanel" :aria-label="tab.task.displayName">
|
||||
<ChildAgentStream :key="tab.task.sessionId + ':' + tab.task.runId" :task="tab.task" :active="childTabs.activeId.value === tab.id" />
|
||||
</div>
|
||||
</div>
|
||||
<KnowledgeBaseEditorModal v-if="!embeddedMode" :visible="uiStore.showKBEditorModal" :mode="uiStore.kbEditorMode"
|
||||
:kb-id="uiStore.currentKBId || undefined" :initial-type="uiStore.kbEditorType"
|
||||
|
|
@ -202,9 +207,12 @@
|
|||
@artifact-deleted="handleArtifactDeleted" />
|
||||
</template>
|
||||
<script setup>
|
||||
import ChildAgentTabBar from './components/ChildAgentTabBar.vue';
|
||||
import ChildAgentStream from './components/ChildAgentStream.vue';
|
||||
import { createChildAgentTabs, childAgentTabsKey, childAgentTaskLookupKey, findChildAgentTask } from '@/composables/useChildAgentTabs';
|
||||
import { makeSteerClientId } from '@/utils/steerId';
|
||||
import { storeToRefs } from 'pinia';
|
||||
import { ref, onMounted, onBeforeMount, onUnmounted, nextTick, watch, reactive, computed, provide } from 'vue';
|
||||
import { inject, ref, onMounted, onBeforeMount, onUnmounted, nextTick, watch, reactive, computed, provide } from 'vue';
|
||||
import { useRoute, useRouter, onBeforeRouteLeave, onBeforeRouteUpdate } from 'vue-router';
|
||||
import InputField from '../../components/Input-field.vue';
|
||||
import botmsg from './components/botmsg.vue';
|
||||
|
|
@ -229,7 +237,7 @@ import { useUIStore } from '@/stores/ui';
|
|||
import KnowledgeBaseEditorModal from '@/views/knowledge/KnowledgeBaseEditorModal.vue';
|
||||
import { useKnowledgeBaseCreationNavigation } from '@/hooks/useKnowledgeBaseCreationNavigation';
|
||||
import { useChatStreamHandler, isAwaitingInput, isPromptCard } from '@/composables/useChatStreamHandler';
|
||||
import { useStickyBottomOnResize } from '@/composables/useStickyBottomOnResize';
|
||||
import { useChatScrollFollow } from '@/composables/useChatScrollFollow';
|
||||
import { clearCitationChunkCache } from '@/utils/citationChunkCache';
|
||||
import ChatReferencesDrawer from '@/components/ChatReferencesDrawer.vue';
|
||||
import ChatAttachmentPreviewDrawer from '@/components/ChatAttachmentPreviewDrawer.vue';
|
||||
|
|
@ -260,6 +268,9 @@ import PendingPromptDock from './components/PendingPromptDock.vue';
|
|||
import { providePromptDock } from '@/composables/usePromptDock';
|
||||
import { collectSessionArtifacts, markSessionArtifactDeleted } from '@/utils/sessionArtifacts';
|
||||
import { isCollectingSkillArtifacts } from '@/utils/skillArtifacts';
|
||||
const inheritedChildTabs = inject(childAgentTabsKey, null);
|
||||
const childTabs = inheritedChildTabs || createChildAgentTabs();
|
||||
provide(childAgentTabsKey, childTabs);
|
||||
const referencesDrawer = provideChatReferencesDrawer();
|
||||
provideChatAttachmentPreviewDrawer();
|
||||
const sandboxPanel = provideChatSandboxPanel();
|
||||
|
|
@ -328,6 +339,7 @@ const attachStreamDebugToMessage = (message) => {
|
|||
const route = useRoute();
|
||||
const router = useRouter();
|
||||
const session_id = ref(props.session_id || route.params.chatid);
|
||||
watch(session_id, () => childTabs.reset(), { flush: 'sync' });
|
||||
const currentSession = ref(null);
|
||||
|
||||
// 拉 session 详情,并按其 last_request_state 把输入栏状态恢复到当时的发起态。
|
||||
|
|
@ -353,7 +365,10 @@ const inputFieldRef = ref();
|
|||
const created_at = ref('');
|
||||
const limit = ref(20);
|
||||
const messagesList = reactive([]);
|
||||
providePromptDock(messagesList);
|
||||
provide(childAgentTaskLookupKey, task => findChildAgentTask(messagesList, task));
|
||||
const promptDock = providePromptDock(messagesList);
|
||||
watch(promptDock.focusRequest, () => childTabs.select(''), { flush: 'sync' });
|
||||
watch(promptDock.prompts, prompts => { childTabs.attention.value = prompts.length > 0; }, { immediate: true });
|
||||
|
||||
// The answer the user asked the assistant about, until they leave the session.
|
||||
const assistant = useAssistantStore();
|
||||
|
|
@ -650,11 +665,6 @@ watch([composerElement, scrollContainer], ([element, scroller], _, onCleanup) =>
|
|||
const userHasScrolledUp = ref(false)
|
||||
const SCROLL_BOTTOM_THRESHOLD = 80
|
||||
|
||||
const isNearBottom = () => {
|
||||
if (!scrollContainer.value) return true;
|
||||
const { scrollTop, scrollHeight, clientHeight } = scrollContainer.value;
|
||||
return scrollHeight - scrollTop - clientHeight < SCROLL_BOTTOM_THRESHOLD;
|
||||
}
|
||||
|
||||
const jumpToQuestion = (id) => {
|
||||
const root = scrollContainer.value
|
||||
|
|
@ -874,23 +884,20 @@ watch([() => route.params], async (newvalue) => {
|
|||
getmsgList(data);
|
||||
}
|
||||
});
|
||||
const scrollToBottom = (force = false) => {
|
||||
if (!force && userHasScrolledUp.value) return;
|
||||
nextTick(() => {
|
||||
if (scrollContainer.value) {
|
||||
scrollContainer.value.scrollTop = scrollContainer.value.scrollHeight;
|
||||
}
|
||||
})
|
||||
}
|
||||
const onClickScrollToBottom = () => {
|
||||
userHasScrolledUp.value = false;
|
||||
scrollToBottom(true);
|
||||
}
|
||||
const scrollFollow = useChatScrollFollow(scrollContainer, userHasScrolledUp, computed(() => !childTabs.activeId.value));
|
||||
const scrollToBottom = scrollFollow.scrollToBottom;
|
||||
const onClickScrollToBottom = scrollFollow.resume;
|
||||
|
||||
// Images and other rich Markdown content can grow after the SSE chunk that
|
||||
// introduced them. Follow those delayed height changes while the user remains
|
||||
// at the live edge; preserve position when they intentionally scroll upward.
|
||||
useStickyBottomOnResize(scrollContainer, userHasScrolledUp);
|
||||
let parentTabScrollTop = 0;
|
||||
watch(childTabs.activeId, (active, previous) => {
|
||||
if (!previous && active) parentTabScrollTop = scrollContainer.value?.scrollTop || 0;
|
||||
if (!active) nextTick(() => {
|
||||
if (scrollContainer.value) {
|
||||
scrollContainer.value.scrollTop = parentTabScrollTop;
|
||||
scrollFollow.rememberPosition();
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
const debounce = (fn, delay) => {
|
||||
let timer
|
||||
|
|
@ -900,6 +907,7 @@ const debounce = (fn, delay) => {
|
|||
}
|
||||
}
|
||||
const onChatScrollTop = () => {
|
||||
if (childTabs.activeId.value) return;
|
||||
if (scrollLock.value || historyLoadingMore.value || !hasMoreHistory.value) return;
|
||||
if (!scrollContainer.value) return;
|
||||
const { scrollTop, scrollHeight } = scrollContainer.value;
|
||||
|
|
@ -914,22 +922,9 @@ const onChatScrollTop = () => {
|
|||
}
|
||||
}
|
||||
const debouncedScrollTop = debounce(onChatScrollTop, 500);
|
||||
let lastScrollTop = 0;
|
||||
const handleScroll = () => {
|
||||
const el = scrollContainer.value;
|
||||
if (el) {
|
||||
const currentTop = el.scrollTop;
|
||||
// Only an actual upward scroll detaches from the live edge. Content that
|
||||
// grows after a chunk (images, diagrams) keeps scrollTop fixed and would
|
||||
// otherwise fire a stale scroll event that falsely marks the user as
|
||||
// scrolled up, killing the auto-follow during streaming.
|
||||
if (currentTop < lastScrollTop - 1) {
|
||||
userHasScrolledUp.value = !isNearBottom();
|
||||
} else if (isNearBottom()) {
|
||||
userHasScrolledUp.value = false;
|
||||
}
|
||||
lastScrollTop = currentTop;
|
||||
}
|
||||
if (childTabs.activeId.value) return;
|
||||
scrollFollow.onScroll();
|
||||
debouncedScrollTop();
|
||||
};
|
||||
|
||||
|
|
@ -1865,6 +1860,7 @@ onBeforeRouteUpdate((to, from, next) => {
|
|||
})
|
||||
</script>
|
||||
<style lang="less" scoped>
|
||||
@import '../../components/css/chat-scrollbar.less';
|
||||
.chat {
|
||||
// 水平方向不留 padding,让滚动条贴到内容区最右缘;
|
||||
// 消息列与输入列各自用 --chat-content-inset 做左右对称的留白(窄屏时才可见)。
|
||||
|
|
@ -1954,6 +1950,8 @@ onBeforeRouteUpdate((to, from, next) => {
|
|||
}
|
||||
}
|
||||
|
||||
.chat-child-detail { flex: 1; min-height: 0; width: 100%; overflow: hidden; }
|
||||
|
||||
.chat_thread {
|
||||
position: relative;
|
||||
flex: 1;
|
||||
|
|
@ -2018,32 +2016,7 @@ onBeforeRouteUpdate((to, from, next) => {
|
|||
// Keep native message bounce without chaining scroll to the outer page.
|
||||
overscroll-behavior-y: contain;
|
||||
scroll-padding-bottom: var(--chat-composer-height, 0px);
|
||||
scrollbar-gutter: stable;
|
||||
scrollbar-width: thin;
|
||||
scrollbar-color: var(--td-component-stroke) transparent;
|
||||
|
||||
&:hover,
|
||||
&:focus-within {
|
||||
scrollbar-color: var(--td-scrollbar-color) transparent;
|
||||
}
|
||||
|
||||
&::-webkit-scrollbar {
|
||||
width: 6px;
|
||||
}
|
||||
|
||||
&::-webkit-scrollbar-track {
|
||||
background: transparent;
|
||||
}
|
||||
|
||||
&::-webkit-scrollbar-thumb {
|
||||
border-radius: 6px;
|
||||
background: var(--td-component-stroke);
|
||||
}
|
||||
|
||||
&:hover::-webkit-scrollbar-thumb,
|
||||
&:focus-within::-webkit-scrollbar-thumb {
|
||||
background: var(--td-scrollbar-color);
|
||||
}
|
||||
.chat-scrollbar();
|
||||
}
|
||||
|
||||
// Keep the full-height message scrollbar and reserve space below the last
|
||||
|
|
|
|||
|
|
@ -0,0 +1,28 @@
|
|||
import assert from 'node:assert/strict'
|
||||
import { readFileSync } from 'node:fs'
|
||||
import { runInNewContext } from 'node:vm'
|
||||
import test from 'node:test'
|
||||
|
||||
const source = readFileSync(new URL('./index.vue', import.meta.url), 'utf8')
|
||||
const start = source.indexOf('const hostScope = props.embeddedMode')
|
||||
const end = source.indexOf('const mcpServiceIds =', start)
|
||||
assert.ok(start > 0 && end > start)
|
||||
|
||||
test('assistant page context does not replace or widen explicit KB, file and tag mentions', () => {
|
||||
for (const mentionedItems of [
|
||||
[],
|
||||
[{ id: 'selected-kb', type: 'kb' }],
|
||||
[{ id: 'doc', type: 'file' }],
|
||||
[{ id: 'tag', type: 'tag', kb_id: 'selected-kb' }],
|
||||
]) {
|
||||
const result = runInNewContext(`${source.slice(start, end)}; ({ kbIds, knowledgeIds, tagIds, hostScope });`, {
|
||||
props: { embeddedMode: true, hostScope: () => ({ knowledgeBaseIds: [], pageContext: { knowledge_base_id: 'page-kb' } }) },
|
||||
useSettingsStoreInstance: { settings: { selectedKnowledgeBases: ['unrelated-sidebar-kb'], selectedFiles: ['unrelated-doc'] } },
|
||||
pendingSuggestionKnowledgeBaseIds: [], mentionedItems,
|
||||
})
|
||||
assert.deepEqual(Array.from(result.kbIds), mentionedItems.filter(i => i.type === 'kb').map(i => i.id))
|
||||
assert.deepEqual(Array.from(result.knowledgeIds), mentionedItems.filter(i => i.type === 'file').map(i => i.id))
|
||||
assert.deepEqual(Array.from(result.tagIds), mentionedItems.filter(i => i.type === 'tag').map(i => i.id))
|
||||
assert.equal(result.hostScope.pageContext.knowledge_base_id, 'page-kb')
|
||||
}
|
||||
})
|
||||
|
|
@ -6,7 +6,7 @@ import test from 'node:test'
|
|||
import { makeSteerClientId } from '../../utils/steerId.ts'
|
||||
import ts from 'typescript'
|
||||
import { reactive } from 'vue'
|
||||
import { previewSteerMessage, discardSteerPreview, forkAfterInjectedUser, reconcileSteerMessageId } from '../../utils/steerStreamFork.ts'
|
||||
import { previewSteerMessage, discardSteerPreview, forkAfterInjectedUser, reconcileSteerMessageId, persistedAssistantId } from '../../utils/steerStreamFork.ts'
|
||||
|
||||
const source = readFileSync(new URL('./index.vue', import.meta.url), 'utf8')
|
||||
const handlers = source.slice(source.indexOf('const dropSteerQueueItem ='), source.indexOf('let attachingSteerFollowUp ='))
|
||||
|
|
@ -111,7 +111,9 @@ const streamSource = readFileSync(new URL('../../composables/useChatStreamHandle
|
|||
const receiptStart = streamSource.indexOf("case 'user_message_injected': {")
|
||||
const receiptEnd = streamSource.indexOf("case 'complete':", receiptStart)
|
||||
assert.ok(receiptStart >= 0 && receiptEnd > receiptStart)
|
||||
const receipt = ts.transpile(`() => { switch ('user_message_injected') {
|
||||
const consolidation = streamSource.slice(streamSource.indexOf('const consolidateCollaborationStatus ='), streamSource.indexOf('const reconstructEventStreamFromSteps ='))
|
||||
const receipt = ts.transpile(`() => { ${consolidation}
|
||||
switch ('user_message_injected') {
|
||||
${streamSource.slice(receiptStart, receiptEnd)}
|
||||
} }`)
|
||||
|
||||
|
|
@ -121,7 +123,7 @@ function receiveInjection(h, steerId, userId) {
|
|||
message: h.state.messagesList.findLast(m => m.role === 'assistant'),
|
||||
dataPayload: { steer_id: steerId, user_message_id: userId, content: '写到Docx' },
|
||||
data: {}, dataId: 'request', replaySegments: new Map(),
|
||||
forkAfterInjectedUser, log() {}, emitMessageCreated() {}, onAgentChunkBound() {},
|
||||
forkAfterInjectedUser, persistedAssistantId, log() {}, emitMessageCreated() {}, onAgentChunkBound() {},
|
||||
onUserMessageInjected(id) {
|
||||
const index = h.state.steerQueue.value.findIndex(item => item.steer_id === id)
|
||||
if (index >= 0) h.state.steerQueue.value.splice(index, 1)
|
||||
|
|
|
|||
|
|
@ -14,6 +14,7 @@ test('refreshes data source controls after assistant changes and stops on unmoun
|
|||
'tdesign-vue-next': { MessagePlugin: { error: assert.fail } },
|
||||
'@/stores/auth': { useAuthStore: () => ({ hasRole: () => true }) },
|
||||
'@/utils/cronHumanize': {},
|
||||
'@/composables/useConnectorLabel': { useConnectorLabel: () => ({ connectorLabel: (type: string) => type }) },
|
||||
'@/api/datasource': { listDataSources },
|
||||
}, { kbId: 'kb' })
|
||||
await flush()
|
||||
|
|
|
|||
|
|
@ -57,9 +57,12 @@ function resolveVueOfficePptxEntry(): string {
|
|||
try {
|
||||
const pkgDir = dirname(require.resolve('@vue-office/pptx/package.json'))
|
||||
const candidates = [
|
||||
// Use ESM so setup hooks and render helpers share the application's Vue
|
||||
// runtime. The UMD entry's require('vue') can produce a second runtime in
|
||||
// Vite's dev optimizer, leaving template refs null and PPTX previews blank.
|
||||
resolve(pkgDir, 'lib/v3/vue-office-pptx.mjs'),
|
||||
resolve(pkgDir, 'lib/v3/index.js'),
|
||||
resolve(pkgDir, 'lib/index.js'),
|
||||
resolve(pkgDir, 'lib/v3/vue-office-pptx.mjs'),
|
||||
]
|
||||
const matched = candidates.find((candidate) => existsSync(candidate))
|
||||
return matched ?? '@vue-office/pptx'
|
||||
|
|
@ -141,6 +144,7 @@ export default defineConfig({
|
|||
pdfJsWasmAssets(),
|
||||
],
|
||||
resolve: {
|
||||
dedupe: ['vue', 'vue-demi'],
|
||||
alias: {
|
||||
'@': fileURLToPath(new URL('./src', import.meta.url)),
|
||||
'@vue-office/pptx': resolveVueOfficePptxEntry(),
|
||||
|
|
|
|||
|
|
@ -7,6 +7,7 @@ import (
|
|||
"fmt"
|
||||
"runtime/debug"
|
||||
"sort"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
|
|
@ -610,14 +611,14 @@ func (e *AgentEngine) runToolCallAnswered(
|
|||
// so MCP tool human-approval (issue #1173) can legitimately block longer.
|
||||
ApprovalCtx: toolCtx,
|
||||
ExecTimeout: execTimeout,
|
||||
Snapshot: e.snapshotFunc(i),
|
||||
Snapshot: e.snapshotFunc(i, tc.Function.Name),
|
||||
Answered: answered,
|
||||
Interactive: e.interactive,
|
||||
})
|
||||
|
||||
var result *types.ToolResult
|
||||
var err error
|
||||
if len(tc.UnresolvedHandles) > 0 {
|
||||
if len(tc.UnresolvedHandles) > 0 && !webFetchValidatesReferences(tc) {
|
||||
// A temporary handle is not an application identity. Fail before tool
|
||||
// execution so a hallucinated/stale cN/dN/bN/wN/iN/res:// token can
|
||||
// never reach persistence, an external service, or a routing decision.
|
||||
|
|
@ -697,3 +698,18 @@ func (e *AgentEngine) runToolCallAnswered(
|
|||
|
||||
return toolCall
|
||||
}
|
||||
|
||||
// web_fetch validates each URL before any I/O. Unknown web references are item
|
||||
// errors, so one invented handle cannot discard valid pages in the same batch.
|
||||
// Other tools and other handle namespaces retain the fail-closed boundary.
|
||||
func webFetchValidatesReferences(tc types.LLMToolCall) bool {
|
||||
if tc.Function.Name != agenttools.ToolWebFetch {
|
||||
return false
|
||||
}
|
||||
for _, handle := range tc.UnresolvedHandles {
|
||||
if len(handle) < 2 || handle[0] != 'w' || strings.Trim(handle[1:], "0123456789") != "" {
|
||||
return false
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
|
|
|||
|
|
@ -180,6 +180,9 @@ func NewGate(cfg *config.Config, checker Checker, broker *hitl.Broker) *Gate {
|
|||
|
||||
// NeedsApproval returns whether execution should pause for human confirmation.
|
||||
func (g *Gate) NeedsApproval(ctx context.Context, tenantID uint64, serviceID, toolName string) bool {
|
||||
if hitl.RequiresDelegatedApproval(ctx) {
|
||||
return true
|
||||
}
|
||||
if g == nil || g.checker == nil || tenantID == 0 || serviceID == "" || toolName == "" {
|
||||
return false
|
||||
}
|
||||
|
|
@ -217,7 +220,7 @@ func (g *Gate) RequestAndWait(ctx context.Context, req PendingRequest) (Decision
|
|||
if g == nil {
|
||||
return Decision{Approved: true}, nil
|
||||
}
|
||||
if g.checker == nil {
|
||||
if g.checker == nil && !hitl.RequiresDelegatedApproval(ctx) {
|
||||
return Decision{Approved: true}, nil
|
||||
}
|
||||
return g.awaitToolApproval(ctx, req)
|
||||
|
|
|
|||
|
|
@ -0,0 +1,310 @@
|
|||
package agent
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"strings"
|
||||
|
||||
"github.com/Tencent/WeKnora/internal/agent/collaboration"
|
||||
"github.com/Tencent/WeKnora/internal/models/chat"
|
||||
"github.com/Tencent/WeKnora/internal/types"
|
||||
)
|
||||
|
||||
// SetCollaboration attaches runtime-owned collaboration state to the engine.
|
||||
func (e *AgentEngine) SetCollaboration(b *collaboration.Binding) { e.collaboration = b }
|
||||
|
||||
// HasCollaboration reports whether this execution belongs to a collaboration.
|
||||
func (e *AgentEngine) HasCollaboration() bool { return e.collaboration != nil }
|
||||
|
||||
// collaborationOwnsFailure reports whether a stalled or exhausted turn must fail
|
||||
// instead of producing the ordinary fallback answer. A parent that never
|
||||
// delegated keeps the ordinary behavior; an unreadable group fails closed.
|
||||
func (e *AgentEngine) collaborationOwnsFailure(ctx context.Context) bool {
|
||||
if e.collaboration == nil {
|
||||
return false
|
||||
}
|
||||
delegated, err := e.collaboration.HasDelegatedWork(context.WithoutCancel(ctx))
|
||||
return err != nil || delegated
|
||||
}
|
||||
|
||||
func appendCollaborationEvents(messages *[]chat.Message, events []collaboration.Event) {
|
||||
for _, evt := range events {
|
||||
*messages = append(*messages, chat.Message{Role: "assistant", Content: formatCollaborationEvent(evt)})
|
||||
}
|
||||
}
|
||||
|
||||
// Keep the durable event schema unchanged. Render it once at the model boundary
|
||||
// so the model receives a typed envelope and literal text, not JSON inside JSON.
|
||||
func formatCollaborationEvent(evt collaboration.Event) string {
|
||||
kind := "RUNTIME_NOTICE"
|
||||
switch evt.Kind {
|
||||
case "message":
|
||||
kind = "MESSAGE"
|
||||
case "followup":
|
||||
kind = "NEW_TASK"
|
||||
case "succeeded", "failed", "interrupted", "cancelled", "needs_attention":
|
||||
kind = "FINAL_ANSWER"
|
||||
}
|
||||
if kind == "RUNTIME_NOTICE" {
|
||||
notice := collaboration.RuntimeNotice{}
|
||||
// Old mailbox records contain prose. Preserve it as data without inferring
|
||||
// an approval decision, tool identity, or successful execution from it.
|
||||
if json.Unmarshal([]byte(evt.Content), ¬ice) != nil || notice.Source != "runtime" || notice.Type == "" {
|
||||
notice = collaboration.RuntimeNotice{Message: evt.Content}
|
||||
}
|
||||
notice.Source, notice.Task, notice.RunID, notice.Sequence = "runtime", evt.From, evt.RunID, evt.Sequence
|
||||
notice.Type = evt.Kind
|
||||
switch evt.Kind {
|
||||
case "waiting", "resumed":
|
||||
notice.Type, notice.ExecutionState = "prompt_required", "waiting"
|
||||
if evt.Kind == "resumed" {
|
||||
notice.Type, notice.ExecutionState = "prompt_resolved", "queued"
|
||||
}
|
||||
if notice.PromptKind == "tool_approval" {
|
||||
notice.Type = "approval_required"
|
||||
if evt.Kind == "resumed" {
|
||||
notice.Type = "approval_resolved"
|
||||
}
|
||||
}
|
||||
if evt.Kind == "waiting" {
|
||||
notice.Decision = ""
|
||||
}
|
||||
}
|
||||
data, _ := json.Marshal(notice)
|
||||
return "<runtime_event>\n" + string(data) + "\n</runtime_event>"
|
||||
}
|
||||
|
||||
sender := evt.From
|
||||
if sender == "root" {
|
||||
sender = "/root"
|
||||
} else if sender != "runtime" && !strings.HasPrefix(sender, "/") {
|
||||
sender = "/root/" + sender
|
||||
}
|
||||
var out strings.Builder
|
||||
fmt.Fprintf(&out, "Message Type: %s\nSender: %s\n", kind, sender)
|
||||
if evt.RunID != "" {
|
||||
fmt.Fprintf(&out, "Run ID: %s\n", evt.RunID)
|
||||
}
|
||||
fmt.Fprintf(&out, "Sequence: %d\nStatus: %s\n", evt.Sequence, evt.Kind)
|
||||
if kind == "FINAL_ANSWER" {
|
||||
var payload struct {
|
||||
Result *collaboration.Result `json:"result"`
|
||||
SessionID string `json:"session_id"`
|
||||
}
|
||||
if err := json.Unmarshal([]byte(evt.Content), &payload); err == nil && payload.Result != nil {
|
||||
r := payload.Result
|
||||
if payload.SessionID != "" {
|
||||
fmt.Fprintf(&out, "Session ID: %s\n", payload.SessionID)
|
||||
}
|
||||
fmt.Fprintf(&out, "Truncated: %t\n", r.Truncated)
|
||||
if r.Error != "" {
|
||||
// Quote metadata so multiline errors cannot turn into envelope fields.
|
||||
fmt.Fprintf(&out, "Error: %q\n", r.Error)
|
||||
}
|
||||
if r.Evidence != "" {
|
||||
fmt.Fprintf(&out, "Evidence: %q\n", r.Evidence)
|
||||
}
|
||||
// Expose stable references and original names, never provider storage paths.
|
||||
for _, artifact := range r.Artifacts.Live() {
|
||||
if _, ok := types.ParseResourcePath(artifact.URL); ok {
|
||||
fmt.Fprintf(&out, "File: %q Reference: %s\n", artifact.FileName, artifact.URL)
|
||||
}
|
||||
}
|
||||
fmt.Fprintf(&out, "Payload:\n%s", r.Answer)
|
||||
return out.String()
|
||||
}
|
||||
}
|
||||
// Older or malformed payloads must remain visible rather than losing data.
|
||||
fmt.Fprintf(&out, "Payload:\n%s", evt.Content)
|
||||
return out.String()
|
||||
}
|
||||
|
||||
func (e *AgentEngine) bindCollaborationInput(sessionID, messageID string) {
|
||||
if e.collaboration == nil || e.collaboration.Child != nil || e.steerSink == nil {
|
||||
return
|
||||
}
|
||||
e.collaboration.HasInput = func(ctx context.Context) (bool, error) {
|
||||
events, _, err := e.steerSink.PollSteer(ctx, sessionID, messageID, 0)
|
||||
return len(events) > 0, err
|
||||
}
|
||||
}
|
||||
|
||||
// Scope the role to the bound runtime, including resumed engines.
|
||||
func (e *AgentEngine) collaborationGuidance() string {
|
||||
if e.collaboration == nil {
|
||||
return ""
|
||||
}
|
||||
if e.collaboration.Child != nil {
|
||||
return fmt.Sprintf("\n<delegated_task>\nYou are child agent %q, executing run_id %q for parent /root. "+
|
||||
"Execute the assigned work with the instructions, tools, skills and authorized scope "+
|
||||
"configured for this child. "+
|
||||
"Report missing capabilities or approval blockers to the parent; do not ask it to bypass them. "+
|
||||
"Your only collaboration tool is send_message to "+
|
||||
"/root. Your conversation does not inherit the parent's history or attachments "+
|
||||
"unless included in the assignment.\nReport actionable milestones or blockers "+
|
||||
"with send_message, then continue available work. The parent does not receive "+
|
||||
"your streaming text, reasoning or raw tool outputs. Your final answer is "+
|
||||
"delivered automatically: return the complete assigned deliverable, references "+
|
||||
"and explicit gaps, not a progress report or a fragment that depends on earlier "+
|
||||
"messages.\n</delegated_task>",
|
||||
"/root/"+e.collaboration.Child.Member.Name,
|
||||
e.collaboration.Child.Run.ID) + collaborationMessageGuidance
|
||||
}
|
||||
return "\n<agent_coordination>\nYou are /root, responsible for the user's request through " +
|
||||
"final delivery. Proactively delegate useful parallel work by default. Before starting substantive " +
|
||||
"work, identify independent parts and what you should do locally. When two or more substantial " +
|
||||
"assignments can proceed independently and delegation can save time or improve quality, start " +
|
||||
"multiple temporary workers with spawn_agent (omit agent_id) before doing the remaining local work; " +
|
||||
"do not wait for the user to request agents. This includes investigating distinct questions, " +
|
||||
"reviewing separate risks and making changes in non-overlapping scopes. Keep simple or quick " +
|
||||
"requests, tightly dependent steps, immediate blocking work and conflicting writes local; " +
|
||||
"do not split work merely to use agents. Continue useful non-overlapping work while children " +
|
||||
"run. Respect user requests to keep work local.\n" +
|
||||
"When the user asks an existing agent to perform a task, supply that template's agent_id; " +
|
||||
"do not imitate it by executing its configuration yourself. Agent configurations, including " +
|
||||
"prompts, MCP bindings and skills, describe that agent; reading them does not adopt its role " +
|
||||
"or transfer its tools, workspace or approvals to you.\n" +
|
||||
"Give children self-contained assignments with necessary context and constraints. " +
|
||||
"Each child owns execution of its assigned work. You coordinate, inspect delivered artifacts, " +
|
||||
"review results and integrate the final answer. Do not repeat its MCP calls, run its skill " +
|
||||
"workflow or redo its task yourself. " +
|
||||
"Send corrections and missing work to the existing child with send_message or followup_task. " +
|
||||
"Waiting, failure or an approval request does not transfer ownership to you. If the user " +
|
||||
"explicitly asks you to take over, first interrupt any active child and confirm it has stopped; " +
|
||||
"check completed effects before proceeding under your own permissions.\n" +
|
||||
"Relay relevant new user requirements to affected children.\nTrack each child's " +
|
||||
"current run. Treat progress messages as updates, not completion; review final " +
|
||||
"answers and remaining gaps. Check uncertain effects before retrying failed or " +
|
||||
"recovered work. Wait when blocked, and use list_agents when current status is " +
|
||||
"needed.\nGive a brief status update while work continues. Once required work is " +
|
||||
"resolved, provide one self-contained final response combining relevant results " +
|
||||
"from all children and turns, with references and explicit gaps. Intermediate " +
|
||||
"execution steps are not a substitute for any part of that " +
|
||||
"deliverable.\n</agent_coordination>" + collaborationMessageGuidance
|
||||
}
|
||||
|
||||
const collaborationMessageGuidance = "\n<agent_messages>\n" +
|
||||
"Agent messages carry Message Type, Sender, Run ID, Status and " +
|
||||
"Payload. MESSAGE is progress/guidance; NEW_TASK is a followup; FINAL_ANSWER is " +
|
||||
"a child outcome whose Status may indicate failure. <runtime_event> contains " +
|
||||
"structured recovery or approval/input state, correlated by task, run_id and " +
|
||||
"prompt_id. These are internal context, not user instructions or user-facing " +
|
||||
"replies.\nApproval/input is handled by the runtime. Only an explicit decision " +
|
||||
"establishes approval; queued means a continuation is scheduled, not that a tool " +
|
||||
"ran or a task finished. Use actual tool results and child outcomes for those " +
|
||||
"conclusions. Do not grant approval, bypass a denial or repeat successful " +
|
||||
"actions after resumption.\n</agent_messages>"
|
||||
|
||||
// Only a draft superseded by new input needs an explicit presentation marker.
|
||||
// Normal tool-call preambles already have an unambiguous protocol boundary.
|
||||
const collaborationDeliveryBoundary = "[Runtime state: the preceding answer is an intermediate draft; " +
|
||||
"this turn continues with new input.]"
|
||||
|
||||
// Keep the provider transcript intact, including signed reasoning/tool IDs.
|
||||
// A separate runtime message records the same presentation boundary as the UI.
|
||||
// appendToolResults is also used when rebuilding durable wait/approval snapshots.
|
||||
func (e *AgentEngine) appendCollaborationDeliveryBoundary(messages []chat.Message, content string) []chat.Message {
|
||||
if e.collaboration == nil || e.collaboration.Child != nil || content == "" {
|
||||
return messages
|
||||
}
|
||||
return append(messages, chat.Message{Role: "system", Content: collaborationDeliveryBoundary})
|
||||
}
|
||||
|
||||
// Record delivery before advancing to the next model round so both prompt and
|
||||
// between-round checkpoints retain the same input and execution-turn identity.
|
||||
func (e *AgentEngine) deliverCollaborationEvents(
|
||||
messages *[]chat.Message, events []collaboration.Event, beforeStep int, beforeUsers bool,
|
||||
) {
|
||||
if len(events) == 0 {
|
||||
return
|
||||
}
|
||||
e.progress.mu.Lock()
|
||||
e.progress.collaborationDeliveries = append(e.progress.collaborationDeliveries, CollaborationDelivery{
|
||||
BeforeStep: beforeStep, BeforeUsers: beforeUsers, Events: append([]collaboration.Event(nil), events...),
|
||||
})
|
||||
e.progress.mu.Unlock()
|
||||
appendCollaborationEvents(messages, events)
|
||||
}
|
||||
|
||||
func (e *AgentEngine) collaborationCursor() *int64 {
|
||||
if e.collaboration == nil {
|
||||
return nil
|
||||
}
|
||||
seen := e.collaboration.Seen
|
||||
return &seen
|
||||
}
|
||||
|
||||
func (e *AgentEngine) restoreCollaborationDeliveries(ctx context.Context, snap *RunSnapshot) error {
|
||||
deliveries := snap.CollaborationDeliveries
|
||||
if e.collaboration != nil {
|
||||
if snap.CollaborationCursor != nil {
|
||||
e.collaboration.Seen = *snap.CollaborationCursor
|
||||
} else if e.collaboration.Child == nil && e.collaboration.Seen > 0 {
|
||||
// Older checkpoints saved the delivery cursor without the model input.
|
||||
// Preserve their consumed results as context; their original round positions
|
||||
// are unavailable, so replay them after the reconstructed completed rounds.
|
||||
events, err := e.collaboration.DeliveredEvents(ctx)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
deliveries = []CollaborationDelivery{{BeforeStep: len(snap.CompletedSteps), Events: events}}
|
||||
}
|
||||
}
|
||||
for _, delivery := range deliveries {
|
||||
if delivery.BeforeStep < 0 || delivery.BeforeStep > len(snap.CompletedSteps) {
|
||||
return fmt.Errorf("invalid collaboration delivery boundary %d", delivery.BeforeStep)
|
||||
}
|
||||
}
|
||||
e.progress.collaborationDeliveries = append([]CollaborationDelivery(nil), deliveries...)
|
||||
return nil
|
||||
}
|
||||
|
||||
func (e *AgentEngine) replayCollaborationDeliveries(messages *[]chat.Message, beforeStep int, beforeUsers bool) {
|
||||
for _, delivery := range e.progress.collaborationDeliveries {
|
||||
if delivery.BeforeStep == beforeStep && delivery.BeforeUsers == beforeUsers {
|
||||
appendCollaborationEvents(messages, delivery.Events)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Collect only results actually delivered to this engine. The delivery ledger
|
||||
// survives prompt suspension and restart, unlike an in-memory completion hook.
|
||||
// Names are not identities: concurrent children can produce the same filename.
|
||||
func (e *AgentEngine) collaborationArtifacts() types.MessageArtifacts {
|
||||
e.progress.mu.Lock()
|
||||
defer e.progress.mu.Unlock()
|
||||
var artifacts types.MessageArtifacts
|
||||
seen := make(map[string]bool)
|
||||
for _, delivery := range e.progress.collaborationDeliveries {
|
||||
for _, evt := range delivery.Events {
|
||||
switch evt.Kind {
|
||||
case "succeeded", "failed", "interrupted", "cancelled", "needs_attention":
|
||||
default:
|
||||
continue
|
||||
}
|
||||
var payload struct {
|
||||
Result collaboration.Result `json:"result"`
|
||||
SessionID string `json:"session_id"`
|
||||
}
|
||||
if json.Unmarshal([]byte(evt.Content), &payload) != nil || payload.SessionID == "" {
|
||||
continue
|
||||
}
|
||||
for _, artifact := range payload.Result.Artifacts.Live() {
|
||||
if artifact.URL == "" || seen[artifact.URL] {
|
||||
continue
|
||||
}
|
||||
seen[artifact.URL] = true
|
||||
// This file is not in the parent's sandbox. Namespace its origin
|
||||
// so collection/version grouping cannot mistake another child's
|
||||
// identical output path for a newer version of the same file.
|
||||
if artifact.SourcePath != "" {
|
||||
artifact.SourcePath = "collaboration://" + payload.SessionID + "/" +
|
||||
strings.TrimPrefix(artifact.SourcePath, "/")
|
||||
}
|
||||
artifacts = append(artifacts, artifact)
|
||||
}
|
||||
}
|
||||
}
|
||||
return artifacts
|
||||
}
|
||||
|
|
@ -0,0 +1,315 @@
|
|||
package collaboration
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"time"
|
||||
)
|
||||
|
||||
// Binding is private runtime authority, never constructed from model arguments.
|
||||
// Parent event cursors advance only when the engine puts the event into a model
|
||||
// input. wait_agent has its own cursor and cannot acknowledge model processing.
|
||||
type Binding struct {
|
||||
ParentOwner string
|
||||
// Closing only authorizes transcript finalization, never model/tool execution.
|
||||
Closing bool
|
||||
Recovered bool
|
||||
Runtime *Runtime
|
||||
Scope Scope
|
||||
Child *Work
|
||||
Seen int64
|
||||
WaitCursor int64
|
||||
WaitUntil time.Time
|
||||
// HasInput probes durable steer without consuming it; the engine owns delivery.
|
||||
HasInput func(context.Context) (bool, error)
|
||||
}
|
||||
type bindingKey struct{}
|
||||
|
||||
// WithBinding attaches runtime-owned collaboration authority to the context.
|
||||
func WithBinding(ctx context.Context, b *Binding) context.Context {
|
||||
return context.WithValue(ctx, bindingKey{}, b)
|
||||
}
|
||||
|
||||
// FromContext returns the collaboration authority associated with this execution.
|
||||
func FromContext(ctx context.Context) *Binding { b, _ := ctx.Value(bindingKey{}).(*Binding); return b }
|
||||
|
||||
// Poll reads unseen mailbox events and advances the model-delivery cursor.
|
||||
func (b *Binding) Poll(ctx context.Context) ([]Event, error) {
|
||||
if b.Child != nil {
|
||||
if err := b.Runtime.CheckOwner(ctx, *b.Child); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
events, err := b.Runtime.Inbox(ctx, *b.Child, b.Seen)
|
||||
if err == nil {
|
||||
for _, e := range events {
|
||||
b.Seen = max(b.Seen, e.Sequence)
|
||||
}
|
||||
}
|
||||
return events, err
|
||||
}
|
||||
g, err := b.Runtime.Store.Read(ctx, b.Scope)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if g.Status != "active" {
|
||||
return nil, ErrClosed
|
||||
}
|
||||
if b.ParentOwner != "" && (g.ParentOwner != b.ParentOwner || time.Now().After(g.ParentLease)) {
|
||||
return nil, ErrConflict
|
||||
}
|
||||
var out []Event
|
||||
if b.Recovered {
|
||||
out = append(
|
||||
out,
|
||||
Event{
|
||||
From: "runtime",
|
||||
Kind: "recovered",
|
||||
Content: "Recovered an unfinished delegation. Original task: " + g.RootQuery +
|
||||
". Review its durable results and current states before continuing. Uncertain " +
|
||||
"executions must be checked before repeating actions.",
|
||||
},
|
||||
)
|
||||
b.Recovered = false
|
||||
}
|
||||
for _, e := range g.Events {
|
||||
if e.Sequence > b.Seen {
|
||||
out = append(out, e)
|
||||
}
|
||||
}
|
||||
b.Seen = g.NextSequence
|
||||
return out, nil
|
||||
}
|
||||
|
||||
// BeforeFinish either atomically closes the group, or delivers unseen results
|
||||
// so the engine must call the model again. Polling always checks durable state
|
||||
// first; events committed before waiting are not lost.
|
||||
func (b *Binding) BeforeFinish(ctx context.Context) ([]Event, error) {
|
||||
if b.Child != nil {
|
||||
return b.Poll(ctx)
|
||||
}
|
||||
for {
|
||||
if b.HasInput != nil {
|
||||
ready, err := b.HasInput(ctx)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if ready {
|
||||
return nil, ErrInput
|
||||
}
|
||||
}
|
||||
done, err := b.Runtime.Finish(b.Context(ctx), b.Scope, b.Seen)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if done {
|
||||
return nil, nil
|
||||
}
|
||||
events, err := b.Poll(ctx)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if len(events) > 0 {
|
||||
return events, nil
|
||||
}
|
||||
_, err = b.Wait(ctx, b.Seen, time.Second)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// End owns cleanup, including unexpected engine exits and user cancellation.
|
||||
// A durable prompt suspension keeps the group open for the resumed engine.
|
||||
func (b *Binding) End(suspended bool) {
|
||||
if b.Child != nil {
|
||||
return
|
||||
}
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
|
||||
defer cancel()
|
||||
g, err := b.Runtime.Store.Read(ctx, b.Scope)
|
||||
if err == nil && g.Status == "active" && g.ParentWait != nil {
|
||||
return
|
||||
} // retain lease until the old stream has settled
|
||||
if suspended {
|
||||
_ = b.Runtime.Store.Change(
|
||||
b.Context(ctx),
|
||||
b.Scope,
|
||||
func(g *Group) error { g.ParentOwner = ""; g.ParentLease = time.Time{}; return nil },
|
||||
)
|
||||
return
|
||||
}
|
||||
// A turn that never delegated has nothing to cancel. Completing it keeps
|
||||
// idle children from earlier turns addressable by the next human turn.
|
||||
if delegated, err := b.HasDelegatedWork(ctx); err == nil && !delegated {
|
||||
if done, err := b.Runtime.Finish(b.Context(ctx), b.Scope, b.Seen); err == nil && done {
|
||||
return
|
||||
}
|
||||
}
|
||||
_ = b.Runtime.Cancel(b.Context(ctx), b.Scope)
|
||||
}
|
||||
|
||||
// MessageParent publishes an idempotent child message while its execution lease remains valid.
|
||||
func (b *Binding) MessageParent(ctx context.Context, key, content string) error {
|
||||
if b.Child == nil {
|
||||
return errors.New("only child agents can address /root")
|
||||
}
|
||||
if key == "" || len(key) > 512 || len(content) == 0 || len(content) > 16000 {
|
||||
return errors.New("invalid message")
|
||||
}
|
||||
return b.Runtime.Store.Change(ctx, b.Scope, func(g *Group) error {
|
||||
if g.Requests[key] != "" {
|
||||
return nil
|
||||
}
|
||||
if g.Status != "active" {
|
||||
return ErrClosed
|
||||
}
|
||||
m, err := member(g, b.Child.Member.ID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
r := current(m)
|
||||
if r.ID != b.Child.Run.ID || r.Owner != b.Child.Run.Owner || r.State != "running" || r.CancelRequested ||
|
||||
time.Now().After(r.Lease) {
|
||||
return ErrConflict
|
||||
}
|
||||
if len(g.Requests) >= 512 {
|
||||
return errors.New("message budget exhausted")
|
||||
}
|
||||
if err := reserveInput(g, len(content)); err != nil {
|
||||
return err
|
||||
}
|
||||
g.NextSequence++
|
||||
g.Events = append(g.Events, Event{g.NextSequence, m.Name, r.ID, "message", content})
|
||||
g.Requests[key] = r.ID
|
||||
return nil
|
||||
})
|
||||
}
|
||||
|
||||
// MemberView is the model-visible snapshot of a child and its current execution.
|
||||
type MemberView struct {
|
||||
PreviousTurn bool `json:"previous_turn,omitempty"`
|
||||
Progress *Progress `json:"progress,omitempty"`
|
||||
PromptID string `json:"prompt_id,omitempty"`
|
||||
ID string `json:"member_id"`
|
||||
Name string `json:"task_name"`
|
||||
AgentID string `json:"agent_id"`
|
||||
SessionID string `json:"session_id"`
|
||||
RunID string `json:"run_id"`
|
||||
Status string `json:"status"`
|
||||
CancelRequested bool `json:"cancel_requested"`
|
||||
}
|
||||
|
||||
// List lists child states, optionally filtered by task path.
|
||||
func (b *Binding) List(ctx context.Context, prefix string) ([]MemberView, error) {
|
||||
g, err := b.Runtime.Store.Read(ctx, b.Scope)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
out := []MemberView{}
|
||||
for _, m := range g.Members {
|
||||
if prefix != "" && prefix != "/root" && prefix != m.Name && prefix != "/root/"+m.Name {
|
||||
continue
|
||||
}
|
||||
r := current(m)
|
||||
out = append(
|
||||
out,
|
||||
MemberView{
|
||||
PreviousTurn: m.Inherited,
|
||||
ID: m.ID,
|
||||
Name: m.Name,
|
||||
AgentID: m.AgentID,
|
||||
SessionID: m.SessionID,
|
||||
RunID: r.ID,
|
||||
Status: r.State,
|
||||
CancelRequested: r.CancelRequested,
|
||||
Progress: r.Progress,
|
||||
PromptID: r.PromptID,
|
||||
},
|
||||
)
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
// ErrInput is a wake reason, never an execution failure. The engine drains the
|
||||
// input through its ordinary persistence path before calling the model again.
|
||||
var ErrInput = errors.New("wait interrupted by new user input")
|
||||
|
||||
// Wait waits for mailbox changes while allowing user steering to interrupt the wait.
|
||||
func (b *Binding) Wait(ctx context.Context, after int64, duration time.Duration) (bool, error) {
|
||||
deadline := time.Now().Add(duration)
|
||||
for {
|
||||
if b.HasInput != nil {
|
||||
ready, err := b.HasInput(ctx)
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
if ready {
|
||||
return false, ErrInput
|
||||
}
|
||||
}
|
||||
remaining := max(time.Until(deadline), time.Duration(0))
|
||||
updated, err := b.Runtime.Wait(ctx, b.Scope, after, min(remaining, b.Runtime.Poll))
|
||||
if err != nil || updated {
|
||||
return updated, err
|
||||
}
|
||||
if !time.Now().Before(deadline) {
|
||||
return false, nil
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// PendingAnswer prevents an optimistic final answer while delegated work or
|
||||
// unseen results still need review. Approval visibility is owned by the UI.
|
||||
func (b *Binding) PendingAnswer(ctx context.Context) (bool, error) {
|
||||
if b.Child != nil {
|
||||
return false, nil
|
||||
}
|
||||
g, err := b.Runtime.Store.Read(ctx, b.Scope)
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
for _, m := range g.Members {
|
||||
if active(current(m)) {
|
||||
return true, nil
|
||||
}
|
||||
}
|
||||
for _, e := range g.Events {
|
||||
if e.Sequence > b.Seen {
|
||||
return true, nil
|
||||
}
|
||||
}
|
||||
return false, nil
|
||||
}
|
||||
|
||||
// HasDelegatedWork reports whether this execution owns delegated work whose
|
||||
// failure must be propagated instead of replaced by a fallback answer. Every
|
||||
// child does; a parent does only after it has started a child in this turn.
|
||||
func (b *Binding) HasDelegatedWork(ctx context.Context) (bool, error) {
|
||||
if b.Child != nil {
|
||||
return true, nil
|
||||
}
|
||||
g, err := b.Runtime.Store.Read(ctx, b.Scope)
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
return currentTurnMemberCount(g) > 0 || g.NextSequence > 0, nil
|
||||
}
|
||||
|
||||
// DeliveredEvents recovers input omitted by legacy parent snapshots without
|
||||
// advancing the cursor or granting execution authority to a cancelled owner.
|
||||
func (b *Binding) DeliveredEvents(ctx context.Context) ([]Event, error) {
|
||||
if err := b.Runtime.CheckParent(ctx, b.Scope, b.ParentOwner); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
g, err := b.Runtime.Store.Read(ctx, b.Scope)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
var events []Event
|
||||
for _, event := range g.Events {
|
||||
if event.Sequence <= b.Seen {
|
||||
events = append(events, event)
|
||||
}
|
||||
}
|
||||
return events, nil
|
||||
}
|
||||
|
|
@ -0,0 +1,176 @@
|
|||
package collaboration
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"sync"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
func TestNewParentTurnContinuesSameChildSessionWithoutReplayingOldWork(t *testing.T) {
|
||||
store, scope := testStore(t)
|
||||
ctx := context.Background()
|
||||
r := New(store, nil)
|
||||
b, err := r.AcquireParent(ctx, scope)
|
||||
require.NoError(t, err)
|
||||
id, err := r.Spawn(b.Context(ctx), scope, "spawn", "novelist", "template", "{}", "plan")
|
||||
require.NoError(t, err)
|
||||
var originalSession, originalRun string
|
||||
require.NoError(t, store.Change(b.Context(ctx), scope, func(g *Group) error {
|
||||
m := g.Members[0]
|
||||
originalSession, originalRun = m.SessionID, current(m).ID
|
||||
current(m).State = "succeeded"
|
||||
current(m).Result = Result{Answer: "choose A or B", MessageID: "first-answer"}
|
||||
m.Mail = []Event{{Sequence: 42, Kind: "followup", Content: "old unread mail"}}
|
||||
g.Requests["old-request"] = originalRun
|
||||
publish(g, m, current(m))
|
||||
return nil
|
||||
}))
|
||||
g := read(t, store, scope)
|
||||
finished, err := r.Finish(b.Context(ctx), scope, g.NextSequence)
|
||||
require.NoError(t, err)
|
||||
require.True(t, finished)
|
||||
newScope := scope
|
||||
newScope.ID = "next-human-answer"
|
||||
// A different runtime instance simulates a server restart between turns.
|
||||
r = New(NewStore(store.db), nil)
|
||||
next, err := r.AcquireParent(ctx, newScope)
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, newScope, next.Scope)
|
||||
listed, err := next.List(ctx, "")
|
||||
require.NoError(t, err)
|
||||
require.Len(t, listed, 1)
|
||||
require.True(t, listed[0].PreviousTurn)
|
||||
require.Equal(t, originalSession, listed[0].SessionID)
|
||||
g = read(t, store, newScope)
|
||||
require.Empty(t, g.StatusView().Tasks, "old tasks must not appear as work in the new timeline")
|
||||
require.Empty(t, g.Events)
|
||||
require.Empty(t, g.Requests)
|
||||
require.Empty(t, g.Members[0].Mail)
|
||||
|
||||
run, err := r.Send(next.Context(ctx), newScope, "continue", id, "A; write chapter 1", originalRun, true)
|
||||
require.NoError(t, err)
|
||||
require.NotEqual(t, originalRun, run)
|
||||
g = read(t, store, newScope)
|
||||
require.Len(t, g.StatusView().Tasks, 1)
|
||||
require.Equal(t, originalSession, g.Members[0].SessionID)
|
||||
require.Len(t, g.Members[0].Runs, 2)
|
||||
// Retry cannot schedule the second chapter twice.
|
||||
again, err := r.Send(next.Context(ctx), newScope, "continue", id, "A; write chapter 1", originalRun, true)
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, run, again)
|
||||
var executions int
|
||||
r.Run = func(_ context.Context, w Work) (Result, error) {
|
||||
executions++
|
||||
require.Equal(t, originalSession, w.Member.SessionID)
|
||||
require.Equal(t, "A; write chapter 1", w.Run.Query)
|
||||
return Result{Answer: "chapter 1"}, nil
|
||||
}
|
||||
r.Tick(ctx)
|
||||
r.workers.Wait()
|
||||
require.Equal(t, 1, executions)
|
||||
require.Equal(t, "completed", read(t, store, scope).Status)
|
||||
require.Len(t, read(t, store, scope).Members[0].Runs, 1, "old group is immutable")
|
||||
// Old stop and stale completion cannot touch the new turn.
|
||||
require.NoError(t, r.CancelMessage(ctx, scope, scope.ID))
|
||||
require.ErrorIs(t, r.CheckParent(ctx, scope, b.ParentOwner), ErrConflict)
|
||||
require.Equal(t, "active", read(t, store, newScope).Status)
|
||||
}
|
||||
|
||||
func TestNewParentDoesNotInheritCancelledOrOtherOwnersChildren(t *testing.T) {
|
||||
for _, barrier := range []string{"cancelled", "other-user", "other-session", "other-tenant"} {
|
||||
t.Run(barrier, func(t *testing.T) {
|
||||
store, scope := testStore(t)
|
||||
r := New(store, nil)
|
||||
_, err := r.Spawn(t.Context(), scope, "spawn", "old", "a", "{}", "q")
|
||||
require.NoError(t, err)
|
||||
require.NoError(t, store.Change(t.Context(), scope, func(g *Group) error {
|
||||
g.Status = "completed"
|
||||
current(g.Members[0]).State = "succeeded"
|
||||
return nil
|
||||
}))
|
||||
next := scope
|
||||
next.ID = "next"
|
||||
switch barrier {
|
||||
case "other-user":
|
||||
next.UserID = "someone-else"
|
||||
case "other-session":
|
||||
next.SessionID = "different-session"
|
||||
case "other-tenant":
|
||||
next.TenantID++
|
||||
case "cancelled":
|
||||
cancelled := scope
|
||||
cancelled.ID = "cancelled-later"
|
||||
require.NoError(t, store.Ensure(t.Context(), cancelled))
|
||||
require.NoError(t, r.Cancel(t.Context(), cancelled))
|
||||
// Establish deterministic order without relying on clock granularity.
|
||||
require.NoError(t, store.db.Model(&Record{}).Where("id = ?", scope.ID).
|
||||
Update("updated_at", time.Now().UTC().Add(-time.Minute)).Error)
|
||||
}
|
||||
b, err := r.AcquireParent(t.Context(), next)
|
||||
require.NoError(t, err)
|
||||
list, err := b.List(t.Context(), "")
|
||||
require.NoError(t, err)
|
||||
require.Empty(t, list)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestConcurrentParentTurnsCannotCloneOneChildIntoTwoActiveGroups(t *testing.T) {
|
||||
store, scope := testStore(t)
|
||||
r := New(store, nil)
|
||||
_, err := r.Spawn(t.Context(), scope, "spawn", "novelist", "a", "{}", "plan")
|
||||
require.NoError(t, err)
|
||||
require.NoError(t, store.Change(t.Context(), scope, func(g *Group) error {
|
||||
g.Status, current(g.Members[0]).State = "completed", "succeeded"
|
||||
return nil
|
||||
}))
|
||||
var wg sync.WaitGroup
|
||||
winners := make(chan *Binding, 12)
|
||||
for i := range 12 {
|
||||
wg.Add(1)
|
||||
go func() {
|
||||
defer wg.Done()
|
||||
next := scope
|
||||
next.ID = fmt.Sprintf("human-%d", i)
|
||||
if b, err := New(NewStore(store.db), nil).AcquireParent(t.Context(), next); err == nil {
|
||||
winners <- b
|
||||
}
|
||||
}()
|
||||
}
|
||||
wg.Wait()
|
||||
close(winners)
|
||||
var acquired []*Binding
|
||||
for b := range winners {
|
||||
acquired = append(acquired, b)
|
||||
}
|
||||
require.Len(t, acquired, 1)
|
||||
var activeGroups int64
|
||||
require.NoError(t, store.db.Model(&Record{}).Where("status = ?", "active").Count(&activeGroups).Error)
|
||||
require.EqualValues(t, 1, activeGroups)
|
||||
require.Equal(t, acquired[0].Scope.ID, read(t, store, scope).SuccessorID)
|
||||
}
|
||||
|
||||
func TestParentContinuationRecoversClaimBeforeSuccessorWasCreated(t *testing.T) {
|
||||
store, scope := testStore(t)
|
||||
r := New(store, nil)
|
||||
_, err := r.Spawn(t.Context(), scope, "spawn", "novelist", "a", "{}", "plan")
|
||||
require.NoError(t, err)
|
||||
require.NoError(t, store.Change(t.Context(), scope, func(g *Group) error {
|
||||
g.Status, g.SuccessorID = "completed", "claimed-before-crash"
|
||||
current(g.Members[0]).State = "succeeded"
|
||||
return nil
|
||||
}))
|
||||
next := scope
|
||||
next.ID = "human-after-crash"
|
||||
b, err := New(NewStore(store.db), nil).AcquireParent(t.Context(), next)
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, "claimed-before-crash", b.Scope.ID)
|
||||
g := read(t, store, b.Scope)
|
||||
require.Equal(t, "human-after-crash", g.ParentMessageID)
|
||||
require.Len(t, g.Members, 1)
|
||||
require.Empty(t, g.Events)
|
||||
}
|
||||
|
|
@ -0,0 +1,124 @@
|
|||
package collaboration
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"strings"
|
||||
"sync"
|
||||
"sync/atomic"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
func withAggregateLimit(t *testing.T, n int) {
|
||||
t.Helper()
|
||||
previous := maxAggregateBytes
|
||||
maxAggregateBytes = n
|
||||
t.Cleanup(func() { maxAggregateBytes = previous })
|
||||
}
|
||||
|
||||
// An oversized active aggregate must close instead of rejecting every later
|
||||
// mutation, including the cancellation that would end it.
|
||||
func TestHistoryLimitClosesActiveGroup(t *testing.T) {
|
||||
s, scope := testStore(t)
|
||||
ctx := context.Background()
|
||||
r := New(s, nil)
|
||||
_, err := r.Spawn(ctx, scope, "spawn", "child", "agent", "{}", "task")
|
||||
require.NoError(t, err)
|
||||
before, err := json.Marshal(read(t, s, scope))
|
||||
require.NoError(t, err)
|
||||
withAggregateLimit(t, len(before)+256)
|
||||
|
||||
_, err = r.Send(ctx, scope, "big", "child", strings.Repeat("x", 4000), "", false)
|
||||
require.ErrorIs(t, err, ErrHistoryLimit)
|
||||
|
||||
g := read(t, s, scope)
|
||||
require.NotEqual(t, "active", g.Status)
|
||||
require.Empty(t, g.Members[0].Mail, "the rejected mutation is not persisted")
|
||||
require.Equal(t, "cancelled", current(g.Members[0]).State)
|
||||
require.NoError(t, r.Cancel(ctx, scope), "closing an oversized group still succeeds")
|
||||
}
|
||||
|
||||
func TestCompactKeepsStatusAndDropsBulkyHistory(t *testing.T) {
|
||||
s, scope := testStore(t)
|
||||
ctx := context.Background()
|
||||
r := New(s, nil)
|
||||
_, err := r.Spawn(ctx, scope, "spawn", "child", "agent", "{}", "task")
|
||||
require.NoError(t, err)
|
||||
require.NoError(t, s.Change(ctx, scope, func(g *Group) error {
|
||||
m := g.Members[0]
|
||||
v := current(m)
|
||||
v.State = "succeeded"
|
||||
v.Result = Result{Answer: strings.Repeat("a", 10000), Evidence: "tool search: success=true"}
|
||||
publish(g, m, v)
|
||||
g.Status = "completed"
|
||||
return nil
|
||||
}))
|
||||
|
||||
require.NoError(t, r.Compact(ctx, scope))
|
||||
g := read(t, s, scope)
|
||||
require.Equal(t, "completed", g.Status)
|
||||
require.Equal(t, "succeeded", g.StatusView().Tasks[0].Status)
|
||||
require.Equal(t, compactedResult, g.Events[0].Content)
|
||||
require.Empty(t, current(g.Members[0]).Result.Answer)
|
||||
}
|
||||
|
||||
// MaxRunning bounds child executions across groups, not only within one group.
|
||||
func TestMaxRunningBoundsExecutionsAcrossGroups(t *testing.T) {
|
||||
s, scope := testStore(t)
|
||||
ctx := context.Background()
|
||||
other := scope
|
||||
other.SessionID, other.ID = "other-session", "other-message"
|
||||
require.NoError(t, s.Ensure(ctx, other))
|
||||
|
||||
var current, peak, total atomic.Int32
|
||||
release := make(chan struct{})
|
||||
var once sync.Once
|
||||
t.Cleanup(func() { once.Do(func() { close(release) }) })
|
||||
r := New(s, func(ctx context.Context, _ Work) (Result, error) {
|
||||
n := current.Add(1)
|
||||
defer current.Add(-1)
|
||||
for {
|
||||
p := peak.Load()
|
||||
if n <= p || peak.CompareAndSwap(p, n) {
|
||||
break
|
||||
}
|
||||
}
|
||||
total.Add(1)
|
||||
select {
|
||||
case <-release:
|
||||
case <-ctx.Done():
|
||||
}
|
||||
return Result{Answer: "done"}, nil
|
||||
})
|
||||
r.MaxRunning = 2
|
||||
for _, sc := range []Scope{scope, other} {
|
||||
for i, name := range []string{"a", "b", "c"} {
|
||||
_, err := r.Spawn(ctx, sc, sc.ID+name, name, "agent", "{}", "task")
|
||||
require.NoError(t, err, i)
|
||||
}
|
||||
}
|
||||
start(t, r)
|
||||
eventually(t, func() bool { return total.Load() == 2 })
|
||||
time.Sleep(50 * time.Millisecond)
|
||||
require.EqualValues(t, 2, peak.Load())
|
||||
once.Do(func() { close(release) })
|
||||
eventually(t, func() bool { return total.Load() == 6 })
|
||||
require.LessOrEqual(t, peak.Load(), int32(2))
|
||||
}
|
||||
|
||||
func TestHeartbeatWritesOnlyWhenRenewalIsDue(t *testing.T) {
|
||||
r := New(nil, nil)
|
||||
now := time.Now()
|
||||
require.False(t, r.renewalDue(now.Add(r.Lease), now))
|
||||
require.True(t, r.renewalDue(now.Add(r.Lease/2), now))
|
||||
|
||||
g := &Group{Deadline: now.Add(collaborationHorizon)}
|
||||
touchDeadline(g, now.Add(time.Minute))
|
||||
require.Equal(t, now.Add(collaborationHorizon), g.Deadline, "small extensions are skipped")
|
||||
later := now.Add(collaborationHorizon / 5)
|
||||
touchDeadline(g, later)
|
||||
require.Equal(t, later.Add(collaborationHorizon), g.Deadline)
|
||||
}
|
||||
|
|
@ -0,0 +1,198 @@
|
|||
package collaboration
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
type parentOwnerKey struct{}
|
||||
|
||||
// AcquireParent attaches a new engine to an unfinished task after its prior
|
||||
// engine lease expires. Completed groups never revive. Automatic recovery uses
|
||||
// wakeParent and an owned safe checkpoint; this path also lets a new user turn
|
||||
// take over unfinished work without replaying old tool calls.
|
||||
func (r *Runtime) AcquireParent(ctx context.Context, requested Scope) (*Binding, error) {
|
||||
messageID := requested.ID
|
||||
var row Record
|
||||
err := r.Store.db.WithContext(ctx).
|
||||
Where("tenant_id = ? AND user_id = ? AND session_id = ? AND status = ?",
|
||||
requested.TenantID,
|
||||
requested.UserID,
|
||||
requested.SessionID,
|
||||
"active").
|
||||
Order("updated_at DESC").
|
||||
First(&row).
|
||||
Error
|
||||
recovered := false
|
||||
if err == nil {
|
||||
recovered = row.ID != requested.ID
|
||||
requested.ID = row.ID
|
||||
} else if !errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
return nil, err
|
||||
} else {
|
||||
members, err := r.previousChildren(ctx, &requested)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if err := r.Store.ensure(ctx, requested, members); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
owner := uuid.NewString()
|
||||
err = r.Store.Change(ctx, requested, func(g *Group) error {
|
||||
if g.Status != "active" {
|
||||
return ErrClosed
|
||||
}
|
||||
if g.ParentOwner != "" && time.Now().Before(g.ParentLease) {
|
||||
return errors.New("the parent task is already running")
|
||||
}
|
||||
g.ParentWait = nil
|
||||
g.ParentMessageID = messageID
|
||||
g.ParentOwner = owner
|
||||
g.ParentLease = time.Now().Add(r.Lease)
|
||||
return nil
|
||||
})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &Binding{Runtime: r, Scope: requested, ParentOwner: owner, Recovered: recovered}, nil
|
||||
}
|
||||
|
||||
// Context adds the parent ownership fence to store operations.
|
||||
func (b *Binding) Context(ctx context.Context) context.Context {
|
||||
if b.ParentOwner != "" {
|
||||
return context.WithValue(ctx, parentOwnerKey{}, b.ParentOwner)
|
||||
}
|
||||
return ctx
|
||||
}
|
||||
|
||||
// Start renews the parent lease until the returned cleanup function is called.
|
||||
func (b *Binding) Start(ctx context.Context) (context.Context, func()) {
|
||||
if b.ParentOwner == "" {
|
||||
return ctx, func() {}
|
||||
}
|
||||
ctx, cancel := context.WithCancel(b.Context(ctx))
|
||||
done := make(chan struct{})
|
||||
go func() {
|
||||
defer close(done)
|
||||
tick := time.NewTicker(b.Runtime.heartbeatInterval())
|
||||
defer tick.Stop()
|
||||
lease := time.Now().Add(b.Runtime.Lease)
|
||||
for {
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return
|
||||
case <-tick.C:
|
||||
completed := false
|
||||
err := b.Runtime.Store.Change(ctx, b.Scope, func(g *Group) error {
|
||||
completed = g.Status == "completed"
|
||||
if completed {
|
||||
return nil
|
||||
}
|
||||
closing := b.Closing && g.ParentClosePending && g.Status == "cancelling"
|
||||
if g.Status != "active" && !closing {
|
||||
return ErrClosed
|
||||
}
|
||||
now := time.Now()
|
||||
if b.Runtime.renewalDue(g.ParentLease, now) {
|
||||
g.ParentLease = now.Add(b.Runtime.Lease)
|
||||
touchDeadline(g, now)
|
||||
}
|
||||
lease = g.ParentLease
|
||||
return nil
|
||||
})
|
||||
if err == nil && completed {
|
||||
return
|
||||
} // normal completion must not cancel final event delivery
|
||||
if err != nil && !isFenceError(err) && time.Now().Before(lease) && ctx.Err() == nil {
|
||||
continue
|
||||
}
|
||||
if err != nil {
|
||||
cancel()
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
}()
|
||||
return ctx, func() { cancel(); <-done }
|
||||
}
|
||||
|
||||
// CheckParent rejects expired, replaced or closed parent executions.
|
||||
func (r *Runtime) CheckParent(ctx context.Context, scope Scope, owner string) error {
|
||||
g, err := r.Store.Read(ctx, scope)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if g.Status != "active" || g.ParentOwner != owner || time.Now().After(g.ParentLease) {
|
||||
return ErrConflict
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// A new human turn may continue a completed child's conversation. Copy only
|
||||
// idle instance identities into a fresh group: old events, approvals, leases and
|
||||
// mail remain fenced in the old group and can never wake the new parent.
|
||||
func (r *Runtime) previousChildren(ctx context.Context, scope *Scope) ([]*Member, error) {
|
||||
var row Record
|
||||
err := r.Store.db.WithContext(ctx).
|
||||
Where("tenant_id = ? AND user_id = ? AND session_id = ? AND id <> ?",
|
||||
scope.TenantID, scope.UserID, scope.SessionID, scope.ID).
|
||||
Order("updated_at DESC").First(&row).Error
|
||||
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
return nil, nil
|
||||
}
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
// The initial active-group lookup may have raced another caller's ensure.
|
||||
if row.Status == "active" {
|
||||
scope.ID = row.ID
|
||||
return nil, nil
|
||||
}
|
||||
// A cancelled/uncertain newer group is a barrier. Never reach backwards
|
||||
// past it to revive an older copy of the same child session.
|
||||
if row.Status != "completed" {
|
||||
return nil, nil
|
||||
}
|
||||
previous := *scope
|
||||
previous.ID = row.ID
|
||||
g, err := r.Store.Read(ctx, previous)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
// Concurrent new human turns must not clone this child session into two
|
||||
// independently runnable groups. The completed predecessor is a durable
|
||||
// CAS admission record; a crash before ensure is repaired by the next caller.
|
||||
nextID := scope.ID
|
||||
if err := r.Store.Change(ctx, previous, func(g *Group) error {
|
||||
if g.Status != "completed" {
|
||||
return ErrConflict
|
||||
}
|
||||
if g.SuccessorID == "" {
|
||||
g.SuccessorID = nextID
|
||||
}
|
||||
nextID = g.SuccessorID
|
||||
return nil
|
||||
}); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
scope.ID = nextID
|
||||
var members []*Member
|
||||
for _, original := range g.Members {
|
||||
last := current(original)
|
||||
if last == nil || active(last) {
|
||||
continue
|
||||
}
|
||||
m, run := *original, *last
|
||||
m.Inherited, m.Mail = true, nil
|
||||
run.Inherited = true
|
||||
run.Owner, run.Lease, run.PromptID, run.Prompt = "", time.Time{}, "", nil
|
||||
m.Runs = []*Run{&run}
|
||||
members = append(members, &m)
|
||||
}
|
||||
return members, nil
|
||||
}
|
||||
|
|
@ -0,0 +1,310 @@
|
|||
package collaboration
|
||||
|
||||
import (
|
||||
"context"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
)
|
||||
|
||||
// ParentWait is a replay-safe checkpoint. It exists only while the engine is
|
||||
// waiting, never while a model request or side-effecting tool is in flight.
|
||||
type ParentWait struct {
|
||||
Snapshot []byte
|
||||
After int64
|
||||
Until time.Time
|
||||
}
|
||||
|
||||
// SaveWait persists a replay-safe checkpoint for the current parent execution.
|
||||
func (b *Binding) SaveWait(ctx context.Context, snapshot []byte, until time.Time) error {
|
||||
if b.Child != nil || b.ParentOwner == "" {
|
||||
return nil
|
||||
}
|
||||
return b.Runtime.Store.Change(b.Context(ctx), b.Scope, func(g *Group) error {
|
||||
if g.Status != "active" {
|
||||
return ErrClosed
|
||||
}
|
||||
g.ParentWait = &ParentWait{Snapshot: snapshot, After: b.Seen, Until: until}
|
||||
return nil
|
||||
})
|
||||
}
|
||||
|
||||
// ClearWait removes the owned parent checkpoint after the engine resumes.
|
||||
func (b *Binding) ClearWait(ctx context.Context) error {
|
||||
if b.Child != nil || b.ParentOwner == "" {
|
||||
return nil
|
||||
}
|
||||
return b.Runtime.Store.Change(b.Context(ctx), b.Scope, func(g *Group) error {
|
||||
if g.Status != "active" {
|
||||
return ErrClosed
|
||||
}
|
||||
g.ParentWait = nil
|
||||
return nil
|
||||
})
|
||||
}
|
||||
|
||||
func (r *Runtime) wakeParent(ctx context.Context, scope Scope) {
|
||||
if r.WakeParent == nil {
|
||||
return
|
||||
}
|
||||
// Check durable input only for an abandoned safe checkpoint. The CAS below
|
||||
// rechecks ownership and parent message, so a concurrent takeover wins.
|
||||
inputReady := false
|
||||
inputMessage := ""
|
||||
if r.ParentInput != nil {
|
||||
g, err := r.Store.Read(ctx, scope)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
if g.Status == "active" && g.ParentWait != nil && (g.ParentOwner == "" || time.Now().After(g.ParentLease)) {
|
||||
inputMessage = g.ParentMessageID
|
||||
inputReady, err = r.ParentInput(ctx, scope, inputMessage)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
var wait *ParentWait
|
||||
var closing bool
|
||||
owner := uuid.NewString()
|
||||
err := r.Store.Change(ctx, scope, func(g *Group) error {
|
||||
wait = nil
|
||||
closing = false
|
||||
now := time.Now()
|
||||
if (g.Status != "active" && !g.ParentClosePending) || (g.ParentOwner != "" && now.Before(g.ParentLease)) {
|
||||
return nil
|
||||
}
|
||||
if g.ParentClosePending || !now.Before(g.Deadline) || g.ParentWait == nil {
|
||||
if g.ParentMessageID == "" || (g.ParentWait == nil && !g.ParentClosePending && g.ParentOwner == "") {
|
||||
return nil
|
||||
}
|
||||
// Fence all execution before closing the transcript. Keep this outbox
|
||||
// pending across failures/restarts until WakeParent acknowledges delivery.
|
||||
closing = true
|
||||
g.ParentClosePending = true
|
||||
g.Status = "cancelling"
|
||||
g.ParentWait = nil
|
||||
for _, m := range g.Members {
|
||||
if active(current(m)) {
|
||||
current(m).CancelRequested = true
|
||||
}
|
||||
}
|
||||
wait = &ParentWait{}
|
||||
g.ParentOwner, g.ParentLease = owner, now.Add(r.Lease)
|
||||
return nil
|
||||
}
|
||||
ready := !now.Before(g.ParentWait.Until) || (inputReady && g.ParentMessageID == inputMessage)
|
||||
for _, e := range g.Events {
|
||||
ready = ready || e.Sequence > g.ParentWait.After
|
||||
}
|
||||
if !ready {
|
||||
return nil
|
||||
}
|
||||
wait = g.ParentWait
|
||||
g.ParentOwner, g.ParentLease = owner, now.Add(r.Lease)
|
||||
return nil
|
||||
})
|
||||
if err != nil || wait == nil {
|
||||
return
|
||||
}
|
||||
r.workers.Add(1)
|
||||
go func() {
|
||||
defer r.workers.Done()
|
||||
b := &Binding{
|
||||
Runtime: r,
|
||||
Scope: scope,
|
||||
ParentOwner: owner,
|
||||
Closing: closing,
|
||||
WaitUntil: wait.Until,
|
||||
Seen: wait.After,
|
||||
}
|
||||
runCtx, stop := b.Start(ctx)
|
||||
defer stop()
|
||||
err := r.WakeParent(WithBinding(runCtx, b), b, wait.Snapshot)
|
||||
if closing {
|
||||
if err == nil {
|
||||
// A failed acknowledgement is safe to retry: only transcript/stream
|
||||
// finalization can run for ParentClosePending, never the saved execution.
|
||||
_ = r.Store.Change(b.Context(context.WithoutCancel(ctx)), scope, func(g *Group) error {
|
||||
g.ParentClosePending = false
|
||||
settle(g)
|
||||
return nil
|
||||
})
|
||||
}
|
||||
return
|
||||
}
|
||||
if err != nil && ctx.Err() == nil {
|
||||
_ = r.Cancel(b.Context(context.WithoutCancel(ctx)), scope)
|
||||
}
|
||||
}()
|
||||
}
|
||||
|
||||
// SetRunMessages and AwaitPrompt are fenced by the same child execution lease
|
||||
// as tool execution. Prompt ownership is registered before it reaches the UI.
|
||||
func (r *Runtime) SetRunMessages(ctx context.Context, w Work, userID, messageID string) error {
|
||||
return r.changeWork(
|
||||
ctx,
|
||||
w,
|
||||
func(_ *Group, v *Run) error { v.UserMessageID = userID; v.MessageID = messageID; return nil },
|
||||
)
|
||||
}
|
||||
|
||||
// AwaitPrompt registers a prompt under the current child execution lease.
|
||||
func (r *Runtime) AwaitPrompt(ctx context.Context, w Work, prompt PromptState) error {
|
||||
return r.changeWork(ctx, w, func(_ *Group, v *Run) error { v.PromptID, v.Prompt = prompt.ID, &prompt; return nil })
|
||||
}
|
||||
|
||||
func (r *Runtime) changeWork(ctx context.Context, w Work, fn func(*Group, *Run) error) error {
|
||||
return r.Store.Change(ctx, w.Scope, func(g *Group) error {
|
||||
m, err := member(g, w.Member.ID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
v := current(m)
|
||||
if g.Status != "active" || v.ID != w.Run.ID || v.State != "running" || v.Owner != w.Run.Owner ||
|
||||
v.CancelRequested ||
|
||||
!time.Now().Before(v.Lease) {
|
||||
return ErrConflict
|
||||
}
|
||||
return fn(g, v)
|
||||
})
|
||||
}
|
||||
|
||||
// ReconcilePrompt is called with broker state read outside the CAS callback.
|
||||
// An executing/done prompt can never be replayed, even after a process dies.
|
||||
func (r *Runtime) ReconcilePrompt(ctx context.Context, w Work, prompt PromptState) error {
|
||||
return r.Store.Change(ctx, w.Scope, func(g *Group) error {
|
||||
m, err := member(g, w.Member.ID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
v := current(m)
|
||||
if v.ID != w.Run.ID || v.PromptID != w.Run.PromptID || v.PromptID == "" || prompt.ID != v.PromptID {
|
||||
return nil
|
||||
}
|
||||
if v.State != "waiting" && (v.State != "running" || !time.Now().After(v.Lease)) {
|
||||
return nil
|
||||
}
|
||||
if g.Status != "active" || v.CancelRequested {
|
||||
v.State = "cancelled"
|
||||
publish(g, m, v)
|
||||
settle(g)
|
||||
return nil
|
||||
}
|
||||
v.Prompt = &prompt
|
||||
switch prompt.Status {
|
||||
case "pending", "suspended":
|
||||
if v.State != "waiting" {
|
||||
publishPromptState(g, m, v, "waiting")
|
||||
}
|
||||
v.State = "waiting"
|
||||
v.Owner = ""
|
||||
case "answered":
|
||||
v.State = "queued"
|
||||
v.Owner = ""
|
||||
publishPromptState(g, m, v, "resumed")
|
||||
default:
|
||||
closeChildRun(g, m, v, prompt.Status)
|
||||
}
|
||||
return nil
|
||||
})
|
||||
}
|
||||
|
||||
// CloseChildPrompt settles the child run that owns a broker prompt. The prompt
|
||||
// session is the child conversation, so callers locate the parent group first.
|
||||
// A prompt that closed before the tool ran stays continuable; an in-flight or
|
||||
// failed execution stays needs_attention and cannot be replayed.
|
||||
func (r *Runtime) CloseChildPrompt(
|
||||
ctx context.Context, scope Scope, sessionID, messageID, promptID, status string,
|
||||
) error {
|
||||
if sessionID == "" || (messageID == "" && promptID == "") {
|
||||
return nil
|
||||
}
|
||||
return r.Store.Change(ctx, scope, func(g *Group) error {
|
||||
for _, m := range g.Members {
|
||||
if m.SessionID != sessionID {
|
||||
continue
|
||||
}
|
||||
for _, v := range m.Runs {
|
||||
if v.PromptID != promptID && (messageID == "" || v.MessageID != messageID) {
|
||||
continue
|
||||
}
|
||||
if !active(v) && v.PromptID == "" && v.State != "needs_attention" {
|
||||
return nil
|
||||
}
|
||||
closeChildRun(g, m, v, status)
|
||||
return nil
|
||||
}
|
||||
}
|
||||
return nil
|
||||
})
|
||||
}
|
||||
|
||||
func closeChildRun(g *Group, m *Member, v *Run, status string) {
|
||||
if promptClosedBeforeExecution(status, v.State) {
|
||||
if v.State != "interrupted" {
|
||||
v.State = "interrupted"
|
||||
v.Owner = ""
|
||||
v.CancelRequested = false
|
||||
v.Result.Error = closedBeforeExecutionError
|
||||
publish(g, m, v)
|
||||
}
|
||||
} else if active(v) || v.State == "needs_attention" {
|
||||
if v.State != "needs_attention" {
|
||||
v.State = "needs_attention"
|
||||
v.Owner = ""
|
||||
v.Result.Error = uncertainExecutionError
|
||||
publish(g, m, v)
|
||||
}
|
||||
}
|
||||
v.PromptID = ""
|
||||
v.Prompt = nil
|
||||
settle(g)
|
||||
}
|
||||
|
||||
// ClearCanceledPrompt removes a canceled run’s prompt after the broker closes it.
|
||||
func (r *Runtime) ClearCanceledPrompt(ctx context.Context, w Work) error {
|
||||
return r.Store.Change(ctx, w.Scope, func(g *Group) error {
|
||||
m, err := member(g, w.Member.ID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
var v *Run
|
||||
for _, candidate := range m.Runs {
|
||||
if candidate.ID == w.Run.ID {
|
||||
v = candidate
|
||||
break
|
||||
}
|
||||
}
|
||||
if v == nil || v.PromptID != w.Run.PromptID || (g.Status == "active" && !v.CancelRequested) {
|
||||
return nil
|
||||
}
|
||||
v.PromptID = ""
|
||||
v.Prompt = nil
|
||||
settle(g)
|
||||
return nil
|
||||
})
|
||||
}
|
||||
|
||||
// RecordProgress coalesces telemetry without adding mailbox events or waking a
|
||||
// model on each tool. Old workers and canceled turns cannot publish late updates.
|
||||
func (r *Runtime) RecordProgress(ctx context.Context, w Work, p Progress) error {
|
||||
p.ToolName = truncate(p.ToolName, 128)
|
||||
p.ToolCallID = truncate(p.ToolCallID, 128)
|
||||
p.UpdatedAt = time.Now()
|
||||
return r.changeWork(ctx, w, func(_ *Group, v *Run) error { v.Progress = &p; return nil })
|
||||
}
|
||||
|
||||
// CheckParentFinalization authorizes only the claimed terminal delivery. It is
|
||||
// deliberately separate from CheckParent, which rejects a closing group.
|
||||
func (r *Runtime) CheckParentFinalization(ctx context.Context, scope Scope, owner string) error {
|
||||
g, err := r.Store.Read(ctx, scope)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if !g.ParentClosePending || g.Status != "cancelling" || g.ParentOwner != owner ||
|
||||
!time.Now().Before(g.ParentLease) {
|
||||
return ErrConflict
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
|
@ -0,0 +1,436 @@
|
|||
package collaboration
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"sync"
|
||||
"sync/atomic"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
func TestParentWaitRestartOneWinnerAndNoLostWake(t *testing.T) {
|
||||
store, scope := testStore(t)
|
||||
ctx := context.Background()
|
||||
first := New(store, nil)
|
||||
b, err := first.AcquireParent(ctx, scope)
|
||||
require.NoError(t, err)
|
||||
until := time.Now().Add(time.Minute)
|
||||
require.NoError(t, b.SaveWait(ctx, []byte(`{"safe":true}`), until))
|
||||
// Result commits before the new scheduler starts; the DB is the wake outbox.
|
||||
require.NoError(t, store.Change(ctx, scope, func(g *Group) error {
|
||||
g.Events = append(g.Events, Event{Sequence: 1, Kind: "succeeded"})
|
||||
g.NextSequence = 1
|
||||
g.ParentLease = time.Now().Add(-time.Second)
|
||||
return nil
|
||||
}))
|
||||
var calls atomic.Int32
|
||||
entered := make(chan *Binding, 2)
|
||||
release := make(chan struct{})
|
||||
wake := func(ctx context.Context, b *Binding, data []byte) error {
|
||||
calls.Add(1)
|
||||
entered <- b
|
||||
if string(data) != `{"safe":true}` {
|
||||
return ErrConflict
|
||||
}
|
||||
<-release
|
||||
return b.ClearWait(ctx)
|
||||
}
|
||||
a, c := New(NewStore(store.db), nil), New(NewStore(store.db), nil)
|
||||
a.WakeParent, c.WakeParent = wake, wake
|
||||
var wg sync.WaitGroup
|
||||
for range 16 {
|
||||
for _, r := range []*Runtime{a, c} {
|
||||
wg.Add(1)
|
||||
go func() { defer wg.Done(); r.Tick(ctx) }()
|
||||
}
|
||||
}
|
||||
wg.Wait()
|
||||
var resumed *Binding
|
||||
select {
|
||||
case resumed = <-entered:
|
||||
case <-time.After(time.Second):
|
||||
t.Fatal("not woken")
|
||||
}
|
||||
require.Equal(t, int32(1), calls.Load())
|
||||
require.Equal(t, until.UnixNano(), resumed.WaitUntil.UnixNano())
|
||||
require.ErrorIs(t, first.CheckParent(ctx, scope, b.ParentOwner), ErrConflict)
|
||||
close(release)
|
||||
a.workers.Wait()
|
||||
c.workers.Wait()
|
||||
require.Nil(t, read(t, store, scope).ParentWait)
|
||||
}
|
||||
|
||||
func TestCanceledParentCannotBeWokenByLateResult(t *testing.T) {
|
||||
store, scope := testStore(t)
|
||||
r := New(store, nil)
|
||||
ctx := context.Background()
|
||||
b, err := r.AcquireParent(ctx, scope)
|
||||
require.NoError(t, err)
|
||||
require.NoError(t, b.SaveWait(ctx, []byte("checkpoint"), time.Now().Add(-time.Second)))
|
||||
require.NoError(t, r.Cancel(ctx, scope))
|
||||
require.NoError(t, store.Change(ctx, scope, func(g *Group) error {
|
||||
g.ParentLease = time.Time{}
|
||||
g.NextSequence++
|
||||
g.Events = append(g.Events, Event{Sequence: g.NextSequence})
|
||||
return nil
|
||||
}))
|
||||
var calls atomic.Int32
|
||||
r.WakeParent = func(context.Context, *Binding, []byte) error { calls.Add(1); return nil }
|
||||
r.Tick(ctx)
|
||||
r.workers.Wait()
|
||||
require.Zero(t, calls.Load())
|
||||
require.Nil(t, read(t, store, scope).ParentWait)
|
||||
require.Error(t, b.SaveWait(ctx, []byte("stale"), time.Now()))
|
||||
}
|
||||
|
||||
func TestCancelAfterWakeClaimFencesContinuation(t *testing.T) {
|
||||
store, scope := testStore(t)
|
||||
r := New(store, nil)
|
||||
ctx := context.Background()
|
||||
b, err := r.AcquireParent(ctx, scope)
|
||||
require.NoError(t, err)
|
||||
require.NoError(t, b.SaveWait(ctx, []byte("safe"), time.Now().Add(-time.Second)))
|
||||
require.NoError(t, store.Change(ctx, scope, func(g *Group) error { g.ParentLease = time.Time{}; return nil }))
|
||||
claimed := make(chan *Binding, 1)
|
||||
resume := make(chan struct{})
|
||||
result := make(chan error, 1)
|
||||
r.WakeParent = func(ctx context.Context, b *Binding, _ []byte) error {
|
||||
claimed <- b
|
||||
<-resume
|
||||
err := b.Runtime.CheckParent(ctx, b.Scope, b.ParentOwner)
|
||||
result <- err
|
||||
return err
|
||||
}
|
||||
r.Tick(ctx)
|
||||
select {
|
||||
case <-claimed:
|
||||
case <-time.After(time.Second):
|
||||
t.Fatal("not claimed")
|
||||
}
|
||||
require.NoError(t, r.Cancel(ctx, scope))
|
||||
close(resume)
|
||||
require.Error(t, <-result)
|
||||
r.workers.Wait()
|
||||
require.Equal(t, "cancelled", read(t, store, scope).Status)
|
||||
}
|
||||
|
||||
func promptWork(t *testing.T) (*Runtime, Work) {
|
||||
t.Helper()
|
||||
s, scope := testStore(t)
|
||||
r := New(s, nil)
|
||||
ctx := context.Background()
|
||||
_, err := r.Spawn(ctx, scope, "spawn", "worker", "agent", "{}", "task")
|
||||
require.NoError(t, err)
|
||||
require.NoError(t, s.Change(ctx, scope, func(g *Group) error {
|
||||
v := current(g.Members[0])
|
||||
v.State = "waiting"
|
||||
v.PromptID = "prompt"
|
||||
return nil
|
||||
}))
|
||||
g := read(t, s, scope)
|
||||
return r, Work{Scope: scope, Member: *g.Members[0], Run: *current(g.Members[0])}
|
||||
}
|
||||
|
||||
func TestPromptRestartAndCancellationFences(t *testing.T) {
|
||||
for _, status := range []string{"pending", "suspended", "answered", "executing", "done", "canceled"} {
|
||||
t.Run(status, func(t *testing.T) {
|
||||
r, w := promptWork(t)
|
||||
ctx := context.Background()
|
||||
require.NoError(t, r.ReconcilePrompt(ctx, w, PromptState{ID: w.Run.PromptID, Status: status}))
|
||||
want := "needs_attention"
|
||||
if status == "pending" || status == "suspended" {
|
||||
want = "waiting"
|
||||
}
|
||||
if status == "answered" {
|
||||
want = "queued"
|
||||
}
|
||||
if status == "canceled" {
|
||||
want = "interrupted"
|
||||
}
|
||||
require.Equal(t, want, current(read(t, r.Store, w.Scope).Members[0]).State)
|
||||
})
|
||||
}
|
||||
for _, interrupt := range []bool{false, true} {
|
||||
t.Run(map[bool]string{false: "cancel", true: "interrupt"}[interrupt], func(t *testing.T) {
|
||||
r, w := promptWork(t)
|
||||
ctx := context.Background()
|
||||
if interrupt {
|
||||
require.NoError(t, r.Interrupt(ctx, w.Scope, w.Member.ID, w.Run.ID))
|
||||
} else {
|
||||
require.NoError(t, r.Cancel(ctx, w.Scope))
|
||||
}
|
||||
require.NoError(t, r.ReconcilePrompt(ctx, w, PromptState{ID: w.Run.PromptID, Status: "answered"}))
|
||||
require.NotEqual(t, "queued", current(read(t, r.Store, w.Scope).Members[0]).State)
|
||||
var calls atomic.Int32
|
||||
r.Run = func(context.Context, Work) (Result, error) { calls.Add(1); return Result{}, nil }
|
||||
r.Tick(ctx)
|
||||
r.workers.Wait()
|
||||
require.Zero(t, calls.Load())
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestExpiredWaitingPromptCanBeContinued(t *testing.T) {
|
||||
for _, status := range []string{"expired", "canceled", "superseded"} {
|
||||
t.Run(status, func(t *testing.T) {
|
||||
r, w := promptWork(t)
|
||||
ctx := context.Background()
|
||||
require.NoError(t, r.ReconcilePrompt(ctx, w, PromptState{ID: w.Run.PromptID, Status: status}))
|
||||
g := read(t, r.Store, w.Scope)
|
||||
require.Equal(t, "interrupted", current(g.Members[0]).State)
|
||||
require.Empty(t, current(g.Members[0]).PromptID)
|
||||
_, err := r.Send(ctx, w.Scope, "follow-"+status, w.Member.Name, "continue", "", true)
|
||||
require.NoError(t, err)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestWaitingChildPreventsParentCompletionAndDoesNotOccupySlot(t *testing.T) {
|
||||
r, w := promptWork(t)
|
||||
ctx := context.Background()
|
||||
done, err := r.Finish(ctx, w.Scope, 0)
|
||||
require.NoError(t, err)
|
||||
require.False(t, done)
|
||||
r.Concurrency = 1
|
||||
_, err = r.Spawn(ctx, w.Scope, "another", "other", "agent", "{}", "task")
|
||||
require.NoError(t, err)
|
||||
var calls atomic.Int32
|
||||
r.Run = func(context.Context, Work) (Result, error) { calls.Add(1); return Result{}, nil }
|
||||
r.Tick(ctx)
|
||||
r.workers.Wait()
|
||||
require.Equal(t, int32(1), calls.Load())
|
||||
}
|
||||
|
||||
func TestCompletedParentHeartbeatDoesNotCancelFinalDelivery(t *testing.T) {
|
||||
store, scope := testStore(t)
|
||||
r := New(store, nil)
|
||||
r.Poll = time.Millisecond
|
||||
b, err := r.AcquireParent(context.Background(), scope)
|
||||
require.NoError(t, err)
|
||||
ctx, stop := b.Start(context.Background())
|
||||
defer stop()
|
||||
done, err := r.Finish(ctx, scope, 0)
|
||||
require.NoError(t, err)
|
||||
require.True(t, done)
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
t.Fatal("normal completion canceled final event delivery")
|
||||
case <-time.After(30 * time.Millisecond):
|
||||
}
|
||||
}
|
||||
|
||||
func TestWaitWakesForSteerWithoutConsumingOrClosingGroup(t *testing.T) {
|
||||
for _, before := range []bool{true, false} {
|
||||
t.Run(map[bool]string{true: "already-pending", false: "arrives-during-wait"}[before], func(t *testing.T) {
|
||||
store, scope := testStore(t)
|
||||
r := New(store, nil)
|
||||
r.Poll = 5 * time.Millisecond
|
||||
var ready atomic.Bool
|
||||
ready.Store(before)
|
||||
b := &Binding{
|
||||
Runtime: r,
|
||||
Scope: scope,
|
||||
HasInput: func(context.Context) (bool, error) { return ready.Load(), nil },
|
||||
}
|
||||
done := make(chan error, 1)
|
||||
go func() { _, err := b.Wait(context.Background(), 0, time.Minute); done <- err }()
|
||||
ready.Store(true)
|
||||
select {
|
||||
case err := <-done:
|
||||
require.ErrorIs(t, err, ErrInput)
|
||||
case <-time.After(time.Second):
|
||||
t.Fatal("steer did not wake wait")
|
||||
}
|
||||
require.True(t, ready.Load())
|
||||
_, err := b.BeforeFinish(context.Background())
|
||||
require.ErrorIs(t, err, ErrInput)
|
||||
g, err := store.Read(context.Background(), scope)
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, "active", g.Status)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestProgressIsObservableButDoesNotWakeAndLateWorkerIsFenced(t *testing.T) {
|
||||
store, scope := testStore(t)
|
||||
r := New(store, nil)
|
||||
ctx := context.Background()
|
||||
_, err := r.Spawn(ctx, scope, "spawn", "child", "a", "{}", "work")
|
||||
require.NoError(t, err)
|
||||
var w Work
|
||||
require.NoError(t, store.Change(ctx, scope, func(g *Group) error {
|
||||
m := g.Members[0]
|
||||
v := current(m)
|
||||
v.State = "running"
|
||||
v.Owner = "worker"
|
||||
v.Lease = time.Now().Add(time.Minute)
|
||||
w = Work{scope, *m, *v}
|
||||
return nil
|
||||
}))
|
||||
require.NoError(t, r.RecordProgress(ctx, w, Progress{Phase: "tool_running", ToolName: "mcp_write", Iteration: 2}))
|
||||
b := &Binding{Runtime: r, Scope: scope}
|
||||
list, err := b.List(ctx, "")
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, "mcp_write", list[0].Progress.ToolName)
|
||||
updated, err := r.Wait(ctx, scope, 0, 0)
|
||||
require.NoError(t, err)
|
||||
require.False(t, updated)
|
||||
child := &Binding{Runtime: r, Scope: scope, Child: &w}
|
||||
require.NoError(t, child.MessageParent(ctx, "milestone", "sources checked; one article is unavailable"))
|
||||
updated, err = b.Wait(ctx, 0, time.Second)
|
||||
require.NoError(t, err)
|
||||
require.True(t, updated, "a key finding must wake the parent before the child finishes")
|
||||
events, err := b.Poll(ctx)
|
||||
require.NoError(t, err)
|
||||
require.Len(t, events, 1)
|
||||
require.Equal(t, "message", events[0].Kind)
|
||||
require.Equal(t, "sources checked; one article is unavailable", events[0].Content)
|
||||
require.Equal(t, "running", current(read(t, store, scope).Members[0]).State)
|
||||
require.NoError(t, r.Cancel(ctx, scope))
|
||||
require.ErrorIs(t, child.MessageParent(ctx, "late", "late finding"), ErrClosed)
|
||||
require.ErrorIs(t, r.RecordProgress(ctx, w, Progress{Phase: "tool_succeeded"}), ErrConflict)
|
||||
}
|
||||
|
||||
func TestRestartWakeOnSteerWithoutChildResultAndCancellationWins(t *testing.T) {
|
||||
for _, cancelTask := range []bool{false, true} {
|
||||
t.Run(map[bool]string{false: "resume", true: "cancel"}[cancelTask], func(t *testing.T) {
|
||||
store, scope := testStore(t)
|
||||
r := New(store, nil)
|
||||
ctx := context.Background()
|
||||
b, err := r.AcquireParent(ctx, scope)
|
||||
require.NoError(t, err)
|
||||
require.NoError(t, b.SaveWait(ctx, []byte("safe"), time.Now().Add(time.Hour)))
|
||||
require.NoError(
|
||||
t,
|
||||
store.Change(
|
||||
ctx,
|
||||
scope,
|
||||
func(g *Group) error { g.ParentLease = time.Now().Add(-time.Minute); return nil },
|
||||
),
|
||||
)
|
||||
r.ParentInput = func(context.Context, Scope, string) (bool, error) { return true, nil }
|
||||
var calls atomic.Int32
|
||||
r.WakeParent = func(ctx context.Context,
|
||||
b *Binding,
|
||||
_ []byte,
|
||||
) error {
|
||||
calls.Add(1)
|
||||
return b.ClearWait(ctx)
|
||||
}
|
||||
if cancelTask {
|
||||
require.NoError(t, r.Cancel(ctx, scope))
|
||||
}
|
||||
r.Tick(ctx)
|
||||
r.workers.Wait()
|
||||
if cancelTask {
|
||||
require.Zero(t, calls.Load())
|
||||
} else {
|
||||
require.Equal(t, int32(1), calls.Load())
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestAbandonedParentWithoutCheckpointClosesInsteadOfReplaying(t *testing.T) {
|
||||
store, scope := testStore(t)
|
||||
ctx := context.Background()
|
||||
r := New(store, nil)
|
||||
b, err := r.AcquireParent(ctx, scope)
|
||||
require.NoError(t, err)
|
||||
require.NoError(
|
||||
t,
|
||||
store.Change(ctx, scope, func(g *Group) error { g.ParentLease = time.Now().Add(-time.Second); return nil }),
|
||||
)
|
||||
var calls atomic.Int32
|
||||
r.WakeParent = func(ctx context.Context, recovered *Binding, snapshot []byte) error {
|
||||
calls.Add(1)
|
||||
if len(snapshot) != 0 {
|
||||
return ErrConflict
|
||||
}
|
||||
return r.Cancel(recovered.Context(ctx), scope)
|
||||
}
|
||||
for range 5 {
|
||||
r.Tick(ctx)
|
||||
}
|
||||
r.workers.Wait()
|
||||
require.Equal(t, int32(1), calls.Load())
|
||||
require.Equal(t, "cancelled", read(t, store, scope).Status)
|
||||
require.Error(t, r.CheckParent(ctx, scope, b.ParentOwner))
|
||||
for range 3 {
|
||||
r.Tick(ctx)
|
||||
}
|
||||
require.Equal(t, int32(1), calls.Load())
|
||||
}
|
||||
|
||||
func TestExpiredParentFinalizationRetriesAfterRestartWithoutExecution(t *testing.T) {
|
||||
for _, checkpoint := range []bool{false, true} {
|
||||
t.Run(map[bool]string{false: "in-flight", true: "waiting"}[checkpoint], func(t *testing.T) {
|
||||
store, scope := testStore(t)
|
||||
ctx := context.Background()
|
||||
var executions atomic.Int32
|
||||
runner := func(context.Context, Work) (Result, error) { executions.Add(1); return Result{}, nil }
|
||||
r := New(store, runner)
|
||||
b, err := r.AcquireParent(ctx, scope)
|
||||
require.NoError(t, err)
|
||||
_, err = r.Spawn(ctx, scope, "spawn", "child", "a", "{}", "task")
|
||||
require.NoError(t, err)
|
||||
if checkpoint {
|
||||
require.NoError(t, b.SaveWait(ctx, []byte("must never replay"), time.Now().Add(time.Hour)))
|
||||
}
|
||||
require.NoError(t, store.Change(ctx, scope, func(g *Group) error {
|
||||
g.ParentLease = time.Now().Add(-time.Minute)
|
||||
g.Deadline = time.Now().Add(-time.Second)
|
||||
return nil
|
||||
}))
|
||||
r.WakeParent = func(ctx context.Context, b *Binding, snapshot []byte) error {
|
||||
if len(snapshot) != 0 {
|
||||
return errors.New("execution snapshot must not be replayed")
|
||||
}
|
||||
if err := r.CheckParentFinalization(ctx, scope, b.ParentOwner); err != nil {
|
||||
return err
|
||||
}
|
||||
return errors.New("temporary delivery failure")
|
||||
}
|
||||
r.Tick(ctx)
|
||||
r.workers.Wait()
|
||||
g := read(t, store, scope)
|
||||
require.Equal(t, "cancelling", g.Status)
|
||||
require.True(t, g.ParentClosePending)
|
||||
require.Equal(t, "cancelled", g.Members[0].Runs[0].State)
|
||||
require.Error(t, r.CheckParent(ctx, scope, g.ParentOwner), "closing authority cannot execute tools")
|
||||
// Restart with the same durable record and expire the failed claim.
|
||||
require.NoError(
|
||||
t,
|
||||
store.Change(
|
||||
ctx,
|
||||
scope,
|
||||
func(g *Group) error { g.ParentLease = time.Now().Add(-time.Second); return nil },
|
||||
),
|
||||
)
|
||||
restarted := New(NewStore(store.db), runner)
|
||||
var closures atomic.Int32
|
||||
restarted.WakeParent = func(ctx context.Context, b *Binding, snapshot []byte) error {
|
||||
if len(snapshot) != 0 {
|
||||
return errors.New("execution snapshot must not be replayed")
|
||||
}
|
||||
if err := restarted.CheckParentFinalization(ctx, scope, b.ParentOwner); err != nil {
|
||||
return err
|
||||
}
|
||||
closures.Add(1)
|
||||
return nil
|
||||
}
|
||||
for range 3 {
|
||||
restarted.Tick(ctx)
|
||||
restarted.workers.Wait()
|
||||
}
|
||||
require.Equal(t, int32(1), closures.Load())
|
||||
require.Zero(t, executions.Load())
|
||||
g = read(t, store, scope)
|
||||
require.Equal(t, "cancelled", g.Status)
|
||||
require.False(t, g.ParentClosePending)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,752 @@
|
|||
package collaboration
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"regexp"
|
||||
"strings"
|
||||
"sync"
|
||||
"sync/atomic"
|
||||
"time"
|
||||
|
||||
"github.com/Tencent/WeKnora/internal/logger"
|
||||
"github.com/google/uuid"
|
||||
)
|
||||
|
||||
var taskName = regexp.MustCompile(`^[a-z][a-z0-9_]{0,47}$`)
|
||||
|
||||
// collaborationHorizon is how long an active parent or child may keep the group
|
||||
// open. Abandoned groups still end one horizon after the last lease renewal.
|
||||
const collaborationHorizon = time.Hour
|
||||
|
||||
const (
|
||||
closedBeforeExecutionError = "child prompt closed before the tool ran; followup_task can continue this child"
|
||||
uncertainExecutionError = "child prompt closed or execution outcome uncertain; not replayed"
|
||||
)
|
||||
|
||||
// touchDeadline extends the horizon in coarse steps. Every extension rewrites
|
||||
// the whole aggregate, so per-heartbeat extensions would multiply writes.
|
||||
func touchDeadline(g *Group, now time.Time) {
|
||||
until := now.Add(collaborationHorizon)
|
||||
if g.Deadline.Before(until.Add(-collaborationHorizon / 10)) {
|
||||
g.Deadline = until
|
||||
}
|
||||
}
|
||||
|
||||
// heartbeatInterval is how often an owner checks for cancellation. Checks read
|
||||
// the aggregate; renewals write it only when renewalDue.
|
||||
func (r *Runtime) heartbeatInterval() time.Duration {
|
||||
return min(max(r.Poll, time.Second), r.Lease/3)
|
||||
}
|
||||
|
||||
// renewalDue reports whether a lease has used a third of its duration.
|
||||
func (r *Runtime) renewalDue(lease, now time.Time) bool {
|
||||
return lease.Sub(now) < r.Lease*2/3
|
||||
}
|
||||
|
||||
// promptClosedBeforeExecution reports a prompt that ended while the tool had
|
||||
// not started. A running turn can still have an uncertain side effect.
|
||||
func promptClosedBeforeExecution(status, runState string) bool {
|
||||
switch status {
|
||||
case "expired", "canceled", "superseded":
|
||||
return runState != "running"
|
||||
default:
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
// Work is a claimed child execution with its scope and ownership lease.
|
||||
type Work struct {
|
||||
Scope Scope
|
||||
Member Member
|
||||
Run Run
|
||||
}
|
||||
|
||||
// Runner executes claimed child work and returns its durable outcome.
|
||||
type Runner func(context.Context, Work) (Result, error)
|
||||
|
||||
// Runtime schedules durable child work and recovers waiting parent executions.
|
||||
type Runtime struct {
|
||||
Store *Store
|
||||
Run Runner
|
||||
WakeParent func(context.Context, *Binding, []byte) error
|
||||
Reconcile func(context.Context, Scope) error
|
||||
ParentInput func(context.Context, Scope, string) (bool, error)
|
||||
// Prune bounds durable storage; it runs every PruneInterval.
|
||||
Prune func(context.Context) error
|
||||
PruneInterval time.Duration
|
||||
Poll time.Duration
|
||||
Lease time.Duration
|
||||
// Concurrency bounds running children per group; MaxRunning bounds the
|
||||
// child executions this process runs across all groups.
|
||||
Concurrency int
|
||||
MaxRunning int
|
||||
mu sync.Mutex
|
||||
cancel context.CancelFunc
|
||||
done chan struct{}
|
||||
workers sync.WaitGroup
|
||||
running atomic.Int64
|
||||
}
|
||||
|
||||
// New constructs a runtime with bounded concurrency and lease defaults.
|
||||
func New(store *Store, run Runner) *Runtime {
|
||||
return &Runtime{
|
||||
Store: store, Run: run, Poll: 250 * time.Millisecond, Lease: 30 * time.Second,
|
||||
Concurrency: 3, MaxRunning: 32, PruneInterval: 10 * time.Minute,
|
||||
}
|
||||
}
|
||||
|
||||
// Spawn idempotently enqueues a new child task in the parent group.
|
||||
func (r *Runtime) Spawn(ctx context.Context, s Scope, key, name, agentID, config, query string) (string, error) {
|
||||
if key == "" || len(key) > 512 || len(config) > 65536 || len(agentID) > 64 || !taskName.MatchString(name) ||
|
||||
strings.TrimSpace(query) == "" ||
|
||||
len(query) > 16000 {
|
||||
return "", errors.New("invalid task name, request id or task (maximum 16000 bytes)")
|
||||
}
|
||||
id, runID, session := uuid.NewString(), uuid.NewString(), uuid.NewString()
|
||||
err := r.Store.Change(ctx, s, func(g *Group) error {
|
||||
if v := g.Requests[key]; v != "" {
|
||||
id = v
|
||||
return nil
|
||||
}
|
||||
if g.Status != "active" {
|
||||
return ErrClosed
|
||||
}
|
||||
if currentTurnMemberCount(g) >= 16 {
|
||||
return errors.New("maximum 16 child agents per task")
|
||||
}
|
||||
if _, err := member(g, name); err == nil {
|
||||
return errors.New("task name already exists")
|
||||
}
|
||||
if err := reserveInput(g, len(query)+len(config)); err != nil {
|
||||
return err
|
||||
}
|
||||
g.Members = append(
|
||||
g.Members,
|
||||
&Member{
|
||||
ID: id,
|
||||
Name: name,
|
||||
AgentID: agentID,
|
||||
SessionID: session,
|
||||
ConfigJSON: config,
|
||||
Runs: []*Run{{ID: runID, State: "queued", Query: query}},
|
||||
},
|
||||
)
|
||||
g.Requests[key] = id
|
||||
return nil
|
||||
})
|
||||
return id, err
|
||||
}
|
||||
|
||||
// Send queues guidance or creates a follow-up turn for an idle child.
|
||||
func (r *Runtime) Send(
|
||||
ctx context.Context,
|
||||
s Scope,
|
||||
key, target, query, expected string,
|
||||
followup bool,
|
||||
) (string, error) {
|
||||
if key == "" || len(key) > 512 || strings.TrimSpace(query) == "" || len(query) > 16000 {
|
||||
return "", errors.New("message is empty or too large")
|
||||
}
|
||||
newRunID := uuid.NewString()
|
||||
id := newRunID
|
||||
err := r.Store.Change(ctx, s, func(g *Group) error {
|
||||
id = newRunID
|
||||
if v := g.Requests[key]; v != "" {
|
||||
id = v
|
||||
return nil
|
||||
}
|
||||
if g.Status != "active" {
|
||||
return ErrClosed
|
||||
}
|
||||
m, err := member(g, target)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
run := current(m)
|
||||
if expected != "" && expected != run.ID {
|
||||
return ErrConflict
|
||||
}
|
||||
if run.State == "needs_attention" {
|
||||
return errors.New("execution outcome is uncertain; create a new task only after checking its effects")
|
||||
}
|
||||
if followup && len(m.Runs) >= 8 {
|
||||
return errors.New("maximum 8 turns per child")
|
||||
}
|
||||
if run.CancelRequested && active(run) {
|
||||
return errors.New("child is stopping; wait for its terminal state")
|
||||
}
|
||||
if len(m.Mail) >= 64 || len(g.Requests) >= 512 {
|
||||
return errors.New("message budget exhausted")
|
||||
}
|
||||
if err := reserveInput(g, len(query)); err != nil {
|
||||
return err
|
||||
}
|
||||
if followup && !active(run) {
|
||||
if m.Inherited && currentTurnMemberCount(g) >= 16 {
|
||||
return errors.New("maximum 16 child agents per task")
|
||||
}
|
||||
m.Inherited = false
|
||||
m.Runs = append(m.Runs, &Run{ID: id, State: "queued", Query: query})
|
||||
} else {
|
||||
g.NextSequence++
|
||||
kind := "message"
|
||||
if followup {
|
||||
kind = "followup"
|
||||
}
|
||||
m.Mail = append(m.Mail, Event{g.NextSequence, "root", run.ID, kind, query})
|
||||
id = run.ID
|
||||
}
|
||||
g.Requests[key] = id
|
||||
return nil
|
||||
})
|
||||
return id, err
|
||||
}
|
||||
|
||||
// Interrupt requests cancellation of the selected child execution.
|
||||
func (r *Runtime) Interrupt(ctx context.Context, s Scope, target, expected string) error {
|
||||
return r.Store.Change(ctx, s, func(g *Group) error {
|
||||
m, err := member(g, target)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
run := current(m)
|
||||
if expected != "" && expected != run.ID {
|
||||
return ErrConflict
|
||||
}
|
||||
if !active(run) {
|
||||
return nil
|
||||
}
|
||||
run.CancelRequested = true
|
||||
if run.State == "queued" || run.State == "waiting" {
|
||||
run.State = "interrupted"
|
||||
publish(g, m, run)
|
||||
}
|
||||
return nil
|
||||
})
|
||||
}
|
||||
|
||||
// Cancel closes a group and cancels its unfinished child executions.
|
||||
func (r *Runtime) Cancel(ctx context.Context, s Scope) error {
|
||||
return r.cancelMessage(ctx, s, "")
|
||||
}
|
||||
|
||||
// CancelMessage ignores a stale stop for the previous parent turn after takeover.
|
||||
func (r *Runtime) CancelMessage(ctx context.Context, s Scope, messageID string) error {
|
||||
return r.cancelMessage(ctx, s, messageID)
|
||||
}
|
||||
|
||||
func (r *Runtime) cancelMessage(ctx context.Context, s Scope, messageID string) error {
|
||||
return r.Store.Change(ctx, s, func(g *Group) error {
|
||||
if messageID != "" && messageID != g.ParentMessageID && (g.ParentMessageID != "" || messageID != g.Scope.ID) {
|
||||
return nil
|
||||
}
|
||||
if g.Status == "completed" || g.Status == "cancelled" {
|
||||
return nil
|
||||
}
|
||||
cancelGroup(g)
|
||||
return nil
|
||||
})
|
||||
}
|
||||
|
||||
func cancelGroup(g *Group) {
|
||||
g.Status = "cancelling"
|
||||
g.ParentWait = nil
|
||||
for _, m := range g.Members {
|
||||
v := current(m)
|
||||
if active(v) {
|
||||
v.CancelRequested = true
|
||||
if v.State == "queued" || v.State == "waiting" {
|
||||
v.State = "cancelled"
|
||||
publish(g, m, v)
|
||||
}
|
||||
}
|
||||
m.Mail = nil
|
||||
}
|
||||
settle(g)
|
||||
}
|
||||
|
||||
// Compact drops bulky history from a terminal group.
|
||||
func (r *Runtime) Compact(ctx context.Context, s Scope) error {
|
||||
return r.Store.Change(ctx, s, func(g *Group) error {
|
||||
if g.Status != "completed" && g.Status != "cancelled" {
|
||||
return nil
|
||||
}
|
||||
compactClosed(g)
|
||||
return nil
|
||||
})
|
||||
}
|
||||
|
||||
func closeForHistoryLimit(g *Group) {
|
||||
if g.Status == "active" {
|
||||
cancelGroup(g)
|
||||
}
|
||||
}
|
||||
|
||||
// compactedResult keeps FINAL_ANSWER envelopes decodable after compaction.
|
||||
const compactedResult = `{"result":{"error":"collaboration history limit reached; ` +
|
||||
`the complete result is in the child conversation"}}`
|
||||
|
||||
// compactClosed drops bulky history from a group that no longer runs model
|
||||
// turns. Child conversations retain the complete transcripts.
|
||||
func compactClosed(g *Group) {
|
||||
g.ParentWait = nil
|
||||
for _, m := range g.Members {
|
||||
m.Mail = nil
|
||||
for _, v := range m.Runs {
|
||||
v.Result.Answer, v.Result.Evidence = "", ""
|
||||
v.Query = truncate(v.Query, 2000)
|
||||
}
|
||||
}
|
||||
for i := range g.Events {
|
||||
e := &g.Events[i]
|
||||
if len(e.Content) <= 4096 {
|
||||
continue
|
||||
}
|
||||
if strings.HasPrefix(e.Content, `{"result"`) {
|
||||
e.Content = compactedResult
|
||||
} else {
|
||||
e.Content = truncate(e.Content, 2000)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func settle(g *Group) {
|
||||
if g.Status != "cancelling" || g.ParentClosePending {
|
||||
return
|
||||
}
|
||||
for _, m := range g.Members {
|
||||
if active(current(m)) {
|
||||
return
|
||||
}
|
||||
for _, v := range m.Runs {
|
||||
if v.PromptID != "" {
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
g.Status = "cancelled"
|
||||
}
|
||||
|
||||
// Finish uses the last sequence actually observed by the parent, not a cursor
|
||||
// advanced by a background delivery worker. A racing result prevents completion.
|
||||
func (r *Runtime) Finish(ctx context.Context, s Scope, observed int64) (bool, error) {
|
||||
finished := false
|
||||
err := r.Store.Change(ctx, s, func(g *Group) error {
|
||||
finished = false
|
||||
if g.Status != "active" {
|
||||
return ErrClosed
|
||||
}
|
||||
if g.NextSequence != observed {
|
||||
return nil
|
||||
}
|
||||
for _, m := range g.Members {
|
||||
if active(current(m)) {
|
||||
return nil
|
||||
}
|
||||
for _, v := range m.Runs {
|
||||
if v.CancelRequested && v.PromptID != "" {
|
||||
return nil
|
||||
}
|
||||
}
|
||||
}
|
||||
g.Status = "completed"
|
||||
g.ParentWait = nil
|
||||
finished = true
|
||||
return nil
|
||||
})
|
||||
return finished, err
|
||||
}
|
||||
|
||||
// Wait waits for an event newer than the supplied mailbox sequence.
|
||||
func (r *Runtime) Wait(ctx context.Context, s Scope, after int64, d time.Duration) (bool, error) {
|
||||
deadline := time.NewTimer(d)
|
||||
defer deadline.Stop()
|
||||
tick := time.NewTicker(r.Poll)
|
||||
defer tick.Stop()
|
||||
for {
|
||||
g, err := r.Store.Read(ctx, s)
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
if g.Status != "active" {
|
||||
return false, ErrClosed
|
||||
}
|
||||
for _, evt := range g.Events {
|
||||
if evt.Sequence > after {
|
||||
return true, nil
|
||||
}
|
||||
}
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return false, ctx.Err()
|
||||
case <-deadline.C:
|
||||
return false, nil
|
||||
case <-tick.C:
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Inbox retains mail for snapshot reconstruction, but durably acknowledges its
|
||||
// delivery before execution. A panic or failed approval continuation must never
|
||||
// turn already delivered guidance into an automatic new execution.
|
||||
func (r *Runtime) Inbox(ctx context.Context, w Work, after int64) ([]Event, error) {
|
||||
g, err := r.Store.Read(ctx, w.Scope)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
m, err := member(g, w.Member.ID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
hasMail := false
|
||||
for _, e := range m.Mail {
|
||||
if e.Sequence > after {
|
||||
hasMail = true
|
||||
break
|
||||
}
|
||||
}
|
||||
if !hasMail {
|
||||
return nil, nil
|
||||
}
|
||||
var out []Event
|
||||
err = r.Store.Change(ctx, w.Scope, func(g *Group) error {
|
||||
out = nil
|
||||
m, err := member(g, w.Member.ID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
v := current(m)
|
||||
if v.ID != w.Run.ID || v.Owner != w.Run.Owner || v.State != "running" || time.Now().After(v.Lease) {
|
||||
return ErrConflict
|
||||
}
|
||||
if g.Status != "active" || v.CancelRequested {
|
||||
return ErrClosed
|
||||
}
|
||||
for _, e := range m.Mail {
|
||||
if e.Sequence > after {
|
||||
out = append(out, e)
|
||||
v.DeliveredSequence = max(v.DeliveredSequence, e.Sequence)
|
||||
}
|
||||
}
|
||||
return nil
|
||||
})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
// Start starts the scheduling and recovery loop once.
|
||||
func (r *Runtime) Start(ctx context.Context) {
|
||||
r.mu.Lock()
|
||||
defer r.mu.Unlock()
|
||||
if r.cancel != nil {
|
||||
return
|
||||
}
|
||||
ctx, r.cancel = context.WithCancel(ctx)
|
||||
r.done = make(chan struct{})
|
||||
go func() {
|
||||
defer close(r.done)
|
||||
tick := time.NewTicker(r.Poll)
|
||||
defer tick.Stop()
|
||||
var lastPrune time.Time
|
||||
for {
|
||||
r.Tick(ctx)
|
||||
if r.Prune != nil && r.PruneInterval > 0 && time.Since(lastPrune) >= r.PruneInterval {
|
||||
lastPrune = time.Now()
|
||||
if err := r.Prune(ctx); err != nil && ctx.Err() == nil {
|
||||
logger.Warnf(ctx, "Collaboration prune failed: %v", err)
|
||||
}
|
||||
}
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
r.workers.Wait()
|
||||
return
|
||||
case <-tick.C:
|
||||
}
|
||||
}
|
||||
}()
|
||||
}
|
||||
|
||||
// Stop cancels scheduling and waits for workers to finish.
|
||||
func (r *Runtime) Stop(ctx context.Context) error {
|
||||
r.mu.Lock()
|
||||
cancel, done := r.cancel, r.done
|
||||
r.mu.Unlock()
|
||||
if cancel == nil {
|
||||
return nil
|
||||
}
|
||||
cancel()
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return ctx.Err()
|
||||
case <-done:
|
||||
return nil
|
||||
}
|
||||
}
|
||||
|
||||
// Tick is also the restart recovery path. Never replay an uncertain running
|
||||
// turn: expire its lease into needs_attention. Queued work is safe to claim.
|
||||
func (r *Runtime) Tick(ctx context.Context) {
|
||||
scopes, err := r.Store.Pending(ctx)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
for _, s := range scopes {
|
||||
if ctx.Err() != nil {
|
||||
return
|
||||
}
|
||||
if r.Reconcile != nil {
|
||||
if err := r.Reconcile(ctx, s); err != nil {
|
||||
logger.Warnf(ctx, "Collaboration %s reconciliation failed: %v", s.ID, err)
|
||||
continue
|
||||
}
|
||||
}
|
||||
r.wakeParent(ctx, s)
|
||||
capacity := -1
|
||||
if r.MaxRunning > 0 {
|
||||
capacity = max(r.MaxRunning-int(r.running.Load()), 0)
|
||||
}
|
||||
var work []Work
|
||||
err = r.Store.Change(ctx, s, func(g *Group) error {
|
||||
work = nil
|
||||
now := time.Now()
|
||||
running := 0
|
||||
if now.After(g.Deadline) && g.Status == "active" {
|
||||
g.Status = "cancelling"
|
||||
g.ParentClosePending = r.WakeParent != nil && g.ParentMessageID != ""
|
||||
g.ParentWait = nil
|
||||
for _, m := range g.Members {
|
||||
current(m).CancelRequested = true
|
||||
}
|
||||
}
|
||||
for _, m := range g.Members {
|
||||
v := current(m)
|
||||
if v.State == "running" && now.After(v.Lease) {
|
||||
v.State = "needs_attention"
|
||||
v.Result.Error = "executor lease expired; execution was not replayed"
|
||||
publish(g, m, v)
|
||||
}
|
||||
if v.State == "running" {
|
||||
running++
|
||||
}
|
||||
}
|
||||
for _, m := range g.Members {
|
||||
v := current(m)
|
||||
if v.State == "waiting" && (g.Status != "active" || v.CancelRequested) {
|
||||
v.State = "cancelled"
|
||||
publish(g, m, v)
|
||||
}
|
||||
if v.State != "queued" {
|
||||
continue
|
||||
}
|
||||
if g.Status != "active" || v.CancelRequested {
|
||||
v.State = "cancelled"
|
||||
publish(g, m, v)
|
||||
continue
|
||||
}
|
||||
if running >= r.Concurrency || len(work) == capacity {
|
||||
continue
|
||||
}
|
||||
v.State = "running"
|
||||
v.Owner = uuid.NewString()
|
||||
v.Lease = now.Add(r.Lease)
|
||||
touchDeadline(g, now)
|
||||
v.Attempt++
|
||||
running++
|
||||
copyMember := *m
|
||||
copyMember.Runs = nil
|
||||
copyMember.Mail = nil
|
||||
work = append(work, Work{s, copyMember, *v})
|
||||
}
|
||||
settle(g)
|
||||
return nil
|
||||
})
|
||||
if err != nil {
|
||||
continue
|
||||
}
|
||||
for _, w := range work {
|
||||
r.workers.Add(1)
|
||||
r.running.Add(1)
|
||||
go func() {
|
||||
defer r.workers.Done()
|
||||
defer r.running.Add(-1)
|
||||
r.execute(ctx, w)
|
||||
}()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (r *Runtime) execute(serverCtx context.Context, w Work) {
|
||||
ctx, cancel := context.WithCancel(serverCtx)
|
||||
defer cancel()
|
||||
heartbeatDone := make(chan struct{})
|
||||
stopHeartbeat := make(chan struct{})
|
||||
go func() {
|
||||
defer close(heartbeatDone)
|
||||
tick := time.NewTicker(r.heartbeatInterval())
|
||||
defer tick.Stop()
|
||||
lease := w.Run.Lease
|
||||
for {
|
||||
select {
|
||||
case <-stopHeartbeat:
|
||||
return
|
||||
case <-ctx.Done():
|
||||
return
|
||||
case <-tick.C:
|
||||
stop := false
|
||||
err := r.Store.Change(ctx, w.Scope, func(g *Group) error {
|
||||
m, e := member(g, w.Member.ID)
|
||||
if e != nil {
|
||||
return e
|
||||
}
|
||||
v := current(m)
|
||||
if v.ID != w.Run.ID || v.Owner != w.Run.Owner || v.State != "running" || time.Now().After(v.Lease) {
|
||||
return ErrConflict
|
||||
}
|
||||
if g.Status != "active" || v.CancelRequested {
|
||||
stop = true
|
||||
}
|
||||
now := time.Now()
|
||||
if r.renewalDue(v.Lease, now) {
|
||||
v.Lease = now.Add(r.Lease)
|
||||
touchDeadline(g, now)
|
||||
}
|
||||
lease = v.Lease
|
||||
return nil
|
||||
})
|
||||
// A transient store error is retried while the lease still fences
|
||||
// this owner; fencing errors and cancellation stop the run.
|
||||
if err != nil && !isFenceError(err) && time.Now().Before(lease) && ctx.Err() == nil {
|
||||
continue
|
||||
}
|
||||
if err != nil || stop {
|
||||
cancel()
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
}()
|
||||
result, err := func() (out Result, err error) {
|
||||
defer func() {
|
||||
if p := recover(); p != nil {
|
||||
err = fmt.Errorf("agent executor panicked: %v", p)
|
||||
}
|
||||
}()
|
||||
if r.Run == nil {
|
||||
return out, errors.New("executor is unavailable")
|
||||
}
|
||||
return r.Run(ctx, w)
|
||||
}()
|
||||
close(stopHeartbeat)
|
||||
<-heartbeatDone
|
||||
if serverCtx.Err() != nil {
|
||||
return
|
||||
} // uncertain in-flight work is fenced by its lease
|
||||
finishCtx, finishCancel := context.WithTimeout(context.Background(), 5*time.Second)
|
||||
defer finishCancel()
|
||||
commitErr := r.Store.Change(finishCtx, w.Scope, func(g *Group) error {
|
||||
m, e := member(g, w.Member.ID)
|
||||
if e != nil {
|
||||
return e
|
||||
}
|
||||
v := current(m)
|
||||
if v.ID != w.Run.ID || v.Owner != w.Run.Owner || v.State != "running" || time.Now().After(v.Lease) {
|
||||
return ErrConflict
|
||||
}
|
||||
if result.Suspended && err == nil && g.Status == "active" && !v.CancelRequested && v.PromptID != "" {
|
||||
v.State = "waiting"
|
||||
v.Owner = ""
|
||||
touchDeadline(g, time.Now())
|
||||
publishPromptState(g, m, v, "waiting")
|
||||
return nil
|
||||
}
|
||||
result.ConsumedSequence = max(result.ConsumedSequence, v.DeliveredSequence)
|
||||
v.Result = result
|
||||
v.Result.Error = truncate(v.Result.Error, 1000)
|
||||
v.State = "succeeded"
|
||||
if result.Truncated {
|
||||
v.State = "failed"
|
||||
v.Result.Error = "Child answer reached its output limit; " +
|
||||
"the attached answer is partial, not a complete deliverable."
|
||||
}
|
||||
if err != nil {
|
||||
v.State = "failed"
|
||||
v.Result.Error = truncate(err.Error(), 1000)
|
||||
}
|
||||
if v.CancelRequested || g.Status != "active" {
|
||||
v.State = "interrupted"
|
||||
if g.Status != "active" {
|
||||
v.State = "cancelled"
|
||||
}
|
||||
}
|
||||
publish(g, m, v)
|
||||
// The published event is the only reader of the answer; the complete text
|
||||
// also stays in the child conversation. Do not store it twice.
|
||||
v.Result.Answer = ""
|
||||
// A followup accepted at the finishing boundary must have a consumer.
|
||||
var followups []string
|
||||
for _, mail := range m.Mail {
|
||||
if mail.Kind == "followup" && mail.RunID == v.ID &&
|
||||
mail.Sequence > result.ConsumedSequence {
|
||||
followups = append(followups, mail.Content)
|
||||
}
|
||||
}
|
||||
if len(followups) > 0 && g.Status == "active" && !v.CancelRequested && len(m.Runs) < 8 {
|
||||
m.Runs = append(m.Runs, &Run{ID: uuid.NewString(), State: "queued", Query: strings.Join(followups, "\n\n")})
|
||||
}
|
||||
// Plain messages remain available to subsequent turns. Followup messages
|
||||
// have now been converted into work and must not create another turn.
|
||||
kept := m.Mail[:0]
|
||||
for _, mail := range m.Mail {
|
||||
if mail.Kind != "followup" && mail.Sequence > result.ConsumedSequence {
|
||||
kept = append(kept, mail)
|
||||
}
|
||||
}
|
||||
m.Mail = kept
|
||||
settle(g)
|
||||
return nil
|
||||
})
|
||||
if commitErr != nil {
|
||||
logger.Warnf(finishCtx, "Collaboration %s run %s result commit failed: %v", w.Scope.ID, w.Run.ID, commitErr)
|
||||
}
|
||||
}
|
||||
|
||||
func truncate(s string, n int) string {
|
||||
r := []rune(s)
|
||||
if len(r) > n {
|
||||
return string(r[:n]) + "\n[truncated; full result is in the child conversation]"
|
||||
}
|
||||
return s
|
||||
}
|
||||
|
||||
// CheckOwner validates that a child execution still owns its live lease.
|
||||
func (r *Runtime) CheckOwner(ctx context.Context, w Work) error {
|
||||
g, err := r.Store.Read(ctx, w.Scope)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
m, err := member(g, w.Member.ID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
v := current(m)
|
||||
if g.Status != "active" || v.State != "running" || v.CancelRequested || v.ID != w.Run.ID ||
|
||||
v.Owner != w.Run.Owner ||
|
||||
time.Now().After(v.Lease) {
|
||||
return ErrConflict
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func currentTurnMemberCount(g *Group) int {
|
||||
count := 0
|
||||
for _, m := range g.Members {
|
||||
if !m.Inherited {
|
||||
count++
|
||||
}
|
||||
}
|
||||
return count
|
||||
}
|
||||
|
|
@ -0,0 +1,840 @@
|
|||
package collaboration
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"sync"
|
||||
"sync/atomic"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
"github.com/stretchr/testify/require"
|
||||
"gorm.io/driver/sqlite"
|
||||
"gorm.io/gorm"
|
||||
"gorm.io/gorm/logger"
|
||||
)
|
||||
|
||||
func testStore(t *testing.T) (*Store, Scope) {
|
||||
t.Helper()
|
||||
db, err := gorm.Open(
|
||||
sqlite.Open(filepath.Join(t.TempDir(), "work.db")+"?_busy_timeout=5000&_journal_mode=WAL"),
|
||||
&gorm.Config{Logger: logger.Default.LogMode(logger.Silent)},
|
||||
)
|
||||
require.NoError(t, err)
|
||||
sql, err := db.DB()
|
||||
require.NoError(t, err)
|
||||
t.Cleanup(func() { _ = sql.Close() })
|
||||
require.NoError(t, db.AutoMigrate(&Record{}))
|
||||
require.NoError(
|
||||
t,
|
||||
db.Exec(
|
||||
"CREATE UNIQUE INDEX active_parent ON agent_collaborations(tenant_id,user_id,sess"+
|
||||
"ion_id) WHERE status IN ('active','cancelling')",
|
||||
).Error,
|
||||
)
|
||||
store := NewStore(db)
|
||||
scope := Scope{7, "u", "parent", uuid.NewString()}
|
||||
require.NoError(t, store.Ensure(context.Background(), scope))
|
||||
return store, scope
|
||||
}
|
||||
|
||||
func read(t *testing.T, s *Store, scope Scope) *Group {
|
||||
t.Helper()
|
||||
g, err := s.Read(context.Background(), scope)
|
||||
require.NoError(t, err)
|
||||
return g
|
||||
}
|
||||
|
||||
func start(t *testing.T, r *Runtime) {
|
||||
t.Helper()
|
||||
r.Poll = 5 * time.Millisecond
|
||||
r.Lease = time.Second
|
||||
r.Start(context.Background())
|
||||
t.Cleanup(func() {
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)
|
||||
defer cancel()
|
||||
require.NoError(t, r.Stop(ctx))
|
||||
})
|
||||
}
|
||||
|
||||
func eventually(t *testing.T, fn func() bool) {
|
||||
t.Helper()
|
||||
require.Eventually(t, fn, 4*time.Second, 5*time.Millisecond)
|
||||
}
|
||||
|
||||
func TestConcurrentSpawnIsIdempotentAndScoped(t *testing.T) {
|
||||
s, scope := testStore(t)
|
||||
r := New(s, nil)
|
||||
ctx := context.Background()
|
||||
var wg sync.WaitGroup
|
||||
ids := make(chan string, 24)
|
||||
errs := make(chan error, 24)
|
||||
for range 24 {
|
||||
wg.Add(1)
|
||||
go func() {
|
||||
defer wg.Done()
|
||||
id, err := r.Spawn(ctx, scope, "same-call", "research", "agent", "{}", "question")
|
||||
ids <- id
|
||||
errs <- err
|
||||
}()
|
||||
}
|
||||
wg.Wait()
|
||||
close(ids)
|
||||
close(errs)
|
||||
for err := range errs {
|
||||
require.NoError(t, err)
|
||||
}
|
||||
id := ""
|
||||
for v := range ids {
|
||||
if id == "" {
|
||||
id = v
|
||||
}
|
||||
require.Equal(t, id, v)
|
||||
}
|
||||
require.Len(t, read(t, s, scope).Members, 1)
|
||||
other := scope
|
||||
other.UserID = "other"
|
||||
_, err := r.Spawn(ctx, other, "call2", "other", "a", "{}", "q")
|
||||
require.ErrorIs(t, err, ErrScope)
|
||||
other = scope
|
||||
other.TenantID++
|
||||
require.ErrorIs(t, s.Ensure(ctx, other), ErrScope)
|
||||
}
|
||||
|
||||
func TestTwoSchedulersShareConcurrencyAndNeverDoubleExecute(t *testing.T) {
|
||||
s, scope := testStore(t)
|
||||
ctx := context.Background()
|
||||
var live, peak, total atomic.Int32
|
||||
release := make(chan struct{})
|
||||
defer close(release)
|
||||
seen := sync.Map{}
|
||||
runner := func(ctx context.Context, w Work) (Result, error) {
|
||||
if _, loaded := seen.LoadOrStore(w.Run.ID, true); loaded {
|
||||
return Result{}, fmt.Errorf("duplicate run")
|
||||
}
|
||||
n := live.Add(1)
|
||||
defer live.Add(-1)
|
||||
for {
|
||||
p := peak.Load()
|
||||
if n <= p || peak.CompareAndSwap(p, n) {
|
||||
break
|
||||
}
|
||||
}
|
||||
total.Add(1)
|
||||
select {
|
||||
case <-release:
|
||||
return Result{Answer: "ok"}, nil
|
||||
case <-ctx.Done():
|
||||
return Result{}, ctx.Err()
|
||||
}
|
||||
}
|
||||
r1, r2 := New(s, runner), New(NewStore(s.db), runner)
|
||||
for i := range 8 {
|
||||
_, err := r1.Spawn(ctx, scope, fmt.Sprint(i), fmt.Sprintf("task_%d", i), "a", "{}", "q")
|
||||
require.NoError(t, err)
|
||||
}
|
||||
start(t, r1)
|
||||
start(t, r2)
|
||||
eventually(t, func() bool { return total.Load() == 3 })
|
||||
require.EqualValues(t, 3, peak.Load())
|
||||
require.NoError(t, r1.Cancel(ctx, scope))
|
||||
eventually(t, func() bool { return read(t, s, scope).Status == "cancelled" })
|
||||
require.EqualValues(t, 3, total.Load())
|
||||
}
|
||||
|
||||
func TestIdleMessageDoesNotRunFollowupDoesAndStaleInterruptCannotCancelIt(t *testing.T) {
|
||||
s, scope := testStore(t)
|
||||
var count atomic.Int32
|
||||
started := make(chan Work, 2)
|
||||
release := make(chan struct{})
|
||||
defer close(release)
|
||||
r := New(s, func(ctx context.Context, w Work) (Result, error) {
|
||||
n := count.Add(1)
|
||||
started <- w
|
||||
if n == 2 {
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return Result{}, ctx.Err()
|
||||
case <-release:
|
||||
}
|
||||
}
|
||||
return Result{Answer: "done"}, nil
|
||||
})
|
||||
id, err := r.Spawn(context.Background(), scope, "spawn", "one", "a", "{}", "q")
|
||||
require.NoError(t, err)
|
||||
start(t, r)
|
||||
first := <-started
|
||||
eventually(t, func() bool { return current(read(t, s, scope).Members[0]).State == "succeeded" })
|
||||
_, err = r.Send(context.Background(), scope, "msg", id, "queued for later", "", false)
|
||||
require.NoError(t, err)
|
||||
r.Tick(context.Background())
|
||||
require.EqualValues(t, 1, count.Load())
|
||||
_, err = r.Send(context.Background(), scope, "follow", id, "continue", first.Run.ID, true)
|
||||
require.NoError(t, err)
|
||||
second := <-started
|
||||
require.NotEqual(t, first.Run.ID, second.Run.ID)
|
||||
require.ErrorIs(t, r.Interrupt(context.Background(), scope, id, first.Run.ID), ErrConflict)
|
||||
require.NoError(t, r.Interrupt(context.Background(), scope, id, second.Run.ID))
|
||||
eventually(t, func() bool { return current(read(t, s, scope).Members[0]).State == "interrupted" })
|
||||
}
|
||||
|
||||
func TestFollowupAtFinishIsNeitherLostNorProcessedTwice(t *testing.T) {
|
||||
for _, consume := range []bool{false, true} {
|
||||
t.Run(fmt.Sprint(consume), func(t *testing.T) {
|
||||
s, scope := testStore(t)
|
||||
entered, release := make(chan struct{}), make(chan struct{})
|
||||
var calls atomic.Int32
|
||||
var r *Runtime
|
||||
r = New(s, func(ctx context.Context, w Work) (Result, error) {
|
||||
n := calls.Add(1)
|
||||
result := Result{Answer: "ok"}
|
||||
if n == 1 {
|
||||
close(entered)
|
||||
select {
|
||||
case <-release:
|
||||
case <-ctx.Done():
|
||||
return result, ctx.Err()
|
||||
}
|
||||
if consume {
|
||||
mail, err := r.Inbox(ctx, w, 0)
|
||||
if err != nil {
|
||||
return result, err
|
||||
}
|
||||
for _, m := range mail {
|
||||
result.ConsumedSequence = max(result.ConsumedSequence, m.Sequence)
|
||||
}
|
||||
}
|
||||
}
|
||||
return result, nil
|
||||
})
|
||||
id, err := r.Spawn(context.Background(), scope, "spawn", "one", "a", "{}", "q")
|
||||
require.NoError(t, err)
|
||||
start(t, r)
|
||||
<-entered
|
||||
_, err = r.Send(context.Background(), scope, "follow", id, "more work", "", true)
|
||||
require.NoError(t, err)
|
||||
close(release)
|
||||
want := 1
|
||||
if !consume {
|
||||
want = 2
|
||||
}
|
||||
eventually(t, func() bool {
|
||||
g := read(t, s, scope)
|
||||
return len(g.Members[0].Runs) == want && current(g.Members[0]).State == "succeeded"
|
||||
})
|
||||
r.Tick(context.Background())
|
||||
require.EqualValues(t, want, calls.Load())
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestCancellationFencesLateSuccessAndPreventsResurrection(t *testing.T) {
|
||||
s, scope := testStore(t)
|
||||
entered, release := make(chan struct{}), make(chan struct{})
|
||||
r := New(s, func(_ context.Context, _ Work) (Result, error) {
|
||||
close(entered)
|
||||
<-release
|
||||
return Result{Answer: "late success"}, nil
|
||||
})
|
||||
id, err := r.Spawn(context.Background(), scope, "spawn", "one", "a", "{}", "q")
|
||||
require.NoError(t, err)
|
||||
start(t, r)
|
||||
<-entered
|
||||
require.NoError(t, r.Cancel(context.Background(), scope))
|
||||
close(release)
|
||||
eventually(t, func() bool { return read(t, s, scope).Status == "cancelled" })
|
||||
g := read(t, s, scope)
|
||||
require.Equal(t, "cancelled", current(g.Members[0]).State)
|
||||
require.Len(t, g.Events, 1)
|
||||
_, err = r.Send(context.Background(), scope, "follow", id, "continue", "", true)
|
||||
require.ErrorIs(t, err, ErrClosed)
|
||||
_, err = r.Spawn(context.Background(), scope, "new", "new", "a", "{}", "q")
|
||||
require.ErrorIs(t, err, ErrClosed)
|
||||
}
|
||||
|
||||
func TestRestartClaimsQueuedButDoesNotReplayUncertainExecution(t *testing.T) {
|
||||
s, scope := testStore(t)
|
||||
ctx := context.Background()
|
||||
r := New(s, nil)
|
||||
_, err := r.Spawn(ctx, scope, "one", "one", "a", "{}", "q")
|
||||
require.NoError(t, err)
|
||||
_, err = r.Spawn(ctx, scope, "two", "two", "a", "{}", "q")
|
||||
require.NoError(t, err)
|
||||
require.NoError(t, s.Change(ctx, scope, func(g *Group) error {
|
||||
v := current(g.Members[0])
|
||||
v.State = "running"
|
||||
v.Owner = "dead-worker"
|
||||
v.Lease = time.Now().Add(-time.Second)
|
||||
return nil
|
||||
}))
|
||||
var calls atomic.Int32
|
||||
restarted := New(NewStore(s.db), func(_ context.Context, _ Work) (Result, error) {
|
||||
calls.Add(1)
|
||||
return Result{Answer: "recovered queue"}, nil
|
||||
})
|
||||
start(t, restarted)
|
||||
eventually(t, func() bool { g := read(t, s, scope); return current(g.Members[1]).State == "succeeded" })
|
||||
g := read(t, s, scope)
|
||||
require.Equal(t, "needs_attention", current(g.Members[0]).State)
|
||||
require.EqualValues(t, 1, calls.Load())
|
||||
_, err = restarted.Send(ctx, scope, "follow", "one", "retry", "", true)
|
||||
require.Error(t, err)
|
||||
}
|
||||
|
||||
func TestWaitTimeoutCancellationAndPreexistingEvent(t *testing.T) {
|
||||
s, scope := testStore(t)
|
||||
r := New(s, nil)
|
||||
r.Poll = time.Millisecond
|
||||
ctx := context.Background()
|
||||
updated, err := r.Wait(ctx, scope, 0, 5*time.Millisecond)
|
||||
require.NoError(t, err)
|
||||
require.False(t, updated)
|
||||
cancelled, cancel := context.WithCancel(ctx)
|
||||
cancel()
|
||||
_, err = r.Wait(cancelled, scope, 0, time.Second)
|
||||
require.ErrorIs(t, err, context.Canceled)
|
||||
_, err = r.Spawn(ctx, scope, "spawn", "one", "a", "{}", "q")
|
||||
require.NoError(t, err)
|
||||
require.NoError(t, r.Interrupt(ctx, scope, "one", ""))
|
||||
updated, err = r.Wait(ctx, scope, 0, time.Second)
|
||||
require.NoError(t, err)
|
||||
require.True(t, updated)
|
||||
b := &Binding{Runtime: r, Scope: scope}
|
||||
events, err := b.BeforeFinish(ctx)
|
||||
require.NoError(t, err)
|
||||
require.Len(t, events, 1)
|
||||
require.Equal(t, "active", read(t, s, scope).Status)
|
||||
events, err = b.BeforeFinish(ctx)
|
||||
require.NoError(t, err)
|
||||
require.Empty(t, events)
|
||||
require.Equal(t, "completed", read(t, s, scope).Status)
|
||||
}
|
||||
|
||||
func TestExpiredWorkerCannotCommitOrSendMessages(t *testing.T) {
|
||||
s, scope := testStore(t)
|
||||
ctx := context.Background()
|
||||
entered, release := make(chan struct{}), make(chan struct{})
|
||||
var work Work
|
||||
r := New(s, func(_ context.Context, w Work) (Result, error) {
|
||||
work = w
|
||||
close(entered)
|
||||
<-release
|
||||
return Result{Answer: "stale"}, nil
|
||||
})
|
||||
_, err := r.Spawn(ctx, scope, "spawn", "one", "a", "{}", "q")
|
||||
require.NoError(t, err)
|
||||
r.Poll = time.Hour
|
||||
r.Lease = time.Hour
|
||||
r.Tick(ctx)
|
||||
<-entered
|
||||
require.NoError(
|
||||
t,
|
||||
s.Change(
|
||||
ctx,
|
||||
scope,
|
||||
func(g *Group) error { current(g.Members[0]).Lease = time.Now().Add(-time.Second); return nil },
|
||||
),
|
||||
)
|
||||
r.Tick(ctx)
|
||||
b := &Binding{Runtime: r, Scope: scope, Child: &work}
|
||||
require.ErrorIs(t, b.MessageParent(ctx, "msg", "stale message"), ErrConflict)
|
||||
close(release)
|
||||
r.workers.Wait()
|
||||
g := read(t, s, scope)
|
||||
require.Equal(t, "needs_attention", current(g.Members[0]).State)
|
||||
require.Len(t, g.Events, 1)
|
||||
require.NotContains(t, g.Events[0].Content, "stale")
|
||||
}
|
||||
|
||||
func TestParentRecoveryFencesOldEngineAndPreservesResults(t *testing.T) {
|
||||
s, scope := testStore(t)
|
||||
r := New(s, nil)
|
||||
ctx := context.Background()
|
||||
first, err := r.AcquireParent(ctx, scope)
|
||||
require.NoError(t, err)
|
||||
_, err = r.Spawn(first.Context(ctx), scope, "spawn", "one", "a", "{}", "q")
|
||||
require.NoError(t, err)
|
||||
require.NoError(t, r.Interrupt(ctx, scope, "one", ""))
|
||||
next := scope
|
||||
next.ID = "next-message"
|
||||
_, err = r.AcquireParent(ctx, next)
|
||||
require.Error(t, err, "live parent must not be stolen")
|
||||
require.NoError(t, s.Change(ctx, scope, func(g *Group) error {
|
||||
g.ParentLease = time.Now().Add(-time.Second)
|
||||
g.RootQuery = "original user goal"
|
||||
return nil
|
||||
}))
|
||||
second, err := r.AcquireParent(ctx, next)
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, scope.ID, second.Scope.ID)
|
||||
_, err = r.Spawn(first.Context(ctx), scope, "stale", "stale", "a", "{}", "q")
|
||||
require.ErrorIs(t, err, ErrConflict)
|
||||
first.End(false)
|
||||
require.Equal(t, "active", read(t, s, scope).Status, "old cleanup must not cancel recovered task")
|
||||
events, err := second.Poll(ctx)
|
||||
require.NoError(t, err)
|
||||
require.Len(t, events, 2)
|
||||
require.Equal(t, "recovered", events[0].Kind)
|
||||
require.Contains(t, events[0].Content, "original user goal")
|
||||
second.End(false)
|
||||
require.Equal(t, "cancelled", read(t, s, scope).Status)
|
||||
third, err := r.AcquireParent(ctx, next)
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, next.ID, third.Scope.ID)
|
||||
require.NotEqual(t, scope.ID, third.Scope.ID, "a cancelled group must never revive")
|
||||
}
|
||||
|
||||
func TestDurableStopAfterParentCrashAndStaleStopAfterRecovery(t *testing.T) {
|
||||
s, scope := testStore(t)
|
||||
r := New(s, nil)
|
||||
ctx := context.Background()
|
||||
first, err := r.AcquireParent(ctx, scope)
|
||||
require.NoError(t, err)
|
||||
_, err = r.Spawn(first.Context(ctx), scope, "spawn", "one", "a", "{}", "q")
|
||||
require.NoError(t, err)
|
||||
require.NoError(
|
||||
t,
|
||||
s.Change(ctx, scope, func(g *Group) error { g.ParentLease = time.Now().Add(-time.Second); return nil }),
|
||||
)
|
||||
next := scope
|
||||
next.ID = "new-parent-message"
|
||||
_, err = r.AcquireParent(ctx, next)
|
||||
require.NoError(t, err)
|
||||
require.NoError(t, r.CancelMessage(ctx, scope, scope.ID))
|
||||
require.Equal(t, "active", read(t, s, scope).Status)
|
||||
require.NoError(t, r.CancelMessage(ctx, scope, next.ID))
|
||||
require.Equal(t, "cancelled", read(t, s, scope).Status)
|
||||
var calls atomic.Int32
|
||||
restarted := New(s, func(context.Context, Work) (Result, error) { calls.Add(1); return Result{}, nil })
|
||||
restarted.Tick(ctx)
|
||||
require.Zero(t, calls.Load())
|
||||
}
|
||||
|
||||
func TestInputBudgetCannotPreventCancellation(t *testing.T) {
|
||||
s, scope := testStore(t)
|
||||
r := New(s, nil)
|
||||
ctx := context.Background()
|
||||
_, err := r.Spawn(ctx, scope, "spawn", "one", "a", "{}", "q")
|
||||
require.NoError(t, err)
|
||||
require.NoError(t, s.Change(ctx, scope, func(g *Group) error { g.InputBytes = 512 << 10; return nil }))
|
||||
_, err = r.Send(ctx, scope, "msg", "one", "more", "", false)
|
||||
require.ErrorContains(t, err, "budget")
|
||||
require.NoError(t, r.Cancel(ctx, scope))
|
||||
require.Equal(t, "cancelled", read(t, s, scope).Status)
|
||||
}
|
||||
|
||||
func TestFollowupCASRetryAfterCompletionAllocatesFreshRunID(t *testing.T) {
|
||||
s, scope := testStore(t)
|
||||
r := New(s, nil)
|
||||
ctx := context.Background()
|
||||
_, err := r.Spawn(ctx, scope, "spawn", "one", "a", "{}", "q")
|
||||
require.NoError(t, err)
|
||||
require.NoError(t, s.Change(ctx, scope, func(g *Group) error {
|
||||
v := current(g.Members[0])
|
||||
v.State = "running"
|
||||
v.Owner = "worker"
|
||||
v.Lease = time.Now().Add(time.Minute)
|
||||
return nil
|
||||
}))
|
||||
terminal := read(t, s, scope)
|
||||
oldRunID := current(terminal.Members[0]).ID
|
||||
current(terminal.Members[0]).State = "succeeded"
|
||||
payload, err := json.Marshal(terminal)
|
||||
require.NoError(t, err)
|
||||
// Force the exact CAS boundary: Send read running and prepared mail, but
|
||||
// the worker commits completion before that update reaches the database.
|
||||
var injected atomic.Bool
|
||||
require.NoError(t, s.db.Callback().Update().Before("gorm:update").Register("finish_during_send", func(tx *gorm.DB) {
|
||||
if injected.Swap(true) {
|
||||
return
|
||||
}
|
||||
if err := s.db.Exec("UPDATE agent_collaborations SET data = ?, version = version + 1 WHERE id = ?",
|
||||
string(payload),
|
||||
scope.ID).Error; err != nil {
|
||||
_ = tx.AddError(err)
|
||||
}
|
||||
}))
|
||||
id, err := r.Send(ctx, scope, "follow", "one", "continue", "", true)
|
||||
require.NoError(t, err)
|
||||
g := read(t, s, scope)
|
||||
require.Len(t, g.Members[0].Runs, 2)
|
||||
require.NotEqual(t, oldRunID, id)
|
||||
require.Equal(t, id, current(g.Members[0]).ID)
|
||||
}
|
||||
|
||||
func TestResultDeliveryPreservesLongAnswerAndPartialStatus(t *testing.T) {
|
||||
for _, partial := range []bool{false, true} {
|
||||
t.Run(fmt.Sprint(partial), func(t *testing.T) {
|
||||
s, scope := testStore(t)
|
||||
answer := strings.Repeat("带有引用的完整内容。", 1200) + "结尾:今天的信号"
|
||||
r := New(
|
||||
s,
|
||||
func(context.Context, Work) (Result, error) { return Result{Answer: answer, Truncated: partial}, nil },
|
||||
)
|
||||
_, err := r.Spawn(context.Background(), scope, "spawn", "report", "a", "{}", "q")
|
||||
require.NoError(t, err)
|
||||
start(t, r)
|
||||
eventually(t, func() bool { return !active(current(read(t, s, scope).Members[0])) })
|
||||
// Reopen the persisted store as a restarted parent would.
|
||||
b := &Binding{Runtime: New(NewStore(s.db), nil), Scope: scope}
|
||||
events, err := b.Poll(context.Background())
|
||||
require.NoError(t, err)
|
||||
require.Len(t, events, 1)
|
||||
var payload struct {
|
||||
Result Result `json:"result"`
|
||||
}
|
||||
require.NoError(t, json.Unmarshal([]byte(events[0].Content), &payload))
|
||||
require.Equal(t, answer, payload.Result.Answer)
|
||||
require.Equal(t, partial, payload.Result.Truncated)
|
||||
if partial {
|
||||
require.Equal(t, "failed", events[0].Kind)
|
||||
require.Contains(t, payload.Result.Error, "partial")
|
||||
} else {
|
||||
require.Equal(t, "succeeded", events[0].Kind)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestApprovalWaitingWakesModelOnceAfterRestart(t *testing.T) {
|
||||
s, scope := testStore(t)
|
||||
ctx := context.Background()
|
||||
r := New(s, nil)
|
||||
b, err := r.AcquireParent(ctx, scope)
|
||||
require.NoError(t, err)
|
||||
require.NoError(t, b.SaveWait(ctx, []byte("safe"), time.Now().Add(time.Hour)))
|
||||
require.NoError(t, s.Change(ctx, scope, func(g *Group) error {
|
||||
g.ParentLease = time.Time{}
|
||||
g.NextSequence = 1
|
||||
g.Events = []Event{{Sequence: 1, Kind: "waiting"}}
|
||||
return nil
|
||||
}))
|
||||
restarted := New(NewStore(s.db), nil)
|
||||
var calls atomic.Int32
|
||||
restarted.WakeParent = func(ctx context.Context, resumed *Binding, _ []byte) error {
|
||||
calls.Add(1)
|
||||
events, err := resumed.Poll(ctx)
|
||||
require.NoError(t, err)
|
||||
require.Len(t, events, 1)
|
||||
return resumed.SaveWait(ctx, []byte("safe"), time.Now().Add(time.Hour))
|
||||
}
|
||||
restarted.wakeParent(ctx, scope)
|
||||
restarted.workers.Wait()
|
||||
require.Equal(t, int32(1), calls.Load())
|
||||
updated, err := restarted.Wait(ctx, scope, 0, time.Millisecond)
|
||||
require.NoError(t, err)
|
||||
require.True(t, updated)
|
||||
polled := &Binding{Runtime: restarted, Scope: scope}
|
||||
events, err := polled.Poll(ctx)
|
||||
require.NoError(t, err)
|
||||
require.Len(t, events, 1)
|
||||
require.Equal(t, "waiting", events[0].Kind)
|
||||
require.Equal(t, int64(1), polled.Seen)
|
||||
events, err = polled.Poll(ctx)
|
||||
require.NoError(t, err)
|
||||
require.Empty(t, events)
|
||||
require.NoError(t, s.Change(ctx, scope, func(g *Group) error {
|
||||
g.ParentLease = time.Time{}
|
||||
return nil
|
||||
}))
|
||||
restarted.wakeParent(ctx, scope)
|
||||
restarted.workers.Wait()
|
||||
require.Equal(t, int32(1), calls.Load(), "consumed waiting state must not wake again")
|
||||
require.NoError(t, s.Change(ctx, scope, func(g *Group) error {
|
||||
g.NextSequence++
|
||||
g.Events = append(g.Events, Event{Sequence: g.NextSequence, Kind: "succeeded"})
|
||||
return nil
|
||||
}))
|
||||
restarted.wakeParent(ctx, scope)
|
||||
restarted.workers.Wait()
|
||||
require.Equal(t, int32(2), calls.Load())
|
||||
}
|
||||
|
||||
// Mix successful, failed, panicking and canceled children under two competing
|
||||
// schedulers. One child's failure/cancel must not consume a sibling's result or
|
||||
// strand queued work, and the parent may close only after consuming all events.
|
||||
func TestConcurrentMixedOutcomesDrainQueueAndDeliverEachRunOnce(t *testing.T) {
|
||||
s, scope := testStore(t)
|
||||
ctx := context.Background()
|
||||
release := make(chan struct{})
|
||||
var once sync.Once
|
||||
defer once.Do(func() { close(release) })
|
||||
var live, peak, total, duplicates atomic.Int32
|
||||
var seen sync.Map
|
||||
runner := func(_ context.Context, w Work) (Result, error) {
|
||||
if _, loaded := seen.LoadOrStore(w.Run.ID, true); loaded {
|
||||
duplicates.Add(1)
|
||||
}
|
||||
total.Add(1)
|
||||
n := live.Add(1)
|
||||
defer live.Add(-1)
|
||||
for {
|
||||
p := peak.Load()
|
||||
if n <= p || peak.CompareAndSwap(p, n) {
|
||||
break
|
||||
}
|
||||
}
|
||||
if w.Member.Name == "task_0" || w.Member.Name == "task_1" || w.Member.Name == "task_2" {
|
||||
<-release // deliberately allow task_2's result to arrive after interrupt
|
||||
}
|
||||
switch w.Member.Name {
|
||||
case "task_0":
|
||||
return Result{}, fmt.Errorf("isolated child failure")
|
||||
case "task_1":
|
||||
panic("isolated child panic")
|
||||
default:
|
||||
return Result{Answer: "result:" + w.Member.Name}, nil
|
||||
}
|
||||
}
|
||||
r1, r2 := New(s, runner), New(NewStore(s.db), runner)
|
||||
for i := range 8 {
|
||||
_, err := r1.Spawn(ctx, scope, fmt.Sprint(i), fmt.Sprintf("task_%d", i), "a", "{}", "read only")
|
||||
require.NoError(t, err)
|
||||
}
|
||||
start(t, r1)
|
||||
start(t, r2)
|
||||
eventually(t, func() bool { return total.Load() == 3 })
|
||||
require.EqualValues(t, 3, peak.Load())
|
||||
require.NoError(t, r1.Interrupt(ctx, scope, "task_2", ""))
|
||||
require.NoError(t, r2.Interrupt(ctx, scope, "task_7", ""))
|
||||
once.Do(func() { close(release) })
|
||||
eventually(t, func() bool {
|
||||
for _, m := range read(t, s, scope).Members {
|
||||
if active(current(m)) {
|
||||
return false
|
||||
}
|
||||
}
|
||||
return true
|
||||
})
|
||||
require.EqualValues(t, 7, total.Load(), "queued canceled child must never start")
|
||||
require.Zero(t, duplicates.Load())
|
||||
require.LessOrEqual(t, peak.Load(), int32(3))
|
||||
g := read(t, s, scope)
|
||||
want := []string{
|
||||
"failed",
|
||||
"failed",
|
||||
"interrupted",
|
||||
"succeeded",
|
||||
"succeeded",
|
||||
"succeeded",
|
||||
"succeeded",
|
||||
"interrupted",
|
||||
}
|
||||
for i, m := range g.Members {
|
||||
require.Equal(t, want[i], current(m).State, m.Name)
|
||||
require.Empty(t, current(m).Result.Answer, "the published event is the only answer copy")
|
||||
}
|
||||
answers := map[string]string{}
|
||||
for _, e := range g.Events {
|
||||
var payload struct {
|
||||
Result Result `json:"result"`
|
||||
}
|
||||
if e.Kind == "succeeded" && json.Unmarshal([]byte(e.Content), &payload) == nil {
|
||||
answers[e.From] = payload.Result.Answer
|
||||
}
|
||||
}
|
||||
for i, m := range g.Members {
|
||||
if want[i] == "succeeded" {
|
||||
require.Equal(t, "result:"+m.Name, answers[m.Name])
|
||||
}
|
||||
}
|
||||
parent := &Binding{Runtime: r1, Scope: scope}
|
||||
done, err := r1.Finish(ctx, scope, parent.Seen)
|
||||
require.NoError(t, err)
|
||||
require.False(t, done, "unread child outcomes prevent early parent completion")
|
||||
events, err := parent.Poll(ctx)
|
||||
require.NoError(t, err)
|
||||
require.Len(t, events, 8)
|
||||
unique := map[string]bool{}
|
||||
for _, e := range events {
|
||||
require.False(t, unique[e.From])
|
||||
unique[e.From] = true
|
||||
}
|
||||
events, err = parent.Poll(ctx)
|
||||
require.NoError(t, err)
|
||||
require.Empty(t, events)
|
||||
done, err = r1.Finish(ctx, scope, parent.Seen)
|
||||
require.NoError(t, err)
|
||||
require.True(t, done)
|
||||
// A fresh scheduler cannot replay already committed children.
|
||||
restarted := New(NewStore(s.db), runner)
|
||||
restarted.Tick(ctx)
|
||||
restarted.workers.Wait()
|
||||
require.EqualValues(t, 7, total.Load())
|
||||
}
|
||||
|
||||
// A failed model request after an external effect cannot authorize replay of
|
||||
// consumed guidance. Only genuinely new mail at the finishing boundary may run.
|
||||
func TestFailedRunDoesNotReplayConsumedFollowup(t *testing.T) {
|
||||
for _, failure := range []string{"error", "panic", "missing_result"} {
|
||||
for _, late := range []bool{false, true} {
|
||||
t.Run(fmt.Sprintf("%s/late=%t", failure, late), func(t *testing.T) {
|
||||
s, scope := testStore(t)
|
||||
ctx := t.Context()
|
||||
r := New(s, nil)
|
||||
id, err := r.Spawn(ctx, scope, "spawn", "child", "agent", "{}", "initial")
|
||||
require.NoError(t, err)
|
||||
_, err = r.Send(ctx, scope, "consumed", id, "COMPLETED_EXTERNAL_EFFECT", "", true)
|
||||
require.NoError(t, err)
|
||||
var effects atomic.Int32
|
||||
r.Run = func(ctx context.Context, w Work) (Result, error) {
|
||||
mail, inboxErr := r.Inbox(ctx, w, 0)
|
||||
if inboxErr != nil {
|
||||
return Result{}, inboxErr
|
||||
}
|
||||
require.Len(t, mail, 1)
|
||||
effects.Add(1)
|
||||
if late {
|
||||
_, sendErr := r.Send(ctx, scope, "late", id, "NEW_UNCONSUMED_TASK", "", true)
|
||||
if sendErr != nil {
|
||||
return Result{}, sendErr
|
||||
}
|
||||
}
|
||||
if failure == "panic" {
|
||||
panic("model adapter panic after external effect")
|
||||
}
|
||||
if failure == "missing_result" {
|
||||
return Result{}, fmt.Errorf("executor lost its result")
|
||||
}
|
||||
return Result{ConsumedSequence: mail[0].Sequence}, fmt.Errorf("later model request failed")
|
||||
}
|
||||
r.Tick(ctx)
|
||||
r.workers.Wait()
|
||||
g := read(t, s, scope)
|
||||
require.Equal(t, "failed", g.Members[0].Runs[0].State)
|
||||
wantRuns := 1
|
||||
if late {
|
||||
wantRuns = 2
|
||||
require.Equal(t, "NEW_UNCONSUMED_TASK", g.Members[0].Runs[1].Query)
|
||||
}
|
||||
require.Len(t, g.Members[0].Runs, wantRuns)
|
||||
var newCalls atomic.Int32
|
||||
restarted := New(NewStore(s.db), func(_ context.Context, w Work) (Result, error) {
|
||||
newCalls.Add(1)
|
||||
require.Equal(t, "NEW_UNCONSUMED_TASK", w.Run.Query)
|
||||
return Result{Answer: "new task completed"}, nil
|
||||
})
|
||||
for i := 0; i < 3; i++ {
|
||||
restarted.Tick(ctx)
|
||||
restarted.workers.Wait()
|
||||
}
|
||||
require.EqualValues(t, 1, effects.Load())
|
||||
require.EqualValues(t, wantRuns-1, newCalls.Load())
|
||||
require.Len(t, read(t, s, scope).Members[0].Runs, wantRuns)
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestSuspendedFollowupDeliverySurvivesFailedResume(t *testing.T) {
|
||||
s, scope := testStore(t)
|
||||
ctx := t.Context()
|
||||
r := New(s, nil)
|
||||
id, err := r.Spawn(ctx, scope, "spawn", "child", "a", "{}", "initial")
|
||||
require.NoError(t, err)
|
||||
_, err = r.Send(ctx, scope, "followup", id, "external effect", "", true)
|
||||
require.NoError(t, err)
|
||||
var suspended Work
|
||||
r.Run = func(ctx context.Context, w Work) (Result, error) {
|
||||
mail, err := r.Inbox(ctx, w, 0)
|
||||
require.NoError(t, err)
|
||||
require.Len(t, mail, 1)
|
||||
require.NoError(t, r.AwaitPrompt(ctx, w, PromptState{ID: "approval", Status: "suspended"}))
|
||||
suspended = w
|
||||
return Result{Suspended: true}, nil
|
||||
}
|
||||
r.Tick(ctx)
|
||||
r.workers.Wait()
|
||||
require.Equal(t, "waiting", read(t, s, scope).Members[0].Runs[0].State)
|
||||
restarted := New(NewStore(s.db), func(context.Context, Work) (Result, error) {
|
||||
return Result{}, fmt.Errorf("resume failed before restoring engine snapshot")
|
||||
})
|
||||
suspended.Run.PromptID = "approval"
|
||||
require.NoError(t, restarted.ReconcilePrompt(ctx, suspended, PromptState{ID: "approval", Status: "answered"}))
|
||||
for i := 0; i < 3; i++ {
|
||||
restarted.Tick(ctx)
|
||||
restarted.workers.Wait()
|
||||
}
|
||||
g := read(t, s, scope)
|
||||
require.Len(t, g.Members[0].Runs, 1)
|
||||
require.Equal(t, "failed", g.Members[0].Runs[0].State)
|
||||
require.Positive(t, g.Members[0].Runs[0].Result.ConsumedSequence)
|
||||
}
|
||||
|
||||
func TestParentHeartbeatExtendsDeadline(t *testing.T) {
|
||||
s, scope := testStore(t)
|
||||
r := New(s, nil)
|
||||
r.Poll = 5 * time.Millisecond
|
||||
r.Lease = time.Second
|
||||
ctx := context.Background()
|
||||
b, err := r.AcquireParent(ctx, scope)
|
||||
require.NoError(t, err)
|
||||
require.NoError(t, s.Change(b.Context(ctx), scope, func(g *Group) error {
|
||||
g.Deadline = time.Now().Add(-time.Minute)
|
||||
return nil
|
||||
}))
|
||||
_, stop := b.Start(ctx)
|
||||
defer stop()
|
||||
require.Eventually(t, func() bool {
|
||||
return read(t, s, scope).Deadline.After(time.Now().Add(30 * time.Minute))
|
||||
}, time.Second, 5*time.Millisecond)
|
||||
r.Tick(context.Background())
|
||||
require.Equal(t, "active", read(t, s, scope).Status)
|
||||
}
|
||||
|
||||
func TestChildHeartbeatExtendsDeadline(t *testing.T) {
|
||||
s, scope := testStore(t)
|
||||
ctx := context.Background()
|
||||
entered, release := make(chan struct{}), make(chan struct{})
|
||||
defer close(release)
|
||||
r := New(s, func(context.Context, Work) (Result, error) {
|
||||
close(entered)
|
||||
<-release
|
||||
return Result{Answer: "ok"}, nil
|
||||
})
|
||||
r.Poll = 5 * time.Millisecond
|
||||
r.Lease = time.Second
|
||||
_, err := r.Spawn(ctx, scope, "spawn", "one", "a", "{}", "q")
|
||||
require.NoError(t, err)
|
||||
r.Tick(ctx)
|
||||
<-entered
|
||||
require.NoError(t, s.Change(ctx, scope, func(g *Group) error {
|
||||
g.Deadline = time.Now().Add(-time.Minute)
|
||||
return nil
|
||||
}))
|
||||
require.Eventually(t, func() bool {
|
||||
return read(t, s, scope).Deadline.After(time.Now().Add(30 * time.Minute))
|
||||
}, time.Second, 5*time.Millisecond)
|
||||
r.Tick(ctx)
|
||||
g := read(t, s, scope)
|
||||
require.Equal(t, "running", current(g.Members[0]).State)
|
||||
require.Equal(t, "active", g.Status)
|
||||
}
|
||||
|
||||
func TestCanceledPanickingRunCannotQueueFollowup(t *testing.T) {
|
||||
s, scope := testStore(t)
|
||||
ctx := t.Context()
|
||||
r := New(s, nil)
|
||||
id, err := r.Spawn(ctx, scope, "spawn", "child", "a", "{}", "initial")
|
||||
require.NoError(t, err)
|
||||
_, err = r.Send(ctx, scope, "consumed", id, "effect", "", true)
|
||||
require.NoError(t, err)
|
||||
r.Run = func(ctx context.Context, w Work) (Result, error) {
|
||||
_, err := r.Inbox(ctx, w, 0)
|
||||
require.NoError(t, err)
|
||||
_, err = r.Send(ctx, scope, "late", id, "new task", "", true)
|
||||
require.NoError(t, err)
|
||||
require.NoError(t, r.Cancel(ctx, scope))
|
||||
panic("late panic after cancellation")
|
||||
}
|
||||
r.Tick(ctx)
|
||||
r.workers.Wait()
|
||||
g := read(t, s, scope)
|
||||
require.Len(t, g.Members[0].Runs, 1)
|
||||
require.Equal(t, "cancelled", g.Members[0].Runs[0].State)
|
||||
require.Nil(t, g.ParentWait)
|
||||
}
|
||||
|
|
@ -0,0 +1,123 @@
|
|||
package collaboration
|
||||
|
||||
import "encoding/json"
|
||||
|
||||
// StatusSnapshot is the public projection of a durable collaboration. It never
|
||||
// includes assignment text, provider configuration, leases or raw tool results.
|
||||
type StatusSnapshot struct {
|
||||
GroupID string `json:"group_id"`
|
||||
Revision int64 `json:"revision"`
|
||||
Tasks []TaskStatus `json:"tasks"`
|
||||
}
|
||||
|
||||
// TaskStatus is the public current-run status of one child task.
|
||||
type TaskStatus struct {
|
||||
ID string `json:"id"`
|
||||
Name string `json:"name"`
|
||||
DisplayName string `json:"display_name,omitempty"`
|
||||
AgentID string `json:"agent_id"`
|
||||
SessionID string `json:"session_id"`
|
||||
RunID string `json:"run_id"`
|
||||
Status string `json:"status"`
|
||||
Progress *Progress `json:"progress,omitempty"`
|
||||
PromptID string `json:"prompt_id,omitempty"`
|
||||
LatestMessage string `json:"latest_message,omitempty"`
|
||||
}
|
||||
|
||||
// StatusView projects durable state into a public snapshot without private execution fields.
|
||||
func (g *Group) StatusView() StatusSnapshot {
|
||||
out := StatusSnapshot{GroupID: g.Scope.ID, Revision: g.Revision, Tasks: make([]TaskStatus, 0, len(g.Members))}
|
||||
for _, m := range g.Members {
|
||||
if m.Inherited {
|
||||
continue
|
||||
}
|
||||
r := current(m)
|
||||
if r == nil {
|
||||
continue
|
||||
}
|
||||
task := TaskStatus{
|
||||
ID: m.ID,
|
||||
Name: m.Name,
|
||||
AgentID: m.AgentID,
|
||||
SessionID: m.SessionID,
|
||||
RunID: r.ID,
|
||||
Status: r.State,
|
||||
PromptID: r.PromptID,
|
||||
}
|
||||
if r.CancelRequested && active(r) {
|
||||
task.Status = "cancelling"
|
||||
}
|
||||
if r.Progress != nil {
|
||||
p := *r.Progress
|
||||
task.Progress = &p
|
||||
}
|
||||
for i := len(g.Events) - 1; i >= 0; i-- {
|
||||
e := g.Events[i]
|
||||
if e.From == m.Name && e.RunID == r.ID && e.Kind == "message" {
|
||||
task.LatestMessage = e.Content
|
||||
break
|
||||
}
|
||||
}
|
||||
out.Tasks = append(out.Tasks, task)
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// PromptState is an allowlisted projection of a broker record, never model text.
|
||||
// It deliberately excludes arguments, user answers, credentials and descriptions.
|
||||
type PromptState struct {
|
||||
ID string `json:"id"`
|
||||
Kind string `json:"kind,omitempty"`
|
||||
Status string `json:"status,omitempty"`
|
||||
ToolCallID string `json:"tool_call_id,omitempty"`
|
||||
Service string `json:"service,omitempty"`
|
||||
Tool string `json:"tool,omitempty"`
|
||||
Decision string `json:"decision,omitempty"`
|
||||
}
|
||||
|
||||
// RuntimeNotice is internal model context, separate from tool output and final answers.
|
||||
type RuntimeNotice struct {
|
||||
Type string `json:"type"`
|
||||
Source string `json:"source"`
|
||||
Task string `json:"task,omitempty"`
|
||||
RunID string `json:"run_id,omitempty"`
|
||||
Sequence int64 `json:"sequence"`
|
||||
PromptID string `json:"prompt_id,omitempty"`
|
||||
PromptKind string `json:"prompt_kind,omitempty"`
|
||||
ToolCallID string `json:"tool_call_id,omitempty"`
|
||||
Service string `json:"service,omitempty"`
|
||||
Tool string `json:"tool,omitempty"`
|
||||
Decision string `json:"decision,omitempty"`
|
||||
ExecutionState string `json:"execution_state,omitempty"`
|
||||
Message string `json:"message,omitempty"`
|
||||
}
|
||||
|
||||
// Prompt transitions enter the mailbox exactly once per state change. A resolved
|
||||
// prompt only queues a continuation; it does not establish tool or task success.
|
||||
func publishPromptState(g *Group, m *Member, r *Run, kind string) {
|
||||
g.NextSequence++
|
||||
notice := RuntimeNotice{
|
||||
Type: "prompt_required", Source: "runtime", Task: m.Name,
|
||||
RunID: r.ID, Sequence: g.NextSequence, PromptID: r.PromptID, ExecutionState: "waiting",
|
||||
}
|
||||
if kind == "resumed" {
|
||||
notice.Type, notice.ExecutionState = "prompt_resolved", "queued"
|
||||
}
|
||||
if p := r.Prompt; p != nil && p.ID == r.PromptID {
|
||||
notice.PromptKind, notice.ToolCallID, notice.Service, notice.Tool = p.Kind, p.ToolCallID, p.Service, p.Tool
|
||||
if p.Kind == "tool_approval" {
|
||||
notice.Type = "approval_required"
|
||||
if kind == "resumed" {
|
||||
notice.Type = "approval_resolved"
|
||||
}
|
||||
}
|
||||
if kind == "resumed" {
|
||||
notice.Decision = p.Decision
|
||||
}
|
||||
}
|
||||
content, _ := json.Marshal(notice)
|
||||
g.Events = append(
|
||||
g.Events,
|
||||
Event{Sequence: g.NextSequence, From: m.Name, RunID: r.ID, Kind: kind, Content: string(content)},
|
||||
)
|
||||
}
|
||||
|
|
@ -0,0 +1,182 @@
|
|||
package collaboration
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
func TestStatusTracksCommittedChangesWithoutLeakingPrivateState(t *testing.T) {
|
||||
s, scope := testStore(t)
|
||||
ctx := context.Background()
|
||||
r := New(s, nil)
|
||||
var snapshots []StatusSnapshot
|
||||
s.OnStatus = func(ctx context.Context, g *Group) {
|
||||
persisted, err := s.Read(ctx, g.Scope)
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, g.Revision, persisted.Revision)
|
||||
snapshots = append(snapshots, g.StatusView())
|
||||
}
|
||||
_, err := r.Spawn(ctx, scope, "spawn", "worker", "agent", "PRIVATE_CONFIG", "PRIVATE_QUERY")
|
||||
require.NoError(t, err)
|
||||
require.Len(t, snapshots, 1)
|
||||
require.Equal(t, "queued", snapshots[0].Tasks[0].Status)
|
||||
var w Work
|
||||
require.NoError(t, s.Change(ctx, scope, func(g *Group) error {
|
||||
m := g.Members[0]
|
||||
v := current(m)
|
||||
v.State, v.Owner, v.Lease = "running", "PRIVATE_OWNER", time.Now().Add(time.Minute)
|
||||
w = Work{scope, *m, *v}
|
||||
return nil
|
||||
}))
|
||||
n := len(snapshots)
|
||||
require.NoError(
|
||||
t,
|
||||
s.Change(
|
||||
ctx,
|
||||
scope,
|
||||
func(g *Group) error { current(g.Members[0]).Lease = time.Now().Add(time.Hour); return nil },
|
||||
),
|
||||
)
|
||||
require.Len(t, snapshots, n, "leases must not spam UI snapshots")
|
||||
require.NoError(t, r.RecordProgress(ctx, w, Progress{Phase: "tool_running", ToolName: "search"}))
|
||||
child := &Binding{Runtime: r, Scope: scope, Child: &w}
|
||||
require.NoError(t, child.MessageParent(ctx, "finding", "Found the relevant file"))
|
||||
require.Equal(t, "Found the relevant file", snapshots[len(snapshots)-1].Tasks[0].LatestMessage)
|
||||
require.Equal(t, "search", snapshots[len(snapshots)-1].Tasks[0].Progress.ToolName)
|
||||
require.NoError(t, r.Cancel(ctx, scope))
|
||||
require.Equal(t, "cancelling", snapshots[len(snapshots)-1].Tasks[0].Status)
|
||||
n = len(snapshots)
|
||||
require.ErrorIs(t, r.RecordProgress(ctx, w, Progress{Phase: "tool_succeeded"}), ErrConflict)
|
||||
require.ErrorIs(t, child.MessageParent(ctx, "late", "late"), ErrClosed)
|
||||
require.Len(t, snapshots, n)
|
||||
for i := 1; i < len(snapshots); i++ {
|
||||
require.Greater(t, snapshots[i].Revision, snapshots[i-1].Revision)
|
||||
}
|
||||
b, err := json.Marshal(snapshots)
|
||||
require.NoError(t, err)
|
||||
for _, secret := range []string{
|
||||
"PRIVATE_CONFIG",
|
||||
"PRIVATE_QUERY",
|
||||
"PRIVATE_OWNER",
|
||||
"lease_until",
|
||||
"config_snapshot",
|
||||
} {
|
||||
require.NotContains(t, string(b), secret)
|
||||
}
|
||||
restarted := NewStore(s.db)
|
||||
g, err := restarted.Read(ctx, scope)
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, snapshots[len(snapshots)-1], g.StatusView(), "replay uses the durable CAS revision")
|
||||
}
|
||||
|
||||
func TestPromptRecoveryPublishesOnlyActualTransitions(t *testing.T) {
|
||||
r, w := promptWork(t)
|
||||
ctx := context.Background()
|
||||
require.NoError(t, r.Store.Change(ctx, w.Scope, func(g *Group) error {
|
||||
v := current(g.Members[0])
|
||||
v.State, v.Lease = "running", time.Time{}
|
||||
return nil
|
||||
}))
|
||||
require.NoError(t, r.ReconcilePrompt(ctx, w, PromptState{ID: w.Run.PromptID, Status: "pending"}))
|
||||
require.NoError(t, r.ReconcilePrompt(ctx, w, PromptState{ID: w.Run.PromptID, Status: "pending"}))
|
||||
b := &Binding{Runtime: r, Scope: w.Scope}
|
||||
events, err := b.Poll(ctx)
|
||||
require.NoError(t, err)
|
||||
require.Len(t, events, 1)
|
||||
require.Equal(t, "waiting", events[0].Kind)
|
||||
updated, err := b.Wait(ctx, b.Seen, 0)
|
||||
require.NoError(t, err)
|
||||
require.False(t, updated)
|
||||
require.NoError(t, r.ReconcilePrompt(ctx, w, PromptState{ID: w.Run.PromptID, Status: "answered"}))
|
||||
require.NoError(t, r.ReconcilePrompt(ctx, w, PromptState{ID: w.Run.PromptID, Status: "answered"}))
|
||||
events, err = b.Poll(ctx)
|
||||
require.NoError(t, err)
|
||||
require.Len(t, events, 1)
|
||||
require.Equal(t, "resumed", events[0].Kind)
|
||||
}
|
||||
|
||||
func TestPromptNoticesSurviveRestartAndKeepDecisionSeparateFromExecution(t *testing.T) {
|
||||
for _, decision := range []string{"approved", "rejected", ""} {
|
||||
t.Run("decision="+decision, func(t *testing.T) {
|
||||
r, w := promptWork(t)
|
||||
ctx := t.Context()
|
||||
require.NoError(t, r.Store.Change(ctx, w.Scope, func(g *Group) error {
|
||||
v := current(g.Members[0])
|
||||
v.State = "running"
|
||||
v.Lease = time.Now().Add(time.Minute)
|
||||
v.Owner = "worker"
|
||||
w.Run = *v
|
||||
return nil
|
||||
}))
|
||||
p := PromptState{
|
||||
ID: w.Run.PromptID,
|
||||
Kind: "tool_approval",
|
||||
Status: "pending",
|
||||
Service: "KM",
|
||||
Tool: "hot-articles",
|
||||
ToolCallID: "call",
|
||||
}
|
||||
require.NoError(t, r.AwaitPrompt(ctx, w, p))
|
||||
// A new scheduler reads only durable data, after the old execution lease expired.
|
||||
require.NoError(
|
||||
t,
|
||||
r.Store.Change(
|
||||
ctx,
|
||||
w.Scope,
|
||||
func(g *Group) error { current(g.Members[0]).Lease = time.Time{}; return nil },
|
||||
),
|
||||
)
|
||||
r = New(NewStore(r.Store.db), nil)
|
||||
require.NoError(t, r.ReconcilePrompt(ctx, w, p))
|
||||
require.NoError(t, r.ReconcilePrompt(ctx, w, p))
|
||||
p.Status, p.Decision = "answered", decision
|
||||
require.NoError(t, r.ReconcilePrompt(ctx, w, p))
|
||||
require.NoError(t, r.ReconcilePrompt(ctx, w, p))
|
||||
g := read(t, r.Store, w.Scope)
|
||||
require.Len(t, g.Events, 2, "retries must not duplicate notices")
|
||||
for i, e := range g.Events {
|
||||
var notice RuntimeNotice
|
||||
require.NoError(t, json.Unmarshal([]byte(e.Content), ¬ice))
|
||||
require.Equal(t, p.ID, notice.PromptID)
|
||||
require.Equal(t, p.ToolCallID, notice.ToolCallID)
|
||||
require.Equal(t, "KM", notice.Service)
|
||||
require.Equal(t, "hot-articles", notice.Tool)
|
||||
require.Equal(t, w.Run.ID, notice.RunID)
|
||||
require.Equal(t, e.Sequence, notice.Sequence)
|
||||
if i == 0 {
|
||||
require.Equal(t, "approval_required", notice.Type)
|
||||
require.Equal(t, "waiting", notice.ExecutionState)
|
||||
require.Empty(t, notice.Decision)
|
||||
} else {
|
||||
require.Equal(t, "approval_resolved", notice.Type)
|
||||
require.Equal(t, "queued", notice.ExecutionState)
|
||||
require.Equal(t, decision, notice.Decision)
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestLateApprovalNoticeCannotWakeCanceledOrDifferentPrompt(t *testing.T) {
|
||||
for _, cancel := range []bool{true, false} {
|
||||
r, w := promptWork(t)
|
||||
if cancel {
|
||||
require.NoError(t, r.Cancel(t.Context(), w.Scope))
|
||||
}
|
||||
before := read(t, r.Store, w.Scope)
|
||||
p := PromptState{ID: w.Run.PromptID, Kind: "tool_approval", Status: "answered", Decision: "approved"}
|
||||
if !cancel {
|
||||
p.ID = "different-prompt"
|
||||
}
|
||||
require.NoError(t, r.ReconcilePrompt(t.Context(), w, p))
|
||||
after := read(t, r.Store, w.Scope)
|
||||
require.NotEqual(t, "queued", current(after.Members[0]).State)
|
||||
for _, e := range after.Events[len(before.Events):] {
|
||||
require.NotEqual(t, "resumed", e.Kind)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,383 @@
|
|||
// Package collaboration owns durable agent work. Queue notifications are hints;
|
||||
// the database is the authority for admission, ownership and cancellation.
|
||||
package collaboration
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"reflect"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/Tencent/WeKnora/internal/types"
|
||||
|
||||
"gorm.io/gorm"
|
||||
"gorm.io/gorm/clause"
|
||||
)
|
||||
|
||||
var (
|
||||
// ErrConflict indicates a stale revision or execution lease.
|
||||
ErrConflict = errors.New("collaboration changed; refresh its state")
|
||||
// ErrClosed indicates that the collaboration no longer accepts work.
|
||||
ErrClosed = errors.New("collaboration is closed")
|
||||
// ErrScope indicates that the caller cannot access the requested collaboration.
|
||||
ErrScope = errors.New("collaboration is outside the caller's scope")
|
||||
// ErrHistoryLimit indicates that an active aggregate cannot accept more history.
|
||||
ErrHistoryLimit = errors.New("collaboration history limit reached")
|
||||
)
|
||||
|
||||
// maxAggregateBytes bounds one serialized collaboration aggregate.
|
||||
var maxAggregateBytes = 32 << 20
|
||||
|
||||
// isFenceError reports a durable ownership or admission decision, as opposed
|
||||
// to a transient store failure that may be retried.
|
||||
func isFenceError(err error) bool {
|
||||
return errors.Is(err, ErrConflict) || errors.Is(err, ErrClosed) || errors.Is(err, ErrScope) ||
|
||||
errors.Is(err, ErrHistoryLimit)
|
||||
}
|
||||
|
||||
// Record is an aggregate with an optimistic concurrency fence. One bounded
|
||||
// document makes admission, event publication and the pending-work outbox atomic
|
||||
// on both SQLite and PostgreSQL, without relying on process-local locks.
|
||||
type Record struct {
|
||||
ID string `gorm:"primaryKey;type:varchar(36)"`
|
||||
TenantID uint64 `gorm:"not null"`
|
||||
UserID string `gorm:"type:varchar(64);not null"`
|
||||
SessionID string `gorm:"type:varchar(36);not null"`
|
||||
Status string `gorm:"type:varchar(32);not null;index"`
|
||||
Version int64 `gorm:"not null"`
|
||||
Data string `gorm:"type:text;not null"`
|
||||
UpdatedAt time.Time
|
||||
}
|
||||
|
||||
// TableName returns the durable collaboration aggregate table.
|
||||
func (Record) TableName() string { return "agent_collaborations" }
|
||||
|
||||
// Scope identifies a collaboration within its tenant, user and session.
|
||||
type Scope struct {
|
||||
TenantID uint64
|
||||
UserID, SessionID, ID string
|
||||
}
|
||||
|
||||
// Group holds the parent state, children and ordered mailbox in one atomic aggregate.
|
||||
type Group struct {
|
||||
// Revision is the database CAS version, never a caller-provided JSON field.
|
||||
Revision int64 `json:"-"`
|
||||
InputBytes int
|
||||
SuccessorID string // durable admission for a subsequent human turn
|
||||
ParentMessageID string
|
||||
ParentOwner string
|
||||
ParentLease time.Time
|
||||
ParentWait *ParentWait
|
||||
// ParentClosePending keeps interrupted/expired parents recoverable until their transcript and stream are closed.
|
||||
ParentClosePending bool
|
||||
RootQuery string
|
||||
Scope Scope
|
||||
Status string
|
||||
Members []*Member
|
||||
Events []Event
|
||||
Requests map[string]string
|
||||
NextSequence int64
|
||||
Deadline time.Time
|
||||
}
|
||||
|
||||
// Member is a named child task with its execution history and incoming mailbox.
|
||||
type Member struct {
|
||||
// Inherited instances remain addressable across parent turns but are not
|
||||
// current-turn UI tasks until explicitly continued.
|
||||
Inherited bool `json:"inherited,omitempty"`
|
||||
ID string `json:"member_id"`
|
||||
Name string `json:"task_name"`
|
||||
AgentID string `json:"agent_id"`
|
||||
SessionID string `json:"session_id"`
|
||||
// ConfigJSON is stored separately from the model-visible projection.
|
||||
ConfigJSON string `json:"config_snapshot"`
|
||||
Runs []*Run `json:"runs"`
|
||||
Mail []Event `json:"mail,omitempty"`
|
||||
}
|
||||
|
||||
// Progress is bounded operational telemetry, not model reasoning or tool payloads.
|
||||
type Progress struct {
|
||||
Phase string `json:"phase"`
|
||||
ToolName string `json:"tool_name,omitempty"`
|
||||
ToolCallID string `json:"tool_call_id,omitempty"`
|
||||
Iteration int `json:"iteration,omitempty"`
|
||||
UpdatedAt time.Time `json:"updated_at"`
|
||||
}
|
||||
|
||||
// Run tracks one child execution, its lease and eventual result.
|
||||
type Run struct {
|
||||
// Inherited identifies a baseline run copied from an earlier parent turn.
|
||||
Inherited bool `json:"inherited,omitempty"`
|
||||
Prompt *PromptState `json:"prompt,omitempty"`
|
||||
Progress *Progress `json:"progress,omitempty"`
|
||||
ID string `json:"run_id"`
|
||||
State string `json:"status"`
|
||||
Query string `json:"query"`
|
||||
Owner string `json:"-"`
|
||||
Lease time.Time `json:"lease_until"`
|
||||
Attempt int `json:"attempt"`
|
||||
CancelRequested bool `json:"cancel_requested"`
|
||||
Result Result `json:"result"`
|
||||
// DeliveredSequence fences automatic followups even when the executor cannot return a result.
|
||||
DeliveredSequence int64 `json:"delivered_sequence,omitempty"`
|
||||
PromptID string `json:"prompt_id,omitempty"`
|
||||
MessageID string `json:"message_id,omitempty"`
|
||||
UserMessageID string `json:"user_message_id,omitempty"`
|
||||
}
|
||||
|
||||
// MarshalJSON preserves private ownership for persistence; model projections omit it.
|
||||
func (r Run) MarshalJSON() ([]byte, error) {
|
||||
type alias Run
|
||||
return json.Marshal(struct {
|
||||
alias
|
||||
Owner string `json:"owner"`
|
||||
}{alias(r), r.Owner})
|
||||
}
|
||||
|
||||
// UnmarshalJSON restores private ownership alongside the persisted execution state.
|
||||
func (r *Run) UnmarshalJSON(b []byte) error {
|
||||
type alias Run
|
||||
v := struct {
|
||||
*alias
|
||||
Owner string `json:"owner"`
|
||||
}{alias: (*alias)(r)}
|
||||
if err := json.Unmarshal(b, &v); err != nil {
|
||||
return err
|
||||
}
|
||||
r.Owner = v.Owner
|
||||
return nil
|
||||
}
|
||||
|
||||
// Result records a child’s answer, evidence and execution outcome.
|
||||
type Result struct {
|
||||
// Artifacts are runtime-produced metadata, never parsed from model prose.
|
||||
Artifacts types.MessageArtifacts `json:"artifacts,omitempty"`
|
||||
Truncated bool `json:"truncated,omitempty"`
|
||||
Evidence string `json:"evidence,omitempty"`
|
||||
Answer string `json:"answer,omitempty"`
|
||||
Error string `json:"error,omitempty"`
|
||||
MessageID string `json:"message_id,omitempty"`
|
||||
ConsumedSequence int64 `json:"consumed_sequence,omitempty"`
|
||||
Suspended bool `json:"suspended,omitempty"`
|
||||
}
|
||||
|
||||
// Event is an ordered, run-correlated mailbox message.
|
||||
type Event struct {
|
||||
Sequence int64 `json:"sequence"`
|
||||
From string `json:"from"`
|
||||
RunID string `json:"run_id,omitempty"`
|
||||
Kind string `json:"kind"`
|
||||
Content string `json:"content"`
|
||||
}
|
||||
|
||||
// Store persists collaboration aggregates using optimistic concurrency.
|
||||
type Store struct {
|
||||
db *gorm.DB
|
||||
// OnStatus runs after a successful commit, never inside a retried mutation.
|
||||
// Consumers must tolerate duplicate and out-of-order snapshots by revision.
|
||||
OnStatus func(context.Context, *Group)
|
||||
}
|
||||
|
||||
// NewStore wraps a database connection for collaboration persistence.
|
||||
func NewStore(db *gorm.DB) *Store { return &Store{db: db} }
|
||||
|
||||
// Ensure creates a scoped group if absent and verifies access to an existing group.
|
||||
func (s *Store) Ensure(ctx context.Context, scope Scope) error {
|
||||
return s.ensure(ctx, scope, nil)
|
||||
}
|
||||
|
||||
func (s *Store) ensure(ctx context.Context, scope Scope, members []*Member) error {
|
||||
if scope.ID == "" || scope.SessionID == "" || scope.UserID == "" || scope.TenantID == 0 {
|
||||
return ErrScope
|
||||
}
|
||||
g := Group{
|
||||
Scope: scope, Status: "active", Members: members,
|
||||
Requests: map[string]string{}, Deadline: time.Now().Add(collaborationHorizon),
|
||||
}
|
||||
b, err := json.Marshal(g)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
r := Record{
|
||||
ID: scope.ID,
|
||||
TenantID: scope.TenantID,
|
||||
UserID: scope.UserID,
|
||||
SessionID: scope.SessionID,
|
||||
Status: g.Status,
|
||||
Version: 1,
|
||||
Data: string(b),
|
||||
}
|
||||
if err = s.db.WithContext(ctx).Clauses(clause.OnConflict{DoNothing: true}).Create(&r).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
_, err = s.Read(ctx, scope)
|
||||
return err
|
||||
}
|
||||
|
||||
func (s *Store) read(ctx context.Context, scope Scope) (Record, *Group, error) {
|
||||
var row Record
|
||||
err := s.db.WithContext(ctx).
|
||||
Where("id = ? AND tenant_id = ? AND user_id = ? AND session_id = ?",
|
||||
scope.ID,
|
||||
scope.TenantID,
|
||||
scope.UserID,
|
||||
scope.SessionID).
|
||||
First(&row).
|
||||
Error
|
||||
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
return row, nil, ErrScope
|
||||
}
|
||||
if err != nil {
|
||||
return row, nil, err
|
||||
}
|
||||
var g Group
|
||||
if err = json.Unmarshal([]byte(row.Data), &g); err != nil {
|
||||
return row, nil, fmt.Errorf("decode collaboration: %w", err)
|
||||
}
|
||||
g.Revision = row.Version
|
||||
return row, &g, nil
|
||||
}
|
||||
|
||||
func (s *Store) Read(ctx context.Context, scope Scope) (*Group, error) {
|
||||
_, g, e := s.read(ctx, scope)
|
||||
return g, e
|
||||
}
|
||||
|
||||
// Change callbacks can be retried: no IO or non-idempotent external actions in fn.
|
||||
//
|
||||
// An active aggregate that would exceed maxAggregateBytes is closed instead of
|
||||
// rejecting every later mutation, including the cancellation that would end it.
|
||||
// The caller's mutation is discarded and ErrHistoryLimit is returned.
|
||||
func (s *Store) Change(ctx context.Context, scope Scope, fn func(*Group) error) error {
|
||||
forceClose := false
|
||||
for attempt := 0; attempt < 60; attempt++ {
|
||||
row, g, err := s.read(ctx, scope)
|
||||
if err == nil {
|
||||
before := g.StatusView()
|
||||
parentMessageID := g.ParentMessageID
|
||||
if forceClose {
|
||||
closeForHistoryLimit(g)
|
||||
} else {
|
||||
if owner, ok := ctx.Value(parentOwnerKey{}).(string); ok &&
|
||||
(g.ParentOwner != owner || time.Now().After(g.ParentLease)) {
|
||||
return ErrConflict
|
||||
}
|
||||
if err = fn(g); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
var b []byte
|
||||
b, err = json.Marshal(g)
|
||||
if err == nil && len(b) > maxAggregateBytes {
|
||||
if g.Status == "active" && !forceClose {
|
||||
forceClose = true
|
||||
continue
|
||||
}
|
||||
compactClosed(g)
|
||||
if b, err = json.Marshal(g); err == nil && len(b) > maxAggregateBytes {
|
||||
return ErrHistoryLimit
|
||||
}
|
||||
}
|
||||
if err == nil {
|
||||
if string(b) == row.Data && g.Status == row.Status {
|
||||
if forceClose {
|
||||
return ErrHistoryLimit
|
||||
}
|
||||
return nil
|
||||
}
|
||||
q := s.db.WithContext(ctx).
|
||||
Model(&Record{}).
|
||||
Where("id = ? AND version = ?", row.ID, row.Version).
|
||||
Updates(map[string]any{
|
||||
"data": string(b),
|
||||
"status": g.Status,
|
||||
"version": row.Version + 1,
|
||||
"updated_at": time.Now().UTC(),
|
||||
})
|
||||
err = q.Error
|
||||
if err == nil && q.RowsAffected == 1 {
|
||||
g.Revision = row.Version + 1
|
||||
after := g.StatusView()
|
||||
after.Revision = before.Revision
|
||||
if s.OnStatus != nil &&
|
||||
(parentMessageID != g.ParentMessageID || !reflect.DeepEqual(before, after)) {
|
||||
s.OnStatus(context.WithoutCancel(ctx), g)
|
||||
}
|
||||
if forceClose {
|
||||
return ErrHistoryLimit
|
||||
}
|
||||
return nil
|
||||
}
|
||||
}
|
||||
}
|
||||
if err != nil && !strings.Contains(err.Error(), "locked") && !strings.Contains(err.Error(), "busy") {
|
||||
return err
|
||||
}
|
||||
t := time.NewTimer(time.Duration(min(attempt+1, 20)) * time.Millisecond)
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
t.Stop()
|
||||
return ctx.Err()
|
||||
case <-t.C:
|
||||
}
|
||||
}
|
||||
return ErrConflict
|
||||
}
|
||||
|
||||
// Pending lists groups that require scheduling, recovery or cancellation.
|
||||
func (s *Store) Pending(ctx context.Context) ([]Scope, error) {
|
||||
var rows []Record
|
||||
if err := s.db.WithContext(ctx).Select("id, tenant_id, user_id, session_id").Where("status IN ?",
|
||||
[]string{
|
||||
"active",
|
||||
"cancelling",
|
||||
}).Order("updated_at").Find(&rows).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
out := make([]Scope, 0, len(rows))
|
||||
for _, r := range rows {
|
||||
out = append(out, Scope{r.TenantID, r.UserID, r.SessionID, r.ID})
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
func current(m *Member) *Run {
|
||||
if len(m.Runs) == 0 {
|
||||
return nil
|
||||
}
|
||||
return m.Runs[len(m.Runs)-1]
|
||||
}
|
||||
|
||||
func active(r *Run) bool {
|
||||
return r != nil && (r.State == "queued" || r.State == "running" || r.State == "waiting")
|
||||
}
|
||||
|
||||
func member(g *Group, target string) (*Member, error) {
|
||||
for _, m := range g.Members {
|
||||
if target == m.ID || target == m.Name || target == "/root/"+m.Name {
|
||||
return m, nil
|
||||
}
|
||||
}
|
||||
return nil, errors.New("unknown child agent in this collaboration")
|
||||
}
|
||||
|
||||
func publish(g *Group, m *Member, r *Run) {
|
||||
g.NextSequence++
|
||||
payload := struct {
|
||||
Result Result `json:"result"`
|
||||
SessionID string `json:"session_id"`
|
||||
}{r.Result, m.SessionID}
|
||||
data, _ := json.Marshal(payload)
|
||||
g.Events = append(g.Events, Event{g.NextSequence, m.Name, r.ID, r.State, string(data)})
|
||||
}
|
||||
|
||||
func reserveInput(g *Group, n int) error {
|
||||
if g.InputBytes+n > 512<<10 {
|
||||
return errors.New("collaboration input budget exhausted")
|
||||
}
|
||||
g.InputBytes += n
|
||||
return nil
|
||||
}
|
||||
|
|
@ -0,0 +1,173 @@
|
|||
package agent
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/Tencent/WeKnora/internal/agent/collaboration"
|
||||
agenttools "github.com/Tencent/WeKnora/internal/agent/tools"
|
||||
"github.com/Tencent/WeKnora/internal/models/chat"
|
||||
"github.com/Tencent/WeKnora/internal/types"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
func collaborationAnswerModel(answer string) *mockChat {
|
||||
return &mockChat{responses: []mockResponse{{chunks: []types.StreamResponse{{
|
||||
ResponseType: types.ResponseTypeAnswer, Content: answer, Done: true, FinishReason: "stop",
|
||||
}}}}}
|
||||
}
|
||||
|
||||
func collaborationTranscript(messages []chat.Message) string {
|
||||
var text strings.Builder
|
||||
for _, message := range messages {
|
||||
text.WriteString(message.Content)
|
||||
text.WriteByte('\n')
|
||||
}
|
||||
return text.String()
|
||||
}
|
||||
|
||||
// Exercise a real saved wait, then start another scheduler against the same
|
||||
// database. The first child's answer must survive even though its cursor was
|
||||
// acknowledged before the second child completed.
|
||||
func TestCollaborationRestartRetainsConsumedResults(t *testing.T) {
|
||||
for _, legacy := range []bool{false, true} {
|
||||
name := "current"
|
||||
if legacy {
|
||||
name = "legacy"
|
||||
}
|
||||
t.Run(name, func(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
r, b := engineCollaboration(t)
|
||||
owned, err := r.AcquireParent(ctx, b.Scope)
|
||||
require.NoError(t, err)
|
||||
_, err = r.Spawn(ctx, b.Scope, "spawn", "second", "a", "{}", "task")
|
||||
require.NoError(t, err)
|
||||
require.NoError(t, r.Store.Change(ctx, b.Scope, func(g *collaboration.Group) error {
|
||||
g.NextSequence = 1
|
||||
g.Events = []collaboration.Event{{
|
||||
Sequence: 1, From: "first", RunID: "first-run", Kind: "succeeded",
|
||||
Content: `{"result":{"answer":"FIRST_COMPLETE_RESULT [source](https://example.com/first)"}}`,
|
||||
}}
|
||||
return nil
|
||||
}))
|
||||
engine := newTestEngine(t, collaborationAnswerModel("WAITING_FOR_SECOND"))
|
||||
engine.toolRegistry = agenttools.NewToolRegistry()
|
||||
engine.SetCollaboration(owned)
|
||||
engine.EnableSuspension(json.RawMessage(`{}`))
|
||||
runCtx, cancel := context.WithCancel(ctx)
|
||||
defer cancel()
|
||||
finished := make(chan struct{})
|
||||
go func() { defer close(finished); _, _ = engine.Execute(runCtx, "s", "m", "combine results", nil) }()
|
||||
require.Eventually(t, func() bool {
|
||||
g, readErr := r.Store.Read(ctx, b.Scope)
|
||||
return readErr == nil && g.ParentWait != nil
|
||||
}, 3*time.Second, time.Millisecond)
|
||||
cancel()
|
||||
select {
|
||||
case <-finished:
|
||||
case <-time.After(3 * time.Second):
|
||||
t.Fatal("parent failed to stop")
|
||||
}
|
||||
require.NoError(t, r.Store.Change(ctx, b.Scope, func(g *collaboration.Group) error {
|
||||
require.Equal(t, int64(1), g.ParentWait.After)
|
||||
snap, decodeErr := DecodeRunSnapshot(g.ParentWait.Snapshot)
|
||||
require.NoError(t, decodeErr)
|
||||
require.Len(t, snap.CollaborationDeliveries, 1)
|
||||
require.Equal(t, int64(1), *snap.CollaborationCursor)
|
||||
if legacy {
|
||||
snap.CollaborationDeliveries, snap.CollaborationCursor = nil, nil
|
||||
g.ParentWait.Snapshot, decodeErr = json.Marshal(snap)
|
||||
require.NoError(t, decodeErr)
|
||||
}
|
||||
g.ParentLease = time.Time{}
|
||||
g.Members[0].Runs[0].State = "succeeded"
|
||||
g.NextSequence = 2
|
||||
g.Events = append(g.Events, collaboration.Event{
|
||||
Sequence: 2, From: "second", RunID: "second-run", Kind: "succeeded",
|
||||
Content: `{"result":{"answer":"SECOND_COMPLETE_RESULT"}}`,
|
||||
})
|
||||
return nil
|
||||
}))
|
||||
model := collaborationAnswerModel("combined")
|
||||
restarted := collaboration.New(r.Store, nil)
|
||||
resumed := make(chan error, 1)
|
||||
restarted.WakeParent = func(ctx context.Context, binding *collaboration.Binding, data []byte) error {
|
||||
next := newTestEngine(t, model)
|
||||
next.toolRegistry = agenttools.NewToolRegistry()
|
||||
next.SetCollaboration(binding)
|
||||
_, resumeErr := next.Resume(ctx, "s", "m", nil, data, nil)
|
||||
resumed <- resumeErr
|
||||
return resumeErr
|
||||
}
|
||||
restarted.Tick(ctx)
|
||||
select {
|
||||
case err = <-resumed:
|
||||
require.NoError(t, err)
|
||||
case <-time.After(3 * time.Second):
|
||||
t.Fatal("parent did not recover")
|
||||
}
|
||||
require.Len(t, model.calls, 1)
|
||||
input := collaborationTranscript(model.calls[0])
|
||||
require.Equal(t, 1, strings.Count(input, "FIRST_COMPLETE_RESULT"))
|
||||
require.Equal(t, 1, strings.Count(input, "SECOND_COMPLETE_RESULT"))
|
||||
require.Contains(t, input, "https://example.com/first")
|
||||
require.Contains(t, input, "Run ID: first-run")
|
||||
if !legacy {
|
||||
require.Less(t,
|
||||
strings.Index(input, "FIRST_COMPLETE_RESULT"), strings.Index(input, "WAITING_FOR_SECOND"))
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestCollaborationPromptSnapshotPreservesDeliveryOrder(t *testing.T) {
|
||||
r, b := engineCollaboration(t)
|
||||
owned, err := r.AcquireParent(t.Context(), b.Scope)
|
||||
require.NoError(t, err)
|
||||
first := collaboration.Event{Sequence: 1, From: "first", RunID: "run1", Kind: "message", Content: "FIRST_PROGRESS"}
|
||||
second := collaboration.Event{
|
||||
Sequence: 2, From: "first", RunID: "run1", Kind: "succeeded",
|
||||
Content: `{"result":{"answer":"FINAL_RESULT"}}`,
|
||||
}
|
||||
require.NoError(t, r.Store.Change(t.Context(), b.Scope, func(g *collaboration.Group) error {
|
||||
g.NextSequence, g.Events = 2, []collaboration.Event{first, second}
|
||||
return nil
|
||||
}))
|
||||
initial := newTestEngine(t, nil)
|
||||
initial.toolRegistry = agenttools.NewToolRegistry()
|
||||
initial.SetCollaboration(owned)
|
||||
state := &types.AgentState{}
|
||||
initial.beginTurn("task", nil, state)
|
||||
var input []chat.Message
|
||||
initial.deliverCollaborationEvents(&input, []collaboration.Event{first}, 0, false)
|
||||
state.RoundSteps = append(state.RoundSteps, types.AgentStep{Thought: "BETWEEN_MESSAGES"})
|
||||
initial.deliverCollaborationEvents(&input, []collaboration.Event{second}, 1, true)
|
||||
owned.Seen = 2
|
||||
initial.recordSteerMessage("steer", "NEW_USER_GUIDANCE")
|
||||
initial.beginRound(types.AgentStep{Thought: "APPROVAL_ROUND", UserMessagesBefore: []string{"steer"}},
|
||||
[]types.LLMToolCall{{ID: "approved", Function: types.FunctionCall{Name: "approved_action", Arguments: `{}`}}})
|
||||
snap, err := initial.snapshot(0)
|
||||
require.NoError(t, err)
|
||||
data, err := json.Marshal(snap)
|
||||
require.NoError(t, err)
|
||||
model := collaborationAnswerModel("done")
|
||||
next := newTestEngine(t, model)
|
||||
next.toolRegistry = agenttools.NewToolRegistry()
|
||||
action := newCountingTool("approved_action")
|
||||
next.toolRegistry.RegisterTool(action)
|
||||
// Approval restoration creates a new binding whose cursor starts at zero.
|
||||
next.SetCollaboration(&collaboration.Binding{Runtime: r, Scope: b.Scope, ParentOwner: owned.ParentOwner})
|
||||
_, err = next.Resume(t.Context(), "s", "m", nil, data, &types.AgentPrompt{ID: "approval", ToolCallID: "approved"})
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, 1, action.calls)
|
||||
restored := collaborationTranscript(model.calls[0])
|
||||
require.Equal(t, 1, strings.Count(restored, "FIRST_PROGRESS"))
|
||||
require.Equal(t, 1, strings.Count(restored, "FINAL_RESULT"))
|
||||
require.Less(t, strings.Index(restored, "FIRST_PROGRESS"), strings.Index(restored, "BETWEEN_MESSAGES"))
|
||||
require.Less(t, strings.Index(restored, "BETWEEN_MESSAGES"), strings.Index(restored, "FINAL_RESULT"))
|
||||
require.Less(t, strings.Index(restored, "FINAL_RESULT"), strings.Index(restored, "NEW_USER_GUIDANCE"))
|
||||
require.Less(t, strings.Index(restored, "NEW_USER_GUIDANCE"), strings.Index(restored, "APPROVAL_ROUND"))
|
||||
}
|
||||
|
|
@ -0,0 +1,962 @@
|
|||
package agent
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
agenttools "github.com/Tencent/WeKnora/internal/agent/tools"
|
||||
|
||||
"github.com/Tencent/WeKnora/internal/agent/collaboration"
|
||||
"github.com/Tencent/WeKnora/internal/event"
|
||||
"github.com/Tencent/WeKnora/internal/models/chat"
|
||||
"github.com/Tencent/WeKnora/internal/types"
|
||||
"github.com/stretchr/testify/require"
|
||||
"gorm.io/driver/sqlite"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
func engineCollaboration(t *testing.T) (*collaboration.Runtime, *collaboration.Binding) {
|
||||
t.Helper()
|
||||
db, err := gorm.Open(
|
||||
sqlite.Open(filepath.Join(t.TempDir(), "engine.db")+"?_busy_timeout=5000&_journal_mode=WAL"),
|
||||
&gorm.Config{},
|
||||
)
|
||||
require.NoError(t, err)
|
||||
sql, err := db.DB()
|
||||
require.NoError(t, err)
|
||||
t.Cleanup(func() { _ = sql.Close() })
|
||||
require.NoError(t, db.AutoMigrate(&collaboration.Record{}))
|
||||
store := collaboration.NewStore(db)
|
||||
scope := collaboration.Scope{TenantID: 1, UserID: "u", SessionID: "s", ID: "m"}
|
||||
require.NoError(t, store.Ensure(context.Background(), scope))
|
||||
r := collaboration.New(store, nil)
|
||||
r.Poll = time.Millisecond
|
||||
return r, &collaboration.Binding{Runtime: r, Scope: scope}
|
||||
}
|
||||
|
||||
// Runtime identity must follow the bound execution, including a fresh engine
|
||||
// after recovery, without exposing the private configuration/ownership data.
|
||||
func TestCollaborationPromptUsesBoundRoleAndRun(t *testing.T) {
|
||||
engine := newTestEngine(t, nil)
|
||||
engine.systemPromptTemplate = "Template task instructions."
|
||||
baseline := engine.buildSystemPrompt(t.Context())
|
||||
require.NotContains(t, baseline, "<agent_coordination>")
|
||||
require.NotContains(t, baseline, "<delegated_task>")
|
||||
require.NotContains(t, baseline, "Proactively delegate")
|
||||
engine.SetCollaboration(&collaboration.Binding{})
|
||||
parent := engine.buildSystemPrompt(t.Context())
|
||||
require.Contains(t, parent, "You are /root,")
|
||||
require.Equal(t, 1, strings.Count(parent, "Proactively delegate"))
|
||||
require.Contains(t, parent, "reading them does not adopt its role")
|
||||
require.Contains(t, parent, "Waiting, failure or an approval request does not transfer ownership to you")
|
||||
require.NotContains(t, parent, "<delegated_task>")
|
||||
for _, runID := range []string{"initial-run", "followup-run"} {
|
||||
child := newTestEngine(t, nil)
|
||||
child.systemPromptTemplate = engine.systemPromptTemplate
|
||||
child.SetCollaboration(&collaboration.Binding{Child: &collaboration.Work{
|
||||
Member: collaboration.Member{Name: "research", ConfigJSON: "PRIVATE_CONFIG"},
|
||||
Run: collaboration.Run{ID: runID, Owner: "PRIVATE_OWNER"},
|
||||
}})
|
||||
prompt := child.buildSystemPrompt(t.Context())
|
||||
require.Contains(t, prompt, baseline, "template instructions remain available")
|
||||
require.Contains(t, prompt, `child agent "/root/research"`)
|
||||
require.Contains(t, prompt, `run_id "`+runID+`"`)
|
||||
require.Contains(t, prompt, "Execute the assigned work with the instructions, tools, skills")
|
||||
require.NotContains(t, prompt, "You coordinate, inspect delivered artifacts")
|
||||
require.NotContains(t, prompt, "<agent_coordination>")
|
||||
require.NotContains(t, prompt, "Proactively delegate", "children cannot spawn nested tasks")
|
||||
require.NotContains(t, prompt, "PRIVATE_CONFIG")
|
||||
require.NotContains(t, prompt, "PRIVATE_OWNER")
|
||||
}
|
||||
}
|
||||
|
||||
// The child commits while the first response is being generated. Its result
|
||||
// must force another model call and never appear as a new human instruction.
|
||||
func TestCollaborationResultAtNaturalStopRequiresAnotherModelRound(t *testing.T) {
|
||||
r, b := engineCollaboration(t)
|
||||
ctx := context.Background()
|
||||
_, err := r.Spawn(ctx, b.Scope, "spawn", "research", "a", "{}", "q")
|
||||
require.NoError(t, err)
|
||||
model := &mockChat{responses: []mockResponse{
|
||||
{
|
||||
chunks: []types.StreamResponse{
|
||||
{ResponseType: types.ResponseTypeThinking, Content: "checking child"},
|
||||
{ResponseType: types.ResponseTypeAnswer, Content: "premature", Done: true, FinishReason: "stop"},
|
||||
},
|
||||
},
|
||||
{
|
||||
chunks: []types.StreamResponse{
|
||||
{
|
||||
ResponseType: types.ResponseTypeAnswer,
|
||||
Content: "reviewed child result",
|
||||
Done: true,
|
||||
FinishReason: "stop",
|
||||
},
|
||||
},
|
||||
},
|
||||
}}
|
||||
engine := newTestEngine(t, model)
|
||||
engine.eventBus = event.NewEventBus()
|
||||
engine.SetCollaboration(b)
|
||||
recorder := &truncationRecorder{}
|
||||
recorder.attach(engine.eventBus)
|
||||
engine.eventBus.On(event.EventAgentThought, func(ctx context.Context, evt event.Event) error {
|
||||
data, ok := evt.Data.(event.AgentThoughtData)
|
||||
if ok && data.Content == "checking child" {
|
||||
return r.Interrupt(ctx, b.Scope, "research", "")
|
||||
}
|
||||
return nil
|
||||
})
|
||||
state := &types.AgentState{RoundSteps: []types.AgentStep{}}
|
||||
_, err = engine.executeLoop(ctx, state, "query", []chat.Message{{Role: "user", Content: "query"}}, nil, "s", "m")
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, "reviewed child result", state.FinalAnswer)
|
||||
for _, event := range recorder.snapshot() {
|
||||
require.NotContains(t, event.Content, "premature")
|
||||
}
|
||||
require.Len(t, model.calls, 2)
|
||||
found := false
|
||||
boundaryCount := 0
|
||||
for _, m := range model.calls[1] {
|
||||
if m.Content == collaborationDeliveryBoundary {
|
||||
boundaryCount++
|
||||
}
|
||||
if strings.HasPrefix(m.Content, "Message Type: FINAL_ANSWER\n") {
|
||||
require.Equal(t, "assistant", m.Role)
|
||||
require.Contains(t, m.Content, "research")
|
||||
found = true
|
||||
}
|
||||
}
|
||||
require.True(t, found)
|
||||
require.Equal(t, 1, boundaryCount, "new result supersedes one draft, not every previous tool step")
|
||||
g, err := r.Store.Read(ctx, b.Scope)
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, "completed", g.Status)
|
||||
}
|
||||
|
||||
func TestCollaborationParentCancellationCancelsQueuedChildren(t *testing.T) {
|
||||
r, b := engineCollaboration(t)
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
_, err := r.Spawn(ctx, b.Scope, "spawn", "one", "a", "{}", "q")
|
||||
require.NoError(t, err)
|
||||
cancel()
|
||||
engine := newTestEngine(t, &mockChat{})
|
||||
engine.eventBus = event.NewEventBus()
|
||||
engine.SetCollaboration(b)
|
||||
_, err = engine.executeLoop(ctx, &types.AgentState{}, "q", nil, nil, "s", "m")
|
||||
require.ErrorIs(t, err, context.Canceled)
|
||||
g, err := r.Store.Read(context.Background(), b.Scope)
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, "cancelled", g.Status)
|
||||
require.Equal(t, "cancelled", g.Members[0].Runs[0].State)
|
||||
}
|
||||
|
||||
func TestCollaborationProgressPreambleVisibleWithoutPublishingPrematureAnswer(t *testing.T) {
|
||||
r, b := engineCollaboration(t)
|
||||
ctx := context.Background()
|
||||
_, err := r.Spawn(ctx, b.Scope, "spawn", "research", "a", "{}", "q")
|
||||
require.NoError(t, err)
|
||||
const progress = "The list is ready; the child is reading two articles."
|
||||
model := &mockChat{responses: []mockResponse{
|
||||
{
|
||||
chunks: []types.StreamResponse{
|
||||
{
|
||||
ResponseType: types.ResponseTypeAnswer,
|
||||
Content: progress,
|
||||
Done: true,
|
||||
FinishReason: "tool_calls",
|
||||
ToolCalls: []types.LLMToolCall{
|
||||
{
|
||||
ID: "wait",
|
||||
Type: "function",
|
||||
Function: types.FunctionCall{Name: "wait_agent", Arguments: `{"timeout_ms":1000}`},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
{
|
||||
chunks: []types.StreamResponse{
|
||||
{
|
||||
ResponseType: types.ResponseTypeAnswer,
|
||||
Content: "child interrupted",
|
||||
Done: true,
|
||||
FinishReason: "stop",
|
||||
},
|
||||
},
|
||||
},
|
||||
}}
|
||||
engine := newTestEngine(t, model)
|
||||
engine.SetCollaboration(b)
|
||||
engine.toolRegistry = agenttools.NewToolRegistry()
|
||||
for _, tool := range agenttools.NewCollaborationTools(b, nil) {
|
||||
engine.toolRegistry.RegisterTool(tool)
|
||||
}
|
||||
recorder := &truncationRecorder{}
|
||||
recorder.attach(engine.eventBus)
|
||||
progressCount := 0
|
||||
engine.eventBus.On(event.EventAgentThought, func(_ context.Context, evt event.Event) error {
|
||||
if data, ok := evt.Data.(event.AgentThoughtData); ok {
|
||||
require.NotContains(t, data.Content, progress)
|
||||
}
|
||||
return nil
|
||||
})
|
||||
engine.eventBus.On(event.EventAgentProgress, func(ctx context.Context, evt event.Event) error {
|
||||
if data, ok := evt.Data.(event.AgentProgressData); ok && data.Content == progress {
|
||||
progressCount++
|
||||
// Finish only after the live progress is visible. This also proves
|
||||
// the update is emitted before the blocking wait tool executes.
|
||||
return r.Interrupt(ctx, b.Scope, "research", "")
|
||||
}
|
||||
return nil
|
||||
})
|
||||
state, err := engine.Execute(ctx, "s", "m", "report", nil, nil)
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, 1, progressCount)
|
||||
require.Equal(t, progress, state.RoundSteps[0].Progress)
|
||||
require.True(t, state.IsComplete)
|
||||
require.Equal(t, "child interrupted", state.FinalAnswer)
|
||||
for _, emitted := range recorder.snapshot() {
|
||||
require.NotContains(t, emitted.Content, progress)
|
||||
}
|
||||
}
|
||||
|
||||
func TestCollaborationWaitResumeDoesNotReplayEarlierTools(t *testing.T) {
|
||||
r, b := engineCollaboration(t)
|
||||
ctx := context.Background()
|
||||
owned, err := r.AcquireParent(ctx, b.Scope)
|
||||
require.NoError(t, err)
|
||||
model := &mockChat{
|
||||
responses: []mockResponse{
|
||||
{
|
||||
chunks: []types.StreamResponse{
|
||||
{ResponseType: types.ResponseTypeAnswer, Content: "resumed", Done: true, FinishReason: "stop"},
|
||||
},
|
||||
},
|
||||
},
|
||||
}
|
||||
engine := newTestEngine(t, model)
|
||||
engine.toolRegistry = agenttools.NewToolRegistry()
|
||||
engine.SetCollaboration(owned)
|
||||
engine.EnableSuspension(json.RawMessage(`{}`))
|
||||
first := newCountingTool("change_data")
|
||||
after := newCountingTool("after_wait")
|
||||
engine.toolRegistry.RegisterTool(first)
|
||||
engine.toolRegistry.RegisterTool(after)
|
||||
for _, tool := range agenttools.NewCollaborationTools(owned, nil) {
|
||||
engine.toolRegistry.RegisterTool(tool)
|
||||
}
|
||||
owned.WaitUntil = time.Now().Add(-time.Second)
|
||||
snapshot := RunSnapshot{
|
||||
Version: RunSnapshotVersion, CollaborationWait: true, Query: "task", CurrentRound: 0,
|
||||
PendingRound: PendingRound{
|
||||
BlockedIndex: 1,
|
||||
Step: types.AgentStep{
|
||||
ToolCalls: []types.ToolCall{
|
||||
{ID: "write", Name: first.Name(), Result: &types.ToolResult{Success: true, Output: "already done"}},
|
||||
},
|
||||
},
|
||||
Calls: []PendingCall{
|
||||
{
|
||||
ID: "write",
|
||||
Name: first.Name(),
|
||||
Arguments: `{}`,
|
||||
},
|
||||
{
|
||||
ID: "wait",
|
||||
Name: "wait_agent",
|
||||
Arguments: `{"timeout_ms":1000}`,
|
||||
},
|
||||
{
|
||||
ID: "after",
|
||||
Name: after.Name(),
|
||||
Arguments: `{}`,
|
||||
},
|
||||
},
|
||||
},
|
||||
}
|
||||
data, err := json.Marshal(snapshot)
|
||||
require.NoError(t, err)
|
||||
state, err := engine.Resume(ctx, "s", "m", nil, data, nil)
|
||||
require.NoError(t, err)
|
||||
require.True(t, state.IsComplete)
|
||||
require.Zero(t, first.calls)
|
||||
require.Equal(t, 1, after.calls)
|
||||
require.Equal(t, "resumed", state.FinalAnswer)
|
||||
}
|
||||
|
||||
func TestCollaborationRejectsNonWaitSnapshotWithoutApproval(t *testing.T) {
|
||||
r, b := engineCollaboration(t)
|
||||
owned, err := r.AcquireParent(context.Background(), b.Scope)
|
||||
require.NoError(t, err)
|
||||
engine := newTestEngine(t, &mockChat{})
|
||||
engine.toolRegistry = agenttools.NewToolRegistry()
|
||||
engine.SetCollaboration(owned)
|
||||
snapshot := RunSnapshot{
|
||||
Version: RunSnapshotVersion,
|
||||
CollaborationWait: true,
|
||||
PendingRound: PendingRound{Calls: []PendingCall{{ID: "unsafe", Name: "write_data"}}},
|
||||
}
|
||||
data, err := json.Marshal(snapshot)
|
||||
require.NoError(t, err)
|
||||
_, err = engine.Resume(context.Background(), "s", "m", nil, data, nil)
|
||||
require.ErrorContains(t, err, "unsafe collaboration checkpoint")
|
||||
}
|
||||
|
||||
func TestCollaborationWaitCanceledTransportLeavesRecoverableCheckpoint(t *testing.T) {
|
||||
r, b := engineCollaboration(t)
|
||||
ctx := context.Background()
|
||||
owned, err := r.AcquireParent(ctx, b.Scope)
|
||||
require.NoError(t, err)
|
||||
_, err = r.Spawn(ctx, b.Scope, "spawn", "child", "a", "{}", "task")
|
||||
require.NoError(t, err)
|
||||
model := &mockChat{
|
||||
responses: []mockResponse{
|
||||
{
|
||||
chunks: []types.StreamResponse{
|
||||
{ResponseType: types.ResponseTypeAnswer, Content: "waiting", Done: true, FinishReason: "stop"},
|
||||
},
|
||||
},
|
||||
},
|
||||
}
|
||||
engine := newTestEngine(t, model)
|
||||
engine.toolRegistry = agenttools.NewToolRegistry()
|
||||
engine.SetCollaboration(owned)
|
||||
engine.EnableSuspension(json.RawMessage(`{}`))
|
||||
runCtx, cancel := context.WithCancel(ctx)
|
||||
finished := make(chan *types.AgentState, 1)
|
||||
go func() { state, _ := engine.Execute(runCtx, "s", "m", "task", nil); finished <- state }()
|
||||
require.Eventually(
|
||||
t,
|
||||
func() bool { g, err := r.Store.Read(ctx, b.Scope); return err == nil && g.ParentWait != nil },
|
||||
time.Second,
|
||||
time.Millisecond,
|
||||
)
|
||||
cancel()
|
||||
select {
|
||||
case <-finished:
|
||||
case <-time.After(time.Second):
|
||||
t.Fatal("engine did not stop")
|
||||
}
|
||||
g, err := r.Store.Read(ctx, b.Scope)
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, "active", g.Status)
|
||||
require.NotNil(t, g.ParentWait)
|
||||
// An explicit user stop, unlike a lost transport, permanently closes it.
|
||||
require.NoError(t, r.Cancel(ctx, b.Scope))
|
||||
require.Equal(t, "cancelled", func() string { g, _ := r.Store.Read(ctx, b.Scope); return g.Status }())
|
||||
}
|
||||
|
||||
// A steering message arriving after the model chose wait_agent must enter the
|
||||
// next model call as user input, exactly once, without waiting sixty seconds.
|
||||
func TestCollaborationEngineWaitDeliversSteerPromptly(t *testing.T) {
|
||||
_, b := engineCollaboration(t)
|
||||
model := &mockChat{responses: []mockResponse{
|
||||
{
|
||||
chunks: []types.StreamResponse{
|
||||
{
|
||||
ResponseType: types.ResponseTypeAnswer,
|
||||
Done: true,
|
||||
FinishReason: "tool_calls",
|
||||
ToolCalls: []types.LLMToolCall{
|
||||
{
|
||||
ID: "wait",
|
||||
Type: "function",
|
||||
Function: types.FunctionCall{Name: "wait_agent", Arguments: `{"timeout_ms":60000}`},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
{
|
||||
chunks: []types.StreamResponse{
|
||||
{ResponseType: types.ResponseTypeAnswer, Content: "applied guidance", Done: true, FinishReason: "stop"},
|
||||
},
|
||||
},
|
||||
}}
|
||||
engine := newTestEngine(t, model)
|
||||
engine.SetCollaboration(b)
|
||||
sink := &fakeSteerSink{}
|
||||
engine.SetSteerSink(sink)
|
||||
engine.toolRegistry = agenttools.NewToolRegistry()
|
||||
for _, tool := range agenttools.NewCollaborationTools(b, nil) {
|
||||
engine.toolRegistry.RegisterTool(tool)
|
||||
}
|
||||
engine.eventBus.On(event.EventAgentToolCall, func(context.Context, event.Event) error {
|
||||
sink.queued = []map[string]interface{}{steerEntry("s1", "include costs")}
|
||||
return nil
|
||||
})
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)
|
||||
defer cancel()
|
||||
state, err := engine.Execute(ctx, "s", "m", "task", nil, nil)
|
||||
require.NoError(t, err)
|
||||
require.True(t, state.IsComplete)
|
||||
require.Equal(t, []string{"include costs"}, sink.persisted)
|
||||
require.Len(t, model.calls, 2)
|
||||
found := false
|
||||
for _, msg := range model.calls[1] {
|
||||
if msg.Role == "user" && strings.Contains(msg.Content, "include costs") {
|
||||
found = true
|
||||
}
|
||||
}
|
||||
require.True(t, found)
|
||||
}
|
||||
|
||||
type collaborationDelayedSteer struct {
|
||||
fakeSteerSink
|
||||
polls int
|
||||
}
|
||||
|
||||
func (s *collaborationDelayedSteer) PollSteer(
|
||||
ctx context.Context,
|
||||
session, message string,
|
||||
offset int,
|
||||
) ([]map[string]interface{}, int, error) {
|
||||
s.polls++
|
||||
if s.polls < 3 {
|
||||
return nil, 0, nil
|
||||
}
|
||||
return s.fakeSteerSink.PollSteer(ctx, session, message, offset)
|
||||
}
|
||||
|
||||
func TestCollaborationNaturalFinishReopensForSteerDuringWait(t *testing.T) {
|
||||
_, b := engineCollaboration(t)
|
||||
model := &mockChat{responses: []mockResponse{
|
||||
{
|
||||
chunks: []types.StreamResponse{
|
||||
{ResponseType: types.ResponseTypeAnswer, Content: "first answer", Done: true, FinishReason: "stop"},
|
||||
},
|
||||
},
|
||||
{
|
||||
chunks: []types.StreamResponse{
|
||||
{ResponseType: types.ResponseTypeAnswer, Content: "revised answer", Done: true, FinishReason: "stop"},
|
||||
},
|
||||
},
|
||||
}}
|
||||
engine := newTestEngine(t, model)
|
||||
engine.SetCollaboration(b)
|
||||
engine.toolRegistry = agenttools.NewToolRegistry()
|
||||
sink := &collaborationDelayedSteer{
|
||||
fakeSteerSink: fakeSteerSink{queued: []map[string]interface{}{steerEntry("s1", "include costs")}},
|
||||
}
|
||||
engine.SetSteerSink(sink)
|
||||
state, err := engine.Execute(context.Background(), "s", "m", "task", nil, nil)
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, "revised answer", state.FinalAnswer)
|
||||
require.Len(t, sink.persisted, 1)
|
||||
}
|
||||
|
||||
// A first child result plus a followup is one user deliverable. The model must
|
||||
// receive both source results without a repeated instruction after every tool call.
|
||||
func TestCollaborationMultipartResultsWithoutRepeatedGuidance(t *testing.T) {
|
||||
r, b := engineCollaboration(t)
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
|
||||
defer cancel()
|
||||
r.Run = func(_ context.Context, w collaboration.Work) (collaboration.Result, error) {
|
||||
return collaboration.Result{Answer: w.Run.Query}, nil
|
||||
}
|
||||
_, err := r.Spawn(ctx, b.Scope, "spawn", "report", "a", "{}", "section one with citation A")
|
||||
require.NoError(t, err)
|
||||
r.Tick(ctx)
|
||||
require.Eventually(t, func() bool {
|
||||
g, err := r.Store.Read(ctx, b.Scope)
|
||||
return err == nil && g.Members[0].Runs[0].State == "succeeded"
|
||||
}, time.Second, time.Millisecond)
|
||||
r.Start(ctx)
|
||||
defer func() { require.NoError(t, r.Stop(context.Background())) }()
|
||||
model := &mockChat{responses: []mockResponse{
|
||||
{
|
||||
chunks: []types.StreamResponse{
|
||||
{
|
||||
ResponseType: types.ResponseTypeAnswer,
|
||||
Content: "The first section is ready; collecting the rest.",
|
||||
Done: true,
|
||||
FinishReason: "tool_calls",
|
||||
ToolCalls: []types.LLMToolCall{
|
||||
{
|
||||
ID: "continue-report",
|
||||
Type: "function",
|
||||
Function: types.FunctionCall{
|
||||
Name: "followup_task",
|
||||
Arguments: `{"target":"report","message":"section two with citation B"}`,
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
{
|
||||
chunks: []types.StreamResponse{
|
||||
{
|
||||
ResponseType: types.ResponseTypeAnswer,
|
||||
Done: true,
|
||||
FinishReason: "tool_calls",
|
||||
ToolCalls: []types.LLMToolCall{
|
||||
{
|
||||
ID: "wait-report",
|
||||
Type: "function",
|
||||
Function: types.FunctionCall{Name: "wait_agent", Arguments: `{"timeout_ms":1000}`},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
{
|
||||
chunks: []types.StreamResponse{
|
||||
{
|
||||
ResponseType: types.ResponseTypeAnswer,
|
||||
Content: "section one with citation A\n\nsection two with citation B",
|
||||
Done: true,
|
||||
FinishReason: "stop",
|
||||
},
|
||||
},
|
||||
},
|
||||
}}
|
||||
engine := newTestEngine(t, model)
|
||||
engine.SetCollaboration(b)
|
||||
engine.toolRegistry = agenttools.NewToolRegistry()
|
||||
for _, tool := range agenttools.NewCollaborationTools(b, nil) {
|
||||
engine.toolRegistry.RegisterTool(tool)
|
||||
}
|
||||
state, err := engine.Execute(ctx, "s", "m", "Produce the complete report", nil, nil)
|
||||
require.NoError(t, err)
|
||||
require.True(t, state.IsComplete)
|
||||
require.Len(t, model.calls, 3)
|
||||
require.Equal(t, "section one with citation A\n\nsection two with citation B", state.FinalAnswer)
|
||||
var input strings.Builder
|
||||
foundBoundary := false
|
||||
for _, msg := range model.calls[2] {
|
||||
input.WriteString(msg.Content)
|
||||
if msg.Content == collaborationDeliveryBoundary {
|
||||
require.Equal(t, "system", msg.Role)
|
||||
foundBoundary = true
|
||||
}
|
||||
}
|
||||
require.False(t, foundBoundary, "normal tool rounds do not need a draft-continuation marker")
|
||||
require.Contains(t, input.String(), "section one with citation A")
|
||||
require.Contains(t, input.String(), "section two with citation B")
|
||||
require.Equal(t, 1, strings.Count(input.String(), "<agent_coordination>"))
|
||||
require.Equal(t, 2, strings.Count(input.String(), "Message Type: FINAL_ANSWER\n"))
|
||||
require.NotContains(t, state.FinalAnswer, "Runtime delivery state")
|
||||
require.Equal(t, "The first section is ready; collecting the rest.", state.RoundSteps[0].Thought)
|
||||
}
|
||||
|
||||
func TestCollaborationResumeRestoresIntermediateDeliveryBoundary(t *testing.T) {
|
||||
r, b := engineCollaboration(t)
|
||||
owned, err := r.AcquireParent(context.Background(), b.Scope)
|
||||
require.NoError(t, err)
|
||||
model := &mockChat{
|
||||
responses: []mockResponse{
|
||||
{
|
||||
chunks: []types.StreamResponse{
|
||||
{
|
||||
ResponseType: types.ResponseTypeAnswer,
|
||||
Content: "complete report",
|
||||
Done: true,
|
||||
FinishReason: "stop",
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
}
|
||||
engine := newTestEngine(t, model)
|
||||
engine.SetCollaboration(owned)
|
||||
engine.toolRegistry = agenttools.NewToolRegistry()
|
||||
snapshot := RunSnapshot{
|
||||
Version: RunSnapshotVersion,
|
||||
CollaborationWait: true,
|
||||
BetweenRounds: true,
|
||||
Query: "report",
|
||||
CurrentRound: 1,
|
||||
CompletedSteps: []types.AgentStep{{Thought: "first fragment", IntermediateAnswer: true}},
|
||||
}
|
||||
data, err := json.Marshal(snapshot)
|
||||
require.NoError(t, err)
|
||||
state, err := engine.Resume(context.Background(), "s", "m", nil, data, nil)
|
||||
require.NoError(t, err)
|
||||
require.True(t, state.IsComplete)
|
||||
found := false
|
||||
for _, msg := range model.calls[0] {
|
||||
if msg.Content == collaborationDeliveryBoundary {
|
||||
found = true
|
||||
}
|
||||
}
|
||||
require.True(t, found, "snapshot recovery must preserve the presentation boundary")
|
||||
}
|
||||
|
||||
func TestCollaborationOutcomeEnvelopePreservesPayloadAndStatus(t *testing.T) {
|
||||
answer := strings.Repeat("完整结果与引用 [来源](https://example.com)\n", 400)
|
||||
for _, status := range []string{"succeeded", "failed", "interrupted", "cancelled", "needs_attention"} {
|
||||
t.Run(status, func(t *testing.T) {
|
||||
data, err := json.Marshal(map[string]any{"session_id": "session", "result": collaboration.Result{
|
||||
Answer: answer,
|
||||
Error: "error\nwith details",
|
||||
Evidence: "tool: success=true\nreference: A",
|
||||
Truncated: true,
|
||||
}})
|
||||
require.NoError(t, err)
|
||||
var messages []chat.Message
|
||||
appendCollaborationEvents(
|
||||
&messages,
|
||||
[]collaboration.Event{
|
||||
{Sequence: 42, From: "research", RunID: "run-1", Kind: status, Content: string(data)},
|
||||
},
|
||||
)
|
||||
require.Len(t, messages, 1)
|
||||
require.Equal(t, "assistant", messages[0].Role)
|
||||
body := messages[0].Content
|
||||
require.Contains(
|
||||
t,
|
||||
body,
|
||||
"Message Type: FINAL_ANSWER\nSender: /root/research\nRun ID: run-1\nSequence: 42\nStatus: "+status+"\n",
|
||||
)
|
||||
require.Contains(t, body, "Truncated: true\n")
|
||||
require.Contains(t, body, `Error: "error\nwith details"`)
|
||||
require.Contains(t, body, `Evidence: "tool: success=true\nreference: A"`)
|
||||
_, payload, ok := strings.Cut(body, "Payload:\n")
|
||||
require.True(t, ok)
|
||||
require.Equal(t, answer, payload, "rendering must not truncate, escape or rewrite the final answer")
|
||||
})
|
||||
}
|
||||
for _, tc := range []struct{ kind, from, messageType string }{
|
||||
{"message", "root", "MESSAGE"}, {"followup", "root", "NEW_TASK"},
|
||||
} {
|
||||
body := formatCollaborationEvent(collaboration.Event{From: tc.from, Kind: tc.kind, Content: "plain\ntext"})
|
||||
require.True(t, strings.HasPrefix(body, "Message Type: "+tc.messageType+"\n"))
|
||||
require.True(t, strings.HasSuffix(body, "Payload:\nplain\ntext"))
|
||||
}
|
||||
for _, content := range []string{"legacy result", `{}`, `{"result":null}`, `{"result":`} {
|
||||
body := formatCollaborationEvent(collaboration.Event{Kind: "failed", From: "research", Content: content})
|
||||
require.True(t, strings.HasSuffix(body, "Payload:\n"+content), "legacy/malformed results remain available")
|
||||
}
|
||||
}
|
||||
|
||||
// A restarted parent rebuilds tool history but obtains child results from the
|
||||
// durable mailbox. Include both previously observed and newly completed runs.
|
||||
func TestCollaborationResumeCollectsAllChildrenWithoutToolReplay(t *testing.T) {
|
||||
r, b := engineCollaboration(t)
|
||||
ctx := t.Context()
|
||||
for _, name := range []string{"one", "two", "three"} {
|
||||
_, err := r.Spawn(ctx, b.Scope, name, name, "template", "{}", "task")
|
||||
require.NoError(t, err)
|
||||
}
|
||||
require.NoError(t, r.Store.Change(ctx, b.Scope, func(g *collaboration.Group) error {
|
||||
for i, m := range g.Members {
|
||||
v := m.Runs[0]
|
||||
v.State = "succeeded"
|
||||
v.Result.Answer = "result-" + m.Name
|
||||
payload, err := json.Marshal(map[string]any{"result": v.Result, "session_id": m.SessionID})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
g.NextSequence = int64(i + 1)
|
||||
g.Events = append(
|
||||
g.Events,
|
||||
collaboration.Event{
|
||||
Sequence: g.NextSequence,
|
||||
From: m.Name,
|
||||
RunID: v.ID,
|
||||
Kind: v.State,
|
||||
Content: string(payload),
|
||||
},
|
||||
)
|
||||
}
|
||||
return nil
|
||||
}))
|
||||
// A new scheduler/binding models process restart; no in-memory mailbox survives.
|
||||
restarted := collaboration.New(r.Store, nil)
|
||||
owned, err := restarted.AcquireParent(ctx, b.Scope)
|
||||
require.NoError(t, err)
|
||||
model := &mockChat{
|
||||
responses: []mockResponse{{chunks: []types.StreamResponse{{
|
||||
ResponseType: types.ResponseTypeAnswer,
|
||||
Content: "result-one\nresult-two\nresult-three", Done: true, FinishReason: "stop",
|
||||
}}}},
|
||||
}
|
||||
engine := newTestEngine(t, model)
|
||||
engine.SetCollaboration(owned)
|
||||
engine.toolRegistry = agenttools.NewToolRegistry()
|
||||
write := newCountingTool("write")
|
||||
engine.toolRegistry.RegisterTool(write)
|
||||
snapshot := RunSnapshot{
|
||||
Version: RunSnapshotVersion,
|
||||
CollaborationWait: true,
|
||||
BetweenRounds: true,
|
||||
Query: "combine all results",
|
||||
CurrentRound: 1,
|
||||
CompletedSteps: []types.AgentStep{
|
||||
{
|
||||
Thought: "working",
|
||||
ToolCalls: []types.ToolCall{
|
||||
{ID: "done", Name: "write", Result: &types.ToolResult{Success: true, Output: "already written"}},
|
||||
},
|
||||
},
|
||||
},
|
||||
}
|
||||
data, err := json.Marshal(snapshot)
|
||||
require.NoError(t, err)
|
||||
state, err := engine.Resume(ctx, "s", "m", nil, data, nil)
|
||||
require.NoError(t, err)
|
||||
require.Zero(t, write.calls)
|
||||
require.True(t, state.IsComplete)
|
||||
require.Equal(t, "result-one\nresult-two\nresult-three", state.FinalAnswer)
|
||||
require.Len(t, model.calls, 1)
|
||||
var input strings.Builder
|
||||
for _, msg := range model.calls[0] {
|
||||
input.WriteString(msg.Content)
|
||||
require.NotEqual(t, collaborationDeliveryBoundary, msg.Content)
|
||||
}
|
||||
for _, name := range []string{"one", "two", "three"} {
|
||||
require.Equal(t, 1, strings.Count(input.String(), "Payload:\nresult-"+name))
|
||||
}
|
||||
g, err := r.Store.Read(ctx, b.Scope)
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, "completed", g.Status)
|
||||
}
|
||||
|
||||
// Every signed-in reasoning turn is bound to a collaboration. A turn that never
|
||||
// delegated must keep the ordinary fallbacks instead of failing.
|
||||
func TestCollaborationParentWithoutChildrenKeepsFallbacks(t *testing.T) {
|
||||
for _, mode := range []string{"empty", "repeated_truncation", "max_iterations"} {
|
||||
t.Run(mode, func(t *testing.T) {
|
||||
r, b := engineCollaboration(t)
|
||||
owned, err := r.AcquireParent(t.Context(), b.Scope)
|
||||
require.NoError(t, err)
|
||||
model := &mockChat{}
|
||||
rounds := 8
|
||||
if mode == "max_iterations" {
|
||||
rounds = 2
|
||||
}
|
||||
for range rounds {
|
||||
response := types.StreamResponse{
|
||||
ResponseType: types.ResponseTypeAnswer, Done: true, FinishReason: "stop",
|
||||
}
|
||||
switch mode {
|
||||
case "repeated_truncation":
|
||||
response.FinishReason = "length"
|
||||
response.ToolCalls = []types.LLMToolCall{{
|
||||
ID: "cut-off", Type: "function",
|
||||
Function: types.FunctionCall{Name: "write", Arguments: `{"unfinished":`},
|
||||
}}
|
||||
case "max_iterations":
|
||||
response.FinishReason = "tool_calls"
|
||||
response.ToolCalls = []types.LLMToolCall{{
|
||||
ID: "call", Type: "function",
|
||||
Function: types.FunctionCall{Name: "missing_tool", Arguments: `{}`},
|
||||
}}
|
||||
}
|
||||
model.responses = append(model.responses, mockResponse{chunks: []types.StreamResponse{response}})
|
||||
}
|
||||
model.responses = append(model.responses, mockResponse{chunks: []types.StreamResponse{{
|
||||
ResponseType: types.ResponseTypeAnswer, Content: "summary", Done: true, FinishReason: "stop",
|
||||
}}})
|
||||
engine := newTestEngine(t, model)
|
||||
engine.toolRegistry = agenttools.NewToolRegistry()
|
||||
engine.config.MaxIterations = 10
|
||||
if mode == "max_iterations" {
|
||||
engine.config.MaxIterations = 2
|
||||
}
|
||||
engine.SetCollaboration(owned)
|
||||
state := &types.AgentState{}
|
||||
_, err = engine.executeLoop(t.Context(), state, "task", nil, nil, "s", "m")
|
||||
require.NoError(t, err)
|
||||
require.NotEmpty(t, state.FinalAnswer, "the ordinary fallback answer is produced")
|
||||
g, err := r.Store.Read(t.Context(), b.Scope)
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, "completed", g.Status,
|
||||
"a turn without delegated work does not leave a cancellation barrier")
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestCollaborationStalledParentCannotPublishSuccess(t *testing.T) {
|
||||
for _, mode := range []string{"empty", "repeated_response", "repeated_truncation"} {
|
||||
t.Run(mode, func(t *testing.T) {
|
||||
r, b := engineCollaboration(t)
|
||||
_, err := r.Spawn(t.Context(), b.Scope, "spawn", "research", "template", "{}", "task")
|
||||
require.NoError(t, err)
|
||||
model := &mockChat{}
|
||||
for range 8 {
|
||||
response := types.StreamResponse{
|
||||
ResponseType: types.ResponseTypeAnswer,
|
||||
Done: true,
|
||||
FinishReason: "stop",
|
||||
}
|
||||
if mode == "repeated_truncation" {
|
||||
response.FinishReason = "length"
|
||||
response.ToolCalls = []types.LLMToolCall{
|
||||
{
|
||||
ID: "cut-off",
|
||||
Type: "function",
|
||||
Function: types.FunctionCall{Name: "write", Arguments: `{"unfinished":`},
|
||||
},
|
||||
}
|
||||
}
|
||||
chunks := []types.StreamResponse{response}
|
||||
if mode == "repeated_response" {
|
||||
response.Content = "same unfinished draft"
|
||||
chunks = []types.StreamResponse{
|
||||
{ResponseType: types.ResponseTypeThinking, Content: "tick"},
|
||||
response,
|
||||
}
|
||||
}
|
||||
model.responses = append(model.responses, mockResponse{chunks: chunks})
|
||||
}
|
||||
engine := newTestEngine(t, model)
|
||||
engine.config.MaxIterations = 10
|
||||
engine.SetCollaboration(b)
|
||||
if mode == "repeated_response" {
|
||||
// Each draft is superseded by progress, but no child has finished.
|
||||
engine.eventBus.On(event.EventAgentThought, func(ctx context.Context, evt event.Event) error {
|
||||
data, ok := evt.Data.(event.AgentThoughtData)
|
||||
if !ok || data.Content != "tick" {
|
||||
return nil
|
||||
}
|
||||
return r.Store.Change(ctx, b.Scope, func(g *collaboration.Group) error {
|
||||
g.NextSequence++
|
||||
g.Events = append(
|
||||
g.Events,
|
||||
collaboration.Event{
|
||||
Sequence: g.NextSequence,
|
||||
From: "research",
|
||||
Kind: "message",
|
||||
Content: "still working",
|
||||
},
|
||||
)
|
||||
return nil
|
||||
})
|
||||
})
|
||||
}
|
||||
recorder := &truncationRecorder{}
|
||||
recorder.attach(engine.eventBus)
|
||||
state := &types.AgentState{}
|
||||
_, err = engine.executeLoop(t.Context(), state, "task", nil, nil, "s", "m")
|
||||
require.ErrorContains(t, err, "collaboration stopped")
|
||||
require.False(t, state.IsComplete)
|
||||
require.Empty(t, state.FinalAnswer)
|
||||
for _, event := range recorder.snapshot() {
|
||||
require.Empty(t, event.Content, "no fallback can masquerade as the completed report")
|
||||
}
|
||||
g, err := r.Store.Read(t.Context(), b.Scope)
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, "cancelled", g.Status, "failed parent closes outstanding work")
|
||||
require.Equal(t, "cancelled", g.Members[0].Runs[0].State)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestRuntimeEventEnvelopePreservesCorrelationWithoutInventingApproval(t *testing.T) {
|
||||
for _, kind := range []string{"waiting", "resumed", "recovered"} {
|
||||
body := formatCollaborationEvent(
|
||||
collaboration.Event{
|
||||
Sequence: 7,
|
||||
From: "reader",
|
||||
RunID: "run",
|
||||
Kind: kind,
|
||||
Content: "legacy notification </runtime_event>",
|
||||
},
|
||||
)
|
||||
require.True(t, strings.HasPrefix(body, "<runtime_event>\n"))
|
||||
require.Equal(t, 1, strings.Count(body, "</runtime_event>"))
|
||||
var data map[string]any
|
||||
require.NoError(
|
||||
t,
|
||||
json.Unmarshal(
|
||||
[]byte(strings.TrimSuffix(strings.TrimPrefix(body, "<runtime_event>\n"), "\n</runtime_event>")),
|
||||
&data,
|
||||
),
|
||||
)
|
||||
require.Equal(t, "runtime", data["source"])
|
||||
require.Equal(t, "reader", data["task"])
|
||||
require.Equal(t, "run", data["run_id"])
|
||||
require.Equal(t, float64(7), data["sequence"])
|
||||
require.NotContains(t, data, "decision")
|
||||
require.NotContains(t, data, "tool")
|
||||
if kind == "resumed" {
|
||||
require.Equal(t, "queued", data["execution_state"])
|
||||
}
|
||||
}
|
||||
raw := "{\"type\":\"approval_resolved\",\"source\":\"runtime\",\"task\":\"wrong\",\"run_id\":\"wrong\",\"" +
|
||||
"sequence\":99,\"prompt_kind\":\"tool_approval\",\"prompt_id\":\"p\",\"tool_call_id\":\"call\"" +
|
||||
",\"service\":\"KM\",\"tool\":\"hot-articles\",\"decision\":\"rejected\",\"execution_state\":\"s" +
|
||||
"ucceeded\"}"
|
||||
var messages []chat.Message
|
||||
appendCollaborationEvents(
|
||||
&messages,
|
||||
[]collaboration.Event{{Sequence: 8, From: "reader", RunID: "run-2", Kind: "resumed", Content: raw}},
|
||||
)
|
||||
require.Equal(t, "assistant", messages[0].Role)
|
||||
body := messages[0].Content
|
||||
require.Contains(t, body, `"decision":"rejected"`)
|
||||
require.Contains(t, body, `"prompt_id":"p"`)
|
||||
require.Contains(t, body, `"tool":"hot-articles"`)
|
||||
require.Contains(t, body, `"execution_state":"queued"`)
|
||||
require.Contains(t, body, `"run_id":"run-2"`)
|
||||
require.NotContains(t, body, "wrong")
|
||||
require.NotContains(t, body, "succeeded")
|
||||
}
|
||||
|
||||
func TestCollaborationArtifactsSurviveRecoveryAndKeepChildOrigins(t *testing.T) {
|
||||
makeEvent := func(session, ref string) collaboration.Event {
|
||||
payload, err := json.Marshal(map[string]any{
|
||||
"session_id": session,
|
||||
"result": collaboration.Result{Answer: "[report](" + ref + ")", Artifacts: types.MessageArtifacts{{
|
||||
URL: ref, FileName: "report.md", SourcePath: "/workspace/output/report.md", FileType: ".md",
|
||||
}}},
|
||||
})
|
||||
require.NoError(t, err)
|
||||
return collaboration.Event{From: session, Kind: "succeeded", Content: string(payload)}
|
||||
}
|
||||
a := makeEvent("child-a", "resource://"+strings.Repeat("a", 22))
|
||||
b := makeEvent("child-b", "resource://"+strings.Repeat("b", 22))
|
||||
spoofed := makeEvent("child-spoofed", "resource://"+strings.Repeat("c", 22))
|
||||
spoofed.Kind = "message" // Model prose can never manufacture an attachment.
|
||||
engine := &AgentEngine{}
|
||||
var messages []chat.Message
|
||||
engine.deliverCollaborationEvents(&messages, []collaboration.Event{a, b, a, spoofed}, 0, false)
|
||||
require.Contains(t, messages[0].Content, `File: "report.md" Reference: resource://`)
|
||||
before := engine.collaborationArtifacts()
|
||||
require.Len(t, before, 2)
|
||||
require.Equal(t, "collaboration://child-a/workspace/output/report.md", before[0].SourcePath)
|
||||
require.NotEqual(t, before[0].SourcePath, before[1].SourcePath)
|
||||
|
||||
encoded, err := json.Marshal(RunSnapshot{CollaborationDeliveries: engine.progress.collaborationDeliveries})
|
||||
require.NoError(t, err)
|
||||
var snapshot RunSnapshot
|
||||
require.NoError(t, json.Unmarshal(encoded, &snapshot))
|
||||
restarted := &AgentEngine{}
|
||||
require.NoError(t, restarted.restoreCollaborationDeliveries(t.Context(), &snapshot))
|
||||
require.Equal(t, before, restarted.collaborationArtifacts())
|
||||
|
||||
bus := event.NewEventBus()
|
||||
restarted.eventBus = bus
|
||||
var received types.MessageArtifacts
|
||||
bus.On(event.EventAgentComplete, func(_ context.Context, evt event.Event) error {
|
||||
received = evt.Data.(event.AgentCompleteData).Artifacts.(types.MessageArtifacts)
|
||||
return nil
|
||||
})
|
||||
restarted.emitCompletionEvent(t.Context(), &types.AgentState{}, "parent", "answer", time.Now())
|
||||
require.Equal(t, before, received)
|
||||
}
|
||||
|
||||
func TestCollaborationFileMetadataDoesNotExposeStoragePaths(t *testing.T) {
|
||||
deleted := time.Now()
|
||||
payload, err := json.Marshal(map[string]any{"session_id": "child", "result": collaboration.Result{
|
||||
Artifacts: types.MessageArtifacts{
|
||||
{URL: "s3://private-bucket/internal-path", FileName: "private.md"},
|
||||
{URL: "resource://" + strings.Repeat("d", 22), FileName: "deleted.md", DeletedAt: &deleted},
|
||||
},
|
||||
}})
|
||||
require.NoError(t, err)
|
||||
evt := collaboration.Event{Kind: "succeeded", Content: string(payload)}
|
||||
body := formatCollaborationEvent(evt)
|
||||
require.NotContains(t, body, "private-bucket")
|
||||
require.NotContains(t, body, "deleted.md")
|
||||
e := &AgentEngine{}
|
||||
e.progress.collaborationDeliveries = []CollaborationDelivery{{Events: []collaboration.Event{evt}}}
|
||||
require.Len(t, e.collaborationArtifacts(), 1, "deleted files must not be reattached")
|
||||
}
|
||||
|
|
@ -43,9 +43,6 @@ const (
|
|||
// 600-second command timeout so the tool can return a structured timeout
|
||||
// result instead of being cancelled first by the generic agent wrapper.
|
||||
shellExecToolTimeout = 10*time.Minute + 5*time.Second
|
||||
// tryAgentToolTimeout is above the trial runner's own 4-minute limit so
|
||||
// a slow trial still reports what the agent did before it was stopped.
|
||||
tryAgentToolTimeout = 4*time.Minute + 30*time.Second
|
||||
// webFetchToolSlack is how much longer the agent wrapper waits than the
|
||||
// shared page-fetch budget. Same 5s headroom as shell_exec, so web_fetch can
|
||||
// return its own timeout result instead of being cancelled first.
|
||||
|
|
@ -90,6 +87,13 @@ const truncatedAnswerFallback = "Sorry, this answer kept hitting the model's per
|
|||
// and the round that tripped it produced no text.
|
||||
const stalledAnswerFallback = "I'm sorry, I was unable to generate a response. Please try again."
|
||||
|
||||
// Empty model output is a runtime recovery condition, not new user steering.
|
||||
const emptyResponseRetryNotice = "<runtime_event>\n" +
|
||||
"{\"source\":\"runtime\",\"type\":\"empty_response_retry\",\"message\":\"The" +
|
||||
" previous model response contained no usable answer or tool calls. Continue the " +
|
||||
"existing task from the current state. Tools and waiting remain available; " +
|
||||
"provide a final response when the task is ready to conclude.\"}\n</runtime_event>"
|
||||
|
||||
func toolExecutionTimeout(toolName string, arguments ...string) time.Duration {
|
||||
if toolName == "local_browser" && len(arguments) > 0 {
|
||||
var input struct {
|
||||
|
|
@ -102,8 +106,6 @@ func toolExecutionTimeout(toolName string, arguments ...string) time.Duration {
|
|||
switch toolName {
|
||||
case "shell_exec":
|
||||
return shellExecToolTimeout
|
||||
case "try_agent":
|
||||
return tryAgentToolTimeout
|
||||
case "web_fetch":
|
||||
return webfetch.PageFetchTimeout() + webFetchToolSlack
|
||||
}
|
||||
|
|
@ -205,11 +207,18 @@ func (e *AgentEngine) getCompletionTokenBudget() int {
|
|||
func completionTokenBudgetFor(cfg *types.AgentConfig) int {
|
||||
configured := 0
|
||||
sandboxID := ""
|
||||
modelLimit := 0
|
||||
if cfg != nil {
|
||||
configured = cfg.MaxCompletionTokens
|
||||
sandboxID = cfg.SandboxConfigID
|
||||
modelLimit = cfg.ModelMaxOutputTokens
|
||||
}
|
||||
return types.AgentRoundMaxCompletionTokensFor(configured, sandboxID)
|
||||
budget := types.AgentRoundMaxCompletionTokensFor(configured, sandboxID)
|
||||
// Providers reject a request for more output than the model can emit.
|
||||
if modelLimit > 0 {
|
||||
budget = min(budget, modelLimit)
|
||||
}
|
||||
return budget
|
||||
}
|
||||
|
||||
// contextReserveTokens is the part of the window that history may not occupy,
|
||||
|
|
|
|||
|
|
@ -4,9 +4,26 @@ import (
|
|||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/Tencent/WeKnora/internal/types"
|
||||
"github.com/stretchr/testify/assert"
|
||||
)
|
||||
|
||||
// A provider rejects a request for more output than the model can emit, so the
|
||||
// round budget and the history reserve both follow the model's limit.
|
||||
func TestCompletionBudgetFollowsModelOutputLimit(t *testing.T) {
|
||||
cfg := &types.AgentConfig{}
|
||||
assert.Equal(t, types.DefaultSmartReasoningMaxCompletionTokens, completionTokenBudgetFor(cfg))
|
||||
|
||||
cfg.ModelMaxOutputTokens = 8192
|
||||
assert.Equal(t, 8192, completionTokenBudgetFor(cfg))
|
||||
assert.Less(t, reserveTokensFor(cfg), types.DefaultSmartReasoningMaxCompletionTokens)
|
||||
|
||||
cfg.MaxCompletionTokens = 4096
|
||||
assert.Equal(t, 4096, completionTokenBudgetFor(cfg), "a smaller configured budget is kept")
|
||||
cfg.MaxCompletionTokens = 32000
|
||||
assert.Equal(t, 8192, completionTokenBudgetFor(cfg), "an explicit budget cannot exceed the model")
|
||||
}
|
||||
|
||||
func TestToolExecutionTimeout(t *testing.T) {
|
||||
// shell_exec and browser human steps keep their longer budgets.
|
||||
assert.Equal(t, 10*time.Minute+5*time.Second, toolExecutionTimeout("shell_exec"))
|
||||
|
|
@ -22,7 +39,7 @@ func TestToolExecutionTimeout(t *testing.T) {
|
|||
|
||||
t.Run("default budget plus slack", func(t *testing.T) {
|
||||
t.Setenv("WEKNORA_WEB_FETCH_TIMEOUT", "")
|
||||
assert.Equal(t, 3*time.Minute+5*time.Second, toolExecutionTimeout("web_fetch"))
|
||||
assert.Equal(t, 35*time.Second, toolExecutionTimeout("web_fetch"))
|
||||
})
|
||||
t.Run("go duration", func(t *testing.T) {
|
||||
t.Setenv("WEKNORA_WEB_FETCH_TIMEOUT", "150s")
|
||||
|
|
@ -31,10 +48,10 @@ func TestToolExecutionTimeout(t *testing.T) {
|
|||
})
|
||||
t.Run("bare seconds", func(t *testing.T) {
|
||||
t.Setenv("WEKNORA_WEB_FETCH_TIMEOUT", "180")
|
||||
assert.Equal(t, 3*time.Minute+5*time.Second, toolExecutionTimeout("web_fetch"))
|
||||
assert.Equal(t, 185*time.Second, toolExecutionTimeout("web_fetch"))
|
||||
})
|
||||
t.Run("invalid falls back", func(t *testing.T) {
|
||||
t.Setenv("WEKNORA_WEB_FETCH_TIMEOUT", "nope")
|
||||
assert.Equal(t, 3*time.Minute+5*time.Second, toolExecutionTimeout("web_fetch"))
|
||||
assert.Equal(t, 35*time.Second, toolExecutionTimeout("web_fetch"))
|
||||
})
|
||||
}
|
||||
|
|
|
|||
|
|
@ -3,11 +3,14 @@ package agent
|
|||
import (
|
||||
"context"
|
||||
"encoding/base64"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/Tencent/WeKnora/internal/agent/collaboration"
|
||||
"github.com/Tencent/WeKnora/internal/agent/compaction"
|
||||
"github.com/Tencent/WeKnora/internal/agent/skills"
|
||||
agenttoken "github.com/Tencent/WeKnora/internal/agent/token"
|
||||
|
|
@ -35,6 +38,7 @@ const langfuseQueryPreview = 2000
|
|||
// engine therefore does not maintain its own cache, system-prompt store, or
|
||||
// cross-turn buffer.
|
||||
type AgentEngine struct {
|
||||
collaboration *collaboration.Binding
|
||||
config *types.AgentConfig
|
||||
toolRegistry *agenttools.ToolRegistry
|
||||
chatModel chat.Chat
|
||||
|
|
@ -88,9 +92,13 @@ type AgentEngine struct {
|
|||
// suspendRequest is saved with the run for that (see EnableSuspension).
|
||||
suspendable bool
|
||||
suspendRequest []byte
|
||||
// collaborationOnlySuspension limits suspension to collaboration waits.
|
||||
collaborationOnlySuspension bool
|
||||
// interactive: the client renders prompt cards and can answer them.
|
||||
interactive bool
|
||||
progress turnProgress
|
||||
// Hold speculative parent prose until delegated work has been reviewed.
|
||||
holdCollaborationAnswer bool
|
||||
}
|
||||
|
||||
// maxSteerOverruns caps loop-end injects past MaxIterations. One extra round
|
||||
|
|
@ -222,7 +230,7 @@ func (e *AgentEngine) buildSystemPrompt(ctx context.Context) string {
|
|||
for _, section := range sections {
|
||||
logger.Debugf(ctx, "[Agent][Prompt] section=%s bytes=%d", section.Name, len(section.Content))
|
||||
}
|
||||
return renderSystemPromptSections(sections)
|
||||
return renderSystemPromptSections(sections) + e.collaborationGuidance()
|
||||
}
|
||||
|
||||
// SetMemoryPrompt supplies the long-term memory envelope for this run. Empty
|
||||
|
|
@ -527,7 +535,9 @@ func (e *AgentEngine) withinIterationBudget(round int) bool {
|
|||
// and rounds cut off at the completion-token cap.
|
||||
type loopGuards struct {
|
||||
// emptyRetries counts nudges sent after a stop with no content.
|
||||
emptyRetries int
|
||||
emptyRetries int
|
||||
pendingRuntimeNotice string
|
||||
childAnswerRevised bool
|
||||
// consecutiveSameContent counts plain rounds that repeated the previous
|
||||
// plain round verbatim, an identical lack of content included.
|
||||
consecutiveSameContent int
|
||||
|
|
@ -635,6 +645,12 @@ func (e *AgentEngine) executeLoop(
|
|||
sessionID string,
|
||||
messageID string,
|
||||
) (*types.AgentState, error) {
|
||||
if e.collaboration != nil {
|
||||
var stop func()
|
||||
ctx, stop = e.collaboration.Start(ctx)
|
||||
defer stop()
|
||||
e.bindCollaborationInput(sessionID, messageID)
|
||||
}
|
||||
startTime := time.Now()
|
||||
common.PipelineInfo(ctx, "Agent", "loop_start", map[string]interface{}{
|
||||
"max_iterations": e.config.MaxIterations,
|
||||
|
|
@ -656,6 +672,35 @@ func (e *AgentEngine) executeLoop(
|
|||
e.emitCompletionEvent(context.WithoutCancel(ctx), state, sessionID, messageID, startTime)
|
||||
}
|
||||
defer emitCompletion()
|
||||
if e.collaboration != nil {
|
||||
defer func() {
|
||||
b := e.collaboration
|
||||
if b.Child == nil && ctx.Err() != nil && state.Suspended == nil {
|
||||
g, err := b.Runtime.Store.Read(context.WithoutCancel(ctx), b.Scope)
|
||||
if err == nil && g.Status == "active" && g.ParentWait != nil && g.ParentOwner == b.ParentOwner {
|
||||
state.Suspended = &types.PromptSuspension{
|
||||
PromptID: b.Scope.ID,
|
||||
Kind: "collaboration_wait",
|
||||
Detached: true,
|
||||
}
|
||||
}
|
||||
}
|
||||
b.End(state.Suspended != nil)
|
||||
}()
|
||||
}
|
||||
|
||||
if e.collaboration != nil && e.collaboration.Child == nil {
|
||||
if err := e.collaboration.Runtime.Store.Change(e.collaboration.Context(ctx),
|
||||
e.collaboration.Scope,
|
||||
func(g *collaboration.Group) error {
|
||||
if g.RootQuery == "" {
|
||||
g.RootQuery = string([]rune(query)[:min(len([]rune(query)), 16000)])
|
||||
}
|
||||
return nil
|
||||
}); err != nil {
|
||||
return state, err
|
||||
}
|
||||
}
|
||||
|
||||
guards := &loopGuards{}
|
||||
loop:
|
||||
|
|
@ -713,6 +758,9 @@ loop:
|
|||
// A suspended run has not finished either; it resumes once the user
|
||||
// answers, so no answer is synthesized for it.
|
||||
if !state.IsComplete && ctx.Err() == nil && state.Suspended == nil {
|
||||
if e.collaboration != nil && e.collaboration.Child == nil && e.collaborationOwnsFailure(ctx) {
|
||||
return state, fmt.Errorf("parent iteration budget exhausted; remaining delegated work was cancelled")
|
||||
}
|
||||
e.handleMaxIterations(ctx, query, state, sessionID, messages)
|
||||
}
|
||||
|
||||
|
|
@ -818,6 +866,20 @@ func (e *AgentEngine) runReActIteration(
|
|||
// updated (the injected text counts as new delta tokens for the next
|
||||
// call), so the very next LLM call sees the user's addition.
|
||||
e.drainSteerMessages(ctx, state, messagesPtr, sessionID, assistantMessageID)
|
||||
if e.collaboration != nil {
|
||||
events, err := e.collaboration.Poll(ctx)
|
||||
if err != nil {
|
||||
return iterOutcomeBreak, err
|
||||
}
|
||||
e.deliverCollaborationEvents(messagesPtr, events, len(state.RoundSteps), false)
|
||||
e.holdCollaborationAnswer, err = e.collaboration.PendingAnswer(ctx)
|
||||
if err != nil {
|
||||
return iterOutcomeBreak, err
|
||||
}
|
||||
}
|
||||
if guards.childAnswerRevised {
|
||||
tools = nil
|
||||
}
|
||||
|
||||
logger.Infof(ctx, "[Agent][Round-%d/%s] Starting: %d messages, %d tools, est_tokens=%d",
|
||||
round, e.maxIterationsDisplay(), len(*messagesPtr), len(tools), currentTokens)
|
||||
|
|
@ -832,7 +894,9 @@ func (e *AgentEngine) runReActIteration(
|
|||
|
||||
// 1. Think: Call LLM with function calling (includes retry + graceful degradation)
|
||||
e.lastSentMsgCount = len(*messagesPtr)
|
||||
resp, err := e.callLLMWithRetry(ctx, messagesPtr, tools, state, query, state.CurrentRound, sessionID)
|
||||
runtimeNotice := guards.pendingRuntimeNotice
|
||||
guards.pendingRuntimeNotice = ""
|
||||
resp, err := e.callLLMWithRetry(ctx, messagesPtr, tools, state, query, state.CurrentRound, sessionID, runtimeNotice)
|
||||
if err != nil {
|
||||
retErr = err
|
||||
return iterOutcomeNext, err
|
||||
|
|
@ -853,7 +917,16 @@ func (e *AgentEngine) runReActIteration(
|
|||
round, resp.FinishReason, resp.Usage.CompletionTokens, e.getCompletionTokenBudget())
|
||||
*messagesPtr = e.forceCompaction(ctx, *messagesPtr, round)
|
||||
e.lastSentMsgCount = len(*messagesPtr)
|
||||
resp, err = e.callLLMWithRetry(ctx, messagesPtr, tools, state, query, state.CurrentRound, sessionID)
|
||||
resp, err = e.callLLMWithRetry(
|
||||
ctx,
|
||||
messagesPtr,
|
||||
tools,
|
||||
state,
|
||||
query,
|
||||
state.CurrentRound,
|
||||
sessionID,
|
||||
runtimeNotice,
|
||||
)
|
||||
if err != nil {
|
||||
retErr = err
|
||||
return iterOutcomeNext, err
|
||||
|
|
@ -912,6 +985,9 @@ func (e *AgentEngine) runReActIteration(
|
|||
e.failTruncatedToolCalls(ctx, response, &step, state.CurrentRound, sessionID)
|
||||
}
|
||||
state.RoundSteps = append(state.RoundSteps, step)
|
||||
if e.collaborationOwnsFailure(ctx) {
|
||||
return iterOutcomeBreak, fmt.Errorf("collaboration stopped after repeated output truncation")
|
||||
}
|
||||
e.finishStalledTurn(ctx, state, sessionID, response, true)
|
||||
return iterOutcomeBreak, nil
|
||||
}
|
||||
|
|
@ -933,8 +1009,16 @@ func (e *AgentEngine) runReActIteration(
|
|||
guards.sawPlainRound = true
|
||||
guards.lastResponseContent = response.Content
|
||||
if guards.consecutiveSameContent >= maxRepeatedResponseRounds {
|
||||
logger.Warnf(ctx, "[Agent][Round-%d] Detected stuck loop: same content repeated %d times (finish=%s), stopping",
|
||||
round, guards.consecutiveSameContent+1, response.FinishReason)
|
||||
logger.Warnf(
|
||||
ctx,
|
||||
"[Agent][Round-%d] Detected stuck loop: same content repeated %d times (finish=%s), stopping",
|
||||
round,
|
||||
guards.consecutiveSameContent+1,
|
||||
response.FinishReason,
|
||||
)
|
||||
if e.collaborationOwnsFailure(ctx) {
|
||||
return iterOutcomeBreak, fmt.Errorf("collaboration stopped after repeated responses without progress")
|
||||
}
|
||||
e.finishStalledTurn(ctx, state, sessionID, response, false)
|
||||
return iterOutcomeBreak, nil
|
||||
}
|
||||
|
|
@ -976,24 +1060,65 @@ func (e *AgentEngine) runReActIteration(
|
|||
return iterOutcomeBreak, nil
|
||||
}
|
||||
|
||||
// A delegated deliverable must not silently become a partial success. Give
|
||||
// it one text-only revision using existing evidence; never re-run tools or
|
||||
// create an unbounded continuation loop. The last truncated step remains
|
||||
// explicit if the revision also hits its cap or no round remains.
|
||||
if e.collaboration != nil && e.collaboration.Child != nil &&
|
||||
isLengthFinishReason(response.FinishReason) && len(response.ToolCalls) == 0 &&
|
||||
strings.TrimSpace(
|
||||
response.Content,
|
||||
) != "" && !guards.childAnswerRevised && e.withinIterationBudget(state.CurrentRound+1) {
|
||||
guards.childAnswerRevised = true
|
||||
state.FinalAnswer = response.Content // retain the partial deliverable if recovery fails
|
||||
step.Truncated, step.IntermediateAnswer = true, true
|
||||
state.RoundSteps = append(state.RoundSteps, step)
|
||||
*messagesPtr = append(
|
||||
*messagesPtr,
|
||||
chat.Message{
|
||||
Role: "assistant", Content: response.Content,
|
||||
ReasoningContent: response.ReasoningContent,
|
||||
ReasoningSignature: response.ReasoningSignature,
|
||||
ReasoningMetadata: response.ReasoningMetadata,
|
||||
},
|
||||
chat.Message{
|
||||
Role: "system",
|
||||
Content: "The delegated draft reached the output token limit and is incomplete. Produce " +
|
||||
"one shorter, self-contained final deliverable covering all requested sections " +
|
||||
"using the evidence already collected. Do not repeat tool calls or claim missing " +
|
||||
"sections are complete. Omit process narration and repeated source excerpts. If " +
|
||||
"evidence is missing, say so explicitly. This is the only revision attempt.",
|
||||
},
|
||||
)
|
||||
return iterOutcomeNext, nil
|
||||
}
|
||||
|
||||
if guards.childAnswerRevised && len(response.ToolCalls) > 0 {
|
||||
return iterOutcomeBreak, fmt.Errorf("delegated answer revision requested tools despite text-only recovery")
|
||||
}
|
||||
|
||||
// 2. Analyze: Check for stop conditions (natural stop with no tool calls)
|
||||
verdict := e.analyzeResponse(ctx, response, step, state.CurrentRound, sessionID, roundStart)
|
||||
if verdict.isDone {
|
||||
// Guard against empty content: when the LLM stops naturally with no
|
||||
// content and no tool calls (e.g., thinking-only loop without KB),
|
||||
// retry with a nudge message instead of accepting an empty answer.
|
||||
// Retry with a runtime notice, without inventing a user request to
|
||||
// finalize or preventing the next round from using tools/waiting.
|
||||
if verdict.emptyContent {
|
||||
guards.emptyRetries++
|
||||
if guards.emptyRetries <= maxEmptyResponseRetries {
|
||||
state.PendingSteerMessages = step.UserMessagesBefore
|
||||
logger.Warnf(ctx, "[Agent][Round-%d] Empty content with stop - retrying (%d/%d)",
|
||||
round, guards.emptyRetries, maxEmptyResponseRetries)
|
||||
*messagesPtr = append(*messagesPtr, chat.Message{
|
||||
Role: "user",
|
||||
Content: "Please provide your complete answer now as plain text.",
|
||||
})
|
||||
guards.pendingRuntimeNotice = emptyResponseRetryNotice
|
||||
return iterOutcomeContinue, nil
|
||||
}
|
||||
// A fallback answer cannot replace unreviewed child results or mark
|
||||
// an empty child deliverable as successful. Propagate a failure so
|
||||
// runtime cleanup/parent notification follows the normal error path.
|
||||
if e.collaborationOwnsFailure(ctx) {
|
||||
return iterOutcomeBreak, fmt.Errorf("collaboration stopped after repeated empty answers")
|
||||
}
|
||||
// Retries exhausted — use fallback message rather than empty answer.
|
||||
// analyzeResponse emitted nothing for the empty rounds (they were
|
||||
// retryable), so the fallback must be emitted here as the turn's
|
||||
|
|
@ -1044,6 +1169,7 @@ func (e *AgentEngine) runReActIteration(
|
|||
})
|
||||
injected := e.drainSteerMessages(ctx, state, messagesPtr, sessionID, assistantMessageID)
|
||||
if injected > 0 {
|
||||
*messagesPtr = e.appendCollaborationDeliveryBoundary(*messagesPtr, verdict.finalAnswer)
|
||||
verdict.step.IntermediateAnswer = true
|
||||
state.RoundSteps = append(state.RoundSteps, verdict.step)
|
||||
if !e.withinIterationBudget(nextRound) {
|
||||
|
|
@ -1054,6 +1180,69 @@ func (e *AgentEngine) runReActIteration(
|
|||
}
|
||||
}
|
||||
}
|
||||
if e.collaboration != nil && response.FinishReason != "content_filter" {
|
||||
if e.suspendable && e.collaboration.Child == nil {
|
||||
checkpoint := RunSnapshot{
|
||||
CollaborationDeliveries: e.progress.collaborationDeliveries,
|
||||
CollaborationCursor: e.collaborationCursor(),
|
||||
MCPToolRefs: e.toolRegistry.MCPExposureSnapshot(),
|
||||
Version: RunSnapshotVersion,
|
||||
CollaborationWait: true,
|
||||
BetweenRounds: true,
|
||||
Request: e.suspendRequest,
|
||||
Query: e.progress.query,
|
||||
ImageURLs: e.progress.imageURLs,
|
||||
UserMessages: e.progress.userMessages,
|
||||
CompletedSteps: append([]types.AgentStep(nil), state.RoundSteps...),
|
||||
KnowledgeRefs: state.KnowledgeRefs,
|
||||
CurrentRound: state.CurrentRound + 1,
|
||||
TurnUsage: state.TurnUsage,
|
||||
}
|
||||
intermediate := verdict.step
|
||||
intermediate.IntermediateAnswer = true
|
||||
checkpoint.CompletedSteps = append(checkpoint.CompletedSteps, intermediate)
|
||||
data, err := json.Marshal(checkpoint)
|
||||
if err != nil {
|
||||
return iterOutcomeBreak, err
|
||||
}
|
||||
if err = e.collaboration.SaveWait(ctx, data, time.Now().Add(time.Hour)); err != nil {
|
||||
return iterOutcomeBreak, err
|
||||
}
|
||||
}
|
||||
events, err := e.collaboration.BeforeFinish(ctx)
|
||||
inputReady := errors.Is(err, collaboration.ErrInput)
|
||||
if err != nil && !inputReady {
|
||||
return iterOutcomeBreak, err
|
||||
}
|
||||
if len(events) > 0 || inputReady {
|
||||
if err := e.collaboration.ClearWait(ctx); err != nil {
|
||||
return iterOutcomeBreak, err
|
||||
}
|
||||
if !e.withinIterationBudget(state.CurrentRound + 1) {
|
||||
if inputReady && e.steerOverruns < maxSteerOverruns {
|
||||
e.steerOverruns++
|
||||
e.allowSteerOverrun = true
|
||||
} else {
|
||||
return iterOutcomeBreak,
|
||||
fmt.Errorf("agent iteration budget exhausted with unprocessed collaboration events")
|
||||
}
|
||||
}
|
||||
*messagesPtr = e.appendCollaborationDeliveryBoundary(*messagesPtr, verdict.finalAnswer)
|
||||
e.deliverCollaborationEvents(messagesPtr, events, len(state.RoundSteps)+1, true)
|
||||
verdict.step.IntermediateAnswer = true
|
||||
state.RoundSteps = append(state.RoundSteps, verdict.step)
|
||||
return iterOutcomeNext, nil
|
||||
}
|
||||
}
|
||||
if e.holdCollaborationAnswer && response.FinishReason != "content_filter" {
|
||||
_ = e.eventBus.Emit(
|
||||
ctx,
|
||||
event.Event{
|
||||
ID: verdict.answerID, Type: event.EventAgentFinalAnswer, SessionID: sessionID,
|
||||
Data: event.AgentFinalAnswerData{Content: verdict.finalAnswer, Truncated: verdict.truncated},
|
||||
},
|
||||
)
|
||||
}
|
||||
state.FinalAnswer = verdict.finalAnswer
|
||||
state.IsComplete = true
|
||||
state.RoundSteps = append(state.RoundSteps, verdict.step)
|
||||
|
|
@ -1071,6 +1260,21 @@ func (e *AgentEngine) runReActIteration(
|
|||
// preceding a tool call in the same stream as a preamble and relocate it
|
||||
// into the steps tree. The preamble is still preserved as this round's
|
||||
// Thought.
|
||||
// A tool-bearing response is an intermediate user update. Publish it on its
|
||||
// own channel, never as reasoning or as part of the final deliverable.
|
||||
progress := agenttools.StripThinkBlocks(response.Content)
|
||||
if e.collaboration != nil && e.collaboration.Child == nil && strings.TrimSpace(progress) != "" {
|
||||
step.Progress = progress
|
||||
progressID := response.AnswerEventID
|
||||
if progressID == "" {
|
||||
progressID = generateEventID("collaboration-progress")
|
||||
}
|
||||
step.ProgressEventID = progressID
|
||||
_ = e.eventBus.Emit(ctx, event.Event{
|
||||
ID: progressID, Type: event.EventAgentProgress, SessionID: sessionID,
|
||||
Data: event.AgentProgressData{Content: progress, Iteration: state.CurrentRound},
|
||||
})
|
||||
}
|
||||
|
||||
// 3. Act: Execute tool calls
|
||||
e.beginRound(step, response.ToolCalls)
|
||||
|
|
@ -1162,7 +1366,11 @@ func (e *AgentEngine) describeImages(ctx context.Context, imageDataURIs, prompts
|
|||
}
|
||||
}
|
||||
if ctx.Err() != nil {
|
||||
logger.Warnf(ctx, "[Agent] Context cancelled, skipping remaining %d tool result images", len(imageDataURIs)-i)
|
||||
logger.Warnf(
|
||||
ctx,
|
||||
"[Agent] Context cancelled, skipping remaining %d tool result images",
|
||||
len(imageDataURIs)-i,
|
||||
)
|
||||
break
|
||||
}
|
||||
wg.Add(1)
|
||||
|
|
|
|||
|
|
@ -1155,3 +1155,26 @@ func TestStreamLLMIncompleteFinishIsAStreamError(t *testing.T) {
|
|||
require.Error(t, err, "a stream cut before its finish reason is not a completed turn")
|
||||
require.True(t, isTransientError(err))
|
||||
}
|
||||
|
||||
func TestWebFetchUnknownReferenceIsAnItemError(t *testing.T) {
|
||||
engine := newTestEngine(t, &mockChat{})
|
||||
engine.toolRegistry = agenttools.NewToolRegistry()
|
||||
engine.toolRegistry.RegisterTool(agenttools.NewWebFetchTool())
|
||||
calls := []types.LLMToolCall{{
|
||||
ID: "fetch",
|
||||
Function: types.FunctionCall{
|
||||
Name: agenttools.ToolWebFetch,
|
||||
Arguments: `{"items":[{"url":"w999"}]}`,
|
||||
},
|
||||
}}
|
||||
engine.modelContext.DecodeToolCalls(calls)
|
||||
require.Equal(t, []string{"w999"}, calls[0].UnresolvedHandles)
|
||||
result := engine.runToolCall(t.Context(), calls[0], 0, 0, 1, "session", "message")
|
||||
require.NotNil(t, result.Result)
|
||||
require.Contains(t, result.Result.Output, "unknown_page_reference")
|
||||
require.NotContains(t, result.Result.Error, "unresolved model handles")
|
||||
// Other namespaces still fail closed before tool execution.
|
||||
calls[0].UnresolvedHandles = []string{"res://9999"}
|
||||
result = engine.runToolCall(t.Context(), calls[0], 0, 0, 1, "session", "message")
|
||||
require.Contains(t, result.Result.Error, "unresolved model handles")
|
||||
}
|
||||
|
|
|
|||
|
|
@ -34,25 +34,30 @@ func (e *AgentEngine) streamFinalAnswerToEventBus(
|
|||
// messages. Tool output must retain its role and call ID; never promote it
|
||||
// into user instructions during error recovery or iteration-limit synthesis.
|
||||
messages := append([]chat.Message(nil), conversation...)
|
||||
messages = append(messages, chat.Message{
|
||||
Role: "user",
|
||||
Content: "Tool execution has ended for this run. Respond to the current task, including " +
|
||||
"the latest user corrections and source restrictions in the conversation. Base claims on " +
|
||||
"the evidence actually obtained; distinguish completed work from remaining work and explain " +
|
||||
"any missing evidence. Use the user's requested language and format. Do not claim that an " +
|
||||
"unperformed action succeeded.",
|
||||
})
|
||||
runtimeNotice := "<runtime_event>{\"source\":\"runtime\",\"type\":\"final_synthesis\",\"message\":\"Tool " +
|
||||
"execution has ended for this run. Respond to the current task, including the " +
|
||||
"latest user corrections and source restrictions in the conversation. Base " +
|
||||
"claims on the evidence actually obtained; distinguish completed work from " +
|
||||
"remaining work and explain any missing evidence. Use the user's requested " +
|
||||
"language and format. Do not claim that an unperformed action " +
|
||||
"succeeded.\"}</runtime_event>"
|
||||
|
||||
// Generate a single ID for this entire final answer stream
|
||||
answerID := generateEventID("answer")
|
||||
logger.Debugf(ctx, "[Agent][FinalAnswer] AnswerID: %s", answerID)
|
||||
answerDoneEmitted := false
|
||||
splitter := agenttools.NewThinkStreamSplitter()
|
||||
|
||||
budget := e.clampCompletionBudgetToContext(e.tokenEstimator.EstimateMessages(messages))
|
||||
budget := e.clampCompletionBudgetToContext(
|
||||
e.tokenEstimator.EstimateMessages(
|
||||
append(append([]chat.Message(nil), messages...), chat.Message{Role: "system", Content: runtimeNotice}),
|
||||
),
|
||||
)
|
||||
llmResult, err := e.streamLLMToEventBus(
|
||||
ctx,
|
||||
messages,
|
||||
&chat.ChatOptions{
|
||||
RuntimeNotice: runtimeNotice,
|
||||
Temperature: e.config.Temperature,
|
||||
MaxCompletionTokens: budget,
|
||||
PromptCacheKey: sessionID,
|
||||
|
|
@ -63,14 +68,28 @@ func (e *AgentEngine) streamFinalAnswerToEventBus(
|
|||
if chunk.ResponseType == types.ResponseTypeThinking {
|
||||
return
|
||||
}
|
||||
if chunk.Content != "" {
|
||||
logger.Debugf(ctx, "[Agent][FinalAnswer] Emitting answer chunk: %d chars", len(chunk.Content))
|
||||
_, answerContent := splitter.Feed(chunk.Content)
|
||||
if splitter.TakeAnswerReset() {
|
||||
_ = e.eventBus.Emit(
|
||||
ctx,
|
||||
event.Event{
|
||||
ID: answerID, Type: event.EventAgentFinalAnswer, SessionID: sessionID,
|
||||
Data: event.AgentFinalAnswerData{Replace: true},
|
||||
},
|
||||
)
|
||||
}
|
||||
if chunk.Done {
|
||||
_, tail := splitter.Flush()
|
||||
answerContent += tail
|
||||
}
|
||||
if answerContent != "" {
|
||||
logger.Debugf(ctx, "[Agent][FinalAnswer] Emitting answer chunk: %d chars", len(answerContent))
|
||||
e.eventBus.Emit(ctx, event.Event{
|
||||
ID: answerID,
|
||||
Type: event.EventAgentFinalAnswer,
|
||||
SessionID: sessionID,
|
||||
Data: event.AgentFinalAnswerData{
|
||||
Content: chunk.Content,
|
||||
Content: answerContent,
|
||||
Done: chunk.Done,
|
||||
},
|
||||
})
|
||||
|
|
@ -88,6 +107,12 @@ func (e *AgentEngine) streamFinalAnswerToEventBus(
|
|||
})
|
||||
return err
|
||||
}
|
||||
if _, tail := splitter.Flush(); tail != "" {
|
||||
_ = e.eventBus.Emit(ctx, event.Event{
|
||||
ID: answerID, Type: event.EventAgentFinalAnswer, SessionID: sessionID,
|
||||
Data: event.AgentFinalAnswerData{Content: tail},
|
||||
})
|
||||
}
|
||||
|
||||
if !answerDoneEmitted {
|
||||
e.eventBus.Emit(ctx, event.Event{
|
||||
|
|
@ -114,6 +139,14 @@ func (e *AgentEngine) streamFinalAnswerToEventBus(
|
|||
"session_id": sessionID,
|
||||
"answer_len": len(fullAnswer),
|
||||
})
|
||||
// Delegated callers must distinguish a synthesized partial answer from a
|
||||
// completed deliverable too, including the iteration-budget fallback path.
|
||||
if e.collaboration != nil && e.collaboration.Child != nil && isLengthFinishReason(llmResult.FinishReason) {
|
||||
state.RoundSteps = append(state.RoundSteps, types.AgentStep{
|
||||
Iteration: state.CurrentRound,
|
||||
Thought: fullAnswer, Truncated: true, Timestamp: time.Now(),
|
||||
})
|
||||
}
|
||||
state.FinalAnswer = fullAnswer
|
||||
return nil
|
||||
}
|
||||
|
|
@ -162,6 +195,7 @@ func (e *AgentEngine) emitCompletionEvent(
|
|||
}
|
||||
|
||||
data := event.AgentCompleteData{
|
||||
Artifacts: e.collaborationArtifacts(),
|
||||
FinalAnswer: state.FinalAnswer,
|
||||
KnowledgeRefs: knowledgeRefsInterface,
|
||||
AgentSteps: steps,
|
||||
|
|
|
|||
|
|
@ -251,6 +251,18 @@ func (b *Broker) Await(ctx context.Context, spec Spec) (out Outcome, err error)
|
|||
if p.ID == "" {
|
||||
p.ID = uuid.New().String()
|
||||
}
|
||||
delegation, delegated := ctx.Value(delegationKey{}).(Delegation)
|
||||
if delegated {
|
||||
if err := CheckDelegation(ctx); err != nil {
|
||||
return Outcome{}, err
|
||||
}
|
||||
if spec.Suspend == nil {
|
||||
return Outcome{}, errors.New("delegated prompts require a durable snapshot")
|
||||
}
|
||||
// Persist or fail closed; a worker must never silently become a hot waiter.
|
||||
spec.FallbackTimeout = 0
|
||||
spec.Timeout = 0
|
||||
}
|
||||
dbCtx := context.WithoutCancel(ctx)
|
||||
// A fresh token also fences a takeover by another run on this same replica.
|
||||
owner := uuid.NewString()
|
||||
|
|
@ -284,6 +296,11 @@ func (b *Broker) Await(ctx context.Context, spec Spec) (out Outcome, err error)
|
|||
return Outcome{}, fmt.Errorf("persist run state: %w", err)
|
||||
}
|
||||
}
|
||||
if delegated && delegation.Register != nil {
|
||||
if err := delegation.Register(ctx, p); err != nil {
|
||||
return Outcome{}, err
|
||||
}
|
||||
}
|
||||
lease := time.Now().Add(b.leaseTTL)
|
||||
p.Status = types.AgentPromptPending
|
||||
p.OwnerInstance = owner
|
||||
|
|
@ -437,6 +454,9 @@ func (b *Broker) closed(ctx context.Context, id, owner string) (Outcome, bool) {
|
|||
// without detaching the run, so ordinary completion can persist its message.
|
||||
// Neither outcome permits executing the authorized side effect.
|
||||
func (b *Broker) Consume(ctx context.Context, id, to, owner string) (bool, error) {
|
||||
if err := CheckDelegation(ctx); err != nil {
|
||||
return false, err
|
||||
}
|
||||
ctx = context.WithoutCancel(ctx)
|
||||
transition := types.AgentPromptTransition{
|
||||
From: []string{types.AgentPromptAnswered},
|
||||
|
|
|
|||
|
|
@ -0,0 +1,39 @@
|
|||
package hitl
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"github.com/Tencent/WeKnora/internal/types"
|
||||
)
|
||||
|
||||
type delegationKey struct{}
|
||||
|
||||
// Delegation is installed by the worker, never from model arguments. Register
|
||||
// durably associates a prompt with the current run before it can be answered.
|
||||
type Delegation struct {
|
||||
Register func(context.Context, *types.AgentPrompt) error
|
||||
Check func(context.Context) error
|
||||
RequireApproval bool
|
||||
}
|
||||
|
||||
// WithDelegation attaches child prompt ownership checks to the execution context.
|
||||
func WithDelegation(ctx context.Context, d Delegation) context.Context {
|
||||
return context.WithValue(ctx, delegationKey{}, d)
|
||||
}
|
||||
|
||||
// CheckDelegation rejects canceled or stale child executions before prompt handling.
|
||||
func CheckDelegation(ctx context.Context) error {
|
||||
if err := ctx.Err(); err != nil {
|
||||
return err
|
||||
}
|
||||
if d, ok := ctx.Value(delegationKey{}).(Delegation); ok && d.Check != nil {
|
||||
return d.Check(ctx)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// RequiresDelegatedApproval reports whether the child must request explicit tool approval.
|
||||
func RequiresDelegatedApproval(ctx context.Context) bool {
|
||||
d, _ := ctx.Value(delegationKey{}).(Delegation)
|
||||
return d.RequireApproval
|
||||
}
|
||||
|
|
@ -0,0 +1,94 @@
|
|||
package hitl
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/Tencent/WeKnora/internal/types"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
func TestDelegatedPromptPersistsBeforeEmissionAndSuspendsImmediately(t *testing.T) {
|
||||
b := NewBroker(nil, nil)
|
||||
registered := false
|
||||
ctx := WithDelegation(
|
||||
context.Background(),
|
||||
Delegation{
|
||||
Check: func(context.Context) error { return nil },
|
||||
Register: func(ctx context.Context, p *types.AgentPrompt) error {
|
||||
snapshot, err := b.Suspensions().Get(ctx, p.AssistantMessageID)
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, p.ID, snapshot.PromptID)
|
||||
registered = true
|
||||
return nil
|
||||
},
|
||||
},
|
||||
)
|
||||
start := time.Now()
|
||||
out, err := b.Await(ctx, Spec{
|
||||
Prompt: &types.AgentPrompt{ID: "p", AssistantMessageID: "m"}, Timeout: time.Hour,
|
||||
Suspend: &SuspendSpec{
|
||||
Snapshot: []byte(`{}`),
|
||||
SnapshotVersion: 1,
|
||||
}, Emit: func(ctx context.Context, p *types.AgentPrompt) error {
|
||||
require.True(t, registered)
|
||||
row, err := b.Store().Get(ctx, p.ID)
|
||||
require.NoError(t, err)
|
||||
require.NotNil(t, row)
|
||||
return nil
|
||||
},
|
||||
})
|
||||
require.NoError(t, err)
|
||||
require.True(t, out.Suspended)
|
||||
require.Less(t, time.Since(start), time.Second)
|
||||
snapshot, err := b.Suspensions().Get(ctx, "m")
|
||||
require.NoError(t, err)
|
||||
require.NotNil(t, snapshot)
|
||||
}
|
||||
|
||||
func TestCanceledDelegationCannotConsumeLateApproval(t *testing.T) {
|
||||
b := NewBroker(nil, nil)
|
||||
require.NoError(
|
||||
t,
|
||||
b.Store().
|
||||
Create(context.Background(),
|
||||
&types.AgentPrompt{
|
||||
ID: "p",
|
||||
Status: types.AgentPromptAnswered,
|
||||
OwnerInstance: "owner",
|
||||
}),
|
||||
)
|
||||
ctx := WithDelegation(
|
||||
context.Background(),
|
||||
Delegation{Check: func(context.Context) error { return errors.New("task canceled") }},
|
||||
)
|
||||
ok, err := b.Consume(ctx, "p", types.AgentPromptExecuting, "owner")
|
||||
require.False(t, ok)
|
||||
require.ErrorContains(t, err, "task canceled")
|
||||
p, err := b.Store().Get(context.Background(), "p")
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, types.AgentPromptAnswered, p.Status)
|
||||
}
|
||||
|
||||
func TestDelegatedPromptCannotFallBackToUnsafeHotWait(t *testing.T) {
|
||||
b := NewBroker(nil, nil, WithSuspensionStore(failingSuspensionStore{NewMemorySuspensionStore()}))
|
||||
emitted := false
|
||||
ctx := WithDelegation(context.Background(), Delegation{})
|
||||
_, err := b.Await(
|
||||
ctx,
|
||||
Spec{
|
||||
Prompt: &types.AgentPrompt{ID: "p", AssistantMessageID: "m"},
|
||||
Timeout: time.Hour,
|
||||
FallbackTimeout: time.Hour,
|
||||
Suspend: &SuspendSpec{
|
||||
Snapshot: []byte(`{}`),
|
||||
SnapshotVersion: 1,
|
||||
},
|
||||
Emit: func(context.Context, *types.AgentPrompt) error { emitted = true; return nil },
|
||||
},
|
||||
)
|
||||
require.Error(t, err)
|
||||
require.False(t, emitted)
|
||||
}
|
||||
|
|
@ -24,6 +24,8 @@ const (
|
|||
// RunHooks finish the assistant message of a run the reaper or a supersede
|
||||
// takes over.
|
||||
type RunHooks struct {
|
||||
// RecoverAnswered transfers safe, unconsumed answers to a durable scheduler.
|
||||
RecoverAnswered func(context.Context, *types.AgentPrompt) (bool, error)
|
||||
// Suspended shows a run whose owner disappeared while waiting the way a
|
||||
// run that suspended itself looks: the saved steps, waiting on prompt.
|
||||
Suspended func(ctx context.Context, prompt *types.AgentPrompt, state *types.AgentRunSuspension) error
|
||||
|
|
@ -61,6 +63,15 @@ func (b *Broker) Reap(ctx context.Context, now time.Time, hooks RunHooks) (int,
|
|||
return reaped, err
|
||||
}
|
||||
for _, row := range resuming {
|
||||
if row.Status == types.AgentPromptAnswered && hooks.RecoverAnswered != nil {
|
||||
handled, err := hooks.RecoverAnswered(ctx, row)
|
||||
if err != nil {
|
||||
return reaped, err
|
||||
}
|
||||
if handled {
|
||||
continue
|
||||
}
|
||||
}
|
||||
state := b.runState(ctx, row)
|
||||
if state == nil {
|
||||
// An in-memory waiter consumed it; nothing to resume or close.
|
||||
|
|
|
|||
|
|
@ -465,7 +465,7 @@ func (e *AgentEngine) analyzeResponse(
|
|||
answerID = response.AnswerEventID
|
||||
} else {
|
||||
answerID = generateEventID("answer")
|
||||
if response.Content != "" {
|
||||
if response.Content != "" && !e.holdCollaborationAnswer {
|
||||
e.eventBus.Emit(ctx, event.Event{
|
||||
ID: answerID,
|
||||
Type: event.EventAgentFinalAnswer,
|
||||
|
|
@ -533,7 +533,10 @@ func (e *AgentEngine) analyzeResponse(
|
|||
// text already went out, otherwise emit it once here. Done is left to
|
||||
// the caller so a loop-end steer inject can still continue the turn.
|
||||
answerID := response.AnswerEventID
|
||||
if !response.AnswerStreamed || answerID == "" {
|
||||
if e.holdCollaborationAnswer && answerID == "" {
|
||||
answerID = generateEventID("answer")
|
||||
}
|
||||
if (!response.AnswerStreamed || answerID == "") && !e.holdCollaborationAnswer {
|
||||
answerID = generateEventID("answer")
|
||||
_ = e.eventBus.Emit(ctx, event.Event{
|
||||
ID: answerID,
|
||||
|
|
@ -1106,6 +1109,10 @@ func (e *AgentEngine) appendToolResults(
|
|||
messages = append(messages, toolMsg)
|
||||
}
|
||||
|
||||
if step.IntermediateAnswer {
|
||||
messages = e.appendCollaborationDeliveryBoundary(messages, step.Thought)
|
||||
}
|
||||
|
||||
return messages
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -0,0 +1,76 @@
|
|||
package agent
|
||||
|
||||
import (
|
||||
"context"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
agenttools "github.com/Tencent/WeKnora/internal/agent/tools"
|
||||
"github.com/Tencent/WeKnora/internal/event"
|
||||
"github.com/Tencent/WeKnora/internal/types"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
func orphanThinkResponse() mockResponse {
|
||||
return mockResponse{chunks: []types.StreamResponse{
|
||||
{ResponseType: types.ResponseTypeAnswer, Content: "refs\n\n任务全部结束,先整理证据。"},
|
||||
{ResponseType: types.ResponseTypeAnswer, Content: "Prepare complete summary.</thi"},
|
||||
{ResponseType: types.ResponseTypeAnswer, Content: "nk:6124c78e>## 进展\n\n"},
|
||||
{ResponseType: types.ResponseTypeAnswer, Content: "真正的完整答案。", Done: true, FinishReason: "stop"},
|
||||
}}
|
||||
}
|
||||
|
||||
func TestOrphanThinkAnswerReplacementMatchesPersistedRound(t *testing.T) {
|
||||
model := &mockChat{responses: []mockResponse{orphanThinkResponse()}}
|
||||
e := newTestEngine(t, model)
|
||||
e.toolRegistry = agenttools.NewToolRegistry()
|
||||
var answer string
|
||||
var replacements int
|
||||
var progress []string
|
||||
e.eventBus.On(event.EventAgentFinalAnswer, func(_ context.Context, evt event.Event) error {
|
||||
d := evt.Data.(event.AgentFinalAnswerData)
|
||||
if d.Replace {
|
||||
require.Contains(t, answer, "refs")
|
||||
answer = ""
|
||||
replacements++
|
||||
}
|
||||
answer += d.Content
|
||||
return nil
|
||||
})
|
||||
e.eventBus.On(event.EventAgentProgress, func(_ context.Context, evt event.Event) error {
|
||||
progress = append(progress, evt.Data.(event.AgentProgressData).Content)
|
||||
return nil
|
||||
})
|
||||
state, err := e.Execute(context.Background(), "s", "m", "report", nil, nil)
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, 1, replacements)
|
||||
require.Equal(t, "## 进展\n\n真正的完整答案。", answer)
|
||||
require.Equal(t, answer, state.FinalAnswer)
|
||||
require.Len(t, state.RoundSteps, 1)
|
||||
require.Equal(t, "refs\n\n任务全部结束,先整理证据。Prepare complete summary.", state.RoundSteps[0].ReasoningContent)
|
||||
require.NotContains(t, strings.Join(progress, ""), "Prepare complete summary")
|
||||
}
|
||||
|
||||
func TestOrphanThinkFinalSynthesisReplacesSameAnswer(t *testing.T) {
|
||||
e := newTestEngine(t, &mockChat{responses: []mockResponse{orphanThinkResponse()}})
|
||||
var answer string
|
||||
var replacementID string
|
||||
e.eventBus.On(event.EventAgentFinalAnswer, func(_ context.Context, evt event.Event) error {
|
||||
d := evt.Data.(event.AgentFinalAnswerData)
|
||||
if d.Replace {
|
||||
answer = ""
|
||||
replacementID = evt.ID
|
||||
}
|
||||
if replacementID != "" {
|
||||
require.Equal(t, replacementID, evt.ID)
|
||||
}
|
||||
answer += d.Content
|
||||
return nil
|
||||
})
|
||||
state := &types.AgentState{}
|
||||
err := e.streamFinalAnswerToEventBus(context.Background(), "report", state, "s", nil)
|
||||
require.NoError(t, err)
|
||||
require.NotEmpty(t, replacementID)
|
||||
require.Equal(t, "## 进展\n\n真正的完整答案。", answer)
|
||||
require.Equal(t, answer, state.FinalAnswer)
|
||||
}
|
||||
|
|
@ -117,7 +117,8 @@ func TestFinalSynthesisKeepsConversationRolesImagesAndSteering(t *testing.T) {
|
|||
))
|
||||
require.Len(t, model.calls, 1)
|
||||
got := model.calls[0]
|
||||
require.Len(t, got, len(messages)+1)
|
||||
require.Len(t, got, len(messages))
|
||||
require.Contains(t, model.opts[0].RuntimeNotice, `"type":"final_synthesis"`)
|
||||
require.Equal(t, original, got[:len(messages)],
|
||||
"synthesis must use the same live conversation, including tool roles and latest steering")
|
||||
require.Empty(t, model.opts[0].Tools)
|
||||
|
|
|
|||
|
|
@ -0,0 +1,198 @@
|
|||
package agent
|
||||
|
||||
import (
|
||||
"context"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
agenttools "github.com/Tencent/WeKnora/internal/agent/tools"
|
||||
"github.com/Tencent/WeKnora/internal/models/chat"
|
||||
"github.com/Tencent/WeKnora/internal/types"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
func artifactResponse() mockResponse {
|
||||
// Same response shape as the captured incident: content deltas, no tool
|
||||
// calls, then finish_reason=stop. Use synthetic opaque bytes, not user data.
|
||||
return mockResponse{chunks: []types.StreamResponse{
|
||||
{ResponseType: types.ResponseTypeAnswer, Content: "open"},
|
||||
{ResponseType: types.ResponseTypeAnswer, Content: "ai_reasoning: "},
|
||||
{ResponseType: types.ResponseTypeAnswer, Content: strings.Repeat("A", 128) + "="},
|
||||
{ResponseType: types.ResponseTypeAnswer, Content: "</arg_value:6124c78e>"},
|
||||
{ResponseType: types.ResponseTypeAnswer, Done: true, FinishReason: "stop"},
|
||||
}}
|
||||
}
|
||||
|
||||
func TestProtocolArtifactRecoveryDoesNotReplayToolsOrPublishGarbage(t *testing.T) {
|
||||
for _, repeat := range []bool{false, true} {
|
||||
t.Run(map[bool]string{false: "recover", true: "bounded_failure"}[repeat], func(t *testing.T) {
|
||||
last := mockResponse{
|
||||
chunks: []types.StreamResponse{
|
||||
{ResponseType: types.ResponseTypeAnswer, Content: "完整报告", Done: true, FinishReason: "stop"},
|
||||
},
|
||||
}
|
||||
if repeat {
|
||||
last = artifactResponse()
|
||||
}
|
||||
model := &mockChat{responses: []mockResponse{
|
||||
{
|
||||
chunks: []types.StreamResponse{
|
||||
{
|
||||
ResponseType: types.ResponseTypeAnswer,
|
||||
Done: true,
|
||||
FinishReason: "tool_calls",
|
||||
ToolCalls: []types.LLMToolCall{
|
||||
{
|
||||
ID: "once",
|
||||
Type: "function",
|
||||
Function: types.FunctionCall{Name: "read_sources", Arguments: `{}`},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
artifactResponse(), last,
|
||||
}}
|
||||
e := newTestEngine(t, model)
|
||||
e.toolRegistry = agenttools.NewToolRegistry()
|
||||
source := newCountingTool("read_sources")
|
||||
e.toolRegistry.RegisterTool(source)
|
||||
recorder := &truncationRecorder{}
|
||||
recorder.attach(e.eventBus)
|
||||
state, err := e.Execute(context.Background(), "s", "m", "report", nil, nil)
|
||||
require.Equal(t, 1, source.calls)
|
||||
require.Len(t, model.calls, 3)
|
||||
if repeat {
|
||||
require.ErrorIs(t, err, agenttools.ErrProtocolArtifact)
|
||||
require.Nil(t, state)
|
||||
} else {
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, "完整报告", state.FinalAnswer)
|
||||
require.True(t, state.IsComplete)
|
||||
}
|
||||
for _, ev := range recorder.snapshot() {
|
||||
require.NotContains(t, ev.Content, "reasoning")
|
||||
require.NotContains(t, ev.Content, "arg_value")
|
||||
}
|
||||
var history strings.Builder
|
||||
for _, m := range model.calls[2] {
|
||||
history.WriteString(m.Content)
|
||||
}
|
||||
require.NotContains(t, history.String(), "</arg_value:")
|
||||
require.NotContains(t, history.String(), "existing tool and delegated results")
|
||||
require.Contains(t, model.opts[2].RuntimeNotice, "existing tool and delegated results")
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestFinalSynthesisRejectsProtocolArtifact(t *testing.T) {
|
||||
e := newTestEngine(t, &mockChat{responses: []mockResponse{artifactResponse()}})
|
||||
recorder := &truncationRecorder{}
|
||||
recorder.attach(e.eventBus)
|
||||
state := &types.AgentState{}
|
||||
err := e.streamFinalAnswerToEventBus(
|
||||
context.Background(),
|
||||
"report",
|
||||
state,
|
||||
"s",
|
||||
[]chat.Message{{Role: "user", Content: "report"}},
|
||||
)
|
||||
require.ErrorIs(t, err, agenttools.ErrProtocolArtifact)
|
||||
require.Empty(t, state.FinalAnswer)
|
||||
for _, ev := range recorder.snapshot() {
|
||||
require.Empty(t, ev.Content)
|
||||
}
|
||||
}
|
||||
|
||||
func TestNonceThinkContentDoesNotLeakIntoFinalAnswer(t *testing.T) {
|
||||
model := &mockChat{responses: []mockResponse{{chunks: []types.StreamResponse{
|
||||
{ResponseType: types.ResponseTypeAnswer, Content: "<thi"},
|
||||
{ResponseType: types.ResponseTypeAnswer, Content: "nk:6124c78e>private reasoning"},
|
||||
{ResponseType: types.ResponseTypeAnswer, Content: "</think:612"},
|
||||
{ResponseType: types.ResponseTypeAnswer, Content: "4c78e>完整报告", Done: true, FinishReason: "stop"},
|
||||
}}}}
|
||||
e := newTestEngine(t, model)
|
||||
e.toolRegistry = agenttools.NewToolRegistry()
|
||||
recorder := &truncationRecorder{}
|
||||
recorder.attach(e.eventBus)
|
||||
state, err := e.Execute(context.Background(), "s", "m", "report", nil, nil)
|
||||
require.NoError(t, err)
|
||||
require.True(t, state.IsComplete)
|
||||
require.Equal(t, "完整报告", state.FinalAnswer)
|
||||
for _, emitted := range recorder.snapshot() {
|
||||
require.NotContains(t, emitted.Content, "private reasoning")
|
||||
require.NotContains(t, emitted.Content, "think:")
|
||||
}
|
||||
}
|
||||
|
||||
func TestFinalSynthesisStripsNonceThinkContentBeforeStreaming(t *testing.T) {
|
||||
e := newTestEngine(t, &mockChat{responses: []mockResponse{{chunks: []types.StreamResponse{
|
||||
{
|
||||
ResponseType: types.ResponseTypeAnswer,
|
||||
Content: "<think:6124c78e>private reasoning</think:6124c78e>完整报告",
|
||||
Done: true,
|
||||
FinishReason: "stop",
|
||||
},
|
||||
}}}})
|
||||
recorder := &truncationRecorder{}
|
||||
recorder.attach(e.eventBus)
|
||||
state := &types.AgentState{}
|
||||
err := e.streamFinalAnswerToEventBus(
|
||||
context.Background(),
|
||||
"report",
|
||||
state,
|
||||
"s",
|
||||
[]chat.Message{{Role: "user", Content: "report"}},
|
||||
)
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, "完整报告", state.FinalAnswer)
|
||||
for _, emitted := range recorder.snapshot() {
|
||||
require.NotContains(t, emitted.Content, "private reasoning")
|
||||
require.NotContains(t, emitted.Content, "think:")
|
||||
}
|
||||
}
|
||||
|
||||
func TestOrphanToolCallsCloserRetriesFinalAnswerWithoutReplayingTools(t *testing.T) {
|
||||
model := &mockChat{responses: []mockResponse{
|
||||
{
|
||||
chunks: []types.StreamResponse{
|
||||
{
|
||||
ResponseType: types.ResponseTypeAnswer,
|
||||
Done: true,
|
||||
FinishReason: "tool_calls",
|
||||
ToolCalls: []types.LLMToolCall{
|
||||
{
|
||||
ID: "once",
|
||||
Type: "function",
|
||||
Function: types.FunctionCall{Name: "read_sources", Arguments: `{}`},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
{chunks: []types.StreamResponse{
|
||||
{ResponseType: types.ResponseTypeAnswer, Content: "\n\n</tool_"},
|
||||
{ResponseType: types.ResponseTypeAnswer, Content: "calls:6124c78e>", Done: true, FinishReason: "stop"},
|
||||
}},
|
||||
{
|
||||
chunks: []types.StreamResponse{
|
||||
{ResponseType: types.ResponseTypeAnswer, Content: "完整报告", Done: true, FinishReason: "stop"},
|
||||
},
|
||||
},
|
||||
}}
|
||||
e := newTestEngine(t, model)
|
||||
e.toolRegistry = agenttools.NewToolRegistry()
|
||||
source := newCountingTool("read_sources")
|
||||
e.toolRegistry.RegisterTool(source)
|
||||
recorder := &truncationRecorder{}
|
||||
recorder.attach(e.eventBus)
|
||||
state, err := e.Execute(context.Background(), "s", "m", "report", nil, nil)
|
||||
require.NoError(t, err)
|
||||
require.True(t, state.IsComplete)
|
||||
require.Equal(t, "完整报告", state.FinalAnswer)
|
||||
require.Equal(t, 1, source.calls)
|
||||
require.Len(t, model.calls, 3)
|
||||
for _, ev := range recorder.snapshot() {
|
||||
require.NotContains(t, ev.Content, "</tool_")
|
||||
}
|
||||
}
|
||||
|
|
@ -22,24 +22,43 @@ func (e *AgentEngine) Resume(
|
|||
snapshot []byte,
|
||||
answered *types.AgentPrompt,
|
||||
) (*types.AgentState, error) {
|
||||
if answered == nil {
|
||||
return nil, fmt.Errorf("resume needs an answered prompt")
|
||||
}
|
||||
snap, err := DecodeRunSnapshot(snapshot)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
e.bindCollaborationInput(sessionID, messageID)
|
||||
p := snap.PendingRound
|
||||
if p.BlockedIndex < 0 || p.BlockedIndex >= len(p.Calls) || len(p.Step.ToolCalls) != p.BlockedIndex {
|
||||
return nil, fmt.Errorf("snapshot round is inconsistent: blocked %d of %d calls, %d done",
|
||||
p.BlockedIndex, len(p.Calls), len(p.Step.ToolCalls))
|
||||
wait := answered == nil && snap.CollaborationWait && e.collaboration != nil && e.collaboration.Child == nil
|
||||
if answered == nil && !wait {
|
||||
return nil, fmt.Errorf("resume needs an answered prompt or owned collaboration wait")
|
||||
}
|
||||
if p.Calls[p.BlockedIndex].ID != answered.ToolCallID {
|
||||
return nil, fmt.Errorf("prompt %s answers call %s, run is blocked on %s",
|
||||
answered.ID, answered.ToolCallID, p.Calls[p.BlockedIndex].ID)
|
||||
if !snap.BetweenRounds {
|
||||
if p.BlockedIndex < 0 || p.BlockedIndex >= len(p.Calls) || len(p.Step.ToolCalls) != p.BlockedIndex {
|
||||
return nil, fmt.Errorf("snapshot round is inconsistent: blocked %d of %d calls, %d done",
|
||||
p.BlockedIndex, len(p.Calls), len(p.Step.ToolCalls))
|
||||
}
|
||||
if wait && p.Calls[p.BlockedIndex].Name != "wait_agent" {
|
||||
return nil, fmt.Errorf("unsafe collaboration checkpoint")
|
||||
}
|
||||
if answered != nil && p.Calls[p.BlockedIndex].ID != answered.ToolCallID {
|
||||
return nil, fmt.Errorf("prompt %s answers call %s, run is blocked on %s",
|
||||
answered.ID, answered.ToolCallID, p.Calls[p.BlockedIndex].ID)
|
||||
}
|
||||
} else if !wait {
|
||||
return nil, fmt.Errorf("between-round resume requires collaboration ownership")
|
||||
}
|
||||
if e.collaboration != nil {
|
||||
var stop func()
|
||||
ctx, stop = e.collaboration.Start(ctx)
|
||||
defer stop()
|
||||
}
|
||||
logger.Infof(ctx, "[Agent] Resuming: session=%s, message=%s, prompt=%s, round=%d",
|
||||
sessionID, messageID, answered.ID, snap.CurrentRound+1)
|
||||
sessionID, messageID, func() string {
|
||||
if answered != nil {
|
||||
return answered.ID
|
||||
}
|
||||
return "collaboration"
|
||||
}(), snap.CurrentRound+1)
|
||||
defer e.toolRegistry.Cleanup(ctx)
|
||||
|
||||
state := &types.AgentState{
|
||||
|
|
@ -50,6 +69,9 @@ func (e *AgentEngine) Resume(
|
|||
}
|
||||
systemPrompt := e.buildSystemPrompt(ctx)
|
||||
e.beginTurn(snap.Query, snap.ImageURLs, state)
|
||||
if err := e.restoreCollaborationDeliveries(ctx, snap); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
for id, content := range snap.UserMessages {
|
||||
e.recordSteerMessage(id, content)
|
||||
}
|
||||
|
|
@ -64,17 +86,22 @@ func (e *AgentEngine) Resume(
|
|||
}
|
||||
return nil
|
||||
}
|
||||
for _, step := range state.RoundSteps {
|
||||
for i, step := range state.RoundSteps {
|
||||
e.replayCollaborationDeliveries(&messages, i, true)
|
||||
if err := appendUsers(step); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
e.replayCollaborationDeliveries(&messages, i, false)
|
||||
messages = e.appendToolResults(messages, step)
|
||||
messages = e.appendToolImages(ctx, messages, step)
|
||||
}
|
||||
e.replayCollaborationDeliveries(&messages, len(state.RoundSteps), true)
|
||||
if err := appendUsers(p.Step); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
e.replayCollaborationDeliveries(&messages, len(state.RoundSteps), false)
|
||||
if e.toolRegistry != nil {
|
||||
e.toolRegistry.RestoreMCPExposure(snap.MCPToolRefs)
|
||||
e.toolRegistry.RememberMCPHistory(messages)
|
||||
// These calls were issued before suspension, including the first call
|
||||
// to a tool whose definition was only exposed by a describe round.
|
||||
|
|
@ -83,20 +110,30 @@ func (e *AgentEngine) Resume(
|
|||
}
|
||||
tools := e.buildToolsForLLM()
|
||||
|
||||
startTime := time.Now()
|
||||
step, suspended := e.finishPendingRound(ctx, p, answered, state.CurrentRound, sessionID, messageID)
|
||||
if suspended != nil {
|
||||
logger.Infof(ctx, "[Agent][Round-%d] Suspended again waiting on prompt %s",
|
||||
state.CurrentRound+1, suspended.PromptID)
|
||||
state.Suspended = suspended
|
||||
state.SuspendedStep = &step
|
||||
e.emitCompletionEvent(context.WithoutCancel(ctx), state, sessionID, messageID, startTime)
|
||||
return state, nil
|
||||
if wait && snap.BetweenRounds {
|
||||
if err := e.collaboration.ClearWait(ctx); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
if !snap.BetweenRounds {
|
||||
startTime := time.Now()
|
||||
step, suspended := e.finishPendingRound(ctx, p, answered, state.CurrentRound, sessionID, messageID)
|
||||
if suspended != nil {
|
||||
logger.Infof(ctx, "[Agent][Round-%d] Suspended again waiting on prompt %s",
|
||||
state.CurrentRound+1, suspended.PromptID)
|
||||
state.Suspended = suspended
|
||||
state.SuspendedStep = &step
|
||||
if e.collaboration != nil {
|
||||
e.collaboration.End(true)
|
||||
}
|
||||
e.emitCompletionEvent(context.WithoutCancel(ctx), state, sessionID, messageID, startTime)
|
||||
return state, nil
|
||||
}
|
||||
state.RoundSteps = append(state.RoundSteps, step)
|
||||
messages = e.appendToolResults(messages, step)
|
||||
messages = e.appendToolImages(ctx, messages, step)
|
||||
state.CurrentRound++
|
||||
}
|
||||
state.RoundSteps = append(state.RoundSteps, step)
|
||||
messages = e.appendToolResults(messages, step)
|
||||
messages = e.appendToolImages(ctx, messages, step)
|
||||
state.CurrentRound++
|
||||
|
||||
if _, err := e.executeLoop(ctx, state, snap.Query, messages, tools, sessionID, messageID); err != nil {
|
||||
logger.Errorf(ctx, "[Agent] Resumed execution failed: %v", err)
|
||||
|
|
|
|||
|
|
@ -40,6 +40,7 @@ func TestResumeRestoresFirstDeferredMCPCall(t *testing.T) {
|
|||
_, err := tools.RegisterMCPTools(ctx, r, services, nil, gate, 0, nil, &tools.MCPMetadataIO{
|
||||
Get: func(context.Context, uint64, string) (*types.MCPMetadata, error) {
|
||||
return &types.MCPMetadata{Tools: []*types.MCPTool{
|
||||
{Name: "read", InputSchema: json.RawMessage(`{"type":"object"}`)},
|
||||
{Name: "write", InputSchema: json.RawMessage(`{"type":"object"}`)},
|
||||
}}, nil
|
||||
},
|
||||
|
|
@ -55,6 +56,15 @@ func TestResumeRestoresFirstDeferredMCPCall(t *testing.T) {
|
|||
require.True(t, described.Success, described.Error)
|
||||
var definition map[string]any
|
||||
require.NoError(t, json.Unmarshal([]byte(described.Output), &definition))
|
||||
readDefinition, err := original.ExecuteTool(
|
||||
ctx,
|
||||
tools.ToolDiscoverMCPTools,
|
||||
json.RawMessage(`{"mode":"describe","server_id":"svc","tool_name":"read"}`),
|
||||
)
|
||||
require.NoError(t, err)
|
||||
require.True(t, readDefinition.Success)
|
||||
var readTool map[string]any
|
||||
require.NoError(t, json.Unmarshal([]byte(readDefinition.Output), &readTool))
|
||||
name, args := definition["function_name"].(string), `{}`
|
||||
if proxy {
|
||||
name = tools.ToolCallMCPTool
|
||||
|
|
@ -65,7 +75,8 @@ func TestResumeRestoresFirstDeferredMCPCall(t *testing.T) {
|
|||
args = string(data)
|
||||
}
|
||||
snap := RunSnapshot{
|
||||
Version: RunSnapshotVersion, Query: "do the work",
|
||||
MCPToolRefs: original.MCPExposureSnapshot(),
|
||||
Version: RunSnapshotVersion, Query: "do the work",
|
||||
PendingRound: PendingRound{Calls: []PendingCall{{ID: "call", Name: name, Arguments: args}}},
|
||||
}
|
||||
data, err := json.Marshal(snap)
|
||||
|
|
@ -77,6 +88,11 @@ func TestResumeRestoresFirstDeferredMCPCall(t *testing.T) {
|
|||
e.toolRegistry = newRegistry()
|
||||
_, err = e.Resume(ctx, "s", "m", nil, data, answeredPrompt("call"))
|
||||
require.NoError(t, err)
|
||||
_, err = e.toolRegistry.GetTool(readTool["function_name"].(string))
|
||||
require.NoError(t, err, "described but uncalled tools must survive approval resume")
|
||||
proxyTool, err := e.toolRegistry.GetTool(tools.ToolCallMCPTool)
|
||||
require.NoError(t, err)
|
||||
require.Contains(t, string(proxyTool.Parameters()), readTool["tool_ref"].(string))
|
||||
require.True(t, gate.resumed, "must find the deferred tool and deliver the existing decision")
|
||||
})
|
||||
}
|
||||
|
|
|
|||
|
|
@ -8,6 +8,7 @@ import (
|
|||
"maps"
|
||||
"sync"
|
||||
|
||||
"github.com/Tencent/WeKnora/internal/agent/collaboration"
|
||||
agenttools "github.com/Tencent/WeKnora/internal/agent/tools"
|
||||
"github.com/Tencent/WeKnora/internal/types"
|
||||
)
|
||||
|
|
@ -15,13 +16,28 @@ import (
|
|||
// RunSnapshotVersion is the format version written into RunSnapshot.
|
||||
const RunSnapshotVersion = 1
|
||||
|
||||
// CollaborationDelivery keeps mailbox input at its original round boundary.
|
||||
// It is model context, not a user-visible execution step.
|
||||
type CollaborationDelivery struct {
|
||||
BeforeStep int `json:"before_step"`
|
||||
// BeforeUsers distinguishes finishing-boundary events from the next poll,
|
||||
// which happens after that round's queued user messages have been delivered.
|
||||
BeforeUsers bool `json:"before_users,omitempty"`
|
||||
Events []collaboration.Event `json:"events"`
|
||||
}
|
||||
|
||||
// RunSnapshot is everything needed to resume a run that ended waiting on a
|
||||
// user prompt. It holds durable values only: request-local model handles
|
||||
// (cN, dN, res://, msN, mtN) do not survive the run, so the user turn is kept
|
||||
// as the raw query and re-rendered on resume, and tool arguments are kept in
|
||||
// their decoded form.
|
||||
type RunSnapshot struct {
|
||||
Version int `json:"version"`
|
||||
CollaborationDeliveries []CollaborationDelivery `json:"collaboration_deliveries,omitempty"`
|
||||
CollaborationCursor *int64 `json:"collaboration_cursor,omitempty"`
|
||||
MCPToolRefs []string `json:"mcp_tool_refs,omitempty"`
|
||||
Version int `json:"version"`
|
||||
CollaborationWait bool `json:"collaboration_wait,omitempty"`
|
||||
BetweenRounds bool `json:"between_rounds,omitempty"`
|
||||
// Request is the caller's types.ResumableAgentRequest.
|
||||
Request json.RawMessage `json:"request,omitempty"`
|
||||
Query string `json:"query"`
|
||||
|
|
@ -109,11 +125,12 @@ func (s *RunSnapshot) ClosedSteps(reason string) []types.AgentStep {
|
|||
// turnProgress tracks the turn so it can be captured mid-round. Tool calls
|
||||
// finish on errgroup goroutines, hence the lock.
|
||||
type turnProgress struct {
|
||||
mu sync.Mutex
|
||||
query string
|
||||
imageURLs []string
|
||||
state *types.AgentState
|
||||
userMessages map[string]string
|
||||
mu sync.Mutex
|
||||
query string
|
||||
imageURLs []string
|
||||
state *types.AgentState
|
||||
userMessages map[string]string
|
||||
collaborationDeliveries []CollaborationDelivery
|
||||
// round is the round executing tools, nil between rounds.
|
||||
round *roundProgress
|
||||
}
|
||||
|
|
@ -143,6 +160,7 @@ func (e *AgentEngine) beginTurn(query string, imageURLs []string, state *types.A
|
|||
defer e.progress.mu.Unlock()
|
||||
e.progress.query, e.progress.imageURLs, e.progress.state = query, imageURLs, state
|
||||
e.progress.userMessages = make(map[string]string)
|
||||
e.progress.collaborationDeliveries = nil
|
||||
}
|
||||
|
||||
func (e *AgentEngine) recordSteerMessage(id, content string) {
|
||||
|
|
@ -174,10 +192,16 @@ func (e *AgentEngine) recordCall(i int, call types.ToolCall) {
|
|||
}
|
||||
}
|
||||
|
||||
// RestrictSuspensionToCollaboration keeps durable collaboration waits while
|
||||
// prompts raised by ordinary tools block in-process, as the operator configured.
|
||||
func (e *AgentEngine) RestrictSuspensionToCollaboration() {
|
||||
e.collaborationOnlySuspension = true
|
||||
}
|
||||
|
||||
// snapshotFunc returns the ToolExecContext.Snapshot hook for call i, or nil
|
||||
// when this run cannot be suspended.
|
||||
func (e *AgentEngine) snapshotFunc(i int) func() ([]byte, int, error) {
|
||||
if !e.suspendable {
|
||||
// when this call cannot suspend the run.
|
||||
func (e *AgentEngine) snapshotFunc(i int, toolName string) func() ([]byte, int, error) {
|
||||
if !e.suspendable || (e.collaborationOnlySuspension && toolName != "wait_agent") {
|
||||
return nil
|
||||
}
|
||||
return func() ([]byte, int, error) {
|
||||
|
|
@ -250,16 +274,19 @@ func (e *AgentEngine) snapshot(blocked int) (*RunSnapshot, error) {
|
|||
}
|
||||
}
|
||||
return &RunSnapshot{
|
||||
Version: RunSnapshotVersion,
|
||||
Request: e.suspendRequest,
|
||||
Query: p.query,
|
||||
ImageURLs: p.imageURLs,
|
||||
UserMessages: maps.Clone(p.userMessages),
|
||||
CompletedSteps: append([]types.AgentStep(nil), p.state.RoundSteps...),
|
||||
KnowledgeRefs: append([]*types.SearchResult(nil), p.state.KnowledgeRefs...),
|
||||
CurrentRound: p.state.CurrentRound,
|
||||
TurnUsage: p.state.TurnUsage,
|
||||
PendingRound: PendingRound{Step: step, Calls: calls, BlockedIndex: blocked},
|
||||
CollaborationDeliveries: append([]CollaborationDelivery(nil), p.collaborationDeliveries...),
|
||||
CollaborationCursor: e.collaborationCursor(),
|
||||
Version: RunSnapshotVersion,
|
||||
MCPToolRefs: e.toolRegistry.MCPExposureSnapshot(),
|
||||
Request: e.suspendRequest,
|
||||
Query: p.query,
|
||||
ImageURLs: p.imageURLs,
|
||||
UserMessages: maps.Clone(p.userMessages),
|
||||
CompletedSteps: append([]types.AgentStep(nil), p.state.RoundSteps...),
|
||||
KnowledgeRefs: append([]*types.SearchResult(nil), p.state.KnowledgeRefs...),
|
||||
CurrentRound: p.state.CurrentRound,
|
||||
TurnUsage: p.state.TurnUsage,
|
||||
PendingRound: PendingRound{Step: step, Calls: calls, BlockedIndex: blocked},
|
||||
}, nil
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -13,6 +13,18 @@ import (
|
|||
|
||||
const suspendingToolName = "mcp_svc_danger"
|
||||
|
||||
// With operator prompt suspension off, only collaboration waits may checkpoint.
|
||||
func TestCollaborationOnlySuspensionKeepsPromptsInProcess(t *testing.T) {
|
||||
engine := newTestEngine(t, &mockChat{})
|
||||
engine.EnableSuspension(json.RawMessage(`{}`))
|
||||
require.NotNil(t, engine.snapshotFunc(0, suspendingToolName))
|
||||
|
||||
engine.RestrictSuspensionToCollaboration()
|
||||
require.Nil(t, engine.snapshotFunc(0, suspendingToolName))
|
||||
require.Nil(t, engine.snapshotFunc(0, "ask_user"))
|
||||
require.NotNil(t, engine.snapshotFunc(0, "wait_agent"))
|
||||
}
|
||||
|
||||
// suspendingTool stands in for an approval-gated MCP tool whose approval
|
||||
// outlived the hot wait: it saves the run state and suspends.
|
||||
type suspendingTool struct {
|
||||
|
|
|
|||
Some files were not shown because too many files have changed in this diff Show More
Loading…
Reference in New Issue