diff --git a/apps/workbench/docs/main-conversations-design.md b/apps/workbench/docs/main-conversations-design.md new file mode 100644 index 0000000000..d2694d23b6 --- /dev/null +++ b/apps/workbench/docs/main-conversations-design.md @@ -0,0 +1,69 @@ +# Workbench 主对话(LoopX Goal-Backed Main Conversations)设计说明 + +- 复用底座:LoopX `main` 上已合入的 Steward 账本/派工/审核收件箱底座(PR #9355)与既有 Goal/Todo 控制面。 +- 原则:不引入并行账本或绕开 LoopX 的普通子线程;主对话直接复用既有 LoopX Goal、Steward 派工、Steward 审批收件箱与 Core Goal 待办链路。 + +## 1. 核心实体与入口定位 + +### 1.1 主对话即真实 LoopX Goal 会话 +- **归属实体**:主对话不新建平行的 `conversation_kind` 线程表,而是直接绑定真实 LoopX Goal(`LoopxBindings` 的 `/loopx-threads.json` 与线程 `loopx` / `loopxInfo` 投影,携带稳定 `goalId`、`workspace` 与 `permission`)。 +- **免手选 LoopX(定名小写 `loop`)**: + - 侧栏顶栏统一为单个可访问名称为 **「新建」** 的入口(`Sidebar.tsx`,复用 `` 展开 **「新 loop」** 与 **「新对话」**,单模式直达「新对话」,同时移除侧栏常驻创建按钮与手机底部悬浮「新对话」胶囊;`⌘K` 命令面板及折叠侧栏顶栏按钮同步提供);仅柔化左上角 LoopX 品牌图标(浅色/深色均降低饱和与对比),不改动其他图标。 + - 点击「新 loop」即进入 `draftMain` 状态:自动清理 `draftTeam` 与无项目 `scratch`、优先选中支持 Goal 的 Agent、在输入栏保留必要的 ``(`read_only` / `workspace_auto`)与 ``(支持当前项目及既有「新建项目」流程)。 + - 发送首条消息时,自动走既有 `POST /api/loopx/launch/preview` → `` → `POST /api/loopx/launch/apply` 创建真实 LoopX Goal 并绑定 `loop` 线程。 + - **失败显式呈现、绝不静默降级**:当 Core 不可达(`loopx_core_unavailable`)、项目未授权(`workspace_not_granted`)或当前 Agent 不支持 Goal 时,复用 `` 原有错误态与引导,绝不静默降级为普通会话。 +- **既有入口与历史数据兼容**: + - 保留「新对话」(普通会话)与「LoopX 管家」(全局 Steward 收件箱)入口,不破坏既有操作路径。 + - 历史普通会话、历史 Goal 会话与扫描到的本机 Goal 会话直接通过 `isLoopxRow(thread)` 归类;侧栏按需在「筛选」后展开 **全部 / loop / 普通** 三态筛选(按实际展示会话集含多机聚合计算计数,持久化在 `localStorage`,收起态保留一键清除芯片)。默认状态视图按真实数据分为 **要你处理 / 进行中 / 最近**(空组自动收起不占位),其中 **置顶** 维持原语义,**最近** 组内按最近活动顺序保留真实分区、项目名称及 `+` / 菜单等既有操作,同时保留「LoopX 管家」「看板」与溢出入口可达。 + +## 2. 复用的既有服务与最小扩展边界 + +| 能力 | 复用的既有组件/服务 | 本次最小扩展 | +|---|---|---| +| 创建与绑定 Goal | `LoopxService`(`/api/loopx/launch/{preview,apply}`)、`LoopxBindings`、``、`` | 入口改为「开始一件事」直入 `draftMain`,退休 `` | +| 主对话派工(用户 + 模型) | `StewardDispatchService`(`steward_tasks` SQLite 表、`/api/steward/handoff`、`/api/steward/tasks`)、`stewardServer` Unix Socket | 增加 `parent_goal_id`、`parent_thread_id`、`permission_mode`、`client_request_id`、`result_summary` 列(幂等迁移);`returnRoute` 支持 `{ channel: 'main_conversation', goalId, parentThreadId, originId }`;按 `goalId` / `parentThreadId` 过滤;子任务结轮后回写 `resultSummary` 并触发父线程 `thread.updated` | +| 模型自主派工鉴权 | `StewardLedgerService` + `stewardServer`(`/steward/calli.sock`)+ `bin/loochat` + `goalContextBlock` | 仅向绑定了 LoopX Goal 的主对话进程注入作用域令牌 `LOOCHAT_MAIN_SOCKET` / `LOOCHAT_MAIN_TOKEN`;Socket ACL 强制锁定其 `returnRoute` 为自身 `(goalId, threadId)`,仅开放本事项的 `steward_session_handoff` / `steward_task_list` / `steward_surface` / `steward_agent_{send,interrupt}`,子 Agent 与普通线程无令牌且调用返回 `403` | +| 权限审核汇聚与跳转 | `StewardInboxService.surface()`(`/api/steward/surface`)、`ThreadManager.listPendingApprovals()`、`POST /api/approvals/:id`、``、`` | `surface({ goalId, parentThreadId })` 严格按所属 Goal、受管子任务与子线程集合过滤 `thread_approval`、`thread_input`、`plan_approval`、`core_action_proposal`;主对话横幅与审核抽屉支持一键 **「前往审核」** 抵达子线程既有 ``,并在子线程顶栏提供 **「← 主对话」** 返回入口;也支持内联裁决 | +| 持久待办 | Core Goal Todos(``、`/api/loopx/status.json?goal_id=`、`/api/loopx/api/chat/todo/{dry-run,apply}`、`/api/loopx/api/actions/*`) | 在主对话下方 Dock 的 **「待办」** 抽屉直接嵌入 ``,变更回调刷新主对话计数,不建第二套待办存储 | + +## 3. 交互结构(`loop` 顶部督办、内联任务卡与底部状态栏) + +`loop` 会话共用单一作用域状态(`useLoopMatterState`,按 `thread.id:goalId` 隔离),不重复请求、不串事项: +1. **顶部「帮我督办」入口与聊天入口共享同一条原生督办路径**(`` + `loopx/supervision.ts`): + - 点击当前 `loop` 顶部「帮我督办」或在输入框直接发送显式指令(如「帮我督办」/「停止督办」/ `/supervise` / `/unsupervise`)均执行同一个 `executeLoopSupervision()`,不以普通模型同意回复充当启用成功,也不做虚假语义猜测(带附加说明的多句对话按正常聊天发送)。 + - 仅复用既有公开接口:`GET /api/steward/supervision`、`GET /api/steward/supervision/grants`、`POST /api/steward/tasks/:id/supervision/{grant,revoke}`;**绝不**从局部点击或输入触发作用于全实例的 `POST /api/steward/supervision/tick`,也不把全局巡检数字归因到单个 `loop`,而是仅登记本 `loop` 任务授权并由既有后台调度器自然推进、按本 `loop` 任务事件与实际状态验收。 + - **零子任务先点/说「帮我督办」与后续任务衔接边界**:因后端当前仅有按任务授权表 `steward_supervision_grants`(无服务端 per-loop 常驻继承表),前端按 `thread.id:goalId` 在本浏览器 `localStorage` 保存该 `loop` 的显式督办意图: + - **0 子任务时先点/说「帮我督办」**:立即登记该 `loop` 督办意图并如实提示覆盖范围;同一 `loop` 后续在本浏览器打开期间派出的可督办子任务会自动调用既有 `POST /api/steward/tasks/:id/supervision/grant` 补授按任务授权(只读任务仅 `['retry', 'continue']`,不扩权限;若某任务在登记后被手动撤销,则尊重撤销不覆盖)。 + - **刷新与切换 `loop`**:刷新页面或从其他 `loop` 切回后仍保留该 `loop` 意图并补授新出现的未撤销可督办子任务;其他 `loop` 绝不继承。 + - **关闭页面 / 跨设备边界**:已补授成功并落入 SQLite 的按任务授权在关闭页面后仍由后台调度器持续跟进;但关闭页面期间或跨设备在该 `loop` 下新派出的子任务,后端不会在无人打开本浏览器时自动继承,须待本浏览器重开该 `loop` 后自动补授(或未来后端新增服务端 per-loop 授权)。撤销授权或说「停止督办」时同步清除该 `loop` 意图并撤销该 `loop` 全部生效任务授权。 + - **真实状态与权限边界**:分子与分母严格同源(仅统计当前可督办子任务集合中的已授权数,`active <= eligible`);全量授权或零任务已登记且全局已开启时顶栏切为状态按钮而不再重复突出「帮我督办」主按钮;明确区分全局「管家自动督办」开关(未开启时仅记录本 `loop` 子任务授权、不虚报自动巡检已运行,并提供「前往通用设置」引导,绝不静默改动全局开关影响其他项目);只读子任务仅授予 `['retry', 'continue']` 不扩写权限;存在待审批/待确认项时停在审批前,绝不自动放行审批;连点去重、同授权幂等、切 `loop` 互不阻塞/不串回执;撤销仅撤销本 `loop` 任务授权。 +2. **对话流内联子任务卡**(``): + - 直接在 `loop` 对话流中以无外框轻量任务行呈现真实 `StewardTaskRecord`(相对时间不折行、语义状态圆点、内联 Agent/只读来源文字、已授权督办提示与直达子会话 `↗`),通过 `cleanReadableSummary()` 过滤原始 closeout 模板与内部派工 UUID(无可读摘要时隐藏摘要片段),不伪造未知字段(后端未持久化新建/续接唤醒模式故不虚构该角标): + - `waiting` / `awaiting_approval` → `需要你`(雾蓝语义:`--loop-pill-mist-bg` 轻量混合底色 + `--loop-pill-mist-dot` 圆点与箭头 + `--loop-pill-mist-fg` 状态文字 + 深中性主文与中性「已授权督办」辅助层级) + - `running` → `工作中`(`--positive`);`queued_workspace` → `排队中` + - `idle` 且位于 `stewardReviewing` → `待验收`(`--loopx-blue`) + - `failed` / `cancelled` → `已中断`(`--danger` + 真实错误信息) + - `user_intervened` → `已接管`;其余 `idle` / `completed` → `已完成` +3. **底部雾蓝(Neon 方案 A)无框状态胶囊栏**(``): + - 合并重复审批入口:提醒条仅保留单个「去处理」按钮打开「要你处理」抽屉,抽屉内每条审批提供真实裁决按钮 + 单个子会话跳转链接。 + - 采用用户选定的 **雾蓝(Mist Blue,Neon 方案 A)** 底部胶囊:**要你处理 N / 进行中 N / 已完成 N / 待办 N**;移除底部细灰分割线(`border-top: 0`)与胶囊常驻描边(`border: 0`),用浅雾蓝/深雾蓝区分待处理与选中态、用独立中性 `:focus-visible` 聚焦环将键盘焦点与状态文字语义分离,手机 390px 单行排布且按钮高度 `>= 34px`;移除输入框旁重复的 Goal 标题芯片;手动派工表单默认收起在「进行中」抽屉右上角「手动派工」按钮后;派工在途状态、Agent/权限选择、输入与错误及审批动作均按 `(thread.id, goalId)` 隔离;`Esc` 关闭抽屉并将焦点还回触发胶囊,且不中断正在进行的对话轮次。 +4. **侧栏折叠与返回**:由 `loop` 派出的活跃子线程自动折叠在该 `loop` 行下方;子线程等待审核时父行同步亮起等待圆点;打开子线程后顶栏显示「← loop · 标题」。 + +## 4. 归属、权限与并发边界 + +- **跨事项严格隔离与过滤顺序**: + - 后端:`resolveMainScope({ goalId, parentThreadId })` 统一校验归属合法性,拒绝不存在的父线程(`404 parent_thread_not_found`)、未绑定 Goal 的普通线程(`409 parent_thread_not_bound_to_goal`)以及 `goalId` 与父绑定错配(`409 parent_goal_mismatch`)。 + - 过滤先于截断:`scopeThreadIds` / `scopeTaskIds` 无 `LIMIT` 查询所属子会话,并联合 `loopx.bindings.threadsOf(goalId)` 涵盖被绑定 Goal 线程本身与全部合法子会话;`StewardInboxService` 的 `listConcerns` / `listFollowups` / `countDueFollowups` 与 `StewardDispatchService.listTasks` 均在 SQL `WHERE` 归属过滤后再 `LIMIT` 截断,其他事项或历史普通线程数据绝不串入或挤占。 + - 前端:`useLoopMatterState` 以 `(thread.id, goalId)` 为键同步投影作用域快照(切换 `loop` 当帧即刻清零旧事项数据,避免 1 帧跨事项闪现),并对 `supervise`/`revoke` 引入按作用域单调序号防乱序回写覆盖;`MainConversationDock` 使用 `AbortController` + 作用域 ref 丢弃过期响应并将派工选项与提案忽略动作纳入作用域隔离;`` 强制重建。 +- **权限边界与服务端 Binding 权威**: + - 主对话 model-side dispatch 经 `LOOCHAT_MAIN_TOKEN` 访问 `stewardServer` 时,**完全由服务端 `LoopxBinding` 决定** `parentThreadId`、`goalId`、`workspace` 边界与父权限上限: + - 忽略客户端自报的 `returnRoute` / `repo`;`cwd` 必须落在 `binding.workspace` 目录树内,越界返回 `403 cwd_outside_goal_workspace`。 + - 父 Goal 为 `read_only` 时,一律强制派发只读任务(`readonly=true`、`workspace='none'`),禁止申请 `auto_edit` / `full_access` / `readonly=false` 或可写工作区(`403 permission_escalation_denied`)。 + - 父 Goal 为 `workspace_auto` 时,禁止自行提权为 `full_access`(`403 permission_escalation_denied`)。 + - 子 Agent 进程启动时 `sessionEnvironment` 主动清理 `LOOCHAT_MAIN_SOCKET` / `LOOCHAT_MAIN_TOKEN`,防止权限逃逸。 + - **Fail-Closed 权限校验**:`StewardDispatchService.permissionModeFor` 在 `readonly`、显式 `read_only` 或 `ask` 模式下,若目标 adapter 不支持相应权限级别,直接以 `400 unsupported_permission_mode` 拒绝,绝不回退为 `auto_edit` / `full_access` / `undefined`;在 `taskPlan` / `sessionHandoff(spawn)` / `sessionHandoff(continue)` 三处单独传入 `permissionMode: 'read_only'` 时均等价于 `readonly: true`(强制 `workspacePolicy: 'none'`、不建可写 worktree、不占目录写锁)。 +- **并发与重复操作**: + - 派工幂等与并发去重:`sessionHandoff` 在进入任意 `await` 之前同步注册 `inflightClientRequests`,确保并发同 `clientRequestId` 请求只执行一次(意图不同返 `409 client_request_id_conflict`);`mode: 'continue'` 先执行幂等命中检查再核验 `expectedLastTurnId`,避免已成功请求重试被误判为 `409 user_intervened`;`goalContextBlock` 指导模型派工携带稳定 `--request-id`。 + - 失败与取消的幂等键边界:仅当首次启动在创建子线程之前失败(`status === 'failed' && threadId === null`)时才由 `failTaskLaunch` 释放 `client_request_id` 并返回 `503`(`retryable: true`)允许同 key 重试;一旦子线程已创建(`threadId !== null`),即使后续进入 `failed` 或 `cancelled`,同 `clientRequestId` 重试一律返回 `reused: true` 复用原状态,不重启或新建子线程。 + - 审批幂等:`POST /api/approvals/:id` 在 `ThreadManager.resolveApproval()` 首次处理后即移除挂起项,重复点击或跨端已处理返回 `404`;前端按 `approvalId` 禁用连点,并在 `404` 时平滑刷新状态并提示已处理。 + - 目录并发:复用 `StewardDispatchService` 既有 Git Worktree 隔离与同目录 FIFO 写互斥队列。 diff --git a/apps/workbench/packages/daemon/bin/loochat b/apps/workbench/packages/daemon/bin/loochat index 8aa2c57e0a..267dd16649 100755 --- a/apps/workbench/packages/daemon/bin/loochat +++ b/apps/workbench/packages/daemon/bin/loochat @@ -43,6 +43,10 @@ Team commands use LOOCHAT_URL (or LOOCHAT_HOST and LOOCHAT_PORT) and LOOCHAT_TOK loochat ask --text-file FILE|- [--timeout SECONDS] Says the text to the personal assistant (Router) and waits for its reply, default 300 seconds. Prints {threadId, reply}; reply is null when the assistant has not answered in time. Same credentials as team. +loochat main-dispatch --agent ID --title TITLE (--message-file FILE|- | --message TEXT) [--permission MODE] [--cwd DIR] [--request-id KEY] [--readonly] +loochat main-tasks +loochat main-surface + Scoped to the current LoopX Goal main conversation via LOOCHAT_MAIN_SOCKET / LOOCHAT_MAIN_TOKEN. FILE may be - for stdin. Reuse the request ID only when retrying the same request. Members can message existing teammates; only the lead can spawn or stop members. A remote member's task is also written to a handoff markdown file on its machine, and the result it @@ -69,6 +73,66 @@ try { await toolsMain(args); process.exit(process.exitCode ?? 0); } + if (args[0] === 'main-dispatch' || args[0] === 'main-tasks' || args[0] === 'main-surface') { + const socket = process.env.LOOCHAT_MAIN_SOCKET; + const token = process.env.LOOCHAT_MAIN_TOKEN; + if (!socket || !token) throw new Error('Run this command inside a LoopX Goal main conversation.'); + const rpc = (method, params) => new Promise((resolvePromise, rejectPromise) => { + const payload = JSON.stringify({ method, params }); + const req = request({ + socketPath: socket, + path: '/rpc', + method: 'POST', + headers: { + Authorization: `Bearer ${token}`, + 'Content-Type': 'application/json', + 'Content-Length': Buffer.byteLength(payload), + }, + }, (res) => { + let text = ''; + res.setEncoding('utf8'); + res.on('data', (chunk) => { text += chunk; }); + res.on('end', () => { + console.log(text); + if ((res.statusCode ?? 500) >= 400) process.exitCode = 1; + resolvePromise(); + }); + }); + req.setTimeout(30000, () => req.destroy(new Error('Timed out; retry with the same request-id.'))); + req.on('error', rejectPromise); + req.end(payload); + }); + if (args[0] === 'main-tasks') { + await rpc('steward_task_list', {}); + process.exit(process.exitCode ?? 0); + } + if (args[0] === 'main-surface') { + await rpc('steward_surface', {}); + process.exit(process.exitCode ?? 0); + } + const flags = args.slice(1); + const params = { mode: 'spawn' }; + let messageFile; + while (flags.length) { + const flag = flags.shift(); + if (flag === '--readonly') { params.readonly = true; continue; } + const value = flags.shift(); + if (value === undefined) throw new Error(`Missing value: ${flag}`); + if (flag === '--agent') params.agent = value; + else if (flag === '--title') params.title = value; + else if (flag === '--message') params.objective = value; + else if (flag === '--message-file') messageFile = value; + else if (flag === '--cwd') params.cwd = value; + else if (flag === '--permission') params.permissionMode = value; + else if (flag === '--request-id') params.clientRequestId = value; + else throw new Error(`Invalid argument: ${flag}`); + } + if (messageFile) params.objective = readFileSync(messageFile === '-' ? 0 : messageFile, 'utf8'); + if (!params.objective || !params.objective.trim()) throw new Error('Give --message TEXT or --message-file FILE.'); + if (!params.title) params.title = params.objective.trim().split('\n')[0].slice(0, 60); + await rpc('steward_session_handoff', params); + process.exit(process.exitCode ?? 0); + } if (args[0] === 'team' || args[0] === 'ask') { // Like scripts/restart.sh: a hub bound to one interface is not on loopback. const host = !process.env.LOOCHAT_HOST || ['0.0.0.0', '::'].includes(process.env.LOOCHAT_HOST) ? '127.0.0.1' : process.env.LOOCHAT_HOST; diff --git a/apps/workbench/packages/daemon/src/adapters/loopx/context.ts b/apps/workbench/packages/daemon/src/adapters/loopx/context.ts index b0a1212ace..bd3c6cfa1a 100644 --- a/apps/workbench/packages/daemon/src/adapters/loopx/context.ts +++ b/apps/workbench/packages/daemon/src/adapters/loopx/context.ts @@ -31,6 +31,11 @@ export function goalContextBlock(binding: LoopxBinding, state: GoalState | null, } else { lines.push(`Goal 状态暂时读不到(${unavailable ?? '未知原因'})。不要凭记忆说明进度,需要时请用户刷新。`); } - lines.push('Goal 的待办、验收和状态由核心维护,这里不要直接改;需要改动时说明你的建议,由用户在 Goal 页确认。', '', ''); + lines.push( + '如需将子任务派给其他 Agent 并归属当前事项,可执行 `"$LOOCHAT_BIN_DIR/loochat" main-dispatch --agent AGENT_ID --title TITLE --message-file FILE --request-id `(或 `--message TEXT`,重试同一派工请复用相同的 `--request-id` 以防重复创建),并用 `"$LOOCHAT_BIN_DIR/loochat" main-tasks` 查看本事项已派任务状态与结果。', + 'Goal 的待办、验收和状态由核心维护,这里不要直接改;需要改动时说明你的建议,由用户在 Goal 页确认。', + '', + '', + ); return lines.join('\n'); } diff --git a/apps/workbench/packages/daemon/src/adapters/types.ts b/apps/workbench/packages/daemon/src/adapters/types.ts index 553dc9f0cd..802d8fc5aa 100644 --- a/apps/workbench/packages/daemon/src/adapters/types.ts +++ b/apps/workbench/packages/daemon/src/adapters/types.ts @@ -540,6 +540,7 @@ export function sessionEnvironment(base: Record, context?: Recor CALLI_TOOLS_SOCKET: undefined, CALLI_TOOLS_KEY: undefined, CALLI_TOKEN: undefined, LIMI_SOCKET: undefined, LIMI_KEY: undefined, RAH_TOKEN: undefined, LOOPX_WORKBENCH_STEWARD_CREDENTIAL: undefined, LOOCHAT_STEWARD_SOCKET: undefined, + LOOCHAT_MAIN_SOCKET: undefined, LOOCHAT_MAIN_TOKEN: undefined, ...context, }; if (context?.LOOCHAT_BIN_DIR) env.PATH = `${context.LOOCHAT_BIN_DIR}${process.platform === 'win32' ? ';' : ':'}${base.PATH ?? process.env.PATH ?? ''}`; diff --git a/apps/workbench/packages/daemon/src/http.ts b/apps/workbench/packages/daemon/src/http.ts index a39cce4401..3a023f877b 100644 --- a/apps/workbench/packages/daemon/src/http.ts +++ b/apps/workbench/packages/daemon/src/http.ts @@ -999,6 +999,8 @@ export function createHttpServer(deps: HttpDeps): Server { tasks: deps.stewardLedger.dispatch.listTasks({ status: status || null, planId: url.searchParams.get('planId'), + goalId: url.searchParams.get('goalId'), + parentThreadId: url.searchParams.get('parentThreadId'), limit, }), }); @@ -1040,6 +1042,7 @@ export function createHttpServer(deps: HttpDeps): Server { agent: typeof body.agent === 'string' ? body.agent : undefined, model: typeof body.model === 'string' ? body.model : null, effort: typeof body.effort === 'string' ? body.effort : null, + permissionMode: typeof body.permissionMode === 'string' ? body.permissionMode : undefined, workspace: body.workspace, ownerStep: body.ownerStep ?? null, requireApproval: body.requireApproval === true, @@ -1048,6 +1051,7 @@ export function createHttpServer(deps: HttpDeps): Server { expectedLastTurnId: body.expectedLastTurnId, queue: body.queue === true, returnRoute: body.returnRoute ?? null, + clientRequestId: typeof body.clientRequestId === 'string' ? body.clientRequestId : undefined, })); } @@ -1070,10 +1074,16 @@ export function createHttpServer(deps: HttpDeps): Server { if (method === 'GET' && path === '/api/steward/surface') { if (!deps.stewardLedger) throw new HttpError(404, 'steward surface unavailable'); const core = deps.coreUrl ?? deps.loopx?.coreEndpoint; + const goalId = url.searchParams.get('goalId'); + const parentThreadId = url.searchParams.get('parentThreadId'); return sendJson( res, 200, - await deps.stewardLedger.inbox.surface(core !== undefined ? { coreUrl: core } : {}), + await deps.stewardLedger.inbox.surface({ + ...(core !== undefined ? { coreUrl: core } : {}), + ...(goalId ? { goalId } : {}), + ...(parentThreadId ? { parentThreadId } : {}), + }), ); } diff --git a/apps/workbench/packages/daemon/src/index.ts b/apps/workbench/packages/daemon/src/index.ts index 0d054a76a6..23426a9e6e 100644 --- a/apps/workbench/packages/daemon/src/index.ts +++ b/apps/workbench/packages/daemon/src/index.ts @@ -181,6 +181,7 @@ async function main(): Promise { }); const stewardSocketServer = stewardServer(stewardLedger); if (!await listenPrivate(stewardSocketServer, stewardLedger.socketPath)) throw new Error('Steward socket is already in use'); + manager.mainConversationEnv = (threadId) => stewardLedger.mainConversationEnvironment(threadId); // Extensions start after recovery, scheduling and collaboration, and before anything is served, // so the first thing they hear is a machine that is ready. const extensions = new ExtensionHost({ diff --git a/apps/workbench/packages/daemon/src/steward-dispatch.ts b/apps/workbench/packages/daemon/src/steward-dispatch.ts index e2f93429c9..01bc8510ed 100644 --- a/apps/workbench/packages/daemon/src/steward-dispatch.ts +++ b/apps/workbench/packages/daemon/src/steward-dispatch.ts @@ -11,6 +11,7 @@ import type { } from './adapters/loopx/service.js'; import { HttpError } from './errors.js'; import type { StoredEvent } from './events.js'; +import { turnAnswer } from './coordination.js'; import type { Store } from './store.js'; import type { ThreadManager, ThreadView } from './threads.js'; import { isWithinWorkdirs } from './workdirs.js'; @@ -47,8 +48,13 @@ export interface StewardReturnRoute { channel?: string; laneKey?: string; originId?: string; + goalId?: string; + parentThreadId?: string; } +export const STEWARD_TASK_PERMISSION_MODES = ['read_only', 'ask', 'auto_edit', 'full_access'] as const; +export type StewardTaskPermissionMode = (typeof STEWARD_TASK_PERMISSION_MODES)[number]; + export interface StewardTaskRecord { id: string; planId: string | null; @@ -60,6 +66,7 @@ export interface StewardTaskRecord { agent: string; model: string | null; effort: string | null; + permissionMode?: StewardTaskPermissionMode | null; sourceCwd: string; resolvedCwd: string; lockDir: string | null; @@ -70,6 +77,8 @@ export interface StewardTaskRecord { lastTurnId: string | null; expectedLastTurnId?: string | null; returnRoute: StewardReturnRoute | null; + clientRequestId?: string | null; + resultSummary?: string | null; queueSeq: number | null; errorMessage: string | null; createdAt: string; @@ -117,9 +126,11 @@ export interface StewardTaskPlanItemInput { agent?: string; model?: string | null; effort?: string | null; + permissionMode?: StewardTaskPermissionMode | null; workspace?: StewardWorkspacePolicy; ownerStep?: StewardOwnerStep | null; skipProjectMemory?: boolean; + clientRequestId?: string | null; } export interface StewardTaskPlanInput { @@ -148,6 +159,7 @@ export interface StewardSessionHandoffInput { agent?: string; model?: string | null; effort?: string | null; + permissionMode?: StewardTaskPermissionMode | null; workspace?: StewardWorkspacePolicy; ownerStep?: StewardOwnerStep | null; requireApproval?: boolean; @@ -156,6 +168,7 @@ export interface StewardSessionHandoffInput { expectedLastTurnId?: string | null; queue?: boolean; returnRoute?: StewardReturnRoute | null; + clientRequestId?: string | null; } export interface StewardSessionHandoffResult { @@ -165,6 +178,7 @@ export interface StewardSessionHandoffResult { turnId: string | null; queuedId: string | null; imported: boolean; + reused?: boolean; } export interface StewardAgentSendInput { @@ -207,6 +221,7 @@ interface StewardTaskRow { agent: string; model: string | null; effort: string | null; + permission_mode?: string | null; source_cwd: string; resolved_cwd: string; lock_dir: string | null; @@ -218,6 +233,10 @@ interface StewardTaskRow { has_expected_last_turn_id: number; expected_last_turn_id: string | null; return_route_json: string | null; + parent_goal_id?: string | null; + parent_thread_id?: string | null; + client_request_id?: string | null; + result_summary?: string | null; queue_seq: number | null; error_message: string | null; created_at: string; @@ -258,6 +277,33 @@ function normalizeWorkspacePolicy(value: unknown, readonly: boolean): StewardWor throw new HttpError(400, `invalid_workspace_policy:${String(value)}`); } +function normalizeTaskPermissionMode(value: unknown, readonly: boolean): StewardTaskPermissionMode | null { + if (value === undefined || value === null || value === '') return null; + if (value !== 'read_only' && value !== 'ask' && value !== 'auto_edit' && value !== 'full_access') { + throw new HttpError(400, `invalid_permission_mode:${String(value)}`); + } + if (readonly && (value === 'auto_edit' || value === 'full_access')) { + throw new HttpError(400, 'readonly_task_cannot_use_writable_permission'); + } + return value; +} + +function normalizeClientRequestId(value: unknown): string | null { + if (value === undefined || value === null) return null; + if (typeof value !== 'string') throw new HttpError(400, 'invalid_client_request_id'); + const trimmed = value.trim(); + if (!trimmed) return null; + if (trimmed.length > 128) throw new HttpError(400, 'client_request_id_too_long'); + return trimmed; +} + +function clipResultSummary(text: string | null | undefined, max = 400): string | null { + if (!text) return null; + const cleaned = text.trim(); + if (!cleaned) return null; + return cleaned.length > max ? `${cleaned.slice(0, max - 1)}…` : cleaned; +} + function normalizeDoneWhen(value: unknown, readonly: boolean): string[] { if (value === undefined || value === null) { if (!readonly) throw new HttpError(400, 'done_when_required_for_writable_task'); @@ -342,6 +388,19 @@ function parsePendingPromotionJson(raw: string | null | undefined): PendingGoalC function rowToTask(row: StewardTaskRow): StewardTaskRecord { const pendingPromotion = parsePendingPromotionJson(row.pending_promotion_json); + const parsedRoute = row.return_route_json ? (JSON.parse(row.return_route_json) as StewardReturnRoute) : null; + const returnRoute: StewardReturnRoute | null = parsedRoute + ? { + ...parsedRoute, + ...(row.parent_goal_id && !parsedRoute.goalId ? { goalId: row.parent_goal_id } : {}), + ...(row.parent_thread_id && !parsedRoute.parentThreadId ? { parentThreadId: row.parent_thread_id } : {}), + } + : row.parent_goal_id || row.parent_thread_id + ? { + ...(row.parent_goal_id ? { goalId: row.parent_goal_id } : {}), + ...(row.parent_thread_id ? { parentThreadId: row.parent_thread_id } : {}), + } + : null; return { id: row.id, planId: row.plan_id, @@ -353,6 +412,7 @@ function rowToTask(row: StewardTaskRow): StewardTaskRecord { agent: row.agent, model: row.model, effort: row.effort, + ...(row.permission_mode ? { permissionMode: row.permission_mode as StewardTaskPermissionMode } : {}), sourceCwd: row.source_cwd, resolvedCwd: row.resolved_cwd, lockDir: row.lock_dir, @@ -362,7 +422,9 @@ function rowToTask(row: StewardTaskRow): StewardTaskRecord { status: row.status as StewardTaskStatus, lastTurnId: row.last_turn_id, ...(row.has_expected_last_turn_id === 1 ? { expectedLastTurnId: row.expected_last_turn_id } : {}), - returnRoute: row.return_route_json ? (JSON.parse(row.return_route_json) as StewardReturnRoute) : null, + returnRoute, + ...(row.client_request_id ? { clientRequestId: row.client_request_id } : {}), + ...(row.result_summary ? { resultSummary: row.result_summary } : {}), queueSeq: row.queue_seq, errorMessage: row.error_message, createdAt: row.created_at, @@ -391,6 +453,8 @@ export class StewardDispatchService { /** Tracks in-flight startup/background promotion reconciliations per task. */ private readonly promotionReconciliations = new Map>(); private readonly skipMemoryTasks = new Set(); + /** In-flight idempotent sessionHandoff requests keyed by `::`. */ + private readonly inflightClientRequests = new Map }>(); private projectMemoryProvider: ((projectRoot: string) => string | null) | null = null; private readonly unsubscribe: () => void; private disposed = false; @@ -454,6 +518,7 @@ export class StewardDispatchService { agent TEXT NOT NULL, model TEXT, effort TEXT, + permission_mode TEXT, source_cwd TEXT NOT NULL, resolved_cwd TEXT NOT NULL, lock_dir TEXT, @@ -465,6 +530,10 @@ export class StewardDispatchService { has_expected_last_turn_id INTEGER NOT NULL DEFAULT 0, expected_last_turn_id TEXT, return_route_json TEXT, + parent_goal_id TEXT, + parent_thread_id TEXT, + client_request_id TEXT, + result_summary TEXT, queue_seq INTEGER, error_message TEXT, created_at TEXT NOT NULL, @@ -504,9 +573,46 @@ export class StewardDispatchService { if (!cols.has('pending_promotion_json')) { this.deps.store.db.exec(`ALTER TABLE steward_tasks ADD COLUMN pending_promotion_json TEXT`); } - this.deps.store.db.exec( - `CREATE INDEX IF NOT EXISTS idx_steward_tasks_promoted_goal ON steward_tasks(promoted_goal_id)`, - ); + if (!cols.has('permission_mode')) { + this.deps.store.db.exec(`ALTER TABLE steward_tasks ADD COLUMN permission_mode TEXT`); + } + if (!cols.has('parent_goal_id')) { + this.deps.store.db.exec(`ALTER TABLE steward_tasks ADD COLUMN parent_goal_id TEXT`); + } + if (!cols.has('parent_thread_id')) { + this.deps.store.db.exec(`ALTER TABLE steward_tasks ADD COLUMN parent_thread_id TEXT`); + } + if (!cols.has('client_request_id')) { + this.deps.store.db.exec(`ALTER TABLE steward_tasks ADD COLUMN client_request_id TEXT`); + } + if (!cols.has('result_summary')) { + this.deps.store.db.exec(`ALTER TABLE steward_tasks ADD COLUMN result_summary TEXT`); + } + this.deps.store.db.exec(` + CREATE INDEX IF NOT EXISTS idx_steward_tasks_promoted_goal ON steward_tasks(promoted_goal_id); + CREATE INDEX IF NOT EXISTS idx_steward_tasks_parent_goal ON steward_tasks(parent_goal_id); + CREATE INDEX IF NOT EXISTS idx_steward_tasks_parent_thread ON steward_tasks(parent_thread_id); + CREATE UNIQUE INDEX IF NOT EXISTS idx_steward_tasks_client_req + ON steward_tasks(COALESCE(parent_thread_id, ''), client_request_id) + WHERE client_request_id IS NOT NULL; + `); + // Backfill parent Goal / thread ownership columns for tasks persisted before these columns existed. + this.deps.store.db.exec(` + UPDATE steward_tasks + SET + parent_goal_id = COALESCE(parent_goal_id, NULLIF(TRIM(json_extract(return_route_json, '$.goalId')), '')), + parent_thread_id = COALESCE( + parent_thread_id, + NULLIF(TRIM(json_extract(return_route_json, '$.parentThreadId')), ''), + CASE + WHEN json_extract(return_route_json, '$.channel') = 'main_conversation' + THEN NULLIF(TRIM(json_extract(return_route_json, '$.originId')), '') + ELSE NULL + END + ) + WHERE return_route_json IS NOT NULL + AND (parent_goal_id IS NULL OR parent_thread_id IS NULL); + `); } private reconcileOnStart(): void { @@ -580,18 +686,93 @@ export class StewardDispatchService { return (row?.max_seq ?? 0) + 1; } + private normalizeReturnRoute(raw: StewardReturnRoute | null | undefined): StewardReturnRoute | null { + if (!raw || typeof raw !== 'object') return null; + const channel = typeof raw.channel === 'string' && raw.channel.trim() ? raw.channel.trim() : undefined; + const laneKey = typeof raw.laneKey === 'string' && raw.laneKey.trim() ? raw.laneKey.trim() : undefined; + const originId = typeof raw.originId === 'string' && raw.originId.trim() ? raw.originId.trim() : undefined; + let goalId = typeof raw.goalId === 'string' && raw.goalId.trim() ? raw.goalId.trim() : undefined; + const parentThreadId = + typeof raw.parentThreadId === 'string' && raw.parentThreadId.trim() + ? raw.parentThreadId.trim() + : channel === 'main_conversation' + ? originId + : undefined; + if (channel === 'main_conversation' && !parentThreadId) { + throw new HttpError(400, 'parent_thread_required'); + } + if (parentThreadId) { + const parentThread = this.deps.store.getThread(parentThreadId); + if (!parentThread) throw new HttpError(404, 'parent_thread_not_found'); + if (this.deps.loopx) { + const binding = this.deps.loopx.binding(parentThreadId); + if (!binding?.goalId) { + if (channel === 'main_conversation' || goalId) { + throw new HttpError(409, 'parent_thread_not_bound_to_goal'); + } + } else { + if (goalId && goalId !== binding.goalId) { + throw new HttpError(409, 'parent_goal_mismatch'); + } + goalId = binding.goalId; + } + } + } + if (!channel && !laneKey && !originId && !goalId && !parentThreadId) return null; + return { + ...(channel ? { channel } : {}), + ...(laneKey ? { laneKey } : {}), + ...(originId ? { originId } : {}), + ...(goalId ? { goalId } : {}), + ...(parentThreadId ? { parentThreadId } : {}), + }; + } + + /** + * Validate and resolve a Main Conversation query scope (`goalId` and/or `parentThreadId`). + * Rejects nonexistent parent threads (404), unbound ordinary threads (409), and mismatched goal/parent pairs (409). + */ + resolveMainScope(scope: { goalId?: string | null; parentThreadId?: string | null }): { + goalId: string | null; + parentThreadId: string | null; + scoped: boolean; + } { + let goalId = scope.goalId?.trim() || null; + const parentThreadId = scope.parentThreadId?.trim() || null; + if (parentThreadId) { + const parentThread = this.deps.store.getThread(parentThreadId); + if (!parentThread) throw new HttpError(404, 'parent_thread_not_found'); + if (this.deps.loopx) { + const binding = this.deps.loopx.binding(parentThreadId); + if (!binding?.goalId) { + throw new HttpError(409, 'parent_thread_not_bound_to_goal'); + } + if (goalId && goalId !== binding.goalId) { + throw new HttpError(409, 'parent_goal_mismatch'); + } + goalId = binding.goalId; + } + } + return { goalId, parentThreadId, scoped: Boolean(goalId || parentThreadId) }; + } + private insertTask(task: StewardTaskRecord): void { + const parentGoalId = task.returnRoute?.goalId?.trim() || null; + const parentThreadId = + task.returnRoute?.parentThreadId?.trim() || + (task.returnRoute?.channel === 'main_conversation' ? task.returnRoute.originId?.trim() || null : null); this.deps.store.db .prepare( `INSERT INTO steward_tasks ( id, plan_id, title, objective, done_when_json, readonly, owner_step, - agent, model, effort, source_cwd, resolved_cwd, lock_dir, + agent, model, effort, permission_mode, source_cwd, resolved_cwd, lock_dir, workspace_policy, workspace_resolved_json, thread_id, status, last_turn_id, has_expected_last_turn_id, expected_last_turn_id, - return_route_json, queue_seq, error_message, + return_route_json, parent_goal_id, parent_thread_id, client_request_id, result_summary, + queue_seq, error_message, created_at, updated_at, started_at, settled_at, promoted_goal_id, promoted_at, supervision_fenced - ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`, + ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`, ) .run( task.id, @@ -604,6 +785,7 @@ export class StewardDispatchService { task.agent, task.model, task.effort, + task.permissionMode ?? null, task.sourceCwd, task.resolvedCwd, task.lockDir, @@ -615,6 +797,10 @@ export class StewardDispatchService { task.expectedLastTurnId !== undefined ? 1 : 0, task.expectedLastTurnId ?? null, task.returnRoute ? JSON.stringify(task.returnRoute) : null, + parentGoalId, + parentThreadId, + task.clientRequestId ?? null, + task.resultSummary ?? null, task.queueSeq, task.errorMessage, task.createdAt, @@ -638,6 +824,8 @@ export class StewardDispatchService { thread_id = ?, status = ?, last_turn_id = ?, + client_request_id = ?, + result_summary = ?, queue_seq = ?, error_message = ?, updated_at = ?, @@ -656,6 +844,8 @@ export class StewardDispatchService { task.threadId, task.status, task.lastTurnId, + task.clientRequestId ?? null, + task.resultSummary ?? null, task.queueSeq, task.errorMessage, task.updatedAt, @@ -1083,8 +1273,15 @@ export class StewardDispatchService { return row ? this.hydrateTask(rowToTask(row)) : null; } - listTasks(opts: { status?: StewardTaskStatus | null; planId?: string | null; limit?: number } = {}): StewardTaskRecord[] { + listTasks(opts: { + status?: StewardTaskStatus | null; + planId?: string | null; + goalId?: string | null; + parentThreadId?: string | null; + limit?: number; + } = {}): StewardTaskRecord[] { const limit = Math.max(1, Math.min(opts.limit ?? 50, 200)); + const scope = this.resolveMainScope({ goalId: opts.goalId, parentThreadId: opts.parentThreadId }); const where: string[] = []; const args: Array = []; if (opts.status) { @@ -1095,6 +1292,16 @@ export class StewardDispatchService { where.push('plan_id = ?'); args.push(opts.planId); } + if (scope.goalId && scope.parentThreadId) { + where.push('(parent_goal_id = ? OR (parent_goal_id IS NULL AND parent_thread_id = ?))'); + args.push(scope.goalId, scope.parentThreadId); + } else if (scope.goalId) { + where.push('parent_goal_id = ?'); + args.push(scope.goalId); + } else if (scope.parentThreadId) { + where.push('parent_thread_id = ?'); + args.push(scope.parentThreadId); + } const clause = where.length > 0 ? `WHERE ${where.join(' AND ')}` : ''; const rows = this.deps.store.db .prepare(`SELECT * FROM steward_tasks ${clause} ORDER BY created_at DESC, rowid DESC LIMIT ?`) @@ -1102,6 +1309,89 @@ export class StewardDispatchService { return rows.map((row) => this.hydrateTask(rowToTask(row))); } + /** + * Return ALL dispatched child thread IDs owned by the given Goal and/or Main Conversation thread. + * Queries SQL without `LIMIT` so ownership filtering never drops older active/waiting child threads. + */ + scopeThreadIds(scopeInput: { goalId?: string | null; parentThreadId?: string | null }): Set { + const scope = this.resolveMainScope(scopeInput); + const out = new Set(); + if (!scope.scoped) return out; + const where: string[] = ['thread_id IS NOT NULL']; + const args: string[] = []; + if (scope.goalId && scope.parentThreadId) { + where.push('(parent_goal_id = ? OR (parent_goal_id IS NULL AND parent_thread_id = ?))'); + args.push(scope.goalId, scope.parentThreadId); + } else if (scope.goalId) { + where.push('parent_goal_id = ?'); + args.push(scope.goalId); + } else if (scope.parentThreadId) { + where.push('parent_thread_id = ?'); + args.push(scope.parentThreadId); + } + const rows = this.deps.store.db + .prepare(`SELECT DISTINCT thread_id FROM steward_tasks WHERE ${where.join(' AND ')}`) + .all(...args) as Array<{ thread_id: string }>; + for (const row of rows) { + if (row.thread_id) out.add(row.thread_id); + } + return out; + } + + /** Return ALL task IDs owned by the given Goal and/or Main Conversation thread (untruncated). */ + scopeTaskIds(scopeInput: { goalId?: string | null; parentThreadId?: string | null }): Set { + const scope = this.resolveMainScope(scopeInput); + const out = new Set(); + if (!scope.scoped) return out; + const where: string[] = []; + const args: string[] = []; + if (scope.goalId && scope.parentThreadId) { + where.push('(parent_goal_id = ? OR (parent_goal_id IS NULL AND parent_thread_id = ?))'); + args.push(scope.goalId, scope.parentThreadId); + } else if (scope.goalId) { + where.push('parent_goal_id = ?'); + args.push(scope.goalId); + } else if (scope.parentThreadId) { + where.push('parent_thread_id = ?'); + args.push(scope.parentThreadId); + } + const rows = this.deps.store.db + .prepare(`SELECT id FROM steward_tasks WHERE ${where.join(' AND ')}`) + .all(...args) as Array<{ id: string }>; + for (const row of rows) { + if (row.id) out.add(row.id); + } + return out; + } + + /** Return all owning Main Conversation parent thread IDs for a dispatched child thread. */ + parentThreadsForChild(childThreadId: string): string[] { + const rows = this.deps.store.db + .prepare( + `SELECT DISTINCT parent_thread_id FROM steward_tasks + WHERE thread_id = ? AND parent_thread_id IS NOT NULL`, + ) + .all(childThreadId) as Array<{ parent_thread_id: string }>; + return rows.map((r) => r.parent_thread_id).filter(Boolean); + } + + private findTaskByClientRequest(parentThreadId: string | null, clientRequestId: string): StewardTaskRecord | null { + const row = this.deps.store.db + .prepare( + `SELECT * FROM steward_tasks + WHERE COALESCE(parent_thread_id, '') = ? AND client_request_id = ? + LIMIT 1`, + ) + .get(parentThreadId ?? '', clientRequestId) as unknown as StewardTaskRow | undefined; + return row ? this.hydrateTask(rowToTask(row)) : null; + } + + private releaseClientRequestKey(taskId: string): void { + this.deps.store.db + .prepare(`UPDATE steward_tasks SET client_request_id = NULL WHERE id = ?`) + .run(taskId); + } + private hydrateTask(task: StewardTaskRecord): StewardTaskRecord { if (task.status !== 'queued_workspace' || !task.lockDir) return task; const occupant = this.occupyingTask(task.lockDir, task.id); @@ -1223,16 +1513,39 @@ export class StewardDispatchService { return { useWorktree: false, lockDir: canonicalPath(sourceCwd), effectivePolicy: policy }; } - private permissionModeFor(agentId: string, readonly: boolean): string | undefined { + private permissionModeFor( + agentId: string, + readonly: boolean, + requested?: StewardTaskPermissionMode | null, + ): string | undefined { const adapter = this.deps.adapters?.get(agentId); - const modes = (adapter?.capabilities.permissionModes ?? []) as readonly string[]; - if (readonly) { + if (!adapter) { + return requested ?? (readonly ? 'read_only' : undefined); + } + const modes = (adapter.capabilities.permissionModes ?? []) as readonly string[]; + const wantsReadOnly = requested === 'read_only' || (!requested && readonly); + const wantsAsk = requested === 'ask'; + + // Fail closed: never downgrade explicit read_only or ask to auto_edit / full_access / undefined. + if (wantsReadOnly) { if (modes.includes('read_only')) return 'read_only'; if (modes.includes('ask')) return 'ask'; - return undefined; + throw new HttpError(400, `unsupported_permission_mode:${agentId}:${requested ?? 'read_only'}`); + } + if (wantsAsk) { + if (modes.includes('ask')) return 'ask'; + throw new HttpError(400, `unsupported_permission_mode:${agentId}:ask`); + } + if (requested) { + if (modes.length > 0) { + if (modes.includes(requested)) return requested; + throw new HttpError(400, `unsupported_permission_mode:${agentId}:${requested}`); + } + if (requested === 'auto_edit') return undefined; + throw new HttpError(400, `unsupported_permission_mode:${agentId}:${requested}`); } if (modes.includes('auto_edit')) return 'auto_edit'; - return adapter?.capabilities.defaultPermissionMode; + return adapter.capabilities.defaultPermissionMode; } private workModeFor(agentId: string, readonly: boolean): 'execute' | 'plan' { @@ -1246,6 +1559,11 @@ export class StewardDispatchService { const userIntervened = err instanceof HttpError && err.status === 409 && err.message === 'user_intervened'; task.status = userIntervened ? 'user_intervened' : 'failed'; task.errorMessage = userIntervened ? 'user_intervened' : (err instanceof Error ? err.message : String(err)); + // Release clientRequestId ONLY when initial launch failed before any child thread was ever created (`threadId === null`). + // Once a thread exists, failed/cancelled tasks keep their idempotency key so retries reuse the original state without restarting. + if (!userIntervened && task.threadId === null && task.clientRequestId) { + task.clientRequestId = null; + } task.settledAt = now; task.updatedAt = now; task.workspaceResolved = { @@ -1284,7 +1602,7 @@ export class StewardDispatchService { cwd: task.sourceCwd, title: task.title, worktree: opts.useWorktree, - permissionMode: this.permissionModeFor(task.agent, task.readonly), + permissionMode: this.permissionModeFor(task.agent, task.readonly, task.permissionMode), workMode: this.workModeFor(task.agent, task.readonly), model: task.model, effort: task.effort, @@ -1333,9 +1651,20 @@ export class StewardDispatchService { this.updateTask(task); return { task, turnId, queuedId }; } catch (err) { + const origClientRequestId = task.clientRequestId ?? null; + const neverStarted = task.threadId === null; task.startedAt = prevStartedAt; this.failTaskLaunch(task, err, opts.suppressAutoDrain === true); - throw err; + if (err instanceof HttpError) { + throw err; + } + throw new HttpError(503, err instanceof Error ? err.message : String(err), { + code: 'task_launch_failed', + retryable: neverStarted, + taskId: task.id, + ...(task.threadId ? { threadId: task.threadId } : {}), + ...(origClientRequestId ? { clientRequestId: origClientRequestId } : {}), + }); } } @@ -1411,6 +1740,7 @@ export class StewardDispatchService { const planId = `plan_${randomUUID().slice(0, 12)}`; const now = new Date().toISOString(); + const returnRoute = this.normalizeReturnRoute(input.returnRoute); // Validate all tasks before mutating anything. const prepared: StewardTaskRecord[] = []; @@ -1420,13 +1750,17 @@ export class StewardDispatchService { const objective = (item.objective ?? '').trim(); if (!title) throw new HttpError(400, 'task_title_required'); if (!objective) throw new HttpError(400, 'task_objective_required'); - const readonly = item.readonly === true; + const readonly = item.readonly === true || item.permissionMode === 'read_only'; const doneWhen = normalizeDoneWhen(item.doneWhen, readonly); const ownerStep = normalizeOwnerStep(item.ownerStep); if (ownerStep) ownerSteps.add(ownerStep); + const permissionMode = normalizeTaskPermissionMode(item.permissionMode, readonly); + const clientRequestId = normalizeClientRequestId(item.clientRequestId); const workspacePolicy = normalizeWorkspacePolicy(item.workspace, readonly); const sourceCwd = this.resolveCwd({ cwd: item.cwd, repo: item.repo }); const agent = await this.resolveAgent(item.agent); + // Validate permission compatibility before persisting any task row. + this.permissionModeFor(agent, readonly, permissionMode); const taskId = `task_${randomUUID().slice(0, 12)}`; if (item.skipProjectMemory === true) { @@ -1443,6 +1777,7 @@ export class StewardDispatchService { agent, model: item.model ?? null, effort: item.effort ?? null, + ...(permissionMode ? { permissionMode } : {}), sourceCwd, resolvedCwd: sourceCwd, lockDir: null, @@ -1457,7 +1792,8 @@ export class StewardDispatchService { threadId: null, status: 'awaiting_approval', lastTurnId: null, - returnRoute: input.returnRoute ?? null, + returnRoute, + ...(clientRequestId ? { clientRequestId } : {}), queueSeq: null, errorMessage: null, createdAt: now, @@ -1554,159 +1890,306 @@ export class StewardDispatchService { * enforces `expectedLastTurnId` optimistic concurrency fence (`409 user_intervened`), and sends message. */ async sessionHandoff(input: StewardSessionHandoffInput): Promise { - if (input.mode === 'spawn') { - const objective = (input.objective ?? input.message ?? '').trim(); - const title = (input.title ?? objective.split('\n')[0]?.slice(0, 60) ?? '').trim(); - const plan = await this.taskPlan({ - tasks: [ - { - title, - objective, - doneWhen: input.doneWhen, - readonly: input.readonly, - cwd: input.cwd, - repo: input.repo, - agent: input.agent, - model: input.model, - effort: input.effort, - workspace: input.workspace, - ownerStep: input.ownerStep, - }, - ], - requireApproval: input.requireApproval, - returnRoute: input.returnRoute, - }); - const task = plan.tasks[0]!; - return { - mode: 'spawn', - task, - threadId: task.threadId, - turnId: task.lastTurnId, - queuedId: null, - imported: false, - }; - } - - if (input.mode !== 'continue') { + if (input.mode !== 'spawn' && input.mode !== 'continue') { throw new HttpError(400, `invalid_handoff_mode:${String(input.mode)}`); } - - const message = (input.message ?? input.objective ?? '').trim(); - if (!message) throw new HttpError(400, 'handoff_message_required'); - const targetKind = input.targetKind; - const targetId = (input.targetId ?? '').trim(); - if (targetKind !== 'workbench_thread' && targetKind !== 'local_session') { - throw new HttpError(400, 'invalid_target_kind'); + const returnRoute = this.normalizeReturnRoute(input.returnRoute); + const parentThreadId = returnRoute?.parentThreadId ?? null; + const clientRequestId = normalizeClientRequestId(input.clientRequestId); + const objective = (input.objective ?? input.message ?? '').trim(); + const title = (input.title ?? objective.split('\n')[0]?.slice(0, 60) ?? '').trim(); + const readonly = input.readonly === true || input.permissionMode === 'read_only'; + if (input.mode === 'spawn') { + if (!objective) throw new HttpError(400, 'task_objective_required'); + if (!title) throw new HttpError(400, 'task_title_required'); } - if (!targetId) throw new HttpError(400, 'missing_target_id'); + const spawnDoneWhen = input.mode === 'spawn' + ? normalizeDoneWhen( + input.doneWhen !== undefined + ? input.doneWhen + : !readonly && returnRoute?.channel === 'main_conversation' ? [title] : undefined, + readonly, + ) + : undefined; + + const run = async (): Promise => { + if (input.mode === 'spawn') { + const resolvedCwd = this.resolveCwd({ cwd: input.cwd, repo: input.repo }); + const resolvedAgent = await this.resolveAgent(input.agent); + const permissionMode = normalizeTaskPermissionMode(input.permissionMode, readonly); + // Validate adapter permission compatibility up front before creating any row or checking retries. + this.permissionModeFor(resolvedAgent, readonly, permissionMode); + + if (clientRequestId) { + const existing = this.findTaskByClientRequest(parentThreadId, clientRequestId); + if (existing) { + if (existing.status === 'failed' && existing.threadId === null) { + this.releaseClientRequestKey(existing.id); + } else { + const existingFp = JSON.stringify({ + mode: 'spawn', + agent: existing.agent, + cwd: canonicalPath(existing.sourceCwd), + objective: existing.objective, + doneWhen: existing.doneWhen, + readonly: existing.readonly, + permissionMode: existing.permissionMode ?? null, + }); + const currentFp = JSON.stringify({ + mode: 'spawn', + agent: resolvedAgent, + cwd: canonicalPath(resolvedCwd), + objective, + doneWhen: spawnDoneWhen, + readonly, + permissionMode: permissionMode ?? null, + }); + if (existingFp !== currentFp) { + throw new HttpError(409, 'client_request_id_conflict', { + code: 'client_request_id_conflict', + existingTaskId: existing.id, + }); + } + return { + mode: 'spawn', + task: existing, + threadId: existing.threadId, + turnId: existing.lastTurnId, + queuedId: null, + imported: false, + reused: true, + }; + } + } + } - const ownerStep = normalizeOwnerStep(input.ownerStep); - const readonly = input.readonly === true; - const doneWhen = input.doneWhen ? normalizeDoneWhen(input.doneWhen, true) : []; + const plan = await this.taskPlan({ + tasks: [ + { + title, + objective, + doneWhen: spawnDoneWhen, + readonly, + cwd: resolvedCwd, + agent: resolvedAgent, + model: input.model, + effort: input.effort, + permissionMode, + workspace: input.workspace, + ownerStep: input.ownerStep, + clientRequestId, + }, + ], + requireApproval: input.requireApproval, + returnRoute, + }); + const task = plan.tasks[0]!; + if (parentThreadId && parentThreadId !== task.threadId) { + this.deps.manager.notifyCoordination(parentThreadId); + } + return { + mode: 'spawn', + task, + threadId: task.threadId, + turnId: task.lastTurnId, + queuedId: null, + imported: false, + }; + } - let thread: ThreadView; - let imported = false; - if (targetKind === 'local_session') { - const agent = (input.agent ?? '').trim(); - if (!agent) throw new HttpError(400, 'agent_required_for_local_session'); - const existing = this.deps.store.findThreadByAgentSession(agent, targetId); - if (existing) { - thread = this.deps.manager.threadView(existing.id); + const message = (input.message ?? input.objective ?? '').trim(); + if (!message) throw new HttpError(400, 'handoff_message_required'); + const targetKind = input.targetKind; + const targetId = (input.targetId ?? '').trim(); + if (targetKind !== 'workbench_thread' && targetKind !== 'local_session') { + throw new HttpError(400, 'invalid_target_kind'); + } + if (!targetId) throw new HttpError(400, 'missing_target_id'); + + const ownerStep = normalizeOwnerStep(input.ownerStep); + const permissionMode = normalizeTaskPermissionMode(input.permissionMode, readonly); + const doneWhen = input.doneWhen ? normalizeDoneWhen(input.doneWhen, true) : []; + + let thread: ThreadView; + let imported = false; + if (targetKind === 'local_session') { + const agent = (input.agent ?? '').trim(); + if (!agent) throw new HttpError(400, 'agent_required_for_local_session'); + const existing = this.deps.store.findThreadByAgentSession(agent, targetId); + if (existing) { + thread = this.deps.manager.threadView(existing.id); + } else { + // Strict: addDirectory is always false so Steward never silently widens workdir allowlist. + thread = await this.deps.manager.importSession({ agent, sessionId: targetId, addDirectory: false }); + imported = true; + } } else { - // Strict: addDirectory is always false so Steward never silently widens workdir allowlist. - thread = await this.deps.manager.importSession({ agent, sessionId: targetId, addDirectory: false }); - imported = true; + const record = this.deps.store.getThread(targetId); + if (!record) throw new HttpError(404, 'thread_not_found'); + thread = this.deps.manager.threadView(targetId); } - } else { - const record = this.deps.store.getThread(targetId); - if (!record) throw new HttpError(404, 'thread_not_found'); - thread = this.deps.manager.threadView(targetId); - } - if (!isWithinWorkdirs(thread.cwd, this.deps.manager.allowedWorkdirs)) { - throw new HttpError(400, `cwd_outside_workdirs:${thread.cwd}`); - } + if (!isWithinWorkdirs(thread.cwd, this.deps.manager.allowedWorkdirs)) { + throw new HttpError(400, `cwd_outside_workdirs:${thread.cwd}`); + } + if (permissionMode) { + this.permissionModeFor(thread.agent, readonly, permissionMode); + } - if ( - input.expectedLastTurnId !== undefined && - input.expectedLastTurnId !== null && - typeof input.expectedLastTurnId !== 'string' - ) { - throw new HttpError(400, 'invalid_expected_last_turn_id'); - } + if ( + input.expectedLastTurnId !== undefined && + input.expectedLastTurnId !== null && + typeof input.expectedLastTurnId !== 'string' + ) { + throw new HttpError(400, 'invalid_expected_last_turn_id'); + } - // Optimistic concurrency fence: fail-closed with 409 user_intervened if newer turn landed. - const actualLastTurnId = this.deps.store.listTurns(thread.id).at(-1)?.turnId ?? null; - if (input.expectedLastTurnId !== undefined && input.expectedLastTurnId !== actualLastTurnId) { - throw new HttpError(409, 'user_intervened'); - } + // Check idempotency BEFORE expectedLastTurnId so retries of an already-succeeded/threaded continue + // return the same child task without restarting or spuriously failing with 409 user_intervened. + if (clientRequestId) { + const existing = this.findTaskByClientRequest(parentThreadId, clientRequestId); + if (existing) { + if (existing.status === 'failed' && existing.threadId === null) { + this.releaseClientRequestKey(existing.id); + } else { + const sameExpected = + existing.expectedLastTurnId === undefined + ? input.expectedLastTurnId === undefined + : existing.expectedLastTurnId === input.expectedLastTurnId; + if (existing.threadId !== thread.id || existing.objective !== message || !sameExpected) { + throw new HttpError(409, 'client_request_id_conflict', { + code: 'client_request_id_conflict', + existingTaskId: existing.id, + }); + } + return { + mode: 'continue', + task: existing, + threadId: existing.threadId, + turnId: existing.lastTurnId, + queuedId: null, + imported: false, + reused: true, + }; + } + } + } - const now = new Date().toISOString(); - const hasWorktree = Boolean(thread.worktree); - const workspacePolicy: StewardWorkspacePolicy = readonly ? 'none' : hasWorktree ? 'new' : 'existing_queue'; - const task: StewardTaskRecord = { - id: `task_${randomUUID().slice(0, 12)}`, - planId: null, - title: (input.title ?? thread.title).trim() || thread.title, - objective: message, - doneWhen, - readonly, - ownerStep, - agent: thread.agent, - model: thread.model, - effort: thread.effort, - sourceCwd: thread.cwd, - resolvedCwd: thread.cwd, - lockDir: !readonly && !hasWorktree ? canonicalPath(thread.cwd) : null, - workspacePolicy, - workspaceResolved: { - path: thread.cwd, - worktree: thread.worktree ?? null, - queued: false, - queuedBehindTaskId: null, - queuePosition: null, - }, - threadId: thread.id, - status: 'awaiting_approval', - lastTurnId: actualLastTurnId, - ...(input.expectedLastTurnId !== undefined ? { expectedLastTurnId: input.expectedLastTurnId } : {}), - returnRoute: input.returnRoute ?? null, - queueSeq: null, - errorMessage: null, - createdAt: now, - updatedAt: now, - startedAt: null, - settledAt: null, - promotedGoalId: null, - promotedAt: null, - supervisionFenced: false, - }; - this.insertTask(task); + // Optimistic concurrency fence: fail-closed with 409 user_intervened if newer turn landed. + const actualLastTurnId = this.deps.store.listTurns(thread.id).at(-1)?.turnId ?? null; + if (input.expectedLastTurnId !== undefined && input.expectedLastTurnId !== actualLastTurnId) { + throw new HttpError(409, 'user_intervened'); + } - if (ownerStep || input.requireApproval === true) { + const now = new Date().toISOString(); + const hasWorktree = Boolean(thread.worktree); + const workspacePolicy: StewardWorkspacePolicy = readonly ? 'none' : hasWorktree ? 'new' : 'existing_queue'; + const task: StewardTaskRecord = { + id: `task_${randomUUID().slice(0, 12)}`, + planId: null, + title: (input.title ?? thread.title).trim() || thread.title, + objective: message, + doneWhen, + readonly, + ownerStep, + agent: thread.agent, + model: thread.model, + effort: thread.effort, + ...(permissionMode ? { permissionMode } : {}), + sourceCwd: thread.cwd, + resolvedCwd: thread.cwd, + lockDir: !readonly && !hasWorktree ? canonicalPath(thread.cwd) : null, + workspacePolicy, + workspaceResolved: { + path: thread.cwd, + worktree: thread.worktree ?? null, + queued: false, + queuedBehindTaskId: null, + queuePosition: null, + }, + threadId: thread.id, + status: 'awaiting_approval', + lastTurnId: actualLastTurnId, + ...(input.expectedLastTurnId !== undefined ? { expectedLastTurnId: input.expectedLastTurnId } : {}), + returnRoute, + ...(clientRequestId ? { clientRequestId } : {}), + queueSeq: null, + errorMessage: null, + createdAt: now, + updatedAt: now, + startedAt: null, + settledAt: null, + promotedGoalId: null, + promotedAt: null, + supervisionFenced: false, + }; + this.insertTask(task); + + if (ownerStep || input.requireApproval === true) { + return { + mode: 'continue', + task, + threadId: thread.id, + turnId: null, + queuedId: null, + imported, + }; + } + + const dispatched = await this.dispatchPersistedTask(task, { + existingThreadId: thread.id, + promptOverride: message, + queueIfThreadBusy: input.queue === true, + }); + if (parentThreadId && parentThreadId !== thread.id) { + this.deps.manager.notifyCoordination(parentThreadId); + } return { mode: 'continue', - task, + task: dispatched.task, threadId: thread.id, - turnId: null, - queuedId: null, + turnId: dispatched.turnId, + queuedId: dispatched.queuedId, imported, }; + }; + + // Deduplicate concurrent identical clientRequestId calls synchronously BEFORE any await. + if (clientRequestId) { + const key = `${parentThreadId ?? ''}::${clientRequestId}`; + const rawFingerprint = JSON.stringify({ + mode: input.mode, + agent: (input.agent ?? '').trim(), + cwd: (input.cwd ?? '').trim(), + repo: (input.repo ?? '').trim(), + objective: (input.objective ?? input.message ?? '').trim(), + ...(input.mode === 'spawn' ? { doneWhen: spawnDoneWhen } : {}), + readonly: input.readonly === true || input.permissionMode === 'read_only', + permissionMode: input.permissionMode ?? null, + targetKind: input.targetKind ?? null, + targetId: (input.targetId ?? '').trim(), + expectedLastTurnId: input.expectedLastTurnId === undefined ? '__omitted__' : input.expectedLastTurnId, + }); + const inflight = this.inflightClientRequests.get(key); + if (inflight) { + if (inflight.fingerprint !== rawFingerprint) { + throw new HttpError(409, 'client_request_id_conflict'); + } + const prior = await inflight.promise; + return { ...prior, reused: true }; + } + const promise = run(); + this.inflightClientRequests.set(key, { fingerprint: rawFingerprint, promise }); + try { + return await promise; + } finally { + if (this.inflightClientRequests.get(key)?.promise === promise) { + this.inflightClientRequests.delete(key); + } + } } - const dispatched = await this.dispatchPersistedTask(task, { - existingThreadId: thread.id, - promptOverride: message, - queueIfThreadBusy: input.queue === true, - }); - return { - mode: 'continue', - task: dispatched.task, - threadId: thread.id, - turnId: dispatched.turnId, - queuedId: dispatched.queuedId, - imported, - }; + return run(); } /** Send a direct follow-up message to an existing Workbench thread with optional concurrency fence. */ @@ -1797,6 +2280,20 @@ export class StewardDispatchService { private onThreadEvent(ev: StoredEvent): void { if (this.disposed) return; + if ( + ev.type === 'approval.request' || + ev.type === 'approval.resolved' || + ev.type === 'input.request' || + ev.type === 'input.resolved' || + ev.type === 'turn.started' + ) { + for (const parentId of this.parentThreadsForChild(ev.threadId)) { + if (parentId !== ev.threadId) { + this.deps.manager.notifyCoordination(parentId); + } + } + return; + } if (ev.type !== 'turn.done' && ev.type !== 'turn.error') return; const rows = this.deps.store.db .prepare(`SELECT * FROM steward_tasks WHERE thread_id = ? AND status = 'running'`) @@ -1807,7 +2304,11 @@ export class StewardDispatchService { const isError = ev.type === 'turn.error'; const stopReason = typeof ev.data?.stopReason === 'string' ? ev.data.stopReason : null; const errMsg = isError && typeof ev.data?.message === 'string' ? ev.data.message : null; + const answerSummary = isError + ? clipResultSummary(errMsg) + : clipResultSummary(turnAnswer(this.deps.store.listEvents(ev.threadId), ev.turnId, 400)); const lockDirs = new Set(); + const notifyParents = new Set(); for (const row of rows) { // Only settle and release directory occupancy on the SAME Turn's terminal event. @@ -1832,10 +2333,26 @@ export class StewardDispatchService { this.deps.store.db .prepare( `UPDATE steward_tasks SET status = ?, last_turn_id = COALESCE(?, last_turn_id), + result_summary = COALESCE(?, result_summary), error_message = ?, settled_at = ?, updated_at = ? WHERE id = ?`, ) - .run(nextStatus, ev.turnId ?? null, nextStatus === 'cancelled' ? null : errMsg, now, now, row.id); + .run( + nextStatus, + ev.turnId ?? null, + nextStatus === 'cancelled' ? null : answerSummary, + nextStatus === 'cancelled' ? null : errMsg, + now, + now, + row.id, + ); if (row.lock_dir) lockDirs.add(row.lock_dir); + if (row.parent_thread_id && row.parent_thread_id !== ev.threadId) { + notifyParents.add(row.parent_thread_id); + } + } + + for (const parentId of notifyParents) { + this.deps.manager.notifyCoordination(parentId); } for (const lockDir of lockDirs) { diff --git a/apps/workbench/packages/daemon/src/steward-inbox.ts b/apps/workbench/packages/daemon/src/steward-inbox.ts index f590d5998d..441a9982e4 100644 --- a/apps/workbench/packages/daemon/src/steward-inbox.ts +++ b/apps/workbench/packages/daemon/src/steward-inbox.ts @@ -1,6 +1,7 @@ import { randomUUID } from 'node:crypto'; import type { UserQuestion } from './adapters/types.js'; import { coreJson } from './adapters/loopx/core.js'; +import type { LoopxService } from './adapters/loopx/service.js'; import { HttpError } from './errors.js'; import type { Store } from './store.js'; import type { StewardDispatchService, StewardOwnerStep, StewardTaskRecord } from './steward-dispatch.js'; @@ -441,6 +442,7 @@ export interface StewardInboxDeps { manager: ThreadManager; dispatch: StewardDispatchService; supervision?: StewardSupervisionService; + loopx?: LoopxService; coreUrl?: URL | null; } @@ -448,6 +450,8 @@ export interface StewardSurfaceOptions { nowMs?: number; coreUrl?: URL | null; timeoutMs?: number; + goalId?: string | null; + parentThreadId?: string | null; } /** @@ -658,7 +662,12 @@ export class StewardInboxService { return row ? rowToConcern(row) : null; } - listConcerns(opts: { status?: StewardConcernStatus | null; unacknowledgedOnly?: boolean; limit?: number } = {}): StewardConcernRecord[] { + listConcerns(opts: { + status?: StewardConcernStatus | null; + unacknowledgedOnly?: boolean; + threadIds?: ReadonlySet | null; + limit?: number; + } = {}): StewardConcernRecord[] { const limit = Math.max(1, Math.min(opts.limit ?? 50, 200)); const where: string[] = []; const args: Array = []; @@ -669,6 +678,12 @@ export class StewardInboxService { if (opts.unacknowledgedOnly) { where.push('acknowledged_at IS NULL'); } + if (opts.threadIds) { + const ids = [...opts.threadIds]; + if (ids.length === 0) return []; + where.push(`target_thread_id IN (${ids.map(() => '?').join(', ')})`); + args.push(...ids); + } const clause = where.length > 0 ? `WHERE ${where.join(' AND ')}` : ''; const rows = this.deps.store.db .prepare(`SELECT * FROM steward_concerns ${clause} ORDER BY updated_at DESC, rowid DESC LIMIT ?`) @@ -793,35 +808,66 @@ export class StewardInboxService { return row ? rowToFollowup(row) : null; } - listFollowups(opts: { status?: StewardFollowupStatus | null; limit?: number; nowMs?: number } = {}): StewardFollowupRecord[] { + listFollowups(opts: { + status?: StewardFollowupStatus | null; + threadIds?: ReadonlySet | null; + limit?: number; + nowMs?: number; + } = {}): StewardFollowupRecord[] { this.promoteDueFollowups(opts.nowMs); const limit = Math.max(1, Math.min(opts.limit ?? 50, 200)); - const rows = opts.status - ? (this.deps.store.db - .prepare(`SELECT * FROM steward_followups WHERE status = ? ORDER BY due_at ASC, rowid ASC LIMIT ?`) - .all(opts.status, limit) as unknown as FollowupRow[]) - : (this.deps.store.db - .prepare(`SELECT * FROM steward_followups WHERE status != 'cancelled' ORDER BY due_at ASC, rowid ASC LIMIT ?`) - .all(limit) as unknown as FollowupRow[]); + const where: string[] = []; + const args: Array = []; + if (opts.status) { + where.push('status = ?'); + args.push(opts.status); + } else { + where.push(`status != 'cancelled'`); + } + if (opts.threadIds) { + const ids = [...opts.threadIds]; + if (ids.length === 0) return []; + where.push(`thread_id IN (${ids.map(() => '?').join(', ')})`); + args.push(...ids); + } + const rows = this.deps.store.db + .prepare(`SELECT * FROM steward_followups WHERE ${where.join(' AND ')} ORDER BY due_at ASC, rowid ASC LIMIT ?`) + .all(...args, limit) as unknown as FollowupRow[]; return rows.map(rowToFollowup); } - private listActiveFollowups(limit = 100): StewardFollowupRecord[] { + private listActiveFollowups(limit = 100, threadIds?: ReadonlySet | null): StewardFollowupRecord[] { + const where = [`status IN ('due', 'scheduled')`]; + const args: Array = []; + if (threadIds) { + const ids = [...threadIds]; + if (ids.length === 0) return []; + where.push(`thread_id IN (${ids.map(() => '?').join(', ')})`); + args.push(...ids); + } const rows = this.deps.store.db .prepare( `SELECT * FROM steward_followups - WHERE status IN ('due', 'scheduled') + WHERE ${where.join(' AND ')} ORDER BY CASE status WHEN 'due' THEN 0 ELSE 1 END, due_at ASC, rowid ASC LIMIT ?`, ) - .all(limit) as unknown as FollowupRow[]; + .all(...args, limit) as unknown as FollowupRow[]; return rows.map(rowToFollowup); } - private countDueFollowups(): number { + private countDueFollowups(threadIds?: ReadonlySet | null): number { + const where = [`status = 'due'`]; + const args: string[] = []; + if (threadIds) { + const ids = [...threadIds]; + if (ids.length === 0) return 0; + where.push(`thread_id IN (${ids.map(() => '?').join(', ')})`); + args.push(...ids); + } const row = this.deps.store.db - .prepare(`SELECT COUNT(*) AS cnt FROM steward_followups WHERE status = 'due'`) - .get() as { cnt: number } | undefined; + .prepare(`SELECT COUNT(*) AS cnt FROM steward_followups WHERE ${where.join(' AND ')}`) + .get(...args) as { cnt: number } | undefined; return Number(row?.cnt ?? 0); } @@ -885,15 +931,46 @@ export class StewardInboxService { const nowMs = opts.nowMs ?? Date.now(); const effectiveCoreUrl = opts.coreUrl !== undefined ? opts.coreUrl : (this.deps.coreUrl ?? null); const timeoutMs = opts.timeoutMs ?? DEFAULT_CORE_ACTIONS_TIMEOUT_MS; + const scope = this.deps.dispatch.resolveMainScope({ + goalId: opts.goalId, + parentThreadId: opts.parentThreadId, + }); + const scopedGoalId = scope.goalId; + const scopedParentThreadId = scope.parentThreadId; + const scoped = scope.scoped; this.promoteDueFollowups(nowMs); const nowIso = new Date(nowMs).toISOString(); const inlineCards: StewardInlineCard[] = []; const coreResult = await this.fetchCoreActionCards(effectiveCoreUrl, timeoutMs); - inlineCards.push(...coreResult.cards); - - const allTasks = this.deps.dispatch.listTasks({ limit: 200 }); + const coreCards = scoped + ? coreResult.cards.filter((card) => scopedGoalId !== null && card.goalId === scopedGoalId) + : coreResult.cards; + const coreHealth: StewardSurfaceSourceHealth = + coreResult.health.status === 'ok' + ? { status: 'ok', itemCount: coreCards.length } + : coreResult.health; + inlineCards.push(...coreCards); + + const allTasks = scoped + ? this.deps.dispatch.listTasks({ goalId: scopedGoalId, parentThreadId: scopedParentThreadId, limit: 200 }) + : this.deps.dispatch.listTasks({ limit: 200 }); + // Compute ownership sets from untruncated SQL + LoopX bindings (includes bound Goal thread(s) themselves + all owned child threads). + const scopedTaskIds = scoped + ? this.deps.dispatch.scopeTaskIds({ goalId: scopedGoalId, parentThreadId: scopedParentThreadId }) + : new Set(allTasks.map((t) => t.id)); + const scopedThreadIds = scoped + ? this.deps.dispatch.scopeThreadIds({ goalId: scopedGoalId, parentThreadId: scopedParentThreadId }) + : new Set(); + if (scoped) { + if (scopedParentThreadId) scopedThreadIds.add(scopedParentThreadId); + if (scopedGoalId && this.deps.loopx) { + for (const boundThreadId of this.deps.loopx.bindings.threadsOf(scopedGoalId)) { + scopedThreadIds.add(boundThreadId); + } + } + } const pendingPlans = new Map(); const taskByThread = new Map(); for (const task of allTasks) { @@ -930,8 +1007,9 @@ export class StewardInboxService { }); } - // 2. Live thread permission approvals across all Workbench threads + // 2. Live thread permission approvals across Workbench threads (scoped when goalId/parentThreadId is set) for (const approval of this.deps.manager.listPendingApprovals()) { + if (scoped && !scopedThreadIds.has(approval.threadId)) continue; const thread = this.deps.store.getThread(approval.threadId); inlineCards.push({ id: `approval:${approval.approvalId}`, @@ -946,6 +1024,7 @@ export class StewardInboxService { // 3. Live thread user questions / plan prompts for (const pending of this.deps.manager.inputs.listPending()) { + if (scoped && !scopedThreadIds.has(pending.threadId)) continue; const thread = this.deps.store.getThread(pending.threadId); inlineCards.push({ id: `input:${pending.inputId}`, @@ -960,9 +1039,15 @@ export class StewardInboxService { }); } - // 4. Unacknowledged reported concerns (filtered in SQL before LIMIT so history cannot crowd out receipts) - const openConcerns = this.listConcerns({ status: 'open', limit: 100 }); - const reportedConcerns = this.listConcerns({ status: 'reported', unacknowledgedOnly: true, limit: 50 }); + // 4. Unacknowledged reported concerns (filtered by ownership in SQL BEFORE LIMIT so other matters cannot crowd out receipts) + const threadFilter = scoped ? scopedThreadIds : null; + const openConcerns = this.listConcerns({ status: 'open', threadIds: threadFilter, limit: 100 }); + const reportedConcerns = this.listConcerns({ + status: 'reported', + unacknowledgedOnly: true, + threadIds: threadFilter, + limit: 50, + }); for (const concern of reportedConcerns) { inlineCards.push({ id: `concern:${concern.id}`, @@ -976,10 +1061,10 @@ export class StewardInboxService { }); } - // 5. Due follow-ups (filtered by status = 'due' in SQL before LIMIT so fired history cannot hide due cards) - const dueFollowups = this.listFollowups({ status: 'due', limit: 100, nowMs }); - const dueFollowupsCount = this.countDueFollowups(); - const followups = this.listActiveFollowups(100); + // 5. Due follow-ups (filtered by ownership and status='due' in SQL BEFORE LIMIT) + const dueFollowups = this.listFollowups({ status: 'due', threadIds: threadFilter, limit: 100, nowMs }); + const dueFollowupsCount = this.countDueFollowups(threadFilter); + const followups = this.listActiveFollowups(100, threadFilter); for (const fu of dueFollowups) { inlineCards.push({ id: `followup:${fu.id}`, @@ -998,6 +1083,7 @@ export class StewardInboxService { const scheduledRetryByThread = new Map(); if (this.deps.supervision) { for (const q of this.deps.supervision.getPendingFreeTextQuestions()) { + if (scoped && !scopedThreadIds.has(q.threadId)) continue; supervisionThreadsInNeedsYou.add(q.threadId); inlineCards.push({ id: q.id, @@ -1012,6 +1098,7 @@ export class StewardInboxService { }); } for (const alert of this.deps.supervision.getActiveAlerts()) { + if (scoped && !scopedThreadIds.has(alert.threadId)) continue; supervisionThreadsInNeedsYou.add(alert.threadId); inlineCards.push({ id: alert.id, @@ -1027,6 +1114,7 @@ export class StewardInboxService { }); } for (const esc of this.deps.supervision.getEscalatedReviews()) { + if (scoped && !scopedTaskIds.has(esc.taskId) && !(esc.threadId && scopedThreadIds.has(esc.threadId))) continue; escalatedTaskIds.add(esc.taskId); if (esc.threadId) supervisionThreadsInNeedsYou.add(esc.threadId); inlineCards.push({ @@ -1044,6 +1132,7 @@ export class StewardInboxService { }); } for (const retry of this.deps.supervision.status().scheduledRetries) { + if (scoped && !scopedThreadIds.has(retry.threadId)) continue; scheduledRetryByThread.set(retry.threadId, { retryCount: retry.retryCount, nextRetryAt: retry.nextRetryAt, @@ -1117,6 +1206,7 @@ export class StewardInboxService { } for (const thread of this.deps.manager.listThreads({ archived: false })) { + if (scoped && !scopedThreadIds.has(thread.id)) continue; if (seenThreads.has(thread.id)) continue; if (thread.waiting || supervisionThreadsInNeedsYou.has(thread.id)) continue; // Already surfaced in inlineCards const linked = taskByThread.get(thread.id) ?? null; @@ -1170,14 +1260,14 @@ export class StewardInboxService { supervisionEnabled: this.deps.supervision?.isEnabled() ?? false, counts: { needsYou: inlineCards.length, - coreActions: coreResult.cards.length, + coreActions: coreCards.length, inProgress: inProgress.length, stewardReviewing: stewardReviewing.length, openConcerns: openConcerns.length, dueFollowups: dueFollowupsCount, }, sources: { - coreActions: coreResult.health, + coreActions: coreHealth, }, inlineCards, inProgress, diff --git a/apps/workbench/packages/daemon/src/steward-ledger.ts b/apps/workbench/packages/daemon/src/steward-ledger.ts index 3fcbfbe5b5..91c4ee1b3d 100644 --- a/apps/workbench/packages/daemon/src/steward-ledger.ts +++ b/apps/workbench/packages/daemon/src/steward-ledger.ts @@ -1,18 +1,22 @@ import { createHash, randomBytes, timingSafeEqual } from 'node:crypto'; import { chmodSync, existsSync, mkdirSync, renameSync, rmSync, writeFileSync } from 'node:fs'; import { createServer, type Server } from 'node:http'; -import { basename, join } from 'node:path'; +import { basename, dirname, join, resolve } from 'node:path'; +import { fileURLToPath } from 'node:url'; import type { AgentAdapter } from './adapters/types.js'; import { coreJson } from './adapters/loopx/core.js'; -import type { LoopxPermission } from './adapters/loopx/binding.js'; +import type { LoopxBinding, LoopxPermission } from './adapters/loopx/binding.js'; import type { LoopxService } from './adapters/loopx/service.js'; import { HttpError } from './errors.js'; import { GramExclusionIndex, sha256Text } from './gram-exclusion-index.js'; import type { ExternalSession, LocalSessions } from './local-sessions.js'; import type { Store } from './store.js'; +import { isWithinWorkdirs } from './workdirs.js'; import { StewardDispatchService, type StewardOwnerStep, + type StewardReturnRoute, + type StewardTaskPermissionMode, type StewardTaskRecord, type StewardTaskStatus, type StewardWorkspacePolicy, @@ -446,6 +450,7 @@ export class StewardLedgerService { manager: deps.manager, dispatch: this.dispatch, supervision: this.supervision, + loopx: deps.loopx, coreUrl: this.defaultCoreUrl, }); const stewardDir = join(deps.dataDir, 'steward'); @@ -481,6 +486,67 @@ export class StewardLedgerService { } } + private readonly mainTokens = new Map(); + + /** Read the current LoopX Goal binding for a thread, if any. */ + loopxBinding(threadId: string): LoopxBinding | null { + return this.deps.loopx?.binding(threadId) ?? null; + } + + /** Look up a Workbench thread's working directory/worktree origin for workspace ceiling verification. */ + threadWorkspace(threadId: string): string | null { + const th = this.deps.store.getThread(threadId); + if (!th) return null; + return th.worktree?.of ?? th.cwd; + } + + /** + * Scoped socket credentials injected ONLY into LoopX Goal-bound Main Conversation threads. + * Ordinary threads and dispatched child worker threads receive `undefined` and cannot dispatch. + */ + mainConversationEnvironment(threadId: string): Record | undefined { + const binding = this.deps.loopx?.binding(threadId); + if (!binding?.goalId) return undefined; + let entry = this.mainTokens.get(threadId); + if (!entry || entry.goalId !== binding.goalId) { + entry = { + token: randomBytes(32).toString('hex'), + threadId, + goalId: binding.goalId, + }; + this.mainTokens.set(threadId, entry); + } + return { + LOOCHAT_MAIN_SOCKET: this.socketPath, + LOOCHAT_MAIN_TOKEN: entry.token, + LOOCHAT_BIN_DIR: resolve(dirname(fileURLToPath(import.meta.url)), '../bin'), + }; + } + + /** Verify caller credentials on the Steward Unix socket: full supervisor OR Goal-scoped Main Conversation. */ + verifyCaller( + bearerHeader: string | undefined, + ): { role: 'supervisor' } | { role: 'main_conversation'; threadId: string; goalId: string } { + const raw = (bearerHeader ?? '').replace(/^Bearer\s+/i, '').trim(); + const received = Buffer.from(raw, 'utf8'); + const expectedSup = Buffer.from(this.supervisorToken, 'utf8'); + if (expectedSup.length === received.length && timingSafeEqual(expectedSup, received)) { + return { role: 'supervisor' }; + } + for (const entry of this.mainTokens.values()) { + const expectedMain = Buffer.from(entry.token, 'utf8'); + if (expectedMain.length === received.length && timingSafeEqual(expectedMain, received)) { + const currentBinding = this.deps.loopx?.binding(entry.threadId); + if (currentBinding?.goalId === entry.goalId) { + return { role: 'main_conversation', threadId: entry.threadId, goalId: entry.goalId }; + } + this.mainTokens.delete(entry.threadId); + throw new HttpError(403, 'unauthorized_caller_role'); + } + } + throw new HttpError(403, 'unauthorized_caller_role'); + } + dispose(): void { this.supervision.dispose(); this.inbox.dispose(); @@ -1561,9 +1627,16 @@ export class StewardLedgerService { * Enforces caller-credential ACL (`403 unauthorized_caller_role` to workers). */ export function stewardServer(service: StewardLedgerService): Server { + const MAIN_ALLOWED_METHODS = new Set([ + 'steward_session_handoff', + 'steward_task_list', + 'steward_surface', + 'steward_agent_send', + 'steward_agent_interrupt', + ]); return createServer(async (req, res) => { try { - service.verifySupervisorToken(req.headers.authorization); + const caller = service.verifyCaller(req.headers.authorization); if (req.method !== 'POST' || req.url !== '/rpc') { throw new HttpError(404, 'not_found'); } @@ -1587,6 +1660,16 @@ export function stewardServer(service: StewardLedgerService): Server { const method = String(payload.method ?? ''); const params = (payload.params && typeof payload.params === 'object' ? payload.params : {}) as Record; + let mainBinding: LoopxBinding | null = null; + if (caller.role === 'main_conversation') { + if (!MAIN_ALLOWED_METHODS.has(method)) { + throw new HttpError(403, 'unauthorized_caller_role'); + } + mainBinding = service.loopxBinding(caller.threadId); + if (!mainBinding || mainBinding.goalId !== caller.goalId) { + throw new HttpError(403, 'unauthorized_caller_role'); + } + } let result: unknown; if (method === 'steward_ledger_read') { @@ -1651,43 +1734,149 @@ export function stewardServer(service: StewardLedgerService): Server { const rawTargetKind = params.targetKind ?? params.target_kind ?? target?.kind; const rawTargetId = params.targetId ?? params.target_id ?? (rawTargetKind === 'local_session' ? target?.sessionId : target?.threadId); const rawExpected = params.expectedLastTurnId !== undefined ? params.expectedLastTurnId : params.expected_last_turn_id; + const rawPermissionMode = params.permissionMode ?? params.permission_mode; + const rawClientRequestId = params.clientRequestId ?? params.client_request_id; + let effectiveReturnRoute = (params.returnRoute ?? params.return_route) as StewardReturnRoute | null | undefined; + let effectiveCwd = typeof params.cwd === 'string' ? params.cwd : typeof params.workdir === 'string' ? params.workdir : undefined; + let effectiveRepo = typeof params.repo === 'string' ? params.repo : undefined; + let effectiveReadonly = params.readonly === true; + let effectivePermissionMode = + typeof rawPermissionMode === 'string' ? (rawPermissionMode as StewardTaskPermissionMode) : undefined; + let effectiveWorkspace = params.workspace as StewardWorkspacePolicy | undefined; + + if (caller.role === 'main_conversation') { + const binding = mainBinding!; + const goalWorkspace = binding.workspace; + // Server-side binding is sole authority for parent, Goal, workspace boundary, and permission ceiling. + effectiveReturnRoute = { + channel: 'main_conversation', + goalId: binding.goalId, + parentThreadId: caller.threadId, + originId: caller.threadId, + }; + if (effectiveRepo && effectiveRepo.trim()) { + throw new HttpError(403, 'cwd_outside_goal_workspace'); + } + effectiveRepo = undefined; + + if (binding.permission === 'read_only') { + if ( + params.readonly === false || + effectivePermissionMode === 'auto_edit' || + effectivePermissionMode === 'full_access' || + (effectiveWorkspace !== undefined && effectiveWorkspace !== 'none') + ) { + throw new HttpError(403, 'permission_escalation_denied'); + } + effectiveReadonly = true; + effectivePermissionMode = effectivePermissionMode === 'ask' ? 'ask' : 'read_only'; + effectiveWorkspace = 'none'; + } else if (binding.permission === 'workspace_auto') { + if (effectivePermissionMode === 'full_access') { + throw new HttpError(403, 'permission_escalation_denied'); + } + } + + if (params.mode === 'continue') { + const scoped = service.dispatch.scopeThreadIds({ goalId: binding.goalId, parentThreadId: caller.threadId }); + if (rawTargetKind !== 'workbench_thread' || typeof rawTargetId !== 'string' || !scoped.has(rawTargetId)) { + throw new HttpError(403, 'unauthorized_target_thread'); + } + const targetWs = service.threadWorkspace(rawTargetId); + if (!targetWs || !isWithinWorkdirs(targetWs, [goalWorkspace])) { + throw new HttpError(403, 'cwd_outside_goal_workspace'); + } + if (binding.permission === 'read_only') { + const latest = service.dispatch.latestTaskForThread(rawTargetId); + if (latest && !latest.readonly) { + throw new HttpError(403, 'permission_escalation_denied'); + } + } + } else { + const candidate = effectiveCwd && effectiveCwd.trim() + ? resolve(goalWorkspace, effectiveCwd.trim()) + : goalWorkspace; + if (!isWithinWorkdirs(candidate, [goalWorkspace])) { + throw new HttpError(403, 'cwd_outside_goal_workspace'); + } + effectiveCwd = candidate; + } + } + result = await service.dispatch.sessionHandoff({ mode: params.mode as 'spawn' | 'continue', title: typeof params.title === 'string' ? params.title : undefined, objective: typeof params.objective === 'string' ? params.objective : undefined, message: typeof params.message === 'string' ? params.message : typeof params.brief === 'string' ? params.brief : undefined, doneWhen: (params.doneWhen ?? params.done_when) as string[] | undefined, - readonly: params.readonly === true, - cwd: typeof params.cwd === 'string' ? params.cwd : typeof params.workdir === 'string' ? params.workdir : undefined, - repo: typeof params.repo === 'string' ? params.repo : undefined, + readonly: effectiveReadonly, + cwd: effectiveCwd, + repo: effectiveRepo, agent: typeof (params.agent ?? target?.agent) === 'string' ? String(params.agent ?? target?.agent) : undefined, model: typeof params.model === 'string' ? params.model : null, effort: typeof params.effort === 'string' ? params.effort : null, - workspace: params.workspace as StewardWorkspacePolicy | undefined, + permissionMode: effectivePermissionMode, + workspace: effectiveWorkspace, ownerStep: (params.ownerStep ?? params.owner_step) as StewardOwnerStep | null | undefined, requireApproval: (params.requireApproval ?? params.require_approval) === true, targetKind: rawTargetKind === 'workbench_thread' || rawTargetKind === 'local_session' ? rawTargetKind : undefined, targetId: typeof rawTargetId === 'string' ? rawTargetId : undefined, expectedLastTurnId: rawExpected === undefined ? undefined : rawExpected === null ? null : String(rawExpected), queue: params.queue === true, - returnRoute: (params.returnRoute ?? params.return_route) as { channel?: string; laneKey?: string; originId?: string } | null | undefined, + returnRoute: effectiveReturnRoute, + clientRequestId: typeof rawClientRequestId === 'string' ? rawClientRequestId : undefined, }); } else if (method === 'steward_agent_send') { + const targetThreadId = String(params.threadId ?? params.thread_id ?? ''); + if (caller.role === 'main_conversation') { + const binding = mainBinding!; + const scoped = service.dispatch.scopeThreadIds({ goalId: binding.goalId, parentThreadId: caller.threadId }); + if (!scoped.has(targetThreadId) || targetThreadId === caller.threadId) { + throw new HttpError(403, 'unauthorized_target_thread'); + } + const targetWs = service.threadWorkspace(targetThreadId); + if (!targetWs || !isWithinWorkdirs(targetWs, [binding.workspace])) { + throw new HttpError(403, 'cwd_outside_goal_workspace'); + } + if (binding.permission === 'read_only') { + const latest = service.dispatch.latestTaskForThread(targetThreadId); + if (latest && !latest.readonly) { + throw new HttpError(403, 'permission_escalation_denied'); + } + } + } const rawExpected = params.expectedLastTurnId !== undefined ? params.expectedLastTurnId : params.expected_last_turn_id; result = await service.dispatch.agentSend({ - threadId: String(params.threadId ?? params.thread_id ?? ''), + threadId: targetThreadId, message: String(params.message ?? params.text ?? ''), expectedLastTurnId: rawExpected === undefined ? undefined : rawExpected === null ? null : String(rawExpected), queue: params.queue === true, }); } else if (method === 'steward_agent_interrupt') { - result = await service.dispatch.agentInterrupt(String(params.threadId ?? params.thread_id ?? '')); + const targetThreadId = String(params.threadId ?? params.thread_id ?? ''); + if (caller.role === 'main_conversation') { + const binding = mainBinding!; + const scoped = service.dispatch.scopeThreadIds({ goalId: binding.goalId, parentThreadId: caller.threadId }); + if (!scoped.has(targetThreadId) || targetThreadId === caller.threadId) { + throw new HttpError(403, 'unauthorized_target_thread'); + } + } + result = await service.dispatch.agentInterrupt(targetThreadId); } else if (method === 'steward_task_list') { const rawStatus = params.status; result = { tasks: service.dispatch.listTasks({ status: typeof rawStatus === 'string' && rawStatus ? (rawStatus as StewardTaskStatus) : null, planId: typeof (params.planId ?? params.plan_id) === 'string' ? String(params.planId ?? params.plan_id) : null, + ...(caller.role === 'main_conversation' + ? { goalId: mainBinding!.goalId, parentThreadId: caller.threadId } + : { + goalId: typeof (params.goalId ?? params.goal_id) === 'string' ? String(params.goalId ?? params.goal_id) : null, + parentThreadId: + typeof (params.parentThreadId ?? params.parent_thread_id) === 'string' + ? String(params.parentThreadId ?? params.parent_thread_id) + : null, + }), limit: typeof params.limit === 'number' ? params.limit : undefined, }), }; @@ -1744,7 +1933,17 @@ export function stewardServer(service: StewardLedgerService): Server { } else if (method === 'steward_followup_cancel') { result = service.inbox.cancelFollowup(String(params.id ?? params.followupId ?? params.followup_id ?? '')); } else if (method === 'steward_surface') { - result = await service.inbox.surface(); + result = await service.inbox.surface( + caller.role === 'main_conversation' + ? { goalId: caller.goalId, parentThreadId: caller.threadId } + : { + goalId: typeof (params.goalId ?? params.goal_id) === 'string' ? String(params.goalId ?? params.goal_id) : null, + parentThreadId: + typeof (params.parentThreadId ?? params.parent_thread_id) === 'string' + ? String(params.parentThreadId ?? params.parent_thread_id) + : null, + }, + ); } else if (method === 'steward_task_promote_goal') { const rawMode = params.mode ?? 'attach'; if (rawMode !== 'attach') { diff --git a/apps/workbench/packages/daemon/src/threads.ts b/apps/workbench/packages/daemon/src/threads.ts index 5c6f827e83..3361710355 100644 --- a/apps/workbench/packages/daemon/src/threads.ts +++ b/apps/workbench/packages/daemon/src/threads.ts @@ -335,6 +335,7 @@ function isDirectory(path: string): boolean { export class ThreadManager { coordination?: CoordinationManager; borrowing?: import('./borrowing.js').BorrowingService; + mainConversationEnv?: (threadId: string) => Record | undefined; /** Drop an idle process so runtime-only connection context takes effect on resume. */ async refreshRuntime(id: string): Promise { @@ -3776,7 +3777,7 @@ export class ThreadManager { const goal = adapter.id === 'codex' ? this.loopx?.binding(thread.id) : undefined; const session = await adapter.start({ borrowedTool: this.borrowing?.toolForThread(thread.id), - coordinationEnv: this.backgroundThreads.has(thread.id) ? {} : { ...this.coordination?.environment(thread.id), ...this.borrowing?.environment(thread.id), ...this.personal.environment(thread.id) }, + coordinationEnv: this.backgroundThreads.has(thread.id) ? {} : { ...this.coordination?.environment(thread.id), ...this.borrowing?.environment(thread.id), ...this.personal.environment(thread.id), ...this.mainConversationEnv?.(thread.id) }, cwd: thread.cwd, resumeId: thread.agentSessionId ?? undefined, onSessionId: (id) => { diff --git a/apps/workbench/packages/daemon/test/fixtures/fake-acp.mjs b/apps/workbench/packages/daemon/test/fixtures/fake-acp.mjs index 6212956373..f48f739fbe 100644 --- a/apps/workbench/packages/daemon/test/fixtures/fake-acp.mjs +++ b/apps/workbench/packages/daemon/test/fixtures/fake-acp.mjs @@ -516,6 +516,36 @@ rl.on('line', (line) => { update({ sessionUpdate: 'agent_message_chunk', content: { type: 'text', text: JSON.stringify(result) } }); out({ jsonrpc: '2.0', id: msg.id, result: { stopReason: 'end_turn' } }); return; } + const mainDispatchMatch = /(?:^|\n)model-dispatch\s+([^\s]+)\s+([^|]+)\|([^\n]+)/.exec(text.replace(/[\s\S]*?<\/loochat-loopx>\s*/g, '')); + if (mainDispatchMatch) { + const [, targetAgent, rawTitle, rawObjective] = mainDispatchMatch; + const binDir = process.env.LOOCHAT_BIN_DIR; + const cliArgs = [ + join(binDir || '', 'loochat'), + 'main-dispatch', + '--agent', targetAgent.trim(), + '--title', rawTitle.trim(), + '--message', rawObjective.trim(), + '--permission', rawObjective.includes('approve') ? 'ask' : 'auto_edit', + ]; + try { + const rawOut = execFileSync(process.execPath, cliArgs, { encoding: 'utf8' }); + const parsed = JSON.parse(rawOut); + const taskId = parsed?.result?.task?.id ?? ''; + const childThreadId = parsed?.result?.threadId ?? ''; + update({ + sessionUpdate: 'agent_message_chunk', + content: { type: 'text', text: `dispatched:${taskId}:${childThreadId}` }, + }); + } catch (err) { + const msgText = (err && (err.stderr || err.message)) ? String(err.stderr || err.message).trim() : 'dispatch_failed'; + update({ + sessionUpdate: 'agent_message_chunk', + content: { type: 'text', text: `dispatch_error:${msgText}` }, + }); + } + out({ jsonrpc: '2.0', id: msg.id, result: { stopReason: 'end_turn' } }); return; + } const images = blocks.filter((p) => p.type === 'image'); if (images.length) { @@ -572,7 +602,17 @@ rl.on('line', (line) => { update({ sessionUpdate: 'agent_thought_chunk', content: { type: 'text', text: 'thinking' } }); update({ sessionUpdate: 'tool_call', toolCallId: 't1', title: 'Run ls', kind: 'execute', status: 'pending', rawInput: { command: 'ls' } }); update({ sessionUpdate: 'tool_call_update', toolCallId: 't1', status: 'completed', rawOutput: 'a.txt' }); - update({ sessionUpdate: 'agent_message_chunk', content: { type: 'text', text: `echo:${process.env.FAKE_ACP_VISIBLE_ECHO === '1' ? text.split(/\n\n[\s\S]*?<\/loochat-loopx>\s*/g, '').split(/\n\n }> = []; + failNextStarts = 0; + delayAvailableMs = 0; + + constructor( + readonly id: string, + readonly label: string, + readonly permissionModes: readonly PermissionMode[], + readonly defaultPermissionMode?: PermissionMode, + private readonly triggerApprovalOnKeyword = false, + ) {} + + get capabilities() { + return { + resume: true, + approvals: this.permissionModes.includes('ask'), + permissionModes: this.permissionModes, + ...(this.defaultPermissionMode ? { defaultPermissionMode: this.defaultPermissionMode } : {}), + effortLevels: [] as const, + images: false, + deleteSession: false, + history: true, + quota: false, + fork: false, + forkAt: false, + multiAccount: false, + forkInto: false, + }; + } + + async available(): Promise { + if (this.delayAvailableMs > 0) { + await new Promise((r) => setTimeout(r, this.delayAvailableMs)); + } + return true; + } + + async models(): Promise { + return []; + } + + async start(opts: StartOptions): Promise { + if (this.failNextStarts > 0) { + this.failNextStarts -= 1; + throw new Error('simulated_transient_adapter_start_failure'); + } + this.starts.push({ + cwd: opts.cwd, + permissionMode: opts.permissionMode, + coordinationEnv: opts.coordinationEnv, + }); + let mode = opts.permissionMode; + let counter = 0; + return { + id: `${this.id}-sess-${this.starts.length}`, + prompt: async (input, callbacks) => { + counter += 1; + if (this.triggerApprovalOnKeyword && input.text.includes('need-approve') && mode === 'ask') { + const decision = await callbacks.requestApproval({ + title: `Approve ${input.text.slice(0, 40)}`, + options: [ + { optionId: 'allow', name: 'Allow', kind: 'allow_once' }, + { optionId: 'reject', name: 'Reject', kind: 'reject_once' }, + ], + toolCall: {}, + }); + const label = 'cancelled' in decision ? 'cancelled' : decision.optionId; + callbacks.emit({ type: 'message.delta', data: { text: `approved:${label}` } }); + return { stopReason: 'end_turn' }; + } + callbacks.emit({ type: 'message.delta', data: { text: `ok:${this.id}:${counter}:${input.text.slice(0, 50)}` } }); + return { stopReason: 'end_turn' }; + }, + setPermissionMode: async (next) => { + mode = next; + }, + cancel: async () => undefined, + close: async () => undefined, + }; + } +} + +function callUnixSocket( + socketPath: string, + body: unknown, + token?: string, +): Promise<{ status: number; json: Record }> { + const payload = JSON.stringify(body); + return new Promise((resolve, reject) => { + const req = httpRequest( + { + socketPath, + path: '/rpc', + method: 'POST', + headers: { + 'Content-Type': 'application/json', + 'Content-Length': Buffer.byteLength(payload), + ...(token ? { Authorization: `Bearer ${token}` } : {}), + }, + }, + (res) => { + const chunks: Buffer[] = []; + res.on('data', (c) => chunks.push(c as Buffer)); + res.on('end', () => { + const text = Buffer.concat(chunks).toString('utf8'); + resolve({ status: res.statusCode ?? 0, json: text ? JSON.parse(text) : {} }); + }); + }, + ); + req.on('error', reject); + req.end(payload); + }); +} + +async function waitFor(predicate: () => boolean, timeoutMs = 4000): Promise { + const deadline = Date.now() + timeoutMs; + while (Date.now() < deadline) { + if (predicate()) return; + await new Promise((r) => setTimeout(r, 15)); + } + throw new Error('timed out waiting for condition'); +} + +async function createHarness(opts: { coreProposals?: unknown[] } = {}) { + const dir = mkdtempSync(join(tmpdir(), 'main-conv-test-')); + const wsA = join(dir, 'project-a'); + const wsB = join(dir, 'project-b'); + const subA = join(wsA, 'nested'); + mkdirSync(subA, { recursive: true }); + mkdirSync(wsB, { recursive: true }); + const dataDir = join(dir, 'data'); + + let coreServer: Server | null = null; + let coreUrl: URL | null = null; + if (opts.coreProposals) { + coreServer = createServer((req, res) => { + if (req.url?.startsWith('/api/actions')) { + res.writeHead(200, { 'Content-Type': 'application/json' }).end( + JSON.stringify({ proposals: opts.coreProposals }), + ); + return; + } + res.writeHead(404).end(); + }); + await new Promise((r) => coreServer!.listen(0, '127.0.0.1', () => r())); + const addr = coreServer.address(); + assert.ok(addr && typeof addr === 'object'); + coreUrl = new URL(`http://127.0.0.1:${addr.port}`); + } + + const claude = new MockAdapter('claude', 'Claude', ['ask', 'auto_edit', 'full_access'], 'auto_edit', true); + const codex = new MockAdapter('codex', 'Codex', ['ask', 'auto_edit', 'full_access'], 'auto_edit', true); + const writeOnlyAgent = new MockAdapter('traex', 'WriteOnly', ['auto_edit', 'full_access'], 'auto_edit', false); + const noModeAgent = new MockAdapter('pi', 'NoMode', [], undefined, false); + const adapters = new Map([ + ['claude', claude], + ['codex', codex], + ['traex', writeOnlyAgent], + ['pi', noModeAgent], + ]); + + const store = new Store(dataDir); + const attachments = new AttachmentStore(dataDir); + const dirs = new Workdirs([wsA, wsB]); + const manager = new ThreadManager(store, adapters, dirs, attachments); + const loopx = new LoopxService({ dataDir, adapters, dirs, ...(coreUrl ? { core: coreUrl } : {}) }); + loopx.attach(manager); + manager.loopx = loopx; + + const localSessions = new LocalSessions( + { + adapters, + workdirs: () => manager.allowedWorkdirs, + hidden: () => [], + importedSessions: () => store.agentSessionOwners(), + instances: () => [], + listAll: () => false, + }, + { enabled: false }, + ); + + const ledger = new StewardLedgerService({ + store, + manager, + localSessions, + adapters, + loopx, + coreUrl, + dataDir, + }); + manager.mainConversationEnv = (tid) => ledger.mainConversationEnvironment(tid); + const sockServer = stewardServer(ledger); + assert.equal(await listenPrivate(sockServer, ledger.socketPath), true); + + const token = 'test-http-token'; + const httpServer = createHttpServer({ + manager, + loopx, + stewardLedger: ledger, + token, + webDir: null, + version: '0.1.0-test', + }); + await new Promise((r) => httpServer.listen(0, '127.0.0.1', () => r())); + const httpAddr = httpServer.address(); + assert.ok(httpAddr && typeof httpAddr === 'object'); + const httpBase = `http://127.0.0.1:${httpAddr.port}`; + + const bindGoalThread = async (goalId: string, workspace: string, permission: 'read_only' | 'workspace_auto', title: string) => { + const th = await manager.createThread({ agent: 'claude', cwd: workspace, title }); + loopx.bindings.set(th.id, { + goalId, + goalAgentId: 'claude-code', + managedAgentId: null, + goalInstanceId: null, + workspace, + permission, + goalTitle: title, + basis: 'workbench', + source: 'launch', + }); + return th; + }; + + return { + dir, + wsA, + wsB, + subA, + claude, + codex, + writeOnlyAgent, + noModeAgent, + store, + manager, + loopx, + ledger, + httpBase, + token, + bindGoalThread, + close: async () => { + await manager.shutdown(); + await new Promise((r) => httpServer.close(() => r())); + await new Promise((r) => sockServer.close(() => r())); + if (coreServer) await new Promise((r) => coreServer!.close(() => r())); + ledger.dispose(); + store.close(); + rmSync(dir, { recursive: true, force: true }); + }, + }; +} + +test('Hardening 1: model-side dispatch derives authority from server binding, enforces read_only ceiling, blocks cwd/repo escape, and fails closed on unsupported adapter modes', async () => { + const h = await createHarness(); + try { + const roMain = await h.bindGoalThread('goal_ro', h.wsA, 'read_only', 'ReadOnly Matter'); + const autoMain = await h.bindGoalThread('goal_auto', h.wsA, 'workspace_auto', 'Auto Matter'); + const otherMain = await h.bindGoalThread('goal_b', h.wsB, 'workspace_auto', 'Other Matter B'); + const ordinary = await h.manager.createThread({ agent: 'claude', cwd: h.wsA, title: 'Ordinary Chat' }); + + // Ordinary threads never receive a Main Conversation socket token. + assert.equal(h.ledger.mainConversationEnvironment(ordinary.id), undefined); + const roEnv = h.ledger.mainConversationEnvironment(roMain.id); + const autoEnv = h.ledger.mainConversationEnvironment(autoMain.id); + assert.ok(roEnv?.LOOCHAT_MAIN_TOKEN && roEnv.LOOCHAT_MAIN_SOCKET); + assert.ok(autoEnv?.LOOCHAT_MAIN_TOKEN); + + // 1a. Read-only Goal cannot escalate to writable, auto_edit, full_access, or writable workspace. + for (const badParams of [ + { mode: 'spawn', agent: 'codex', title: 'Esc1', objective: 'Edit', readonly: false }, + { mode: 'spawn', agent: 'codex', title: 'Esc2', objective: 'Edit', permissionMode: 'auto_edit' }, + { mode: 'spawn', agent: 'codex', title: 'Esc3', objective: 'Edit', permissionMode: 'full_access' }, + { mode: 'spawn', agent: 'codex', title: 'Esc4', objective: 'Edit', workspace: 'new' }, + ]) { + const res = await callUnixSocket( + h.ledger.socketPath, + { method: 'steward_session_handoff', params: badParams }, + roEnv!.LOOCHAT_MAIN_TOKEN, + ); + assert.equal(res.status, 403, `expected 403 for ${JSON.stringify(badParams)}`); + assert.equal(res.json.error, 'permission_escalation_denied'); + } + + // 1b. Read-only Goal omitting readonly/permission still forces readonly=true & workspace='none' & server returnRoute (ignoring spoofed returnRoute!). + const roOk = await callUnixSocket( + h.ledger.socketPath, + { + method: 'steward_session_handoff', + params: { + mode: 'spawn', + agent: 'codex', + title: 'Inspect subdir', + objective: 'Read nested files', + cwd: 'nested', + returnRoute: { channel: 'main_conversation', goalId: 'goal_b', parentThreadId: otherMain.id }, + }, + }, + roEnv!.LOOCHAT_MAIN_TOKEN, + ); + assert.equal(roOk.status, 200); + assert.equal(roOk.json.result.task.readonly, true); + assert.equal(roOk.json.result.task.workspacePolicy, 'none'); + assert.equal(roOk.json.result.task.returnRoute.goalId, 'goal_ro'); + assert.equal(roOk.json.result.task.returnRoute.parentThreadId, roMain.id); + assert.equal(roOk.json.result.task.sourceCwd, h.subA); + // Child worker must NOT receive Main Conversation socket credentials. + const childStart = h.codex.starts.at(-1)!; + assert.equal(childStart.permissionMode, 'ask'); + assert.equal(childStart.coordinationEnv?.LOOCHAT_MAIN_TOKEN, undefined); + + // 1c. Workspace escape via cwd or repo is rejected with 403. + const escapeCwd = await callUnixSocket( + h.ledger.socketPath, + { method: 'steward_session_handoff', params: { mode: 'spawn', agent: 'codex', title: 'Escape', objective: 'x', cwd: h.wsB } }, + autoEnv!.LOOCHAT_MAIN_TOKEN, + ); + assert.equal(escapeCwd.status, 403); + assert.equal(escapeCwd.json.error, 'cwd_outside_goal_workspace'); + + const escapeRepo = await callUnixSocket( + h.ledger.socketPath, + { method: 'steward_session_handoff', params: { mode: 'spawn', agent: 'codex', title: 'EscapeRepo', objective: 'x', repo: 'project-b' } }, + autoEnv!.LOOCHAT_MAIN_TOKEN, + ); + assert.equal(escapeRepo.status, 403); + assert.equal(escapeRepo.json.error, 'cwd_outside_goal_workspace'); + + // 1d. workspace_auto Goal cannot escalate to full_access. + const fullEsc = await callUnixSocket( + h.ledger.socketPath, + { method: 'steward_session_handoff', params: { mode: 'spawn', agent: 'codex', title: 'Full', objective: 'x', permissionMode: 'full_access' } }, + autoEnv!.LOOCHAT_MAIN_TOKEN, + ); + assert.equal(fullEsc.status, 403); + assert.equal(fullEsc.json.error, 'permission_escalation_denied'); + + // 1e. Fail-closed permission check in StewardDispatchService: write-only / no-mode adapters MUST NOT silently downgrade read_only or ask to auto_edit. + await assert.rejects( + () => h.ledger.dispatch.sessionHandoff({ + mode: 'spawn', + agent: 'traex', + cwd: h.wsA, + title: 'RO on traex', + objective: 'Check', + readonly: true, + returnRoute: { channel: 'main_conversation', goalId: 'goal_auto', parentThreadId: autoMain.id }, + }), + /unsupported_permission_mode:traex:read_only/, + ); + await assert.rejects( + () => h.ledger.dispatch.sessionHandoff({ + mode: 'spawn', + agent: 'traex', + cwd: h.wsA, + title: 'Ask on traex', + objective: 'Check', + permissionMode: 'ask', + returnRoute: { channel: 'main_conversation', goalId: 'goal_auto', parentThreadId: autoMain.id }, + }), + /unsupported_permission_mode:traex:ask/, + ); + await assert.rejects( + () => h.ledger.dispatch.sessionHandoff({ + mode: 'spawn', + agent: 'pi', + cwd: h.wsA, + title: 'Ask on pi', + objective: 'Check', + permissionMode: 'ask', + returnRoute: { channel: 'main_conversation', goalId: 'goal_auto', parentThreadId: autoMain.id }, + }), + /unsupported_permission_mode:pi:ask/, + ); + assert.equal(h.writeOnlyAgent.starts.length, 0); + assert.equal(h.noModeAgent.starts.length, 0); + } finally { + await h.close(); + } +}); + +test('spawn replay binds normalized acceptance criteria over HTTP and preserves existing ledger rows', async () => { + const h = await createHarness(); + try { + const main = await h.bindGoalThread('goal_replay', h.wsA, 'workspace_auto', 'Replay'); + const input = { + mode: 'spawn', agent: 'codex', cwd: h.wsA, title: 'Draft report', objective: 'Write report', + clientRequestId: 'acceptance-replay', requireApproval: true, + doneWhen: ['Include the opening'], + returnRoute: { channel: 'main_conversation', goalId: 'goal_replay', parentThreadId: main.id }, + }; + const post = (body: unknown) => fetch(`${h.httpBase}/api/steward/handoff`, { + method: 'POST', headers: { Authorization: `Bearer ${h.token}`, 'Content-Type': 'application/json' }, + body: JSON.stringify(body), + }); + const first = await post(input); + assert.equal(first.status, 200); + const original = await first.json(); + for (const doneWhen of [input.doneWhen, [' Include the opening ', '']]) { + const response = await post({ ...input, doneWhen }); + assert.equal(response.status, 200); + const replay = await response.json(); + assert.equal(replay.reused, true); + assert.equal(replay.task.id, original.task.id); + } + const conflict = await post({ ...input, doneWhen: ['Include the appendix'] }); + assert.equal(conflict.status, 409); + assert.match(JSON.stringify(await conflict.json()), /client_request_id_conflict/); + const fresh = await post({ ...input, clientRequestId: 'new-acceptance', doneWhen: ['Include the appendix'] }); + assert.equal(fresh.status, 200); + const changed = await fresh.json(); + assert.notEqual(changed.task.id, original.task.id); + assert.deepEqual(changed.task.doneWhen, ['Include the appendix']); + assert.equal(h.store.db.prepare('SELECT COUNT(*) AS n FROM steward_tasks').get()?.n, 2); + assert.equal(h.store.db.prepare('SELECT done_when_json FROM steward_tasks WHERE id = ?').get(original.task.id)?.done_when_json, + JSON.stringify(input.doneWhen)); + + // Rows created through the existing plan API have no request fingerprint metadata. + const historical = await h.ledger.dispatch.taskPlan({ + tasks: [{ ...input, clientRequestId: 'historical-default', doneWhen: [input.title] }], + requireApproval: true, returnRoute: input.returnRoute, + }); + const retry = await post({ ...input, clientRequestId: 'historical-default', doneWhen: undefined }); + assert.equal(retry.status, 200); + assert.equal((await retry.json()).task.id, historical.tasks[0]!.id); + const invalid = await post({ ...input, doneWhen: [] }); + assert.equal(invalid.status, 400); + } finally { + await h.close(); + } +}); + +test('in-flight spawn rejects changed acceptance and reuses normalized or default-equivalent criteria', async () => { + const h = await createHarness(); + try { + const main = await h.bindGoalThread('goal_inflight', h.wsA, 'workspace_auto', 'In flight'); + for (const readonly of [false, true]) { + let release!: () => void; + const gate = new Promise((resolve) => { release = resolve; }); + h.codex.available = async () => { await gate; return true; }; + const input = { + mode: 'spawn' as const, agent: 'codex', cwd: h.wsA, title: 'Include the opening', + objective: 'Write report', readonly, requireApproval: true, + clientRequestId: `acceptance-inflight-${readonly}`, + returnRoute: { channel: 'main_conversation', goalId: 'goal_inflight', parentThreadId: main.id }, + }; + const first = h.ledger.dispatch.sessionHandoff(input); + const equivalent = h.ledger.dispatch.sessionHandoff({ + ...input, doneWhen: readonly ? [' '] : [' Include the opening ', ''], + }); + const conflict = h.ledger.dispatch.sessionHandoff({ ...input, doneWhen: ['Include the appendix'] }); + release(); + const [original, replay, changed] = await Promise.allSettled([first, equivalent, conflict]); + assert.equal(original.status, 'fulfilled'); + assert.equal(replay.status, 'fulfilled'); + assert.equal(changed.status, 'rejected'); + if (original.status !== 'fulfilled' || replay.status !== 'fulfilled' || changed.status !== 'rejected') { + assert.fail('unexpected replay outcomes'); + } + assert.equal(replay.value.task.id, original.value.task.id); + assert.equal(replay.value.reused, true); + assert.ok(changed.reason instanceof HttpError); + assert.equal(changed.reason.status, 409); + } + } finally { + await h.close(); + } +}); + +test('Hardening 2: concurrent clientRequestId runs once, succeeded continue retry precedes expectedLastTurnId fence, and failed first launch is honestly retryable', async () => { + const h = await createHarness(); + try { + const main = await h.bindGoalThread('goal_idemp', h.wsA, 'workspace_auto', 'Idempotency Matter'); + const route = { channel: 'main_conversation', goalId: 'goal_idemp', parentThreadId: main.id, originId: main.id }; + + // 2a. Concurrent spawn calls with the same clientRequestId (even while resolveAgent awaits!) execute strictly ONCE. + h.codex.delayAvailableMs = 40; + const [r1, r2] = await Promise.all([ + h.ledger.dispatch.sessionHandoff({ + mode: 'spawn', + agent: 'codex', + cwd: h.wsA, + title: 'Concurrent Task', + objective: 'Run once', + clientRequestId: 'req-concurrent-1', + returnRoute: route, + }), + h.ledger.dispatch.sessionHandoff({ + mode: 'spawn', + agent: 'codex', + cwd: h.wsA, + title: 'Concurrent Task', + objective: 'Run once', + clientRequestId: 'req-concurrent-1', + returnRoute: route, + }), + ]); + h.codex.delayAvailableMs = 0; + assert.equal(r1.threadId, r2.threadId); + assert.equal(r1.task.id, r2.task.id); + assert.equal(r2.reused, true); + assert.equal(h.codex.starts.length, 1); + + // Conflicting intent with the same clientRequestId returns 409 client_request_id_conflict. + await assert.rejects( + () => h.ledger.dispatch.sessionHandoff({ + mode: 'spawn', + agent: 'codex', + cwd: h.wsA, + title: 'Different Task', + objective: 'Different body', + clientRequestId: 'req-concurrent-1', + returnRoute: route, + }), + /client_request_id_conflict/, + ); + + const childThreadId = r1.threadId!; + await waitFor(() => h.store.getThread(childThreadId)?.status === 'idle'); + const turnBeforeContinue = h.store.listTurns(childThreadId).at(-1)!.turnId; + + // 2b. Succeeded `continue` with expectedLastTurnId: retrying the EXACT SAME request returns the same child task (reused: true) + // instead of failing with 409 user_intervened even though actualLastTurnId advanced! + const cont1 = await h.ledger.dispatch.sessionHandoff({ + mode: 'continue', + targetKind: 'workbench_thread', + targetId: childThreadId, + message: 'Follow up step', + expectedLastTurnId: turnBeforeContinue, + clientRequestId: 'req-cont-1', + returnRoute: route, + }); + await waitFor(() => h.store.getThread(childThreadId)?.status === 'idle'); + const turnAfterContinue = h.store.listTurns(childThreadId).at(-1)!.turnId; + assert.notEqual(turnAfterContinue, turnBeforeContinue); + + const contRetry = await h.ledger.dispatch.sessionHandoff({ + mode: 'continue', + targetKind: 'workbench_thread', + targetId: childThreadId, + message: 'Follow up step', + expectedLastTurnId: turnBeforeContinue, + clientRequestId: 'req-cont-1', + returnRoute: route, + }); + assert.equal(contRetry.reused, true); + assert.equal(contRetry.task.id, cont1.task.id); + assert.equal(contRetry.threadId, childThreadId); + + // 2c-i. Initial launch failure BEFORE any thread is created (`threadId === null`): + // returns honest retryable 503 error and releases clientRequestId so retrying with the exact same key succeeds cleanly. + const origCreateThread = h.manager.createThread.bind(h.manager); + let failCreateOnce = true; + h.manager.createThread = (async (...args: Parameters) => { + if (failCreateOnce) { + failCreateOnce = false; + throw new Error('simulated_pre_thread_launch_failure'); + } + return origCreateThread(...args); + }) as typeof h.manager.createThread; + + let firstErr: unknown = null; + try { + await h.ledger.dispatch.sessionHandoff({ + mode: 'spawn', + agent: 'codex', + cwd: h.wsA, + title: 'Flaky Start', + objective: 'Will fail before thread creation once then pass', + clientRequestId: 'req-retry-launch', + returnRoute: route, + }); + } catch (err) { + firstErr = err; + } finally { + h.manager.createThread = origCreateThread; + } + assert.ok(firstErr instanceof HttpError); + assert.equal(firstErr.status, 503); + assert.equal((firstErr.details as Record)?.retryable, true); + assert.equal((firstErr.details as Record)?.clientRequestId, 'req-retry-launch'); + + // Retry with the exact same clientRequestId now cleanly succeeds and spawns a live child thread. + const retried = await h.ledger.dispatch.sessionHandoff({ + mode: 'spawn', + agent: 'codex', + cwd: h.wsA, + title: 'Flaky Start', + objective: 'Will fail before thread creation once then pass', + clientRequestId: 'req-retry-launch', + returnRoute: route, + }); + assert.equal(retried.reused, undefined); + assert.ok(retried.threadId); + assert.notEqual(retried.task.status, 'failed'); + + // Subsequent retry after success returns the succeeded child (reused: true). + const afterSuccess = await h.ledger.dispatch.sessionHandoff({ + mode: 'spawn', + agent: 'codex', + cwd: h.wsA, + title: 'Flaky Start', + objective: 'Will fail before thread creation once then pass', + clientRequestId: 'req-retry-launch', + returnRoute: route, + }); + assert.equal(afterSuccess.reused, true); + assert.equal(afterSuccess.threadId, retried.threadId); + assert.equal(afterSuccess.task.id, retried.task.id); + + // 2c-ii. Already-threaded `failed` task (`threadId !== null`): retrying with the same clientRequestId + // MUST reuse the existing failed state and threadId without restarting or creating a second thread. + h.codex.failNextStarts = 1; + const startsBeforeFailed = h.codex.starts.length; + const asyncFailAttempt = await h.ledger.dispatch.sessionHandoff({ + mode: 'spawn', + agent: 'codex', + cwd: h.wsA, + title: 'Failed After Thread Created', + objective: 'Will fail after thread exists', + clientRequestId: 'req-failed-with-thread', + returnRoute: route, + }); + assert.ok(asyncFailAttempt.threadId, 'child thread was created before turn failed'); + await waitFor(() => h.ledger.dispatch.getTask(asyncFailAttempt.task.id)?.status === 'failed'); + + const failedRetry = await h.ledger.dispatch.sessionHandoff({ + mode: 'spawn', + agent: 'codex', + cwd: h.wsA, + title: 'Failed After Thread Created', + objective: 'Will fail after thread exists', + clientRequestId: 'req-failed-with-thread', + returnRoute: route, + }); + assert.equal(failedRetry.reused, true); + assert.equal(failedRetry.task.id, asyncFailAttempt.task.id); + assert.equal(failedRetry.threadId, asyncFailAttempt.threadId); + assert.equal(failedRetry.task.status, 'failed'); + assert.equal(h.codex.starts.length, startsBeforeFailed, 'must NOT restart or spawn a second adapter session'); + + // 2c-iii. Already-threaded `cancelled` task (`threadId !== null`): retrying with the same clientRequestId + // MUST reuse the existing cancelled state without restarting or creating a second thread. + const cancelTask = await h.ledger.dispatch.sessionHandoff({ + mode: 'spawn', + agent: 'claude', + cwd: h.wsA, + title: 'Cancelled Child Task', + objective: 'need-approve wait before cancel', + permissionMode: 'ask', + clientRequestId: 'req-cancelled-with-thread', + returnRoute: route, + }); + assert.ok(cancelTask.threadId); + await waitFor(() => h.manager.listPendingApprovals().some((p) => p.threadId === cancelTask.threadId)); + await h.ledger.dispatch.agentInterrupt(cancelTask.threadId!); + await waitFor(() => h.ledger.dispatch.getTask(cancelTask.task.id)?.status === 'cancelled'); + + const claudeStartsBeforeCancelRetry = h.claude.starts.length; + const cancelRetry = await h.ledger.dispatch.sessionHandoff({ + mode: 'spawn', + agent: 'claude', + cwd: h.wsA, + title: 'Cancelled Child Task', + objective: 'need-approve wait before cancel', + permissionMode: 'ask', + clientRequestId: 'req-cancelled-with-thread', + returnRoute: route, + }); + assert.equal(cancelRetry.reused, true); + assert.equal(cancelRetry.task.id, cancelTask.task.id); + assert.equal(cancelRetry.threadId, cancelTask.threadId); + assert.equal(cancelRetry.task.status, 'cancelled'); + assert.equal(h.claude.starts.length, claudeStartsBeforeCancelRetry, 'must NOT restart cancelled task'); + + // 2d. goalContextBlock model dispatch guidance includes a stable --request-id example. + const ctxBlock = goalContextBlock(h.loopx.binding(main.id)!, null, 'unavailable'); + assert.ok(ctxBlock.includes('--request-id'), 'goalContextBlock must guide model to pass a stable --request-id'); + } finally { + await h.close(); + } +}); + +test('Hardening 3: scope filters BEFORE SQL truncation, includes bound Goal thread + children, isolates matters, and rejects unbound/mismatched parents', async () => { + const h = await createHarness({ + coreProposals: [ + { + proposal_id: 'prop_a', + action_kind: 'todo.create', + status: 'preview_ready', + summary: 'Add todo in Goal A', + context: { goal_id: 'goal_a' }, + }, + { + proposal_id: 'prop_b', + action_kind: 'todo.create', + status: 'preview_ready', + summary: 'Add todo in Goal B', + context: { goal_id: 'goal_b' }, + }, + ], + }); + try { + const mainA = await h.bindGoalThread('goal_a', h.wsA, 'workspace_auto', 'Matter A'); + const mainB = await h.bindGoalThread('goal_b', h.wsB, 'workspace_auto', 'Matter B'); + const ordinary = await h.manager.createThread({ agent: 'claude', cwd: h.wsA, title: 'Legacy Ordinary' }); + + // 3a. Reject unbound ordinary parent, nonexistent parent, and mismatched (goalId, parentThreadId). + assert.throws( + () => h.ledger.dispatch.listTasks({ parentThreadId: ordinary.id }), + /parent_thread_not_bound_to_goal/, + ); + assert.throws( + () => h.ledger.dispatch.listTasks({ parentThreadId: 'nonexistent-thread' }), + /parent_thread_not_found/, + ); + assert.throws( + () => h.ledger.dispatch.listTasks({ goalId: 'goal_a', parentThreadId: mainB.id }), + /parent_goal_mismatch/, + ); + await assert.rejects( + () => h.ledger.inbox.surface({ parentThreadId: ordinary.id }), + /parent_thread_not_bound_to_goal/, + ); + await assert.rejects( + () => h.ledger.inbox.surface({ goalId: 'goal_a', parentThreadId: mainB.id }), + /parent_goal_mismatch/, + ); + await assert.rejects( + () => h.ledger.dispatch.sessionHandoff({ + mode: 'spawn', + agent: 'claude', + cwd: h.wsA, + title: 'Spoofed', + objective: 'Should fail', + returnRoute: { channel: 'main_conversation', goalId: 'goal_a', parentThreadId: ordinary.id }, + }), + /parent_thread_not_bound_to_goal/, + ); + + // 3b. Spawn approval-triggering child under Matter A AND ordinary standalone thread approval. + const childADisp = await h.ledger.dispatch.sessionHandoff({ + mode: 'spawn', + agent: 'claude', + cwd: h.wsA, + title: 'Child A Approval', + objective: 'need-approve install A', + permissionMode: 'ask', + returnRoute: { channel: 'main_conversation', goalId: 'goal_a', parentThreadId: mainA.id, originId: mainA.id }, + }); + const childAId = childADisp.threadId!; + + // Trigger approval on an ordinary legacy thread as well. + await h.manager.updateThread(ordinary.id, { permissionMode: 'ask' }); + await h.manager.startTurn(ordinary.id, { text: 'need-approve ordinary legacy' }); + + await waitFor(() => h.manager.listPendingApprovals().length >= 2); + const pendingA = h.manager.listPendingApprovals().find((p) => p.threadId === childAId)!; + assert.ok(pendingA); + + // 3c. Seed 1 concern + 1 due follow-up on Matter A's BOUND Goal thread itself, PLUS 60 reported concerns + // and 110 due follow-ups on Matter B (exceeding LIMIT 50 / LIMIT 100!) to prove SQL filters BEFORE truncation. + const concernA = h.ledger.inbox.createConcern({ title: 'Goal A own concern', targetThreadId: mainA.id }); + h.ledger.inbox.reportConcern({ id: concernA.id, summary: 'Ready for review in A' }); + const followupA = h.ledger.inbox.scheduleFollowup({ prompt: 'Followup on Goal A', afterMinutes: 0, threadId: mainA.id }); + + for (let i = 0; i < 60; i++) { + const c = h.ledger.inbox.createConcern({ title: `Matter B noise ${i}`, targetThreadId: mainB.id }); + h.ledger.inbox.reportConcern({ id: c.id, summary: `Noise B ${i}` }); + } + for (let i = 0; i < 110; i++) { + h.ledger.inbox.scheduleFollowup({ prompt: `Followup B ${i}`, afterMinutes: 0, threadId: mainB.id }); + } + + // Query Matter A by goalId ALONE (must include bound Goal thread mainA AND childA, and NOT be crowded out by Matter B!). + const surfA = await h.ledger.inbox.surface({ goalId: 'goal_a' }); + const cardIdsA = surfA.inlineCards.map((c) => c.id); + assert.ok(cardIdsA.includes(`approval:${pendingA.approvalId}`), 'Matter A must include child A approval'); + assert.ok(cardIdsA.includes('core_action:prop_a'), 'Matter A must include Goal A Core action'); + assert.ok(cardIdsA.includes(`concern:${concernA.id}`), 'Matter A must include bound Goal A own concern despite 60 Matter B concerns'); + assert.ok(cardIdsA.includes(`followup:${followupA.id}`), 'Matter A must include bound Goal A own due followup despite 110 Matter B followups'); + assert.ok(!cardIdsA.includes('core_action:prop_b'), 'Goal B Core action must not leak to Matter A'); + assert.ok(!surfA.inlineCards.some((c) => c.kind === 'thread_approval' && c.threadId === ordinary.id), 'Ordinary approval must not leak to Matter A'); + + // Query Matter B -> must NOT see child A approval, Goal A Core action, or ordinary approval. + const surfB = await h.ledger.inbox.surface({ goalId: 'goal_b', parentThreadId: mainB.id }); + assert.ok(surfB.inlineCards.some((c) => c.id === 'core_action:prop_b')); + assert.ok(!surfB.inlineCards.some((c) => c.id === 'core_action:prop_a')); + assert.ok(!surfB.inlineCards.some((c) => c.kind === 'thread_approval')); + + // 3d. Resolve child A approval via real HTTP POST /api/approvals/:id, then verify duplicate returns 404 and Matter A clears! + const approveRes1 = await fetch(`${h.httpBase}/api/approvals/${encodeURIComponent(pendingA.approvalId)}`, { + method: 'POST', + headers: { Authorization: `Bearer ${h.token}`, 'Content-Type': 'application/json' }, + body: JSON.stringify({ optionId: 'allow' }), + }); + assert.equal(approveRes1.status, 204); + + const approveRes2 = await fetch(`${h.httpBase}/api/approvals/${encodeURIComponent(pendingA.approvalId)}`, { + method: 'POST', + headers: { Authorization: `Bearer ${h.token}`, 'Content-Type': 'application/json' }, + body: JSON.stringify({ optionId: 'allow' }), + }); + assert.equal(approveRes2.status, 404); + + await waitFor(() => { + const task = h.ledger.dispatch.getTask(childADisp.task.id); + return task !== null && task.status === 'idle' && Boolean(task.resultSummary?.includes('approved:allow')); + }); + + const surfAAfter = await h.ledger.inbox.surface({ goalId: 'goal_a', parentThreadId: mainA.id }); + assert.ok(!surfAAfter.inlineCards.some((c) => c.id === `approval:${pendingA.approvalId}`)); + } finally { + await h.close(); + } +}); + +test('Hardening 4: permissionMode=read_only alone is treated as readonly across taskPlan, spawn, and continue without creating writable worktrees', async () => { + const h = await createHarness(); + try { + // Turn wsA into a real git repo so writable policy='new' WOULD create a worktree if readonly were false. + writeFileSync(join(h.wsA, 'README.md'), '# git repo\n'); + execFileSync('git', ['init', '-q', '-b', 'main'], { cwd: h.wsA }); + execFileSync('git', ['config', 'user.email', 'test@example.invalid'], { cwd: h.wsA }); + execFileSync('git', ['config', 'user.name', 'Test'], { cwd: h.wsA }); + execFileSync('git', ['add', 'README.md'], { cwd: h.wsA }); + execFileSync('git', ['commit', '-q', '-m', 'init'], { cwd: h.wsA }); + + const main = await h.bindGoalThread('goal_ro_implicit', h.wsA, 'workspace_auto', 'Git Matter'); + const route = { channel: 'main_conversation', goalId: 'goal_ro_implicit', parentThreadId: main.id, originId: main.id }; + + // 1. taskPlan with permissionMode='read_only' ONLY (no readonly flag, no doneWhen) -> treated as readonly, no worktree. + const planned = await h.ledger.dispatch.taskPlan({ + tasks: [{ title: 'Inspect git via plan', objective: 'Read repo status', cwd: h.wsA, agent: 'codex', permissionMode: 'read_only' }], + returnRoute: route, + }); + assert.equal(planned.tasks[0]!.readonly, true); + assert.equal(planned.tasks[0]!.workspacePolicy, 'none'); + assert.equal(planned.tasks[0]!.workspaceResolved.worktree, null); + assert.equal(planned.tasks[0]!.lockDir, null); + + // 2. sessionHandoff(spawn) with permissionMode='read_only' ONLY -> treated as readonly, no worktree. + const spawned = await h.ledger.dispatch.sessionHandoff({ + mode: 'spawn', + title: 'Inspect git via spawn', + objective: 'Check branches', + cwd: h.wsA, + agent: 'codex', + permissionMode: 'read_only', + returnRoute: route, + }); + assert.equal(spawned.task.readonly, true); + assert.equal(spawned.task.workspacePolicy, 'none'); + assert.equal(spawned.task.workspaceResolved.worktree, null); + assert.equal(spawned.task.lockDir, null); + await waitFor(() => h.store.getThread(spawned.threadId!)?.status === 'idle'); + + // 3. sessionHandoff(continue) with permissionMode='read_only' ONLY -> treated as readonly, workspacePolicy='none', lockDir=null. + const continued = await h.ledger.dispatch.sessionHandoff({ + mode: 'continue', + targetKind: 'workbench_thread', + targetId: spawned.threadId!, + message: 'Check tags read-only', + permissionMode: 'read_only', + returnRoute: route, + }); + assert.equal(continued.task.readonly, true); + assert.equal(continued.task.workspacePolicy, 'none'); + assert.equal(continued.task.lockDir, null); + await waitFor(() => h.store.getThread(spawned.threadId!)?.status === 'idle'); + } finally { + await h.close(); + } +}); diff --git a/apps/workbench/packages/e2e/harness.mjs b/apps/workbench/packages/e2e/harness.mjs index f27ff63eab..92c7a8d6f2 100644 --- a/apps/workbench/packages/e2e/harness.mjs +++ b/apps/workbench/packages/e2e/harness.mjs @@ -298,6 +298,15 @@ export async function openCollaboration(page) { await page.getByRole('menu', { name: '协作', exact: true }).waitFor(); } +/** Starts a new ordinary conversation via the sidebar's unified top-bar "新建" entry (direct or menu). */ +export async function startNewThread(page) { + const btn = page.locator('.sidebar').getByRole('button', { name: '新建', exact: true }); + await btn.click(); + if ((await btn.getAttribute('aria-haspopup')) === 'menu') { + await page.getByRole('menuitem', { name: '新对话', exact: true }).click(); + } +} + /** Register a node and connect its real relay client to this test hub. */ export async function linkDaemon(hub, node, label = 'devbox') { const response = await api(hub, '/api/hosts', { method: 'POST', body: JSON.stringify({ label }) }); diff --git a/apps/workbench/packages/e2e/test/agents.spec.mjs b/apps/workbench/packages/e2e/test/agents.spec.mjs index b22f9a530e..00b9dfb8d0 100644 --- a/apps/workbench/packages/e2e/test/agents.spec.mjs +++ b/apps/workbench/packages/e2e/test/agents.spec.mjs @@ -5,7 +5,7 @@ import assert from 'node:assert/strict'; import { mkdtempSync, rmSync, writeFileSync } from 'node:fs'; import { tmpdir } from 'node:os'; import { join } from 'node:path'; -import { startDaemon, openUi, api, launchBrowser, closeSettings } from '../harness.mjs'; +import { startDaemon, openUi, api, launchBrowser, closeSettings, startNewThread } from '../harness.mjs'; let daemon; let browser; @@ -76,7 +76,7 @@ test('a CLI found on PATH can be added through agent settings', async () => { }); test('turns the terminal added show up marked, and sending asks first', async () => { - await page.locator('.sidebar').getByRole('button', { name: '新对话', exact: true }).click(); + await startNewThread(page); await page.locator('.composer .context-btn').first().click(); await page.locator('.agent-picker-panel').getByRole('button', { name: /^pi/ }).click(); await page.getByRole('menuitemradio', { name: /^pi$/ }).click(); diff --git a/apps/workbench/packages/e2e/test/appearance.spec.mjs b/apps/workbench/packages/e2e/test/appearance.spec.mjs index 54704df747..54c811ddee 100644 --- a/apps/workbench/packages/e2e/test/appearance.spec.mjs +++ b/apps/workbench/packages/e2e/test/appearance.spec.mjs @@ -77,7 +77,7 @@ test('a palette and a mode chosen in the panel show at once', async () => { test('the choice outlives a reload, and a fixed mode does not follow the system', async () => { await page.reload(); - await page.locator('.sidebar').getByRole('button', { name: '新对话', exact: true }).waitFor({ timeout: 10_000 }); + await page.locator('.sidebar').getByRole('button', { name: '新建', exact: true }).waitFor({ timeout: 10_000 }); // The system is light here; the page stays dark because dark was chosen. assert.deepEqual(await look(), { theme: 'dark', palette: 'nord', bg: '#2e3440', meta: '#2e3440' }); @@ -104,7 +104,7 @@ test('the look is on the page before the app starts', async () => { test('a palette this build does not know falls back to the default', async () => { await page.evaluate(() => localStorage.setItem('calli.appearance', JSON.stringify({ mode: 'dark', palette: 'from-the-future' }))); await page.reload(); - await page.locator('.sidebar').getByRole('button', { name: '新对话', exact: true }).waitFor({ timeout: 10_000 }); + await page.locator('.sidebar').getByRole('button', { name: '新建', exact: true }).waitFor({ timeout: 10_000 }); assert.deepEqual(await look(), { theme: 'dark', palette: 'codex', bg: '#212121', meta: '#212121' }); }); diff --git a/apps/workbench/packages/e2e/test/conversation.spec.mjs b/apps/workbench/packages/e2e/test/conversation.spec.mjs index 744d8c17dd..a9cdfc62e7 100644 --- a/apps/workbench/packages/e2e/test/conversation.spec.mjs +++ b/apps/workbench/packages/e2e/test/conversation.spec.mjs @@ -2,7 +2,7 @@ // durations, the work group collapsing once the turn is done. import { test, before, after } from 'node:test'; import assert from 'node:assert/strict'; -import { startDaemon, openUi, launchBrowser } from '../harness.mjs'; +import { startDaemon, openUi, launchBrowser, startNewThread } from '../harness.mjs'; let daemon; let browser; @@ -66,7 +66,7 @@ test('a turn shows thinking, verb-first tool rows, and folds its work away when }); test('while a turn runs its steps stay the story: no changes card until it ends', async () => { - await page.locator('.side-nav').getByRole('button', { name: '新对话', exact: true }).click(); + await startNewThread(page); await page.locator('.composer .context-btn').first().click(); await page.getByRole('menuitemradio', { name: /^pi/ }).click(); await page.locator('.composer textarea').click(); @@ -95,7 +95,7 @@ test('while a turn runs its steps stay the story: no changes card until it ends' }); test('a run of calls folds into one line that counts them, and opens to the calls', async () => { - await page.locator('.side-nav').getByRole('button', { name: '新对话', exact: true }).click(); + await startNewThread(page); await page.locator('.composer .context-btn').first().click(); await page.getByRole('menuitemradio', { name: /^pi/ }).click(); await page.locator('.composer textarea').click(); diff --git a/apps/workbench/packages/e2e/test/drafts.spec.mjs b/apps/workbench/packages/e2e/test/drafts.spec.mjs index 080b28d93c..67563419b6 100644 --- a/apps/workbench/packages/e2e/test/drafts.spec.mjs +++ b/apps/workbench/packages/e2e/test/drafts.spec.mjs @@ -2,7 +2,7 @@ // brings it back, and other threads start with their own. import { test, before, after } from 'node:test'; import assert from 'node:assert/strict'; -import { startDaemon, openUi, api, launchBrowser } from '../harness.mjs'; +import { startDaemon, openUi, api, launchBrowser, startNewThread } from '../harness.mjs'; let daemon; let browser; @@ -61,7 +61,7 @@ test('each thread keeps its own draft', async () => { }); test('a sent first message does not linger in the next new thread', async () => { - await page.locator('.sidebar').getByRole('button', { name: '新对话', exact: true }).click(); + await startNewThread(page); await page.locator('.composer .context-btn').first().click(); await page.getByRole('menuitemradio', { name: /^pi/ }).click(); await box().fill('third thread'); @@ -69,6 +69,6 @@ test('a sent first message does not linger in the next new thread', async () => await page.locator('.topbar-title', { hasText: 'third thread' }).waitFor({ timeout: 10_000 }); assert.equal(await box().inputValue(), ''); - await page.locator('.sidebar').getByRole('button', { name: '新对话', exact: true }).click(); + await startNewThread(page); assert.equal(await box().inputValue(), ''); }); diff --git a/apps/workbench/packages/e2e/test/general-settings.spec.mjs b/apps/workbench/packages/e2e/test/general-settings.spec.mjs index 2b9daf7295..40ad9e7606 100644 --- a/apps/workbench/packages/e2e/test/general-settings.spec.mjs +++ b/apps/workbench/packages/e2e/test/general-settings.spec.mjs @@ -2,7 +2,7 @@ import { test } from 'node:test'; import assert from 'node:assert/strict'; import { mkdirSync } from 'node:fs'; import { join } from 'node:path'; -import { startDaemon, launchBrowser, openUi, api } from '../harness.mjs'; +import { startDaemon, launchBrowser, openUi, api, startNewThread } from '../harness.mjs'; test('general startup preference is shared, respects recent activity and explicit navigation', async () => { const daemon = await startDaemon(); @@ -61,7 +61,7 @@ test('general startup preference is shared, respects recent activity and explici await page.locator('.topbar-title', { hasText: 'Latest conversation' }).waitFor(); // An explicit new-thread action is not undone by subsequent list updates. if (mobile) await page.getByRole('button', { name: '打开对话列表', exact: true }).click(); - await page.locator('.sidebar').getByRole('button', { name: '新对话', exact: true }).click(); + await startNewThread(page); await page.locator('.topbar-title', { hasText: '新对话' }).waitFor(); await page.goto(`${daemon.base}/#/thread/${older.id}`); await page.locator('.topbar-title', { hasText: 'Older pinned conversation' }).waitFor(); diff --git a/apps/workbench/packages/e2e/test/locale.spec.mjs b/apps/workbench/packages/e2e/test/locale.spec.mjs index 73a3da8d26..9416c771ac 100644 --- a/apps/workbench/packages/e2e/test/locale.spec.mjs +++ b/apps/workbench/packages/e2e/test/locale.spec.mjs @@ -46,13 +46,13 @@ async function choose(page, settings, menu, name) { test('with nothing chosen, the page speaks the browser\'s language', async () => { const ja = await signedIn('ja-JP'); assert.equal(await lang(ja), 'ja-JP'); - await ja.getByRole('button', { name: '新しいスレッド' }).first().waitFor(); + await ja.getByRole('button', { name: '新規', exact: true }).first().waitFor(); await ja.context().close(); // A language the hub does not speak falls back to English. const fr = await signedIn('fr-FR'); assert.equal(await lang(fr), 'en-US'); - await fr.getByRole('button', { name: 'New thread' }).first().waitFor(); + await fr.getByRole('button', { name: 'New', exact: true }).first().waitFor(); await fr.context().close(); }); @@ -64,7 +64,7 @@ test('a language picked in the menu applies everywhere and outlives a reload', a await choose(page, '配置', '语言', 'English'); assert.equal(await lang(page), 'en-US'); - await page.getByRole('button', { name: 'New thread' }).first().waitFor(); + await page.getByRole('button', { name: 'New', exact: true }).first().waitFor(); assert.equal(await page.locator('.composer textarea').getAttribute('aria-label'), 'Message'); await page.reload(); @@ -80,7 +80,7 @@ test('a language picked in the menu applies everywhere and outlives a reload', a await choose(page, 'Settings', 'Language', '日本語'); assert.equal(await lang(page), 'ja-JP'); - await page.getByRole('button', { name: '新しいスレッド' }).first().waitFor(); + await page.getByRole('button', { name: '新規', exact: true }).first().waitFor(); // Following the system again forgets the choice: this browser asks for Chinese. await choose(page, '設定', '言語', 'システムに合わせる'); diff --git a/apps/workbench/packages/e2e/test/longthread.spec.mjs b/apps/workbench/packages/e2e/test/longthread.spec.mjs index c38e11510b..1f99f3adf7 100644 --- a/apps/workbench/packages/e2e/test/longthread.spec.mjs +++ b/apps/workbench/packages/e2e/test/longthread.spec.mjs @@ -4,7 +4,7 @@ import assert from 'node:assert/strict'; import { mkdtempSync, rmSync, writeFileSync } from 'node:fs'; import { tmpdir } from 'node:os'; import { join } from 'node:path'; -import { startDaemon, openUi, api, launchBrowser } from '../harness.mjs'; +import { startDaemon, openUi, api, launchBrowser, startNewThread } from '../harness.mjs'; let daemon; let browser; @@ -83,7 +83,7 @@ test('a long thread folds its past, and the ruler jumps between the turns on scr test('short threads show no ruler and no fold', async () => { await openUi(page, daemon); - await page.locator('.sidebar').getByRole('button', { name: '新对话', exact: true }).click(); + await startNewThread(page); await page.locator('.composer .context-btn').first().click(); await page.getByRole('menuitemradio', { name: /^pi/ }).click(); await page.locator('.composer textarea').click(); diff --git a/apps/workbench/packages/e2e/test/main-conversations.spec.mjs b/apps/workbench/packages/e2e/test/main-conversations.spec.mjs new file mode 100644 index 0000000000..be6dc27a0e --- /dev/null +++ b/apps/workbench/packages/e2e/test/main-conversations.spec.mjs @@ -0,0 +1,1328 @@ +// Real-browser Playwright E2E for Workbench loop (Goal-backed main conversations): +// Uses real built Workbench daemon + real built React UI + real Chromium, +// paired with clearly labeled test doubles: in-process synthetic LoopX Core HTTP server + fake ACP/Pi agents. +import { test, before, after } from 'node:test'; +import assert from 'node:assert/strict'; +import { createHash } from 'node:crypto'; +import { mkdirSync, writeFileSync } from 'node:fs'; +import { createServer } from 'node:http'; +import { basename, join } from 'node:path'; +import { startDaemon, openUi, api, launchBrowser, repoRoot } from '../harness.mjs'; + +function workspaceRef(root) { + return `workspace-${createHash('sha256').update(root).digest('hex').slice(0, 12)}`; +} + +async function startFakeCore(grantedRoot) { + const ref = workspaceRef(grantedRoot); + const state = { + simulateDown: false, + goals: new Map(), + proposals: new Map(), + todoPreviews: new Map(), + seq: 0, + }; + + const readBody = async (req) => { + const chunks = []; + for await (const c of req) chunks.push(c); + if (!chunks.length) return {}; + return JSON.parse(Buffer.concat(chunks).toString('utf8')); + }; + + const makeTodoGroup = (list) => { + const done = list.filter((x) => x.status === 'done').length; + return { + items: list, + total_count: list.length, + open_count: list.length - done, + done_count: done, + }; + }; + + const buildStatusPayload = (goalFilter) => { + const goalsList = [...state.goals.values()].map((g) => ({ + id: g.goalId, + goal_id: g.goalId, + parent_id: null, + display_name: g.title, + title: g.title, + objective: g.objective, + status: g.status, + registry_member: true, + activation_state: 'active', + lifecycle_phase: 'executing', + updated_at: g.updatedAt, + agents: [g.agentId], + })); + const attention = [...state.goals.values()] + .filter((g) => !goalFilter || g.goalId === goalFilter) + .map((g) => ({ + goal_id: g.goalId, + status: g.status, + waiting_on: null, + severity: null, + recommended_action: `按当前授权推进 ${g.title}`, + next_action: `按当前授权推进 ${g.title}`, + goal_channel_projection: { display_name: g.title }, + top_todo: g.todos.agent[0] ? { text: g.todos.agent[0].text, priority: g.todos.agent[0].priority, claimed_by: null, updated_at: g.updatedAt } : null, + last_activity_at: g.updatedAt, + user_todos: makeTodoGroup(g.todos.user), + agent_todos: makeTodoGroup(g.todos.agent), + })); + return { + served_at: new Date().toISOString(), + ...(goalFilter ? { goal_filter: goalFilter } : {}), + run_history: { goals: goalsList }, + attention_queue: { items: attention }, + notifications: [], + }; + }; + + const server = createServer(async (req, res) => { + const json = (status, body) => { + res.writeHead(status, { 'Content-Type': 'application/json; charset=utf-8' }).end(JSON.stringify(body)); + }; + if (state.simulateDown) { + return json(503, { error: 'synthetic core outage', error_code: 'loopx_core_unavailable' }); + } + const url = new URL(req.url ?? '/', 'http://127.0.0.1'); + const path = url.pathname; + + if (req.method === 'GET' && path === '/healthz') return json(200, { ok: true }); + if (req.method === 'GET' && path === '/api/chat/projects') { + return json(200, { projects: [{ title: basename(grantedRoot), goal_workspace_ref: ref }] }); + } + if (req.method === 'GET' && path === '/api/attached-sessions') return json(200, { bindings: [] }); + if (req.method === 'GET' && path === '/status.json') { + return json(200, buildStatusPayload(url.searchParams.get('goal_id'))); + } + if (req.method === 'GET' && path === '/api/actions') return json(200, { proposals: [] }); + const loadMatch = /^\/api\/actions\/([^/]+)$/.exec(path); + if (req.method === 'GET' && loadMatch) { + const proposal = state.proposals.get(decodeURIComponent(loadMatch[1])); + return proposal ? json(200, { proposal }) : json(404, { error: 'proposal_not_found' }); + } + if (req.method === 'POST' && path === '/api/actions/preview') { + const body = await readBody(req); + const params = body.normalized_parameters ?? {}; + const proposalId = `prop_${++state.seq}`; + const now = new Date().toISOString(); + const proposal = { + proposal_id: proposalId, + action_kind: body.action_kind ?? 'goal.create', + status: 'preview_ready', + summary: body.summary ?? params.title ?? 'Create Goal', + normalized_parameters: params, + available_transitions: ['apply', 'cancel'], + created_at: now, + updated_at: now, + }; + state.proposals.set(proposalId, proposal); + return json(200, { proposal }); + } + const applyMatch = /^\/api\/actions\/([^/]+)\/apply$/.exec(path); + if (req.method === 'POST' && applyMatch) { + const proposalId = decodeURIComponent(applyMatch[1]); + const proposal = state.proposals.get(proposalId); + if (!proposal) return json(404, { error: 'proposal_not_found' }); + const p = proposal.normalized_parameters ?? {}; + const goalId = String(p.goal_id ?? `goal_${++state.seq}`); + const now = new Date().toISOString(); + const initialTodos = Array.isArray(p.initial_todos) ? p.initial_todos : []; + state.goals.set(goalId, { + goalId, + title: String(p.title ?? goalId), + objective: String(p.objective ?? ''), + status: 'running', + workspace: String(p.workspace_path ?? grantedRoot), + agentId: String(p.agent_id ?? 'claude-code'), + updatedAt: now, + todos: { + user: [], + agent: initialTodos.map((text, idx) => ({ + todo_id: `todo_${goalId}_init_${idx + 1}`, + goal_id: goalId, + role: 'agent', + text: String(text), + title: String(text), + status: 'open', + priority: null, + claimed_by: null, + updated_at: now, + })), + }, + }); + proposal.status = 'applied'; + proposal.updated_at = now; + proposal.receipt = { + outcome: 'goal_created', + resource_ids: { goal_id: goalId, managed_agent_id: null, goal_instance_id: null }, + }; + return json(200, { proposal, turn: null }); + } + if (req.method === 'POST' && path === '/api/chat/todo/dry-run') { + const body = await readBody(req); + const goal = state.goals.get(body.goal_id); + if (!goal) return json(404, { error: 'goal_not_found' }); + const previewId = `prev_${++state.seq}`; + const role = body.role === 'user' ? 'user' : 'agent'; + const item = { + goal_id: goal.goalId, + todo_id: `todo_${++state.seq}`, + text: String(body.text ?? '').trim(), + title: String(body.text ?? '').trim(), + role, + status: 'open', + priority: body.priority ?? null, + claimed_by: body.claimed_by ?? null, + updated_at: new Date().toISOString(), + }; + state.todoPreviews.set(previewId, item); + return json(200, { ok: true, dry_run: true, applied: false, added: true, already_exists: false, preview_id: previewId, todo: item }); + } + if (req.method === 'POST' && path === '/api/chat/todo/apply') { + const body = await readBody(req); + const goal = state.goals.get(body.goal_id); + if (!goal) return json(404, { error: 'goal_not_found' }); + const item = state.todoPreviews.get(body.preview_id) ?? { + goal_id: goal.goalId, + todo_id: `todo_${++state.seq}`, + text: String(body.text ?? '').trim(), + title: String(body.text ?? '').trim(), + role: body.role === 'user' ? 'user' : 'agent', + status: 'open', + priority: body.priority ?? null, + claimed_by: body.claimed_by ?? null, + updated_at: new Date().toISOString(), + }; + goal.todos[item.role].push(item); + goal.updatedAt = new Date().toISOString(); + return json(200, { ok: true, dry_run: false, applied: true, added: true, already_exists: false, preview_id: body.preview_id ?? null, todo: item, receipt: { ok: true } }); + } + return json(404, { error: `unhandled fake core path: ${req.method} ${path}` }); + }); + + await new Promise((r) => server.listen(0, '127.0.0.1', () => r())); + const { port } = server.address(); + return { + url: `http://127.0.0.1:${port}`, + state, + close: () => new Promise((r) => server.close(() => r())), + }; +} + +let fakeCore; +let daemon; +let browser; +let page; +const shotDir = process.env.E2E_SHOT_DIR || ''; + +before(async () => { + const workdir = join('/tmp', `loochat-main-e2e-${Date.now()}`); + mkdirSync(workdir, { recursive: true }); + fakeCore = await startFakeCore(workdir); + const fakeLoopxCli = join(workdir, '.fake-loopx-cli.mjs'); + writeFileSync( + fakeLoopxCli, + `#!/usr/bin/env node +const args = process.argv.slice(2); +const goalIdx = args.indexOf('--goal-id'); +const goalId = goalIdx >= 0 ? args[goalIdx + 1] : ''; +const url = '${fakeCore.url}/status.json' + (goalId ? '?goal_id=' + encodeURIComponent(goalId) : ''); +const res = await fetch(url); +const text = await res.text(); +if (!res.ok) { process.stderr.write(text); process.exit(1); } +process.stdout.write(text); +`, + { mode: 0o755 }, + ); + const fakeAcpPath = join(repoRoot, 'daemon', 'test', 'fixtures', 'fake-acp.mjs'); + // Natural-language test-double wrapper around real fake-acp.mjs so real ACP/socket/approval/supervision + // flows run unchanged while synthetic screenshots show realistic Chinese chat & task summaries instead of raw fixture echoes/UUIDs. + const naturalAcpShim = join(workdir, '.natural-acp-shim.mjs'); + writeFileSync( + naturalAcpShim, + `#!/usr/bin/env node +import { spawn } from 'node:child_process'; +import { createInterface } from 'node:readline'; + +const child = spawn(process.execPath, [${JSON.stringify(fakeAcpPath)}, ...process.argv.slice(2)], { + stdio: ['pipe', 'pipe', 'inherit'], + env: process.env, +}); + +const rewritePrompt = (text) => { + if (typeof text !== 'string') return text; + if (text.includes('请帮我派一个子 Agent 做接口时延巡检')) { + return 'model-dispatch claude 接口时延巡检 | 检查支付接口时延与异常率'; + } + if (text.includes('Task: 核对风控依赖安装') && !text.includes('approve')) { + return text + '\\napprove'; + } + if (text.includes('Task: 整理本周核心看板口径') && !text.includes('slow')) { + return text + '\\nslow'; + } + return text; +}; + +const rewriteReply = (text) => { + if (typeof text !== 'string') return text; + if (text.startsWith('dispatched:task_')) { + return '已为你派出「接口时延巡检」子任务,结果与审批会直接回到当前 loop。'; + } + if (text === 'approved:allow') { + return '已按批准结果完成风控依赖安装与回归校验。'; + } + if (text.startsWith('echo:开始推进 Goal')) { + return '已收到目标,先核对边界与现有待办,再拆分核查子任务并回报进展。'; + } + if (text.startsWith('echo:汇总当前风控依赖与接口时延核查进展')) { + return '风控依赖安装已验收完成;接口时延巡检已完成首轮核查,正等待最终确认。'; + } + if (text.startsWith('echo:')) { + return '已收到:' + text.slice(5); + } + return text; +}; + +const inRl = createInterface({ input: process.stdin }); +inRl.on('line', (line) => { + try { + const msg = JSON.parse(line); + if (msg?.method === 'session/prompt' && Array.isArray(msg?.params?.prompt)) { + msg.params.prompt = msg.params.prompt.map((part) => + part?.type === 'text' ? { ...part, text: rewritePrompt(part.text) } : part, + ); + child.stdin.write(JSON.stringify(msg) + '\\n'); + return; + } + } catch {} + child.stdin.write(line + '\\n'); +}); +inRl.on('close', () => child.stdin.end()); + +const outRl = createInterface({ input: child.stdout }); +outRl.on('line', (line) => { + try { + const msg = JSON.parse(line); + const update = msg?.params?.update; + if (update?.sessionUpdate === 'agent_message_chunk' && update?.content?.type === 'text') { + update.content.text = rewriteReply(update.content.text); + process.stdout.write(JSON.stringify(msg) + '\\n'); + return; + } + } catch {} + process.stdout.write(line + '\\n'); +}); +child.on('exit', (code) => process.exit(code ?? 0)); +`, + { mode: 0o755 }, + ); + daemon = await startDaemon( + { + LOOCHAT_LOOPX_CORE_URL: fakeCore.url, + LOOCHAT_LOOPX_CMD: `${process.execPath} ${fakeLoopxCli}`, + LOOCHAT_CLAUDE_ACP_BIN: naturalAcpShim, + FAKE_ACP_VISIBLE_ECHO: '1', + }, + { workdir }, + ); + browser = await launchBrowser(); + const ctx = await browser.newContext({ viewport: { width: 1280, height: 900 } }); + page = await ctx.newPage(); + if (shotDir) mkdirSync(shotDir, { recursive: true }); +}); + +after(async () => { + await browser?.close(); + await daemon?.stop(); + await fakeCore?.close(); +}); + +async function snap(name, targetPage = page) { + if (!shotDir) return; + await targetPage.screenshot({ path: join(shotDir, `${name}.png`), fullPage: false }); +} + +async function pickFromNewMenu(targetPage, sidebar, label) { + await sidebar.getByRole('button', { name: '新建', exact: true }).click(); + await targetPage.getByRole('menuitem', { name: label, exact: true }).waitFor({ timeout: 5_000 }); + await targetPage.getByRole('menuitem', { name: label, exact: true }).click(); +} + +test('full loop journey: lowercase loop UI, scoped per-loop supervision (no global UI tick), clean readable cards, UI cleanup, approvals, dispatch, todos, A/B isolation', async () => { + // Track every UI-originated POST /api/steward/supervision/tick request to guarantee local UI NEVER triggers instance-wide tick! + let uiTickRequests = 0; + page.on('request', (req) => { + if (req.method() === 'POST' && req.url().includes('/api/steward/supervision/tick')) { + uiTickRequests += 1; + } + }); + + await openUi(page, daemon); + const sidebar = page.locator('.sidebar'); + const newBtn = sidebar.getByRole('button', { name: '新建', exact: true }); + await newBtn.waitFor({ timeout: 10_000 }); + + // Requirement #6d: top-left LoopX brand icon is softened without altering other chrome. + const brandOpacity = await page.locator('.sidebar-top .brand .brand-icon.loo-light').evaluate((el) => Number(getComputedStyle(el).opacity)); + assert.ok(brandOpacity > 0.5 && brandOpacity < 0.9, `expected softened top-left brand icon opacity, got ${brandOpacity}`); + + // 1. Unified single top-bar 新建 entry (menu keyboard & close check), legacy LoopX 管家 intact, old retired, empty sections placeholder omitted. + assert.equal(await sidebar.getByRole('button', { name: 'LoopX 管家', exact: true }).isVisible(), true); + assert.equal(await sidebar.locator('.side-nav').getByRole('button', { name: '新 loop', exact: true }).count(), 0, 'no permanent 新 loop row in side-nav'); + assert.equal(await sidebar.locator('.side-nav').getByRole('button', { name: '新对话', exact: true }).count(), 0, 'no permanent 新对话 row in side-nav'); + assert.equal(await sidebar.getByText('还没有分区。').count(), 0, 'empty sections placeholder must be collapsed/omitted'); + assert.equal(await page.locator('.composer-loopx').count(), 0, 'manual LoopxToggle must be removed'); + + // Verify unified 新建 menu opens with both items, ArrowDown moves focus, Escape closes menu & restores focus to 新建! + await newBtn.click(); + await page.getByRole('menuitem', { name: '新 loop', exact: true }).waitFor({ timeout: 5_000 }); + await page.getByRole('menuitem', { name: '新对话', exact: true }).waitFor({ timeout: 5_000 }); + await page.keyboard.press('ArrowDown'); + const focusedMenuLabel = await page.evaluate(() => document.activeElement?.textContent?.trim() ?? ''); + assert.equal(focusedMenuLabel, '新对话', 'ArrowDown must move focus to second create item'); + await page.keyboard.press('Escape'); + await page.getByRole('menu', { name: '新建' }).waitFor({ state: 'detached', timeout: 5_000 }); + const restoredFocusLabel = await page.evaluate(() => document.activeElement?.getAttribute('aria-label') ?? ''); + assert.equal(restoredFocusLabel, '新建', 'Escape must close create menu and restore focus to 新建'); + + // 2. Open 「新 loop」 via unified 新建 menu and verify Core failure shows original error without silent downgrade. + await pickFromNewMenu(page, sidebar, '新 loop'); + await page.locator('.topbar-title').filter({ hasText: '新 loop' }).waitFor({ timeout: 5_000 }); + await page.locator('.composer-goal-permission').waitFor({ timeout: 5_000 }); + + fakeCore.state.simulateDown = true; + await page.locator('.composer textarea').fill('Core 离线防降级校验'); + await page.locator('.composer textarea').press('Enter'); + const confirmDialog = page.locator('.goal-confirm'); + await confirmDialog.waitFor({ timeout: 10_000 }); + await confirmDialog.locator('.goal-confirm-error').waitFor({ timeout: 10_000 }); + const threadsAfterOutage = await (await api(daemon, '/api/threads')).json(); + assert.equal(threadsAfterOutage.length, 0, 'must NOT silently downgrade to ordinary chat on Core failure'); + await confirmDialog.getByRole('button', { name: '取消' }).click(); + await confirmDialog.waitFor({ state: 'detached', timeout: 5_000 }); + fakeCore.state.simulateDown = false; + + // 3. Create Loop A through real launch/preview -> GoalConfirm -> launch/apply. + await page.locator('.composer textarea').fill('支付风控校验'); + await page.locator('.composer textarea').press('Enter'); + await confirmDialog.waitFor({ timeout: 10_000 }); + await confirmDialog.locator('.goal-confirm-note.ok').waitFor({ timeout: 10_000 }); + await confirmDialog.getByRole('button', { name: '创建 Goal 并开始' }).click(); + await confirmDialog.waitFor({ state: 'detached', timeout: 10_000 }); + + const dock = page.locator('.main-dock'); + await dock.waitFor({ timeout: 10_000 }); + const goalIdA = await dock.getAttribute('data-goal-id'); + const threadIdA = await dock.getAttribute('data-thread-id'); + assert.ok(goalIdA && threadIdA, `expected real goalIdA & threadIdA, got ${goalIdA} / ${threadIdA}`); + assert.ok(fakeCore.state.goals.has(goalIdA), 'goalIdA must exist in Core'); + + // Verify sidebar deduplicates equal goalTitle subtitle under thread title! + const rowAGoalSubCount = await sidebar.locator(`[data-thread-id="${threadIdA}"] .thread-sub-goal`).count(); + assert.equal(rowAGoalSubCount, 0, 'sidebar subtitle must not duplicate thread title when equal to goalTitle'); + + // Requirement #6c: duplicate title beside composer must NOT exist. + assert.equal(await page.locator('.main-dock-goal-tag').count(), 0, 'duplicate composer goal title must be removed'); + + // Requirement #5: top 「帮我督办」 bar is visible above the loop conversation and honestly reports global OFF. + const superviseBar = page.getByTestId('loop-supervise-bar'); + await superviseBar.waitFor({ timeout: 5_000 }); + assert.equal(await superviseBar.getAttribute('data-global-supervision'), 'off'); + + // 4. Create Loop B via unified 新建 -> 「新 loop」 AND dispatch one UNGRANTED task in Loop B to test strict A/B supervision isolation. + await pickFromNewMenu(page, sidebar, '新 loop'); + await page.locator('.composer textarea').fill('周报指标核对'); + await page.locator('.composer textarea').press('Enter'); + await confirmDialog.waitFor({ timeout: 10_000 }); + await confirmDialog.locator('.goal-confirm-note.ok').waitFor({ timeout: 10_000 }); + await confirmDialog.getByRole('button', { name: '创建 Goal 并开始' }).click(); + await confirmDialog.waitFor({ state: 'detached', timeout: 10_000 }); + await page.waitForFunction((prev) => document.querySelector('.main-dock')?.getAttribute('data-goal-id') !== prev, goalIdA); + const goalIdB = await dock.getAttribute('data-goal-id'); + const threadIdB = await dock.getAttribute('data-thread-id'); + assert.ok(goalIdB && goalIdB !== goalIdA); + assert.ok(threadIdB && threadIdB !== threadIdA); + + // Dispatch an ungranted subtask in Loop B (must NEVER be granted or forced by Loop A's supervision actions!). + await page.getByTestId('main-dock-tab-dispatch').click(); + await page.getByTestId('main-dock-toggle-dispatch-form').click(); + const dispatchTrayB = page.getByTestId('main-dock-tray-dispatch'); + await dispatchTrayB.getByLabel('目标 Agent').selectOption('claude'); + await dispatchTrayB.getByLabel('子任务权限').selectOption('read_only'); + await dispatchTrayB.locator('.main-dock-input').fill('整理本周核心看板口径'); + await dispatchTrayB.locator('.main-dock-submit').click(); + const taskRowB = dispatchTrayB.locator('.main-dock-task-row').first(); + await taskRowB.waitFor({ timeout: 10_000 }); + const taskIdB = await taskRowB.getAttribute('data-task-id'); + assert.ok(taskIdB, 'expected taskIdB in Loop B'); + await page.locator('.main-dock-close').click(); + + // 5. Create legacy ordinary conversation via unified 新建 -> 「新对话」. + await pickFromNewMenu(page, sidebar, '新对话'); + await page.locator('.composer textarea').fill('普通会话兼容验证'); + await page.locator('.composer textarea').press('Enter'); + await page.getByText('已收到:普通会话兼容验证').waitFor({ timeout: 15_000 }); + assert.equal(await page.locator('.main-dock').count(), 0, 'ordinary thread must NOT mount MainConversationDock'); + assert.equal(await page.getByTestId('loop-supervise-bar').count(), 0, 'ordinary thread must NOT mount LoopSupervisionBar'); + + // 6. Test on-demand 3-way sidebar filter (全部 / loop / 普通) + active clear chip + reload persistence. + const filterToggle = sidebar.getByTestId('sidebar-kind-filter-toggle'); + const filterGroup = sidebar.locator('.sidebar-kind-filter'); + assert.equal(await filterGroup.count(), 0, 'kind filter pills must be collapsed by default'); + await filterToggle.click(); + await filterGroup.waitFor({ timeout: 5_000 }); + await filterGroup.locator('.sidebar-kind-pill', { hasText: 'loop' }).click(); + assert.equal(await sidebar.locator(`[data-thread-id="${threadIdA}"]`).count(), 1); + assert.equal(await sidebar.locator(`[data-thread-id="${threadIdB}"]`).count(), 1); + assert.equal(await sidebar.locator('.thread-title', { hasText: '普通会话兼容验证' }).count(), 0); + // Collapsing filter bar while filtered retains one-click clear chip 「仅 loop ×」. + await filterToggle.click(); + await sidebar.getByTestId('sidebar-kind-active-chip').waitFor({ timeout: 5_000 }); + + await page.reload(); + await sidebar.locator(`[data-thread-id="${threadIdA}"]`).waitFor({ timeout: 10_000 }); + assert.equal(await sidebar.locator('.thread-title', { hasText: '普通会话兼容验证' }).count(), 0); + await sidebar.getByTestId('sidebar-kind-active-chip').waitFor({ timeout: 5_000 }); + + await filterToggle.click(); + await filterGroup.locator('.sidebar-kind-pill', { hasText: '普通' }).click(); + await sidebar.locator('.thread-title', { hasText: '普通会话兼容验证' }).waitFor({ timeout: 5_000 }); + assert.equal(await sidebar.locator(`[data-thread-id="${threadIdA}"]`).count(), 0); + + await filterGroup.locator('.sidebar-kind-pill', { hasText: '全部' }).click(); + await sidebar.locator(`[data-thread-id="${threadIdA}"]`).waitFor({ timeout: 5_000 }); + assert.equal(await filterGroup.count(), 0, 'choosing 全部 collapses the on-demand filter bar'); + + // 7. Inside Loop A, open 「进行中」 -> verify manual dispatch form is collapsed by default (Req #6b), expand & dispatch approval task. + await sidebar.locator(`[data-thread-id="${threadIdA}"] button.thread-item`).click(); + await page.waitForFunction((g) => document.querySelector('.main-dock')?.getAttribute('data-goal-id') === g, goalIdA); + + await page.getByTestId('main-dock-tab-dispatch').click(); + const dispatchTray = page.getByTestId('main-dock-tray-dispatch'); + await dispatchTray.waitFor({ timeout: 5_000 }); + assert.equal(await dispatchTray.getByTestId('main-dock-dispatch-form').count(), 0, 'manual dispatch form must be collapsed by default'); + + await page.getByTestId('main-dock-toggle-dispatch-form').click(); + await dispatchTray.getByTestId('main-dock-dispatch-form').waitFor({ timeout: 5_000 }); + await dispatchTray.getByLabel('目标 Agent').selectOption('claude'); + await dispatchTray.getByLabel('子任务权限').selectOption('ask'); + await dispatchTray.locator('.main-dock-input').fill('核对风控依赖安装'); + await dispatchTray.locator('.main-dock-submit').click(); + + const childRowA = dispatchTray.locator('.main-dock-task-row').first(); + await childRowA.waitFor({ timeout: 10_000 }); + const childThreadIdA = await childRowA.getAttribute('data-child-thread-id'); + const taskIdA1 = await childRowA.getAttribute('data-task-id'); + assert.ok(childThreadIdA && taskIdA1, 'expected spawned childThreadIdA & taskIdA1'); + + // Wait for child's permission request to surface in BOTH inline task card and single-button approval banner (Req #6a). + const banner = page.getByTestId('main-dock-approval-banner'); + await banner.waitFor({ timeout: 15_000 }); + assert.equal(await banner.locator('button').count(), 1, 'approval banner must have a single deduplicated button'); + const inlineCardA = page.locator(`[data-testid="loop-inline-task-card"][data-child-thread-id="${childThreadIdA}"]`); + await inlineCardA.waitFor({ timeout: 10_000 }); + await page.waitForFunction( + (tid) => document.querySelector(`[data-testid="loop-inline-task-card"][data-child-thread-id="${tid}"]`)?.getAttribute('data-task-state') === 'waiting', + childThreadIdA, + { timeout: 10_000 }, + ); + + // Requirement #5: clicking top 「帮我督办」 while an approval is pending records grant ONLY for Loop A, pauses before approval, keeps global switch OFF, and NEVER calls global tick! + await page.getByTestId('loop-supervise-btn').click(); + const supReceipt = page.getByTestId('loop-supervise-receipt'); + await supReceipt.waitFor({ timeout: 10_000 }); + assert.equal(await supReceipt.getAttribute('data-source'), 'top_bar'); + assert.ok((await supReceipt.innerText()).includes('督办已停在审批前')); + assert.equal(uiTickRequests, 0, 'UI must NEVER call instance-wide POST /api/steward/supervision/tick'); + const supStatusAfterClick = await (await api(daemon, '/api/steward/supervision')).json(); + assert.equal(supStatusAfterClick.enabled, false, 'clicking top supervise must NEVER flip global switch'); + assert.deepEqual(supStatusAfterClick.activeGrants.map((g) => g.taskId), [taskIdA1], 'grant must be strictly scoped to Loop A, never Loop B'); + + const bodyText = await page.locator('main.main').innerText(); + assert.ok(!bodyText.includes(''), 'visible conversation must not contain raw protocol tags'); + assert.ok(!bodyText.includes('goal_not_found'), 'visible Goal card must not show goal_not_found when Core status is available'); + + // Real-data sidebar status grouping: ALL THREE groups visible simultaneously in a real populated state: + // 要你处理 (Loop A waiting approval) + 进行中 (Loop B running read-only subtask) + 最近 (ordinary chat under its real project with "+")! + await sidebar.locator('[data-status-group="need"]').locator(`[data-thread-id="${threadIdA}"]`).waitFor({ timeout: 10_000 }); + await sidebar.locator('[data-status-group="working"]').locator(`[data-thread-id="${threadIdB}"]`).waitFor({ timeout: 10_000 }); + const recentGroup = sidebar.locator('[data-status-group="recent"]'); + await recentGroup.locator('.thread-title', { hasText: '普通会话兼容验证' }).waitFor({ timeout: 10_000 }); + assert.ok(await recentGroup.locator('.group-name').count() >= 1, 'Recent group must preserve real project name'); + assert.ok(await recentGroup.locator('.group-add').count() >= 1, 'Recent group must preserve project + action'); + // Verify empty-group omission dynamically via kind filter: loop-only hides empty 最近, ordinary-only hides empty 要你处理 & 进行中. + await filterToggle.click(); + await filterGroup.locator('.sidebar-kind-pill', { hasText: 'loop' }).click(); + assert.equal(await sidebar.locator('[data-status-group="recent"]').count(), 0, 'empty 最近 group must be omitted when only urgent loops match'); + await filterGroup.locator('.sidebar-kind-pill', { hasText: '普通' }).click(); + assert.equal(await sidebar.locator('[data-status-group="need"]').count(), 0, 'empty 要你处理 group must be omitted when only recent chats match'); + assert.equal(await sidebar.locator('[data-status-group="working"]').count(), 0, 'empty 进行中 group must be omitted when only recent chats match'); + assert.equal(await sidebar.locator('[data-status-group="recent"]').count(), 1, '最近 group remains visible for ordinary chat'); + await filterGroup.locator('.sidebar-kind-pill', { hasText: '全部' }).click(); + await sidebar.locator('[data-status-group="need"]').waitFor({ timeout: 5_000 }); + await sidebar.locator('[data-status-group="working"]').waitFor({ timeout: 5_000 }); + await sidebar.locator('[data-status-group="recent"]').waitFor({ timeout: 5_000 }); + // Verify LoopX 管家 label in .side-modes-row is not truncated even with the orange attention dot on desktop. + const modesNotTruncated = await sidebar.locator('.side-mode-btn span:not(.side-mode-dot)').evaluateAll((els) => + els.every((el) => el.scrollWidth <= el.clientWidth + 1), + ); + assert.equal(modesNotTruncated, true, 'sidebar mode labels (LoopX 管家 / 看板) must not truncate on desktop'); + + // Close open trays to capture clean populated desktop state (light & dark) and assert Neon Plan A Mist Blue + zero borders/hairlines + semantic colors. + await page.getByTestId('loop-supervise-toggle').click(); + await page.getByTestId('main-dock-tray-approvals').waitFor({ timeout: 5_000 }); + await page.locator('.main-dock-close').click(); + await banner.waitFor({ timeout: 5_000 }); + await page.waitForTimeout(220); + const lightColors = await page.evaluate(() => { + const probe = (expr) => { + const el = document.createElement('span'); + el.style.color = expr; + document.body.appendChild(el); + const val = getComputedStyle(el).color; + el.remove(); + return val; + }; + const capsules = [...document.querySelectorAll('.main-dock-capsule')]; + const attCap = document.querySelector('[data-testid="main-dock-tab-approvals"]'); + const inlineCard = document.querySelector('.loop-inline-task-card.is-waiting'); + const dockAlert = document.querySelector('[data-testid="main-dock-approval-banner"]'); + return { + warnToken: probe('var(--warn)'), + mutedToken: probe('var(--muted)'), + mistBgToken: probe('var(--loop-pill-mist-bg)'), + mistFgToken: probe('var(--loop-pill-mist-fg)'), + mistDotToken: probe('var(--loop-pill-mist-dot)'), + mistSurfaceToken: probe('color-mix(in srgb, var(--loop-pill-mist-bg) 55%, var(--bg))'), + dockBorderTop: getComputedStyle(document.querySelector('.main-dock')).borderTopWidth, + stripBorderTop: getComputedStyle(document.querySelector('.main-dock-strip')).borderTopWidth, + capsBorderTop: getComputedStyle(document.querySelector('.main-dock-capsules')).borderTopWidth, + anyCapsuleBorder: capsules.some((el) => getComputedStyle(el).borderTopWidth !== '0px' || getComputedStyle(el).borderLeftWidth !== '0px'), + attCapBg: getComputedStyle(attCap).backgroundColor, + attCapFg: getComputedStyle(attCap).color, + inlineCardBorder: getComputedStyle(inlineCard).borderTopWidth, + superviseWaitingDot: getComputedStyle(document.querySelector('.loop-supervise-dot.is-waiting')).backgroundColor, + inlineWaitingDot: getComputedStyle(inlineCard.querySelector('.loop-inline-task-dot.is-waiting')).backgroundColor, + inlineWaitingText: getComputedStyle(inlineCard.querySelector('.loop-inline-task-status.is-waiting')).color, + inlineWaitingArrow: getComputedStyle(inlineCard.querySelector('.loop-inline-task-arrow')).color, + inlineWaitingSupNote: getComputedStyle(inlineCard.querySelector('.loop-inline-task-sup-note')).color, + dockAlertBg: getComputedStyle(dockAlert).backgroundColor, + dockAlertDot: getComputedStyle(document.querySelector('.main-dock-alert-dot')).backgroundColor, + inlineCardBg: getComputedStyle(inlineCard).backgroundColor, + }; + }); + assert.equal(lightColors.dockBorderTop, '0px', 'bottom dock must have no top hairline'); + assert.equal(lightColors.stripBorderTop, '0px', 'dock strip must have no top hairline'); + assert.equal(lightColors.capsBorderTop, '0px', 'dock capsules must have no top hairline'); + assert.equal(lightColors.anyCapsuleBorder, false, 'dock capsules must have no persistent border'); + assert.equal(lightColors.attCapBg, lightColors.mistBgToken, 'light attention capsule must use Mist Blue bg'); + assert.equal(lightColors.attCapFg, lightColors.mistFgToken, 'light attention capsule must use Mist Blue fg'); + assert.equal(lightColors.inlineCardBorder, '0px', 'inline task row must be frameless'); + assert.equal(lightColors.superviseWaitingDot, lightColors.warnToken, 'top bar waiting dot must resolve to --warn'); + assert.equal(lightColors.inlineCardBg, lightColors.mistSurfaceToken, 'light waiting card must use lighter Mist Blue surface'); + assert.equal(lightColors.dockAlertBg, lightColors.inlineCardBg, 'light approval banner must share Mist Blue waiting surface'); + assert.notEqual(lightColors.inlineCardBg, lightColors.attCapBg, 'light waiting surfaces must stay lighter than Mist Blue capsule'); + assert.equal(lightColors.inlineWaitingDot, lightColors.mistDotToken, 'light waiting dot must use Mist Blue dot token'); + assert.equal(lightColors.inlineWaitingText, lightColors.mistFgToken, 'light waiting status must use Mist Blue fg token'); + assert.equal(lightColors.inlineWaitingArrow, lightColors.mistDotToken, 'light waiting arrow must use Mist Blue dot token'); + assert.equal(lightColors.dockAlertDot, lightColors.mistDotToken, 'light dock alert dot must use Mist Blue dot token'); + assert.equal(lightColors.inlineWaitingSupNote, lightColors.mutedToken, 'light waiting supervised note must use neutral muted text'); + await snap('01-desktop-light-loop-a-supervise-cards'); + + // Verify Mist Blue selected capsule + separate keyboard focus ring (status text & focus separated). + await page.getByTestId('main-dock-tab-approvals').click(); + await page.getByTestId('main-dock-tray-approvals').waitFor({ timeout: 5_000 }); + await page.getByTestId('main-dock-tab-dispatch').focus(); + await page.waitForTimeout(220); + const focusCheck = await page.evaluate(() => { + const probe = (expr) => { + const el = document.createElement('span'); + el.style.color = expr; + document.body.appendChild(el); + const val = getComputedStyle(el).color; + el.remove(); + return val; + }; + const activeCap = document.querySelector('[data-testid="main-dock-tab-approvals"]'); + return { + mistOnBgToken: probe('var(--loop-pill-mist-on-bg)'), + mistOnFgToken: probe('var(--loop-pill-mist-on-fg)'), + kbdFocusToken: probe('var(--loop-kbd-focus)'), + activeCapBg: getComputedStyle(activeCap).backgroundColor, + activeCapFg: getComputedStyle(activeCap).color, + activeCapBorder: getComputedStyle(activeCap).borderTopWidth, + }; + }); + assert.equal(focusCheck.activeCapBg, focusCheck.mistOnBgToken, 'selected capsule must use deeper Mist Blue'); + assert.equal(focusCheck.activeCapFg, focusCheck.mistOnFgToken, 'selected capsule text must use Mist Blue on-fg'); + assert.equal(focusCheck.activeCapBorder, '0px', 'selected capsule must remain borderless'); + assert.notEqual(focusCheck.kbdFocusToken, focusCheck.mistOnBgToken, 'keyboard focus ring token must stay independent of Mist Blue fill'); + await page.keyboard.press('Escape'); + await page.getByTestId('main-dock-tray-approvals').waitFor({ state: 'detached', timeout: 5_000 }); + + // Capture desktop unified 新建 menu + on-demand filter visual state before dark check, + // and verify Escape closes ONLY the topmost 新建 menu without collapsing the open filter bar. + await filterToggle.click(); + await filterGroup.waitFor({ timeout: 5_000 }); + await newBtn.click(); + await page.getByRole('menuitem', { name: '新 loop', exact: true }).waitFor({ timeout: 5_000 }); + await snap('01b-desktop-light-sidebar-menu-filter'); + await page.keyboard.press('Escape'); + await page.getByRole('menuitem', { name: '新 loop', exact: true }).waitFor({ state: 'detached', timeout: 5_000 }); + assert.equal(await filterGroup.count(), 1, 'Escape on 新建 menu must not simultaneously collapse the open filter bar'); + await page.keyboard.press('Escape'); + await filterGroup.waitFor({ state: 'detached', timeout: 5_000 }); + + // Capture mobile light (390x844) while Loop A has real waiting approval (Mist Blue attention + selected capsule) and sidebar shows all 3 groups! + if (shotDir) { + const mobileMistCtx = await browser.newContext({ viewport: { width: 390, height: 844 } }); + const mobileMistPage = await mobileMistCtx.newPage(); + try { + await openUi(mobileMistPage, daemon); + await mobileMistPage.locator('.menu-btn').click(); + await mobileMistPage.locator('[data-status-group="need"]').locator(`[data-thread-id="${threadIdA}"]`).waitFor({ timeout: 10_000 }); + await mobileMistPage.locator('[data-status-group="working"]').locator(`[data-thread-id="${threadIdB}"]`).waitFor({ timeout: 10_000 }); + await mobileMistPage.locator('[data-status-group="recent"]').waitFor({ timeout: 10_000 }); + await mobileMistPage.waitForTimeout(300); + await snap('04a-mobile-light-sidebar-3groups', mobileMistPage); + + await mobileMistPage.locator(`[data-thread-id="${threadIdA}"] button.thread-item`).click(); + await mobileMistPage.getByTestId('main-dock-approval-banner').waitFor({ timeout: 10_000 }); + await mobileMistPage.getByTestId('loop-inline-tasks').waitFor({ timeout: 5_000 }); + await mobileMistPage.evaluate(() => { + const scroller = document.querySelector('.scroller'); + if (scroller) scroller.scrollTop = scroller.scrollHeight; + }); + await mobileMistPage.waitForTimeout(260); + const mobileMistColors = await mobileMistPage.evaluate(() => { + const probe = (expr) => { + const el = document.createElement('span'); + el.style.color = expr; + document.body.appendChild(el); + const val = getComputedStyle(el).color; + el.remove(); + return val; + }; + const attCap = document.querySelector('[data-testid="main-dock-tab-approvals"]'); + const caps = [...document.querySelectorAll('.main-dock-capsule')]; + const ys = caps.map((el) => Math.round(el.getBoundingClientRect().top)); + return { + mistBgToken: probe('var(--loop-pill-mist-bg)'), + attCapBg: getComputedStyle(attCap).backgroundColor, + sameRow: ys.length === 4 && Math.max(...ys) - Math.min(...ys) <= 2, + anyBorder: caps.some((el) => getComputedStyle(el).borderTopWidth !== '0px'), + dockBorderTop: getComputedStyle(document.querySelector('.main-dock')).borderTopWidth, + }; + }); + assert.equal(mobileMistColors.attCapBg, mobileMistColors.mistBgToken, 'mobile light waiting capsule must use Mist Blue bg'); + assert.equal(mobileMistColors.sameRow, true, 'mobile waiting capsules must sit on one row'); + assert.equal(mobileMistColors.anyBorder, false, 'mobile waiting capsules must remain borderless'); + assert.equal(mobileMistColors.dockBorderTop, '0px', 'mobile waiting dock must have no top hairline'); + await snap('05a-mobile-light-loop-a-mist-attention', mobileMistPage); + + // Tap 「要你处理 1」 to verify selected deeper Mist Blue capsule on mobile too. + await mobileMistPage.getByTestId('main-dock-tab-approvals').click(); + await mobileMistPage.getByTestId('main-dock-tray-approvals').waitFor({ timeout: 5_000 }); + await mobileMistPage.waitForTimeout(220); + await snap('05b-mobile-light-loop-a-mist-selected', mobileMistPage); + } finally { + await mobileMistCtx.close(); + } + } + + await page.evaluate(() => document.documentElement.setAttribute('data-theme', 'dark')); + await page.waitForTimeout(220); + const darkColors = await page.evaluate(() => { + const probe = (expr) => { + const el = document.createElement('span'); + el.style.color = expr; + document.body.appendChild(el); + const val = getComputedStyle(el).color; + el.remove(); + return val; + }; + const capsules = [...document.querySelectorAll('.main-dock-capsule')]; + const attCap = document.querySelector('[data-testid="main-dock-tab-approvals"]'); + const inlineCard = document.querySelector('.loop-inline-task-card.is-waiting'); + const dockAlert = document.querySelector('[data-testid="main-dock-approval-banner"]'); + return { + warnToken: probe('var(--warn)'), + mutedToken: probe('var(--muted)'), + mistBgToken: probe('var(--loop-pill-mist-bg)'), + mistFgToken: probe('var(--loop-pill-mist-fg)'), + mistDotToken: probe('var(--loop-pill-mist-dot)'), + mistSurfaceToken: probe('color-mix(in srgb, var(--loop-pill-mist-bg) 55%, var(--bg))'), + dangerToken: probe('var(--danger)'), + positiveToken: probe('var(--positive)'), + loopxBlueToken: probe('var(--loopx-blue)'), + anyCapsuleBorder: capsules.some((el) => getComputedStyle(el).borderTopWidth !== '0px'), + attCapBg: getComputedStyle(attCap).backgroundColor, + attCapFg: getComputedStyle(attCap).color, + superviseWaitingDot: getComputedStyle(document.querySelector('.loop-supervise-dot.is-waiting')).backgroundColor, + inlineWaitingDot: getComputedStyle(inlineCard.querySelector('.loop-inline-task-dot.is-waiting')).backgroundColor, + inlineWaitingText: getComputedStyle(inlineCard.querySelector('.loop-inline-task-status.is-waiting')).color, + inlineWaitingArrow: getComputedStyle(inlineCard.querySelector('.loop-inline-task-arrow')).color, + inlineWaitingSupNote: getComputedStyle(inlineCard.querySelector('.loop-inline-task-sup-note')).color, + dockAlertBg: getComputedStyle(dockAlert).backgroundColor, + dockAlertDot: getComputedStyle(document.querySelector('.main-dock-alert-dot')).backgroundColor, + inlineCardBg: getComputedStyle(inlineCard).backgroundColor, + }; + }); + assert.equal(darkColors.anyCapsuleBorder, false, 'dark dock capsules must remain borderless'); + assert.equal(darkColors.attCapBg, darkColors.mistBgToken, 'dark attention capsule must use dark Mist Blue bg'); + assert.equal(darkColors.attCapFg, darkColors.mistFgToken, 'dark attention capsule must use dark Mist Blue fg'); + assert.equal(darkColors.superviseWaitingDot, darkColors.warnToken, 'dark top bar waiting dot must resolve to dark --warn'); + assert.equal(darkColors.inlineCardBg, darkColors.mistSurfaceToken, 'dark waiting card must use dark lighter Mist Blue surface'); + assert.equal(darkColors.dockAlertBg, darkColors.inlineCardBg, 'dark approval banner must share dark Mist Blue waiting surface'); + assert.notEqual(darkColors.inlineCardBg, darkColors.attCapBg, 'dark waiting surfaces must stay lighter than Mist Blue capsule'); + assert.equal(darkColors.inlineWaitingDot, darkColors.mistDotToken, 'dark waiting dot must use dark Mist Blue dot token'); + assert.equal(darkColors.inlineWaitingText, darkColors.mistFgToken, 'dark waiting status must use dark Mist Blue fg token'); + assert.equal(darkColors.inlineWaitingArrow, darkColors.mistDotToken, 'dark waiting arrow must use dark Mist Blue dot token'); + assert.equal(darkColors.dockAlertDot, darkColors.mistDotToken, 'dark dock alert dot must use dark Mist Blue dot token'); + assert.equal(darkColors.inlineWaitingSupNote, darkColors.mutedToken, 'dark waiting supervised note must use neutral muted text'); + assert.notEqual(darkColors.inlineCardBg, lightColors.inlineCardBg, 'dark inline card tint must differ from light tint'); + assert.equal(darkColors.dangerToken, 'rgb(249, 112, 102)'); + assert.equal(darkColors.positiveToken, 'rgb(63, 154, 114)'); + assert.equal(darkColors.loopxBlueToken, 'rgb(123, 151, 242)'); + await snap('02-desktop-dark-loop-a-supervise-cards'); + await page.evaluate(() => document.documentElement.removeAttribute('data-theme')); + + // 8. Verify cross-loop isolation: Loop B sees ZERO approvals, ZERO supervision grants/receipts from Loop A, and ONLY its own task! + await sidebar.locator(`[data-thread-id="${threadIdB}"] button.thread-item`).click(); + await page.waitForFunction((g) => document.querySelector('.main-dock')?.getAttribute('data-goal-id') === g, goalIdB); + await page.waitForTimeout(300); + assert.equal(await page.getByTestId('main-dock-approval-banner').count(), 0, 'Loop A approval must NOT leak to Loop B'); + assert.equal(await page.getByTestId('loop-supervise-receipt').count(), 0, 'Loop A supervision receipt must NOT leak to Loop B'); + assert.equal(await page.locator(`[data-testid="loop-inline-task-card"][data-task-id="${taskIdA1}"]`).count(), 0, 'Loop A task must NOT leak to Loop B'); + assert.equal(await page.locator(`[data-testid="loop-inline-task-card"][data-task-id="${taskIdB}"]`).count(), 1, 'Loop B keeps its own task'); + + // 9. Return to Loop A -> verify inline waiting card entry & banner 「去处理」 entry -> approve -> return via 「← loop · ...」! + await sidebar.locator(`[data-thread-id="${threadIdA}"] button.thread-item`).click(); + await banner.waitFor({ timeout: 10_000 }); + await inlineCardA.click(); + await page.locator('.action-sheet').waitFor({ timeout: 10_000 }); + await page.getByTestId('back-to-main-conversation').click(); + await page.waitForFunction((g) => document.querySelector('.main-dock')?.getAttribute('data-goal-id') === g, goalIdA); + await banner.waitFor({ timeout: 10_000 }); + await page.getByTestId('main-dock-banner-action').click(); + await page.getByTestId('main-dock-tray-approvals').waitFor({ timeout: 5_000 }); + await page.getByTestId('main-dock-open-approval-thread').first().click(); + + await page.locator('.action-sheet').waitFor({ timeout: 10_000 }); + await page.getByTestId('back-to-main-conversation').waitFor({ timeout: 5_000 }); + assert.ok((await page.getByTestId('back-to-main-conversation').innerText()).includes('loop ·')); + await page.locator('.action-sheet button.primary').click(); + await page.getByText('已按批准结果完成风控依赖安装与回归校验。').waitFor({ timeout: 15_000 }); + + await page.getByTestId('back-to-main-conversation').click(); + await page.waitForFunction((g) => document.querySelector('.main-dock')?.getAttribute('data-goal-id') === g, goalIdA); + await page.waitForFunction(() => document.querySelectorAll('[data-testid="main-dock-approval-banner"]').length === 0, { timeout: 10_000 }); + + // Writable child task enters real 「待验收」(reviewing) under 「进行中」 rather than faking auto-accept! + await page.getByTestId('main-dock-tab-dispatch').click(); + const reviewRowA = page.locator(`[data-testid="main-dock-tray-dispatch"] [data-child-thread-id="${childThreadIdA}"]`); + await reviewRowA.locator('.main-dock-task-summary', { hasText: '已按批准结果完成风控依赖安装与回归校验。' }).waitFor({ timeout: 10_000 }); + assert.equal(await reviewRowA.getAttribute('data-task-state'), 'reviewing'); + + // Explicit owner acceptance via real POST /api/steward/tasks/:id/review moves it to 「已完成」. + await reviewRowA.getByTestId('main-dock-accept-review').click(); + await page.getByTestId('main-dock-tab-done').click(); + await page.locator(`[data-testid="main-dock-tray-done"] [data-child-thread-id="${childThreadIdA}"] .main-dock-task-summary`, { hasText: '已按批准结果完成风控依赖安装与回归校验。' }).waitFor({ timeout: 10_000 }); + await page.locator('.main-dock-close').click(); + + // 10. Model-driven dispatch from Loop A via real LOOCHAT_MAIN_SOCKET + LOOCHAT_MAIN_TOKEN! + await page.locator('.composer textarea').fill('请帮我派一个子 Agent 做接口时延巡检'); + await page.locator('.composer textarea').press('Enter'); + await page.getByText('已为你派出「接口时延巡检」子任务,结果与审批会直接回到当前 loop。').waitFor({ timeout: 15_000 }); + const inlineModelCard = page.locator('[data-testid="loop-inline-task-card"]', { hasText: '接口时延巡检' }); + await inlineModelCard.waitFor({ timeout: 10_000 }); + const childThreadIdModel = await inlineModelCard.getAttribute('data-child-thread-id'); + const taskIdModel = await inlineModelCard.getAttribute('data-task-id'); + assert.ok(childThreadIdModel && taskIdModel && childThreadIdModel !== childThreadIdA); + + // If project memory carried the earlier approval title into the child prompt, approve inline cleanly. + await page.waitForTimeout(300); + const surfBeforeChatSup = await (await api(daemon, `/api/steward/surface?goalId=${encodeURIComponent(goalIdA)}&parentThreadId=${encodeURIComponent(threadIdA)}`)).json(); + if ((surfBeforeChatSup.inlineCards ?? []).some((c) => c.kind === 'thread_approval')) { + if (await page.getByTestId('main-dock-tray-approvals').count() === 0) { + await page.getByTestId('main-dock-tab-approvals').click(); + } + await page.getByTestId('main-dock-tray-approvals').getByRole('button', { name: 'Allow' }).first().click(); + await page.waitForFunction( + async () => document.querySelectorAll('[data-testid="main-dock-tray-approvals"] [data-approval-id]').length === 0, + { timeout: 10_000 }, + ); + await page.locator('.main-dock-close').click(); + } + + // 11. Requirement #5 (chat input 「帮我督办」 + real global switch OFF -> General Settings -> global ON -> controlled scheduler tick verifies Loop A advances & Loop B untouched!): + const beforeChatSuperviseMessages = await page.locator('.msg.user').count(); + await page.locator('.composer textarea').fill('帮我督办'); + await page.locator('.composer textarea').press('Enter'); + await page.waitForFunction( + () => document.querySelector('[data-testid="loop-supervise-receipt"]')?.getAttribute('data-source') === 'chat_input', + { timeout: 10_000 }, + ); + assert.equal(await page.locator('.msg.user').count(), beforeChatSuperviseMessages, 'chat 帮我督办 must NOT fake success with a plain chat turn'); + assert.equal(uiTickRequests, 0, 'chat 帮我督办 must NEVER call global tick'); + const chatReceiptText = await page.getByTestId('loop-supervise-receipt').innerText(); + assert.ok(chatReceiptText.includes('全局自动督办未开启'), `unexpected chat receipt: ${chatReceiptText}`); + // Numerator and denominator must use the exact same eligible task set (1 / 1, NEVER 2 / 1)! + assert.ok((await page.getByTestId('loop-supervise-scope-summary').innerText()).includes('1 / 1')); + + // Open real General Settings via panel link -> explicitly turn on 「管家自动督办」. + await page.getByTestId('loop-supervise-panel-settings').click(); + await page.getByText('管家自动督办').waitFor({ timeout: 5_000 }); + await page.getByRole('button', { name: '管家自动督办' }).click(); + await page.getByRole('menuitemradio', { name: '开启' }).click(); + await page.keyboard.press('Escape'); + await page.locator('.settings-back, .close-settings, button[aria-label="返回"], button[aria-label="关闭"]').first().click().catch(() => {}); + if (await page.getByTestId('loop-supervise-bar').count() === 0) { + await sidebar.locator(`[data-thread-id="${threadIdA}"] button.thread-item`).click(); + } + await page.waitForFunction( + () => document.querySelector('[data-testid="loop-supervise-bar"]')?.getAttribute('data-global-supervision') === 'on', + { timeout: 10_000 }, + ); + // Once global ON + 1/1 eligible granted, top bar replaces generic 「帮我督办」 CTA with active 「督办已生效」 button! + await page.getByTestId('loop-supervise-active-btn').waitFor({ timeout: 5_000 }); + assert.equal(await page.getByTestId('loop-supervise-btn').count(), 0, 'active loop should not keep generic 帮我督办 as primary CTA'); + + // Trigger chat 「帮我督办」 again (idempotent, still 0 UI global ticks!) -> confirms scoped active receipt. + await page.locator('.composer textarea').fill('帮我督办'); + await page.locator('.composer textarea').press('Enter'); + await page.waitForFunction( + () => document.querySelector('[data-testid="loop-supervise-receipt"]')?.textContent?.includes('1 / 1 项可督办子任务'), + { timeout: 10_000 }, + ); + assert.equal(uiTickRequests, 0, 'UI must STILL have 0 calls to global /api/steward/supervision/tick'); + + // Now simulate the native background scheduler via a test-controlled API tick: + // confirm ONLY Loop A's granted task (taskIdModel) is reviewed/tracked, while Loop B's ungranted task (taskIdB) has ZERO grants and ZERO forced supervision events! + const beforeTickStatus = await (await api(daemon, '/api/steward/supervision')).json(); + assert.equal(beforeTickStatus.activeGrants.some((g) => g.taskId === taskIdB), false, 'Loop B must NEVER receive a grant from Loop A'); + assert.equal(beforeTickStatus.activeGrants.some((g) => g.taskId === taskIdModel), true, 'Loop A task must hold active grant'); + + const controlledTick = await (await api(daemon, '/api/steward/supervision/tick', { method: 'POST', body: JSON.stringify({}) })).json(); + assert.ok(controlledTick.reviewsRun >= 1, `expected controlled scheduler tick to review granted Loop A task, got ${JSON.stringify(controlledTick)}`); + const afterTickStatus = await (await api(daemon, '/api/steward/supervision')).json(); + const loopAEvents = (afterTickStatus.recentEvents ?? []).filter((ev) => ev.taskId === taskIdModel); + const loopBEvents = (afterTickStatus.recentEvents ?? []).filter((ev) => ev.taskId === taskIdB); + assert.ok(loopAEvents.length > 0, 'expected per-task supervision events for Loop A granted task'); + assert.equal(loopBEvents.length, 0, 'Loop B ungranted task must have ZERO supervision events after scheduler tick'); + + // Verify raw closeout template text NEVER leaks onto visible task cards! + await page.reload(); + await sidebar.locator(`[data-thread-id="${threadIdA}"] button.thread-item`).click(); + await page.waitForFunction((g) => document.querySelector('.main-dock')?.getAttribute('data-goal-id') === g, goalIdA); + await page.getByTestId('loop-supervise-active-btn').click(); + await page.getByTestId('loop-supervise-panel').waitFor({ timeout: 5_000 }); + const visibleCardsText = await page.getByTestId('loop-inline-tasks').innerText(); + assert.ok(!visibleCardsText.includes('merged="yes|no|n/a"'), `closeout template leaked into inline cards: ${visibleCardsText}`); + assert.ok(!visibleCardsText.includes('dispatched:task_'), `raw dispatch UUID leaked into inline cards: ${visibleCardsText}`); + assert.ok((await page.getByTestId('loop-supervise-scope-summary').innerText()).includes('1 / 1')); + const activeColors = await page.evaluate(() => ({ + superviseActiveDot: getComputedStyle(document.querySelector('.loop-supervise-dot.is-active')).backgroundColor, + superviseActiveBtnText: getComputedStyle(document.querySelector('[data-testid="loop-supervise-active-btn"]')).color, + })); + assert.equal(activeColors.superviseActiveDot, 'rgb(47, 91, 211)'); + assert.equal(activeColors.superviseActiveBtnText, 'rgb(47, 91, 211)'); + await snap('03-desktop-light-loop-a-supervision-active'); + + // Revoke Loop A grants via explicit 「撤销本 loop 授权」 and confirm Loop A grants clear while global switch stays unchanged. + await page.getByTestId('loop-supervise-revoke-btn').click(); + await page.waitForFunction( + () => document.querySelector('[data-testid="loop-supervise-receipt"]')?.getAttribute('data-mode') === 'revoke', + { timeout: 10_000 }, + ); + const supStatusAfterRevoke = await (await api(daemon, '/api/steward/supervision')).json(); + assert.equal(supStatusAfterRevoke.enabled, true, 'revoking loop grant must not alter global switch'); + assert.equal(supStatusAfterRevoke.activeGrants.length, 0, 'Loop A grants must be revoked'); + + // 12. Persistent Core Goal todos directly under loop + reload + two-loop isolation! + await page.getByTestId('main-dock-tab-todos').click(); + const todosTray = page.getByTestId('main-dock-tray-todos'); + await todosTray.waitFor({ timeout: 5_000 }); + await todosTray.getByRole('button', { name: '新建任务' }).click(); + await todosTray.locator('textarea').fill('补齐支付风控回归单测'); + await todosTray.getByRole('button', { name: '预览创建' }).click(); + await todosTray.getByRole('button', { name: '确认创建' }).click(); + await todosTray.getByRole('button', { name: '确认创建' }).waitFor({ state: 'detached', timeout: 10_000 }); + await todosTray.getByText('补齐支付风控回归单测').first().waitFor({ timeout: 10_000 }); + + await sidebar.locator(`[data-thread-id="${threadIdB}"] button.thread-item`).click(); + await page.waitForFunction((g) => document.querySelector('.main-dock')?.getAttribute('data-goal-id') === g, goalIdB); + await todosTray.waitFor({ timeout: 5_000 }); + await page.waitForTimeout(300); + assert.equal(await todosTray.getByText('补齐支付风控回归单测').count(), 0); + await todosTray.getByRole('button', { name: '新建任务' }).click(); + await todosTray.locator('textarea').fill('核对周报指标数据源'); + await todosTray.getByRole('button', { name: '预览创建' }).click(); + await todosTray.getByRole('button', { name: '确认创建' }).click(); + await todosTray.getByRole('button', { name: '确认创建' }).waitFor({ state: 'detached', timeout: 10_000 }); + await todosTray.getByText('核对周报指标数据源').first().waitFor({ timeout: 10_000 }); + + await page.reload(); + await sidebar.locator(`[data-thread-id="${threadIdA}"] button.thread-item`).click(); + await page.waitForFunction((g) => document.querySelector('.main-dock')?.getAttribute('data-goal-id') === g, goalIdA); + await page.getByTestId('main-dock-tab-todos').click(); + await page.getByTestId('main-dock-tray-todos').getByText('补齐支付风控回归单测').waitFor({ timeout: 10_000 }); + assert.equal(await page.getByTestId('main-dock-tray-todos').getByText('核对周报指标数据源').count(), 0); + + // Add a clean natural follow-up turn in Loop A so mobile screenshot shows natural synthetic chat + clean inline cards (zero raw dispatch UUIDs on screen!). + await page.locator('.main-dock-close').click(); + await page.locator('.composer textarea').fill('汇总当前风控依赖与接口时延核查进展'); + await page.locator('.composer textarea').press('Enter'); + await page.getByText('风控依赖安装已验收完成;接口时延巡检已完成首轮核查,正等待最终确认。').waitFor({ timeout: 15_000 }); + + // Mobile viewport (390x844) visual & layout verification (single top-bar 新建, zero bottom hairline, borderless 4 pills on one row). + const mobileCtx = await browser.newContext({ viewport: { width: 390, height: 844 } }); + const mobilePage = await mobileCtx.newPage(); + await openUi(mobilePage, daemon); + await mobilePage.locator('.menu-btn').click(); + await mobilePage.locator(`[data-thread-id="${threadIdA}"] button.thread-item`).waitFor({ timeout: 10_000 }); + await mobilePage.waitForTimeout(350); + // Mobile sidebar uses the same single top-bar 新建 entry (no floating bottom 新对话 pill!). + assert.equal(await mobilePage.locator('.sidebar .sidebar-float .new-thread').count(), 0, 'mobile must not keep floating bottom 新对话 pill'); + await mobilePage.locator('.sidebar').getByRole('button', { name: '新建', exact: true }).waitFor({ timeout: 5_000 }); + await snap('04-mobile-light-sidebar', mobilePage); + await mobilePage.locator(`[data-thread-id="${threadIdA}"] button.thread-item`).click(); + await mobilePage.locator('.main-dock').waitFor({ timeout: 10_000 }); + await mobilePage.getByTestId('loop-supervise-bar').waitFor({ timeout: 5_000 }); + await mobilePage.getByTestId('loop-inline-tasks').waitFor({ timeout: 5_000 }); + await mobilePage.evaluate(() => { + const scroller = document.querySelector('.scroller'); + if (scroller) scroller.scrollTop = scroller.scrollHeight; + }); + await mobilePage.waitForTimeout(250); + // Assert