From 67a73a1777caaaa4efa0ecb04af80aed2afab1e2 Mon Sep 17 00:00:00 2001 From: maxliux5 <5958865+maxliux5@users.noreply.github.com> Date: Fri, 4 Dec 2026 02:47:07 +0800 Subject: [PATCH 1/7] feat(workbench): add Goal-backed main conversations with scoped dispatch, approvals, and todos Add Goal-backed Main Conversations to LoopX Workbench without introducing parallel ledgers: - Direct "Start a thing" entry launches real LoopX Goals via existing /api/loopx/launch/{preview,apply} and , retiring the manual while preserving permission/project selection, Core failure states, ordinary threads, and sidebar 3-way filtering (All / Main / Ordinary). - Persona-style MainConversationDock above the composer reuses StewardDispatchService, StewardInboxService, and for per-matter UI/model dispatch, child approval alerts with jump-to- and return chip, and persistent Core Goal todos. - Enforces server-side LoopxBinding authority ceilings on model-side dispatch (LOOCHAT_MAIN_SOCKET / LOOCHAT_MAIN_TOKEN, scrubbed from child workers), fail-closed permission checks, standalone permissionMode='read_only' readonly handling, SQL-before-LIMIT matter scoping, and concurrent/idempotent clientRequestId handling. Signed-off-by: maxliux5 <5958865+maxliux5@users.noreply.github.com> --- .../docs/main-conversations-design.md | 53 ++ apps/workbench/packages/daemon/bin/loochat | 64 ++ .../daemon/src/adapters/loopx/context.ts | 7 +- .../packages/daemon/src/adapters/types.ts | 1 + apps/workbench/packages/daemon/src/http.ts | 12 +- apps/workbench/packages/daemon/src/index.ts | 1 + .../packages/daemon/src/steward-dispatch.ts | 817 ++++++++++++++---- .../packages/daemon/src/steward-inbox.ts | 146 +++- .../packages/daemon/src/steward-ledger.ts | 221 ++++- apps/workbench/packages/daemon/src/threads.ts | 3 +- .../daemon/test/fixtures/fake-acp.mjs | 42 +- .../daemon/test/main-conversations.test.ts | 811 +++++++++++++++++ .../e2e/test/main-conversations.spec.mjs | 494 +++++++++++ apps/workbench/packages/web/src/App.tsx | 171 +++- apps/workbench/packages/web/src/api.ts | 124 ++- .../packages/web/src/components/GoalTasks.tsx | 9 +- .../src/components/MainConversationDock.tsx | 650 ++++++++++++++ .../packages/web/src/components/Sidebar.tsx | 67 +- .../packages/web/src/i18n/locales/en.ts | 47 + .../packages/web/src/i18n/locales/ja.ts | 47 + .../packages/web/src/i18n/locales/zh.ts | 47 + .../packages/web/src/loopx/loopx.css | 365 ++++++++ apps/workbench/packages/web/src/sidebar.ts | 18 +- .../web/test/main-conversations.test.ts | 302 +++++++ 24 files changed, 4283 insertions(+), 236 deletions(-) create mode 100644 apps/workbench/docs/main-conversations-design.md create mode 100644 apps/workbench/packages/daemon/test/main-conversations.test.ts create mode 100644 apps/workbench/packages/e2e/test/main-conversations.spec.mjs create mode 100644 apps/workbench/packages/web/src/components/MainConversationDock.tsx create mode 100644 apps/workbench/packages/web/test/main-conversations.test.ts diff --git a/apps/workbench/docs/main-conversations-design.md b/apps/workbench/docs/main-conversations-design.md new file mode 100644 index 0000000000..2b28e95703 --- /dev/null +++ b/apps/workbench/docs/main-conversations-design.md @@ -0,0 +1,53 @@ +# 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**: + - 侧栏一级入口新增 **「开始一件事」**(`Sidebar.tsx`、`⌘K` 命令面板及折叠侧栏顶栏按钮同步提供),同时移除旧输入框上的手选 `` 按钮。 + - 点击「开始一件事」即进入 `draftMain` 状态:自动清理 `draftTeam` 与无项目 `scratch`、优先选中支持 Goal 的 Agent、在输入栏保留必要的 ``(`read_only` / `workspace_auto`)与 ``(支持当前项目及既有「新建项目」流程)。 + - 发送首条消息时,自动走既有 `POST /api/loopx/launch/preview` → `` → `POST /api/loopx/launch/apply` 创建真实 LoopX Goal 并绑定主对话线程。 + - **失败显式呈现、绝不静默降级**:当 Core 不可达(`loopx_core_unavailable`)、项目未授权(`workspace_not_granted`)或当前 Agent 不支持 Goal 时,复用 `` 原有错误态与引导,绝不静默降级为普通会话。 +- **既有入口与历史数据兼容**: + - 保留「新对话」(普通会话)与「LoopX 管家」(全局 Steward 收件箱)入口,不破坏既有操作路径。 + - 历史普通会话、历史 Goal 会话与扫描到的本机 Goal 会话直接通过 `isLoopxRow(thread)` 归类,侧栏支持 **全部 / 主对话 / 普通** 三态筛选(持久化在 `localStorage`),刷新、重开后归属稳定。 + +## 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. 交互结构(参考 Persona Dock) + +主对话线程在输入框上方挂载 ``(仅对真实 Goal 会话渲染): +1. **待审核提醒条**:当本事项存在子 Agent 权限请求、等待输入或 Core Action 提案时,以克制的琥珀态单行提示浮现,提供「前往审核」直达子线程 `` 或「查看审核」展开抽屉。 +2. **单行胶囊条**:`待审核 N`、`派工 N`、`待办 N` 三个 30px 单色胶囊 + 右侧当前 Goal 标识;同一时间仅展开一个可滚动抽屉,`Esc` 关闭抽屉且不中断正在进行的对话轮次。 +3. **侧栏折叠与返回**:由主对话派出的活跃子线程自动折叠在该主对话行下方(复用意图一致的并行子行抽屉);子线程等待审核时父行同步亮起等待圆点;打开子线程后顶栏显示「← 主对话 · 标题」。 + +## 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` 截断,其他事项或历史普通线程数据绝不串入或挤占。 + - 前端:`MainConversationDock` 在 `thread.id` / `goalId` 切换时立即清空旧态并使用 `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..9a3f4698d6 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,300 @@ 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 returnRoute = this.normalizeReturnRoute(input.returnRoute); + const parentThreadId = returnRoute?.parentThreadId ?? null; + const clientRequestId = normalizeClientRequestId(input.clientRequestId); + + const run = async (): Promise => { + if (input.mode === 'spawn') { + const objective = (input.objective ?? input.message ?? '').trim(); + const title = (input.title ?? objective.split('\n')[0]?.slice(0, 60) ?? '').trim(); + if (!objective) throw new HttpError(400, 'task_objective_required'); + if (!title) throw new HttpError(400, 'task_title_required'); + const readonly = input.readonly === true || input.permissionMode === 'read_only'; + const doneWhen = + input.doneWhen !== undefined + ? input.doneWhen + : !readonly && returnRoute?.channel === 'main_conversation' + ? [title] + : undefined; + 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, + readonly: existing.readonly, + permissionMode: existing.permissionMode ?? null, + }); + const currentFp = JSON.stringify({ + mode: 'spawn', + agent: resolvedAgent, + cwd: canonicalPath(resolvedCwd), + objective, + 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 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 readonly = input.readonly === true; - const doneWhen = input.doneWhen ? normalizeDoneWhen(input.doneWhen, true) : []; + const plan = await this.taskPlan({ + tasks: [ + { + title, + objective, + doneWhen, + 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 readonly = input.readonly === true || input.permissionMode === 'read_only'; + 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(), + 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 +2274,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 +2298,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 +2327,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('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/test/main-conversations.spec.mjs b/apps/workbench/packages/e2e/test/main-conversations.spec.mjs new file mode 100644 index 0000000000..3933c19a1c --- /dev/null +++ b/apps/workbench/packages/e2e/test/main-conversations.spec.mjs @@ -0,0 +1,494 @@ +// Real-browser Playwright E2E for Workbench Main Conversations (Goal-backed): +// 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 } from '../harness.mjs'; + +function workspaceRef(root) { + return `workspace-${createHash('sha256').update(root).digest('hex').slice(0, 12)}`; +} + +/** + * In-process synthetic LoopX Core test double implementing the exact HTTP contract used by + * LoopxService (/api/chat/projects, /api/actions/preview, /api/actions/:id/apply, /api/actions), + * GoalTasks (/api/loopx/status.json?goal_id=, /api/chat/todo/dry-run, /api/chat/todo/apply), + * and useLoopxStatus (/status.json). + */ +async function startFakeCore(grantedRoot) { + const ref = workspaceRef(grantedRoot); + const state = { + simulateDown: false, + goals: new Map(), // goalId -> { goalId, title, objective, status, workspace, agentId, todos: { user: [], agent: [] } } + proposals: new Map(), // proposalId -> proposal + todoPreviews: new Map(), // previewId -> { goalId, role, text, priority, claimedBy } + 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') { + const goalFilter = url.searchParams.get('goal_id'); + return json(200, buildStatusPayload(goalFilter)); + } + 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 () => { + // Start daemon with a pre-created workdir so fakeCore grants that exact workdir. + const workdir = join('/tmp', `loochat-main-e2e-${Date.now()}`); + mkdirSync(workdir, { recursive: true }); + fakeCore = await startFakeCore(workdir); + // Provide a test-double loopx CLI shim backed by fakeCore so GoalState reads return real Goal status instead of goal_not_found. + 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 }, + ); + daemon = await startDaemon( + { + LOOCHAT_LOOPX_CORE_URL: fakeCore.url, + LOOCHAT_LOOPX_CMD: `${process.execPath} ${fakeLoopxCli}`, + 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 }); +} + +test('full Main Conversation journey: start Goal without toggle, Core failure guard, filter/reload, UI + model dispatch, child ActionSheet approval, Core todos, two-matter isolation', async () => { + await openUi(page, daemon); + const sidebar = page.locator('.sidebar'); + await sidebar.getByRole('button', { name: '开始一件事', exact: true }).waitFor({ timeout: 10_000 }); + + // 1. Legacy entries intact; old manual is completely retired. + assert.equal(await sidebar.getByRole('button', { name: '新对话', exact: true }).isVisible(), true); + assert.equal(await sidebar.getByRole('button', { name: 'LoopX 管家', exact: true }).isVisible(), true); + assert.equal(await page.locator('.composer-loopx').count(), 0, 'manual LoopxToggle must be removed'); + + // 2. Click 「开始一件事」 and verify Core failure shows original error without silent downgrade. + await sidebar.getByRole('button', { name: '开始一件事', exact: true }).click(); + await page.locator('.topbar-title').filter({ hasText: '开始一件事' }).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 Matter A through real launch/preview -> GoalConfirm -> launch/apply. + await page.locator('.composer textarea').fill('Matter A 支付风控校验'); + 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'); + + // 4. Create Matter B via 「开始一件事」. + await sidebar.getByRole('button', { name: '开始一件事', exact: true }).click(); + await page.locator('.composer textarea').fill('Matter B 周报指标核对'); + 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); + + // 5. Create legacy ordinary conversation via 「新对话」. + await sidebar.getByRole('button', { name: '新对话', exact: true }).click(); + await page.locator('.composer textarea').fill('普通会话兼容验证'); + await page.locator('.composer textarea').press('Enter'); + await page.getByText('echo:普通会话兼容验证').waitFor({ timeout: 15_000 }); + assert.equal(await page.locator('.main-dock').count(), 0, 'ordinary thread must NOT mount MainConversationDock'); + + // 6. Test 3-way sidebar filter (全部 / 主对话 / 普通) + reload persistence. + const filterGroup = sidebar.locator('.sidebar-kind-filter'); + await filterGroup.getByRole('button', { name: '主对话', exact: true }).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); + + // Reload page while filter is on 「主对话」 -> filter and ownership stay stable. + 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 filterGroup.getByRole('button', { name: '普通', exact: true }).click(); + await sidebar.locator('.thread-title', { hasText: '普通会话兼容验证' }).waitFor({ timeout: 5_000 }); + assert.equal(await sidebar.locator(`[data-thread-id="${threadIdA}"]`).count(), 0); + + await filterGroup.getByRole('button', { name: '全部', exact: true }).click(); + await sidebar.locator(`[data-thread-id="${threadIdA}"]`).waitFor({ timeout: 5_000 }); + + // 7. Inside Matter A, dispatch a child Claude agent with ask permission + "approve install". + 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 }); + await dispatchTray.getByLabel('目标 Agent').selectOption('claude'); + await dispatchTray.getByLabel('子任务权限').selectOption('ask'); + await dispatchTray.locator('.main-dock-input').fill('approve install'); + 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'); + assert.ok(childThreadIdA, 'expected spawned childThreadIdA'); + + // Wait for child's permission request to surface in Matter A's dock (both badge & approval banner/status). + await page.getByTestId('main-dock-approval-banner').waitFor({ timeout: 15_000 }); + await childRowA.locator('.main-dock-pill.is-waiting').waitFor({ timeout: 10_000 }); + // Assert neither protocol blocks nor goal_not_found errors appear in the visible conversation or Goal overview. + 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'); + await snap('01-desktop-light-matter-a-approval-dispatch'); + + // Capture dark-mode screenshot of the same populated Matter A view. + await page.evaluate(() => document.documentElement.setAttribute('data-theme', 'dark')); + await snap('02-desktop-dark-matter-a-approval-dispatch'); + await page.evaluate(() => document.documentElement.removeAttribute('data-theme')); + + // 8. Verify cross-matter isolation: Matter B sees ZERO approvals and ZERO dispatches from Matter A. + 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, 'Matter A approval must NOT leak to Matter B'); + assert.equal(await page.getByTestId('main-dock-tray-dispatch').locator('.main-dock-task-row').count(), 0, 'Matter A dispatch must NOT leak to Matter B'); + + // 9. Return to Matter A, click 「前往审核」 -> arrive on child thread's existing -> approve -> return to Matter A! + await sidebar.locator(`[data-thread-id="${threadIdA}"] button.thread-item`).click(); + await page.getByTestId('main-dock-approval-banner').waitFor({ timeout: 10_000 }); + await page.getByTestId('main-dock-approval-banner').getByRole('button', { name: '前往审核' }).click(); + + // Landed on child thread with existing ActionSheet and topbar back chip! + await page.locator('.action-sheet').waitFor({ timeout: 10_000 }); + await page.getByTestId('back-to-main-conversation').waitFor({ timeout: 5_000 }); + await page.locator('.action-sheet button.primary').click(); + await page.getByText('approved:allow').waitFor({ timeout: 15_000 }); + + // Jump back to Matter A and confirm approval prompt cleared & dispatch settled with result! + 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 }); + await page.getByTestId('main-dock-tab-dispatch').click(); + await page.locator(`[data-child-thread-id="${childThreadIdA}"] .main-dock-task-summary`, { hasText: 'approved:allow' }).waitFor({ timeout: 10_000 }); + + // 10. Model-driven dispatch from Matter A via real LOOCHAT_MAIN_SOCKET + LOOCHAT_MAIN_TOKEN! + await page.locator('.composer textarea').fill('model-dispatch claude 模型自派指标巡检 | check latency metrics'); + await page.locator('.composer textarea').press('Enter'); + await page.getByText('dispatched:task_', { exact: false }).waitFor({ timeout: 15_000 }); + const modelDispatchRow = page.getByTestId('main-dock-tray-dispatch').locator('.main-dock-task-row', { hasText: '模型自派指标巡检' }); + await modelDispatchRow.waitFor({ timeout: 10_000 }); + const childThreadIdModel = await modelDispatchRow.getAttribute('data-child-thread-id'); + assert.ok(childThreadIdModel && childThreadIdModel !== childThreadIdA); + + // 11. Persistent Core Goal todos directly under Main Conversation + reload + two-matter 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('补齐 Matter A 支付风控单测'); + 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('补齐 Matter A 支付风控单测').first().waitFor({ timeout: 10_000 }); + await snap('03-desktop-light-matter-a-todos'); + + // Switch to Matter B, verify Matter A todo absent, add Matter B todo. + 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('补齐 Matter A 支付风控单测').count(), 0); + await todosTray.getByRole('button', { name: '新建任务' }).click(); + await todosTray.locator('textarea').fill('整理 Matter B 周报数据源'); + 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('整理 Matter B 周报数据源').first().waitFor({ timeout: 10_000 }); + + // Reload browser and verify both Matter A & Matter B todos reopen with exact ownership! + 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('补齐 Matter A 支付风控单测').waitFor({ timeout: 10_000 }); + assert.equal(await page.getByTestId('main-dock-tray-todos').getByText('整理 Matter B 周报数据源').count(), 0); + + // Mobile viewport (390x844) visual verification capture. + if (shotDir) { + 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(400); + 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('main-dock-tab-dispatch').click(); + await mobilePage.getByTestId('main-dock-tray-dispatch').waitFor({ timeout: 5_000 }); + await mobilePage.waitForTimeout(250); + await snap('05-mobile-light-matter-a-dock', mobilePage); + await mobileCtx.close(); + } + + console.log( + JSON.stringify({ + e2eEvidence: { + goalIdA, + threadIdA, + childThreadIdA, + childThreadIdModel, + goalIdB, + threadIdB, + }, + }), + ); +}); diff --git a/apps/workbench/packages/web/src/App.tsx b/apps/workbench/packages/web/src/App.tsx index 62e6ff3111..4323149995 100644 --- a/apps/workbench/packages/web/src/App.tsx +++ b/apps/workbench/packages/web/src/App.tsx @@ -93,7 +93,7 @@ import { extensionStorage } from './extensions/host'; import { prepareOverview } from './overview-reading'; import { ChangeDiffDialog } from './components/ChangeDiffDialog'; import { AgentsPage } from './components/AgentsPage'; -import type { AgentMention, ChangedFile, Coordination, MemberDefault, SearchHit } from './api'; +import type { AgentMention, ChangedFile, Coordination, MemberDefault, SearchHit, StewardTaskRecord } from './api'; import { Popover } from './components/Popover'; import { SideChat } from './components/SideChat'; import { McpPage } from './components/McpPage'; @@ -117,7 +117,8 @@ import { needsYouGoalIds, sortGoalTree } from './loopx/status'; import { ActivityPage } from './components/ActivityPage'; import { LoopxGoalGroup } from './components/LoopxGoalGroup'; import { drivenByApp } from './loopx/session'; -import { GoalConfirm, GoalPermissionPicker, LoopxToggle } from './components/LoopxGoal'; +import { GoalConfirm, GoalPermissionPicker } from './components/LoopxGoal'; +import { MainConversationDock } from './components/MainConversationDock'; import { SendCancelled } from './drafts'; import { defaultGoalPermission, fetchGoalCapabilities, goalOf, type GoalAgentCapability, type GoalPermission } from './loopx/launch'; import { ExtensionsPage } from './components/ExtensionsPage'; @@ -147,7 +148,7 @@ import { ConnectDialog, DemoBar } from './components/ConnectDialog'; import { DemoApi, DemoError } from './demo/DemoApi'; import { EMPTY_MODEL_PREFERENCE, type DraftModelPreference } from '../../daemon/src/model-preferences'; import { ThreadQuickSwitch } from './components/ThreadQuickSwitch'; -import { IconDownload, IconCheck, IconBell, AgentMark, IconActivity, IconAgents, IconArchive, IconArrowDown, IconBack, IconClose, IconEdit, IconFolder, IconGauge, IconGlobe, IconList, IconMenu, IconSettings, IconMore, IconOverview, IconPalette, IconPlus, IconPuzzle, IconServer, IconShield, IconSidebar, IconSignIn, IconSignOut, IconSparkle, IconTerminal, IconTrace, IconLanguage, IconWaveform, IconSideChat } from './components/icons'; +import { IconDownload, IconCheck, IconBell, AgentMark, IconActivity, IconAgents, IconArchive, IconArrowDown, IconBack, IconClose, IconEdit, IconFolder, IconGauge, IconGlobe, IconList, IconMenu, IconSettings, IconMore, IconOverview, IconPalette, IconPlus, IconPuzzle, IconServer, IconShield, IconSidebar, IconSignIn, IconSignOut, IconSparkle, IconTerminal, IconTrace, IconLanguage, IconWaveform, IconSideChat, LooMark } from './components/icons'; import { StatReadings } from './components/SessionStats'; import { ThreadTracePanel } from './components/TracePanel'; import { chooseLocale, locale, LOCALES, localeChoice, t } from './i18n'; @@ -681,8 +682,8 @@ function Hub({ token, onToken, connect, hostId = null, onHost, start, showcase } const [draftCwd, setDraftCwd] = useState(() => typeof start === 'object' && 'draft' in start ? start.draft.project ?? keptDraft?.cwd ?? '' : keptDraft?.cwd ?? ''); // A new thread may start in a git worktree of its directory; offered only when the directory is in a repository. const [draftWorktree, setDraftWorktree] = useState(false); - // A new conversation can be handed to LoopX as a Goal: it then runs under the Goal's own two permission levels. - const [draftLoopx, setDraftLoopx] = useState(false); + // Starting a thing: enters Goal-backed Main Conversation mode directly without a manual LoopX toggle. + const [draftMain, setDraftMain] = useState(false); const [goalCaps, setGoalCaps] = useState([]); const [draftGoalPermission, setDraftGoalPermission] = useState(null); const [pendingGoal, setPendingGoal] = useState<{ text: string; onCreated?: (threadId: string) => void; resolve: () => void; reject: (e: unknown) => void } | null>(null); @@ -704,8 +705,13 @@ function Hub({ token, onToken, connect, hostId = null, onHost, start, showcase } if (api.demo || !token) return; void fetchGoalCapabilities(token).then(setGoalCaps, () => setGoalCaps([])); }, [token]); // eslint-disable-line react-hooks/exhaustive-deps - // An agent that cannot hold a Goal takes the mode back off. - useEffect(() => { if (draftLoopx && goalCap && !goalCap.available) setDraftLoopx(false); }, [draftAgent, goalCap?.available]); // eslint-disable-line react-hooks/exhaustive-deps + // In main-conversation mode, prefer a Goal-capable agent automatically when capabilities load, without downgrading to ordinary chat. + useEffect(() => { + if (!draftMain || !goalCaps.length) return; + if (goalCap?.available) return; + const capable = goalCaps.find((cap) => cap.available)?.agent; + if (capable && capable !== draftAgent) setDraftAgent(capable); + }, [draftMain, goalCaps, goalCap?.available, draftAgent]); const draftChoice = fitDraftModelPreference(modelPreferences.preferences[draftAgent] ?? EMPTY_MODEL_PREFERENCE, modelsByAgent[draftAgent] ?? [], draftCaps?.effortLevels ?? [], Boolean(draftCaps?.speed)); const { model: draftModel, effort: draftEffort, speed: draftSpeed } = draftChoice; @@ -880,7 +886,8 @@ function Hub({ token, onToken, connect, hostId = null, onHost, start, showcase } // Text quoted out of a message by selecting it. const [handoffTarget, setHandoffTarget] = useState(null); const handoffActive = Boolean(selectedId && handoffTarget?.thread.id === selectedId); - const composerDraftKey = handoffActive ? (hostId ? `host:${hostId}:handoff:${selectedId}` : `handoff:${selectedId}`) : (hostId ? `host:${hostId}:${selectedId ?? (draftTeam ? `new:team:${draftTeam}` : 'new')}` : selectedId ?? (draftTeam ? `new:team:${draftTeam}` : 'new')); + const newDraftSuffix = draftMain ? 'new:main' : draftTeam ? `new:team:${draftTeam}` : 'new'; + const composerDraftKey = handoffActive ? (hostId ? `host:${hostId}:handoff:${selectedId}` : `handoff:${selectedId}`) : (hostId ? `host:${hostId}:${selectedId ?? newDraftSuffix}` : selectedId ?? newDraftSuffix); const draftKeys = useDraftKeys(); const [draftGeneration, setDraftGeneration] = useState(0); const draftGenerationRef = useRef(0); @@ -1185,9 +1192,46 @@ function Hub({ token, onToken, connect, hostId = null, onHost, start, showcase } }, [timeline, planSkip]); const waitingOn = waiting[0] ?? null; + const [stewardTasks, setStewardTasks] = useState([]); + useEffect(() => { + if (!api || api.demo || !token) { + setStewardTasks([]); + return; + } + let alive = true; + void api.stewardTasks({ limit: 200 }).then((res) => { + if (alive) setStewardTasks(res.tasks); + }).catch(() => undefined); + return () => { alive = false; }; + }, [api, token, todosKey, threads.length]); + + const { dispatchedChildren, dispatchedParentByChild } = useMemo(() => { + const byParent = new Map(); + const parentByChild = new Map(); + const threadById = new Map(threads.map((item) => [item.id, item])); + const seenChild = new Set(); + for (const task of stewardTasks) { + const childId = task.threadId; + const parentId = task.returnRoute?.parentThreadId + ?? (task.returnRoute?.channel === 'main_conversation' ? task.returnRoute.originId : undefined); + if (!childId || !parentId || childId === parentId || seenChild.has(childId)) continue; + const child = threadById.get(childId); + const parent = threadById.get(parentId); + if (!child || !parent || child.archivedAt || parent.archivedAt) continue; + seenChild.add(childId); + parentByChild.set(childId, parent); + byParent.set(parentId, [...(byParent.get(parentId) ?? []), child]); + } + return { dispatchedChildren: byParent, dispatchedParentByChild: parentByChild }; + }, [stewardTasks, threads]); + const topLevelThreads = useMemo(() => ownRows(threads), [threads]); // Her conversation is reached through her, from the sidebar's own row and the desk, not listed twice. - const listedThreads = useMemo(() => routerThreadId ? topLevelThreads.filter((t) => t.id !== routerThreadId) : topLevelThreads, [topLevelThreads, routerThreadId]); + // Dispatched child threads of an active Goal main conversation nest under their parent row. + const listedThreads = useMemo( + () => topLevelThreads.filter((t) => t.id !== routerThreadId && !dispatchedParentByChild.has(t.id)), + [topLevelThreads, routerThreadId, dispatchedParentByChild], + ); useEffect(() => { if (!startupPending.current || !startupSettings) return; @@ -2114,8 +2158,8 @@ function Hub({ token, onToken, connect, hostId = null, onHost, start, showcase } const id = selectedId; const created = (threadId: string) => onCreated?.(hostId ? `host:${hostId}:${threadId}` : threadId); try { - // A Goal is reviewed by the LoopX core before it exists; the draft stays in the box until it is created or backed out of. - if (!id && draftLoopx && !draftTeam) { + // A Goal main conversation always routes through Core preview + confirmation; never silently downgrade to ordinary chat. + if (!id && draftMain && !draftTeam) { if (images.length || videos.length) throw new Error(t('loopx.goal.noMedia')); return await new Promise((resolve, reject) => setPendingGoal({ text, onCreated: created, resolve, reject })); } @@ -2424,6 +2468,7 @@ function Hub({ token, onToken, connect, hostId = null, onHost, start, showcase } const newThread = (opts: { cwd?: string; sectionId?: string | null; scratch?: boolean; beside?: Thread } = {}) => navigate(() => { void modelPreferences.refresh(); if (showcase) { showcase.onInstall(); return; } + setDraftMain(false); const targetKey = hostId ? `host:${hostId}:${opts.beside || !draftTeam ? 'new' : `new:team:${draftTeam}`}` : opts.beside || !draftTeam ? 'new' : `new:team:${draftTeam}`; // Directory selection and visible read attachments are separate; restoring the former never recreates the latter. replaceAutomaticComposerReference(targetKey, opts.beside ? pendingThreadReference(opts.beside) : null); @@ -2442,6 +2487,31 @@ function Hub({ token, onToken, connect, hostId = null, onHost, start, showcase } setDraftSectionId(opts.sectionId ?? null); }); + const newMain = (opts: { cwd?: string } = {}) => navigate(() => { + void modelPreferences.refresh(); + if (showcase) { showcase.onInstall(); return; } + const targetKey = hostId ? `host:${hostId}:new:main` : 'new:main'; + replaceAutomaticComposerReference(targetKey, null); + const generation = ++draftGenerationRef.current; + composerScopeRef.current = JSON.stringify([targetKey, generation]); + setDraftGeneration(generation); + setMessageReference(null); setNoteSignal(null); setRestore(null); + setDraftTeam(null); + setDraftScratch(false); + setDraftWorktree(false); + setDraftCollaboration(false); + setDraftSectionId(null); + setDraftMain(true); + const preferredCwd = opts.cwd ?? (draftCwd || roots[0]?.path || ''); + if (preferredCwd) setDraftCwd(preferredCwd); + const capable = goalCaps.find((c) => c.agent === draftAgent && c.available)?.agent + ?? goalCaps.find((c) => c.available)?.agent; + if (capable && capable !== draftAgent) pickAgent(capable); + setSelectedId(null); + setView('thread'); + setDrawer(false); + }); + // A turn a search found: its thread is opened and the conversation is brought to that turn. An // archived thread comes back out of the archive, as it does when opened from anywhere else. const openHit = async (hit: SearchHit) => { @@ -2682,14 +2752,14 @@ function Hub({ token, onToken, connect, hostId = null, onHost, start, showcase } // strip is only for choosing them, before the thread exists. const header = selected || threadPending ? null : ( <> - { const id = teamRecipient(value); setDraftTeam(id); if (id) { setDraftScratch(false); setDraftWorktree(false); setDraftCollaboration(false); } else pickAgent(value); }} accounts={accounts} onAddAccount={addAccount} /> + { const id = teamRecipient(value); setDraftTeam(id); if (id) { setDraftScratch(false); setDraftWorktree(false); setDraftCollaboration(false); } else pickAgent(value); }} accounts={accounts} onAddAccount={addAccount} /> { setDraftCwd(cwd); setDraftScratch(false); @@ -2793,7 +2863,7 @@ function Hub({ token, onToken, connect, hostId = null, onHost, start, showcase } ); const left = (<> - {goalOf(selected) ? null : !selected && draftLoopx ? ( + {goalOf(selected) ? null : !selected && draftMain ? ( ) : ( { + if (!selected || isOptimisticThreadId(selected.id) || api?.demo) return null; + const binding = goalOf(selected); + if (binding?.goalId) return binding.goalId; + if (selected.loopxInfo && !selected.loopxInfo.missing && selected.loopxInfo.goalId) { + return selected.loopxInfo.goalId; + } + return null; + }, [selected, api]); // Where the thread runs, beside its title; a page or a team task names itself instead. const placeShown = Boolean(selected && !viewTitle && !(host && !hostUp) && !selected.coordination?.team && !atMember); const leadTitle = atMember ? threads.find((v) => v.id === selected!.coordination!.rootId)?.title ?? '' : ''; @@ -3079,6 +3159,7 @@ function Hub({ token, onToken, connect, hostId = null, onHost, start, showcase } showEmptySections={!showcase} threads={listedThreads} members={teamMembers} + dispatchedChildren={dispatchedChildren} forks={forkMembers} onForkSubchat={threadActions.forkSubchat} sections={sections} @@ -3086,6 +3167,8 @@ function Hub({ token, onToken, connect, hostId = null, onHost, start, showcase } selectedId={selectedId} onSelect={pick} onNew={() => newThread()} + onNewMain={demo ? undefined : () => newMain()} + mainDraftActive={!selected && !onPage && draftMain} onNewIn={newThread} compact={compact} onSearch={api ? (q) => api.search(q) : undefined} @@ -3163,6 +3246,10 @@ function Hub({ token, onToken, connect, hostId = null, onHost, start, showcase } + ) : compact && dispatchedParent ? ( + ) : ( + {!demo && ( + + )} @@ -3188,7 +3280,7 @@ function Hub({ token, onToken, connect, hostId = null, onHost, start, showcase } {compact && placeShown ? ( ) : ( -
{host && !hostUp ? host.label : viewTitle ?? (selected ? (onRouterThread ? routerTitle : selected.title) : threadPending ? '' : t('sidebar.newThread'))}
+
{host && !hostUp ? host.label : viewTitle ?? (selected ? (onRouterThread ? routerTitle : selected.title) : threadPending ? '' : draftMain ? t('mainConv.newTitle') : t('sidebar.newThread'))}
)} {!selected && !threadPending && host && hostUp &&
{host.label}
} @@ -3200,6 +3292,11 @@ function Hub({ token, onToken, connect, hostId = null, onHost, start, showcase } {agentLabel(selected!.agent)} · {t('app.leadThread', leadTitle)} )} + {dispatchedParent && ( + + )} {(selected || onSteward) && ( @@ -3578,7 +3675,15 @@ function Hub({ token, onToken, connect, hostId = null, onHost, start, showcase } /> ) : (
-

{draftScratch ? t('app.emptyScratch') : t('app.emptyIn', folderName(draftCwd))}

+ {draftMain ? ( + <> + +

{t('mainConv.emptyHeading')}

+ {draftCwd &&

{t('mainConv.emptySub', folderName(draftCwd))}

} + + ) : ( +

{draftScratch ? t('app.emptyScratch') : t('app.emptyIn', folderName(draftCwd))}

+ )}
)} {selected && } @@ -3595,6 +3700,22 @@ function Hub({ token, onToken, connect, hostId = null, onHost, start, showcase } {!onPage && !(host && !hostUp) && (
+ {selected && selectedMainGoalId && !voice.state.active && !handoffActive && ( + g.goalId === selectedMainGoalId)} + attention={loopxStatus?.attention.find((a) => a.goalId === selectedMainGoalId)} + refreshTick={todosKey} + onOpenThread={pick} + onOpenGoal={(gid) => openGoal(gid)} + onChanged={goalsChanged} + /> + )} {selectedId && } {(voice.state.active || voice.state.error) && void voice.stop()} /> : undefined} running={voice.state.active ? false : running} disabled={modeBusy} - sendDisabled={!selected && ((!draftCwd && !draftScratch) || modelPreferences.status !== 'ready')} - placeholder={voice.state.active ? t('app.placeholder.continue') : onRouterThread && !running ? t('pet.threadPlaceholder') : demo ? t('app.placeholder.demo') : workMode === 'plan' && !running ? t('composerMenu.planOn') : writing && !running ? t('writing.placeholder') : selected ? (running ? t('sideChat.queuePlaceholder') : t('app.placeholder.continue')) : draftScratch ? t('app.placeholder.scratch') : t('app.placeholder.startIn', folderName(draftCwd))} + sendDisabled={!selected && ((!draftCwd && (!draftScratch || draftMain)) || modelPreferences.status !== 'ready')} + placeholder={voice.state.active ? t('app.placeholder.continue') : onRouterThread && !running ? t('pet.threadPlaceholder') : demo ? t('app.placeholder.demo') : workMode === 'plan' && !running ? t('composerMenu.planOn') : writing && !running ? t('writing.placeholder') : selected ? (running ? t('sideChat.queuePlaceholder') : t('app.placeholder.continue')) : draftMain ? t('mainConv.placeholder', folderName(draftCwd)) : draftScratch ? t('app.placeholder.scratch') : t('app.placeholder.startIn', folderName(draftCwd))} onSend={voice.state.active ? async (text, images, _mentions, videos = []) => { try { await voice.appendText(text, images.map(img => ({ data: img.data, mimeType: img.mimeType })), await Promise.all(videos.map(async video => (await api.uploadVideo(selectedId!, video.file)).id))); } catch (error) { handleError(error); throw error; } @@ -3650,19 +3771,15 @@ function Hub({ token, onToken, connect, hostId = null, onHost, start, showcase } header={header} writingMode={draftTeam ? undefined : { active: !!writing, disabled: writingBusy, onChange: active => void changeWriting(active ? 'draft' : null) }} takeover={outOfPlan && !voice.state.active ? { from: agentLabel(selected!.agent), current: selected!.agent, go: (agent, note) => threadActions.forkContinue(selected!, { agent }, note || undefined) } : undefined} - banner={<>{selected && !api.demo && drivenByApp(selected.loopxInfo, selected.origin) &&

{t('loopx.driven')}

}{writing && !draftTeam && void changeWriting(stage)} onEnd={() => void changeWriting(null)} + banner={<>{!selected && draftMain && goalCap && !goalCap.available &&

{t('mainConv.agentHint', goalCap.reason ?? '')}

}{selected && !api.demo && drivenByApp(selected.loopxInfo, selected.origin) &&

{t('loopx.driven')}

}{writing && !draftTeam && void changeWriting(stage)} onEnd={() => void changeWriting(null)} onOpen={file => void openFileLink(file).catch(handleError)} habits={habitsPath ? { path: habitsPath, ready: habitsReady } : null} onCheckHabits={() => void checkWritingHabits()} onOpenHabits={path => void openFileLink(path).catch(handleError)} />}} - planMode={!draftTeam && activeCaps?.workModes?.includes('plan') ? { active: workMode === 'plan', disabled: running || modeBusy, onChange: active => void changeWorkMode(active ? 'plan' : 'execute') } : undefined} + planMode={!draftTeam && !draftMain && activeCaps?.workModes?.includes('plan') ? { active: workMode === 'plan', disabled: running || modeBusy, onChange: active => void changeWorkMode(active ? 'plan' : 'execute') } : undefined} left={draftTeam ? undefined : left} right={draftTeam ? undefined : right} composerActions={<> - {!selected && !draftTeam && (api.demo || goalCap) && ( - // The demo has no hub to hand a Goal to: the mark stays, so the entry can be found, and says what it needs. - setDraftLoopx(on => !on)} /> - )} {(canVoice || canVoiceDraft) && !voice.state.active && ( + )} + + +
+ )} + + {openTab && ( +
+
+ + {openTab === 'approvals' + ? t('mainConv.dock.approvals') + : openTab === 'dispatch' + ? t('mainConv.dock.dispatch') + : t('mainConv.dock.todos')} + + +
+ +
+ {openTab === 'approvals' && ( +
+ {approvalNotice &&

{approvalNotice}

} + {approvalError &&

{approvalError}

} + {approvalCards.length === 0 ? ( +

{t('mainConv.dock.noApprovals')}

+ ) : ( +
+ {approvalCards.map((card) => { + if (card.kind === 'thread_approval') { + const busy = approvalBusyIds.has(card.approvalId); + return ( +
+
+ {card.title} + {card.threadTitle} +
+
+ + {card.options.map((opt) => ( + + ))} +
+
+ ); + } + if (card.kind === 'thread_input') { + return ( +
+
+ {card.title} + {card.threadTitle} +
+
+ +
+
+ ); + } + if (card.kind === 'plan_approval') { + const busy = approvalBusyIds.has(`plan:${card.planId}`); + return ( +
+
+ {card.title} + {card.ownerSteps.join(' · ') || t('mainConv.dock.status.awaiting_approval')} +
+
+ + +
+
+ ); + } + if (card.kind === 'core_action_proposal') { + return ( + api.stewardDismissCoreAction(proposalId).then(() => reloadNow())} + /> + ); + } + return null; + })} +
+ )} +
+ )} + + {openTab === 'dispatch' && ( +
+
void handleDispatch(e)}> +
+ + +
+
+ setDispatchText(e.target.value)} + disabled={dispatching} + /> + +
+ {dispatchError &&

{dispatchError}

} +
+ + {tasks.length === 0 ? ( +

{t('mainConv.dock.noDispatches')}

+ ) : ( +
    + {tasks.map((task) => { + const childThread = task.threadId ? threadById.get(task.threadId) : undefined; + const isWaiting = Boolean( + task.threadId && (approvalThreadIds.has(task.threadId) || childThread?.waiting), + ); + const tone = dispatchStatusTone(task.status, isWaiting); + const agentLabel = agents.find((a) => a.id === task.agent)?.label ?? task.agent; + const summary = task.resultSummary || task.errorMessage || null; + return ( +
  • +
    + {task.title} + + {agentLabel} + + {dispatchStatusLabel(task.status, isWaiting)} + + +
    + {summary &&

    {summary}

    } + {task.threadId && ( +
    + +
    + )} +
  • + ); + })} +
+ )} +
+ )} + + {openTab === 'todos' && ( +
+ { + setTodoRefreshKey((n) => n + 1); + onChanged(); + }} + /> +
+ )} +
+
+ )} + +
+
+ + + + + +
+ + + + {goal?.title || thread.loopxInfo?.goalTitle || goalId} + {goal?.status === 'completed' && } + +
+ + ); +} diff --git a/apps/workbench/packages/web/src/components/Sidebar.tsx b/apps/workbench/packages/web/src/components/Sidebar.tsx index 4f98ac1fee..e93c45f816 100644 --- a/apps/workbench/packages/web/src/components/Sidebar.tsx +++ b/apps/workbench/packages/web/src/components/Sidebar.tsx @@ -9,14 +9,14 @@ import { clockLabel } from '../timeline'; import { useInTitlebar, useLongPress, useStoredFlag, useStoredSet } from '../hooks'; import { attentionCount, threadMark, waitingLabel, type ThreadMark } from '../notices'; import { folderName } from '../paths'; -import { buildActivity, buildMerged, buildSidebar, externalThreadRow, locateThreadInSidebar, markTerms, navOverflow, projectDir, SEARCH_MIN, snoozed, snoozeTimeLabel, taggedAgents, withExternalSessions, type ForkSubchatItem, type HostSource } from '../sidebar'; +import { buildActivity, buildMerged, buildSidebar, externalThreadRow, filterThreadsByKind, locateThreadInSidebar, markTerms, navOverflow, projectDir, SEARCH_MIN, snoozed, snoozeTimeLabel, taggedAgents, withExternalSessions, type ForkSubchatItem, type HostSource, type SidebarKindFilter } from '../sidebar'; import { timeAgo } from '../sessions'; import { deliveredPreview } from '../timeline'; import { HostSwitcher } from './Hosts'; import { Menu } from './Menu'; import type { HostIconName } from '@calli/extension-api'; import { HostIcon } from '../extensions/ui'; -import { AgentMark, IconAgents, IconBell, IconCheck, IconChevron, IconCrab, IconClock, IconClose, IconDesktop, IconEdit, IconFork, IconHandover, IconFolder, IconList, IconMore, IconPin, IconPlus, IconSearch, IconSettings, IconSidebar, IconSideChat, IconSparkle, IconServer } from './icons'; +import { AgentMark, IconAgents, IconBell, IconCheck, IconChevron, IconCrab, IconClock, IconClose, IconDesktop, IconEdit, IconFork, IconHandover, IconFolder, IconList, IconMore, IconPin, IconPlus, IconSearch, IconSettings, IconSidebar, IconSideChat, IconSparkle, IconServer, LooMark } from './icons'; import { t } from '../i18n'; import './fork-subchat.css'; @@ -54,6 +54,8 @@ interface Props { threads: Thread[]; /** Each lead thread's team members, by the lead's id: rows under the lead instead of threads of their own. */ members?: Map; + /** Dispatched child agent threads owned by a Goal main conversation, nested under that main conversation. */ + dispatchedChildren?: Map; /** Grouped forked sub-conversations by their root thread id: merged into the parallel drawer under the lead. */ forks?: Map; /** Opens the one-step grouped sub-conversation fork dialog for a thread. */ @@ -64,6 +66,9 @@ interface Props { selectedId: string | null; onSelect: (id: string) => void; onNew: () => void; + /** Starts a new LoopX Goal main conversation. */ + onNewMain?: () => void; + mainDraftActive?: boolean; /** Starts a new thread with a directory or section pre-filled, from a group's "+". */ onNewIn: (opts: { cwd?: string; sectionId?: string; scratch?: boolean }) => void; onThreadMenu: (thread: Thread, x: number, y: number) => void; @@ -158,6 +163,7 @@ export function Sidebar({ showEmptySections = true, threads, members, + dispatchedChildren, forks, onForkSubchat, sections, @@ -165,6 +171,8 @@ export function Sidebar({ selectedId, onSelect, onNew, + onNewMain, + mainDraftActive = false, onNewIn, onThreadMenu, onSectionMenu, @@ -235,23 +243,41 @@ export function Sidebar({ // Finished work folds away closed on arrival — it is storage, not news — the count still saying // how much is in there, and the choice sticking per device. Like T3's Settled shelf. const [doneOpen, setDoneOpen] = useStoredFlag(`${storagePrefix}.doneOpen`); + const [kindFilter, setKindFilter] = useState(() => { + try { + const saved = localStorage.getItem(`${storagePrefix}.kindFilter`); + return saved === 'main' || saved === 'ordinary' ? saved : 'all'; + } catch { + return 'all'; + } + }); + const chooseKindFilter = (next: SidebarKindFilter) => { + setKindFilter(next); + try { localStorage.setItem(`${storagePrefix}.kindFilter`, next); } catch { /* ignore storage errors */ } + }; const scrollRef = useRef(null); const pendingRevealRef = useRef(null); const doneFoldOpen = () => Boolean(search.trim()) || doneOpen; // This machine's sessions that are not threads yet mix into the list by their time; every // machine's own list (the merged view) shows threads only. const everyRow = merged ? threads : withExternalSessions(threads, external); - const withExternal = everyRow; + const withExternal = filterThreadsByKind(everyRow, kindFilter); + const filteredMerged = merged + ? merged.map((source) => ({ ...source, threads: filterThreadsByKind(source.threads, kindFilter) })) + : null; const model = buildSidebar(withExternal, sections, search); - const mergedModel = merged ? buildMerged(merged, search, new Date(), selectedId) : null; + const mergedModel = filteredMerged ? buildMerged(filteredMerged, search, new Date(), selectedId) : null; const activity = byActivity && !mergedModel ? buildActivity(withExternal, search, new Date(), selectedId) : null; // Out of their project groups, rows say where they are and what was asked last. const flat = byActivity || Boolean(mergedModel); // The machine on screen being down hides its list, unless every machine is listed. const down = hostDown && !mergedModel; const wanted = attentionCount(threads, selectedId); + const waitingDispatched = dispatchedChildren + ? [...dispatchedChildren.values()].flat().filter((thread) => thread.waiting).length + : 0; // The bell's red dot is for what waits on the person: a session asking, a Goal needing a decision. Unread results only count in the title. - const waitingOnYou = threads.filter((thread) => thread.waiting).length + needsYouGoals.size; + const waitingOnYou = threads.filter((thread) => thread.waiting).length + waitingDispatched + needsYouGoals.size; // While searching, everything is expanded so matches are never hidden inside a closed group. const isOpen = (key: string) => Boolean(search.trim()) || !collapsed.has(key); @@ -259,7 +285,7 @@ export function Sidebar({ const toggleActivity = () => { const next = !byActivity; if (!next && !mergedModel && selectedId) { - const loc = locateThreadInSidebar(model, selectedId, members, forks); + const loc = locateThreadInSidebar(model, selectedId, members, forks, dispatchedChildren); if (loc) { if (loc.groupKey && collapsed.has(loc.groupKey)) toggle(loc.groupKey); if (loc.parallelParentId && teamOpen.get(loc.parallelParentId) === false) { @@ -450,7 +476,14 @@ export function Sidebar({ ); }; - const teamOf = (thread: Thread) => members?.get(thread.id); + const teamOf = (thread: Thread) => { + const team = members?.get(thread.id) ?? []; + const dispatched = dispatchedChildren?.get(thread.id) ?? []; + if (!dispatched.length) return team.length ? team : undefined; + if (!team.length) return dispatched; + const seen = new Set(team.map((m) => m.id)); + return [...team, ...dispatched.filter((d) => !seen.has(d.id))]; + }; const forksOf = (list: Thread[], team: Thread[] = []): ForkSubchatItem[] => { if (!forks?.size) return []; const teamIds = new Set(team.map((m) => m.id)); @@ -815,6 +848,11 @@ export function Sidebar({
{(() => { const links = [ + onNewMain && ( + + ), // On a wide screen a new thread is the first row, like Codex; a phone keeps the floating button by the thumb. !compact && (
)} + {!down && !search.trim() && ( +
+ {(['all', 'main', 'ordinary'] as const).map((kind) => ( + + ))} +
+ )} {!down && groups} {/* Reading the machine's sessions, or importing one, went wrong: said here, where the rows are, with a way to try again. Cleared by the next attempt. */} diff --git a/apps/workbench/packages/web/src/i18n/locales/en.ts b/apps/workbench/packages/web/src/i18n/locales/en.ts index 096f6c4ebb..1e8da34324 100644 --- a/apps/workbench/packages/web/src/i18n/locales/en.ts +++ b/apps/workbench/packages/web/src/i18n/locales/en.ts @@ -3411,4 +3411,51 @@ export const en: Messages = { 'loopx.promote.confirmCreate': 'Confirm promote to Goal', 'loopx.promote.handoverBadge': 'Local supervision handed off', 'loopx.promote.linkedGoal': (goalId: string) => `Attached Goal · ${goalId}`, + 'sidebar.newMain': 'Start a task', + 'sidebar.kindFilter.label': 'Filter conversations by type', + 'sidebar.kindFilter.all': 'All', + 'sidebar.kindFilter.main': 'Main', + 'sidebar.kindFilter.ordinary': 'Chat', + 'sidebar.dispatchedCount': (n: number) => `${n} dispatched`, + 'sidebar.kind.dispatched': 'Dispatched agent', + 'mainConv.newTitle': 'Start a task', + 'mainConv.emptyHeading': 'Start something with LoopX', + 'mainConv.emptySub': (dir: string) => `Creates a real LoopX Goal in ${dir} for ongoing execution`, + 'mainConv.placeholder': (dir: string) => `Describe what to accomplish in ${dir}; send to preview and start the LoopX Goal…`, + 'mainConv.agentHint': (reason: string) => `Selected agent cannot start a LoopX Goal: ${reason}. You can switch agents in the preview dialog.`, + 'mainConv.backToMain': 'Back to main conversation', + 'mainConv.parentChip': (title: string) => `Main · ${title}`, + 'mainConv.paletteNew': 'Start a task (LoopX Main Conversation)', + 'mainConv.dock.label': 'Main conversation bar', + 'mainConv.dock.approvals': 'Approvals', + 'mainConv.dock.dispatch': 'Dispatch', + 'mainConv.dock.todos': 'Todos', + 'mainConv.dock.close': 'Close tray', + 'mainConv.dock.approvalBanner': (n: number) => `${n} pending approval(s) in this matter`, + 'mainConv.dock.viewApprovals': 'Review', + 'mainConv.dock.goApprove': 'Open approval', + 'mainConv.dock.approve': 'Approve', + 'mainConv.dock.goHandle': 'Handle', + 'mainConv.dock.noApprovals': 'No pending approvals or confirmations for this matter.', + 'mainConv.dock.dispatchAgent': 'Target agent', + 'mainConv.dock.dispatchPermission': 'Task permission', + 'mainConv.dock.permAsk': 'Ask each time', + 'mainConv.dock.permAutoEdit': 'Auto edit', + 'mainConv.dock.permFullAccess': 'Full access', + 'mainConv.dock.permReadOnly': 'Read only', + 'mainConv.dock.dispatchPlaceholder': 'Dispatch a subtask to another agent; status, results and approvals return here…', + 'mainConv.dock.dispatchSubmit': 'Dispatch', + 'mainConv.dock.dispatching': 'Dispatching…', + 'mainConv.dock.noDispatches': 'No dispatched tasks yet. Dispatch here or let the model delegate subtasks.', + 'mainConv.dock.openChild': 'Open child thread', + 'mainConv.dock.status.queued_workspace': 'Queued', + 'mainConv.dock.status.running': 'Running', + 'mainConv.dock.status.waiting': 'Approval needed', + 'mainConv.dock.status.awaiting_approval': 'Needs confirm', + 'mainConv.dock.status.idle': 'Done', + 'mainConv.dock.status.completed': 'Completed', + 'mainConv.dock.status.failed': 'Failed', + 'mainConv.dock.status.cancelled': 'Cancelled', + 'mainConv.dock.status.user_intervened': 'Intervened', + 'mainConv.dock.alreadyHandled': 'This approval was already handled elsewhere; status refreshed.', }; diff --git a/apps/workbench/packages/web/src/i18n/locales/ja.ts b/apps/workbench/packages/web/src/i18n/locales/ja.ts index d5e35c3beb..4a35a6f900 100644 --- a/apps/workbench/packages/web/src/i18n/locales/ja.ts +++ b/apps/workbench/packages/web/src/i18n/locales/ja.ts @@ -3407,4 +3407,51 @@ export const ja: Messages = { 'loopx.promote.confirmCreate': 'Goal に昇格', 'loopx.promote.handoverBadge': 'ローカル監督を引き継ぎ済み', 'loopx.promote.linkedGoal': (goalId: string) => `紐付け済み Goal · ${goalId}`, + 'sidebar.newMain': 'タスクを開始', + 'sidebar.kindFilter.label': '会話タイプで絞り込み', + 'sidebar.kindFilter.all': 'すべて', + 'sidebar.kindFilter.main': 'メイン', + 'sidebar.kindFilter.ordinary': '通常', + 'sidebar.dispatchedCount': (n: number) => `委任 ${n}`, + 'sidebar.kind.dispatched': '委任エージェント', + 'mainConv.newTitle': 'タスクを開始', + 'mainConv.emptyHeading': 'LoopX でタスクを開始', + 'mainConv.emptySub': (dir: string) => `${dir} で LoopX Goal を作成して継続実行します`, + 'mainConv.placeholder': (dir: string) => `${dir} で進める内容を入力してください。送信後に LoopX Goal をプレビュー・開始します…`, + 'mainConv.agentHint': (reason: string) => `選択中のエージェントは LoopX Goal を開始できません:${reason}。プレビュー画面で切り替えられます。`, + 'mainConv.backToMain': 'メイン会話へ戻る', + 'mainConv.parentChip': (title: string) => `メイン · ${title}`, + 'mainConv.paletteNew': 'タスクを開始(LoopX メイン会話)', + 'mainConv.dock.label': 'メイン会話バー', + 'mainConv.dock.approvals': '承認待ち', + 'mainConv.dock.dispatch': '委任', + 'mainConv.dock.todos': 'ToDo', + 'mainConv.dock.close': 'パネルを閉じる', + 'mainConv.dock.approvalBanner': (n: number) => `この案件で ${n} 件の承認待ちがあります`, + 'mainConv.dock.viewApprovals': '確認する', + 'mainConv.dock.goApprove': '承認へ移動', + 'mainConv.dock.approve': '承認', + 'mainConv.dock.goHandle': '対応する', + 'mainConv.dock.noApprovals': 'この案件に承認待ちや確認事項はありません。', + 'mainConv.dock.dispatchAgent': '委任先エージェント', + 'mainConv.dock.dispatchPermission': '権限', + 'mainConv.dock.permAsk': '毎回確認', + 'mainConv.dock.permAutoEdit': '自動編集', + 'mainConv.dock.permFullAccess': 'フル権限', + 'mainConv.dock.permReadOnly': '読み取り専用', + 'mainConv.dock.dispatchPlaceholder': '他のエージェントへサブタスクを委任(結果と承認はこの案件に戻ります)…', + 'mainConv.dock.dispatchSubmit': '委任する', + 'mainConv.dock.dispatching': '委任中…', + 'mainConv.dock.noDispatches': '委任履歴はまだありません。ここから委任するかモデルから指示できます。', + 'mainConv.dock.openChild': '子会話を開く', + 'mainConv.dock.status.queued_workspace': '待機中', + 'mainConv.dock.status.running': '実行中', + 'mainConv.dock.status.waiting': '承認待ち', + 'mainConv.dock.status.awaiting_approval': '確認待ち', + 'mainConv.dock.status.idle': '完了', + 'mainConv.dock.status.completed': '完了', + 'mainConv.dock.status.failed': '失敗', + 'mainConv.dock.status.cancelled': 'キャンセル', + 'mainConv.dock.status.user_intervened': '手動介入', + 'mainConv.dock.alreadyHandled': 'この承認は既に他所で処理されました。状態を更新しました。', }; diff --git a/apps/workbench/packages/web/src/i18n/locales/zh.ts b/apps/workbench/packages/web/src/i18n/locales/zh.ts index 413073b65a..7855869b82 100644 --- a/apps/workbench/packages/web/src/i18n/locales/zh.ts +++ b/apps/workbench/packages/web/src/i18n/locales/zh.ts @@ -3409,6 +3409,53 @@ export const zh = { 'loopx.promote.confirmCreate': '确认升级为 Goal', 'loopx.promote.handoverBadge': '本地督办已交接', 'loopx.promote.linkedGoal': (goalId: string) => `已挂接 Goal · ${goalId}`, + 'sidebar.newMain': '开始一件事', + 'sidebar.kindFilter.label': '按会话类型筛选', + 'sidebar.kindFilter.all': '全部', + 'sidebar.kindFilter.main': '主对话', + 'sidebar.kindFilter.ordinary': '普通', + 'sidebar.dispatchedCount': (n: number) => `已派工 ${n}`, + 'sidebar.kind.dispatched': '子 Agent 派工', + 'mainConv.newTitle': '开始一件事', + 'mainConv.emptyHeading': '用 LoopX 开始一件事', + 'mainConv.emptySub': (dir: string) => `将在 ${dir} 中创建真实 LoopX Goal 并持续推进`, + 'mainConv.placeholder': (dir: string) => `描述要在 ${dir} 完成的事情,发送后预览并启动 LoopX Goal…`, + 'mainConv.agentHint': (reason: string) => `当前 Agent 暂不可启动 LoopX Goal:${reason}。发送后可在预览弹窗中切换可用 Agent。`, + 'mainConv.backToMain': '返回主对话', + 'mainConv.parentChip': (title: string) => `主对话 · ${title}`, + 'mainConv.paletteNew': '开始一件事(LoopX 主对话)', + 'mainConv.dock.label': '主对话工作栏', + 'mainConv.dock.approvals': '待审核', + 'mainConv.dock.dispatch': '派工', + 'mainConv.dock.todos': '待办', + 'mainConv.dock.close': '收起面板', + 'mainConv.dock.approvalBanner': (n: number) => `${n} 项子 Agent 或事项审核待处理`, + 'mainConv.dock.viewApprovals': '查看审核', + 'mainConv.dock.goApprove': '前往审核', + 'mainConv.dock.approve': '批准', + 'mainConv.dock.goHandle': '前往处理', + 'mainConv.dock.noApprovals': '当前事项没有待处理的审核或确认。', + 'mainConv.dock.dispatchAgent': '目标 Agent', + 'mainConv.dock.dispatchPermission': '子任务权限', + 'mainConv.dock.permAsk': '每次询问', + 'mainConv.dock.permAutoEdit': '自动编辑', + 'mainConv.dock.permFullAccess': '完全权限', + 'mainConv.dock.permReadOnly': '只读检查', + 'mainConv.dock.dispatchPlaceholder': '派一项子任务给其他 Agent,结果与审核会回到本事项…', + 'mainConv.dock.dispatchSubmit': '派工', + 'mainConv.dock.dispatching': '派工中…', + 'mainConv.dock.noDispatches': '还没有派工记录。可直接在这里或让模型派任务给其他 Agent。', + 'mainConv.dock.openChild': '打开子对话', + 'mainConv.dock.status.queued_workspace': '排队中', + 'mainConv.dock.status.running': '执行中', + 'mainConv.dock.status.waiting': '待审核', + 'mainConv.dock.status.awaiting_approval': '待确认', + 'mainConv.dock.status.idle': '已完成', + 'mainConv.dock.status.completed': '已完成', + 'mainConv.dock.status.failed': '失败', + 'mainConv.dock.status.cancelled': '已取消', + 'mainConv.dock.status.user_intervened': '已接管', + 'mainConv.dock.alreadyHandled': '该审核已在其他入口处理,已刷新状态。', }; export type Messages = typeof zh; diff --git a/apps/workbench/packages/web/src/loopx/loopx.css b/apps/workbench/packages/web/src/loopx/loopx.css index 70ab1030f5..2e89b69889 100644 --- a/apps/workbench/packages/web/src/loopx/loopx.css +++ b/apps/workbench/packages/web/src/loopx/loopx.css @@ -714,3 +714,368 @@ .goal-task-gate { display: grid; gap: 4px; padding: 8px 10px; border: 1px solid var(--loopx-blue); border-radius: 8px; background: var(--loopx-blue-soft); color: var(--text); font-size: 12.5px; } .goal-task-gate p { margin: 0; } .goal-task-gate-next { color: var(--muted); font-size: 12px; } + +/* Sidebar conversation-kind filter (全部 / 主对话 / 普通) */ +.sidebar-kind-filter { + display: grid; + grid-template-columns: repeat(3, minmax(0, 1fr)); + gap: 2px; + margin: 4px 10px 8px; + padding: 2px; + border: 1px solid var(--border); + border-radius: 9px; + background: var(--surface-2, var(--surface)); +} +.sidebar-kind-pill { + min-height: 26px; + padding: 2px 6px; + border: 0; + border-radius: 7px; + background: transparent; + color: var(--muted); + font-size: 12px; + font-weight: 500; + cursor: pointer; + white-space: nowrap; + overflow: hidden; + text-overflow: ellipsis; +} +.sidebar-kind-pill:hover { color: var(--text); } +.sidebar-kind-pill.active { + background: var(--surface); + color: var(--text); + box-shadow: 0 1px 2px rgba(0, 0, 0, 0.06); +} + +/* Main conversation empty state & draft notice */ +.empty-main-mark { + display: inline-flex; + align-items: center; + justify-content: center; + margin-bottom: 8px; + color: var(--text); +} +.empty-sub { + margin: 6px 0 0; + color: var(--muted); + font-size: 13px; +} +.main-draft-hint { + margin: 0 0 6px; + padding: 6px 10px; + border: 1px solid var(--border); + border-radius: 8px; + background: var(--surface-2, var(--surface)); + color: var(--muted); + font-size: 12.5px; +} + +/* Persona-style Main Conversation Dock (monochrome precision, amber attention, one tray at a time) */ +.main-dock { + width: min(100%, var(--chat-max, 780px)); + margin: 0 auto 6px; + display: flex; + flex-direction: column; + gap: 6px; +} +.main-dock-alert { + display: flex; + flex-wrap: wrap; + align-items: center; + gap: 8px; + padding: 7px 11px; + border: 1px solid color-mix(in srgb, var(--warn, #b45309) 38%, var(--border)); + border-radius: 10px; + background: color-mix(in srgb, var(--warn, #b45309) 8%, var(--surface)); + color: var(--text); + font-size: 12.5px; +} +.main-dock-alert-dot { + width: 7px; + height: 7px; + border-radius: 50%; + background: var(--warn, #b45309); + flex: none; +} +.main-dock-alert-text { + flex: 1 1 200px; + min-width: 0; + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; +} +.main-dock-alert-detail { color: var(--muted); font-weight: 400; } +.main-dock-alert-actions { display: flex; align-items: center; gap: 6px; flex: none; } + +.main-dock-strip { + display: flex; + flex-wrap: wrap; + align-items: center; + justify-content: space-between; + gap: 6px 10px; +} +.main-dock-capsules { + display: flex; + flex-wrap: wrap; + align-items: center; + gap: 6px; +} +.main-dock-capsule { + display: inline-flex; + align-items: center; + gap: 6px; + height: 30px; + padding: 0 11px; + border: 1px solid var(--border); + border-radius: 999px; + background: var(--surface); + color: var(--text); + font-size: 12.5px; + font-weight: 500; + cursor: pointer; +} +.main-dock-capsule:hover { background: var(--surface-2, var(--active)); } +.main-dock-capsule.active { + background: var(--text); + border-color: var(--text); + color: var(--surface); +} +.main-dock-capsule.has-attention:not(.active) { + border-color: color-mix(in srgb, var(--warn, #b45309) 45%, var(--border)); +} +.main-dock-count { + display: inline-flex; + align-items: center; + justify-content: center; + min-width: 17px; + height: 17px; + padding: 0 5px; + border-radius: 999px; + background: var(--surface-2, var(--active)); + color: var(--text); + font-size: 11px; + font-weight: 600; + font-variant-numeric: tabular-nums; +} +.main-dock-capsule.active .main-dock-count { + background: color-mix(in srgb, var(--surface) 18%, transparent); + color: var(--surface); +} +.main-dock-count.is-attention { + background: color-mix(in srgb, var(--warn, #b45309) 16%, transparent); + color: var(--warn, #b45309); +} +.main-dock-capsule.active .main-dock-count.is-attention { + background: var(--warn, #b45309); + color: #fff; +} +.main-dock-count.is-live { + background: var(--loopx-blue-soft); + color: var(--loopx-blue); +} +.main-dock-goal-tag { + display: inline-flex; + align-items: center; + gap: 5px; + min-width: 0; + max-width: 240px; + color: var(--muted); + font-size: 12px; +} +.main-dock-goal-tag span { + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; +} + +.main-dock-tray { + border: 1px solid var(--border); + border-radius: 12px; + background: var(--surface); + box-shadow: 0 6px 20px rgba(0, 0, 0, 0.08); + overflow: hidden; +} +.main-dock-tray-head { + display: flex; + align-items: center; + justify-content: space-between; + padding: 8px 12px; + border-bottom: 1px solid var(--border); +} +.main-dock-tray-title { font-size: 12.5px; font-weight: 600; color: var(--text); } +.main-dock-close { + display: inline-flex; + align-items: center; + justify-content: center; + width: 24px; + height: 24px; + border: 0; + border-radius: 6px; + background: transparent; + color: var(--muted); + cursor: pointer; +} +.main-dock-close:hover { background: var(--surface-2, var(--active)); color: var(--text); } +.main-dock-tray-body { + max-height: min(360px, 44vh); + overflow-y: auto; + padding: 10px 12px; +} + +.main-dock-empty { margin: 4px 0; font-size: 12.5px; color: var(--muted); } +.main-dock-note { margin: 0 0 8px; padding: 6px 10px; border-radius: 8px; background: var(--surface-2, var(--active)); color: var(--text); font-size: 12.5px; } +.main-dock-error { margin: 6px 0 0; padding: 6px 10px; border-radius: 8px; background: rgba(192, 57, 43, 0.1); color: var(--text); font-size: 12.5px; } + +.main-dock-card-list { display: grid; gap: 8px; } +.main-dock-card { + display: grid; + gap: 8px; + padding: 9px 11px; + border: 1px solid var(--border); + border-radius: 10px; + background: var(--surface); +} +.main-dock-card-head { + display: flex; + flex-wrap: wrap; + align-items: center; + justify-content: space-between; + gap: 6px; +} +.main-dock-card-title { font-size: 13px; font-weight: 500; color: var(--text); overflow-wrap: anywhere; } +.main-dock-card-actions { display: flex; flex-wrap: wrap; gap: 6px; } + +.main-dock-action-btn, +.main-dock-link-btn { + height: 27px; + padding: 0 10px; + border: 1px solid var(--border); + border-radius: 7px; + background: var(--surface); + color: var(--text); + font-size: 12px; + font-weight: 500; + cursor: pointer; +} +.main-dock-action-btn:hover:not(:disabled), +.main-dock-link-btn:hover:not(:disabled) { background: var(--surface-2, var(--active)); } +.main-dock-action-btn.is-primary, +.main-dock-link-btn.is-primary { + background: var(--accent, var(--text)); + border-color: var(--accent, var(--text)); + color: var(--accent-fg, var(--surface)); +} +.main-dock-action-btn.is-primary:hover:not(:disabled), +.main-dock-link-btn.is-primary:hover:not(:disabled) { + opacity: 0.9; + background: var(--accent, var(--text)); +} +.main-dock-action-btn:disabled { opacity: 0.55; cursor: not-allowed; } + +.main-dock-dispatch { display: grid; gap: 10px; } +.main-dock-dispatch-form { display: grid; gap: 7px; } +.main-dock-dispatch-controls { display: flex; flex-wrap: wrap; gap: 6px; } +.main-dock-select { + height: 30px; + padding: 0 8px; + border: 1px solid var(--border); + border-radius: 8px; + background: var(--surface); + color: var(--text); + font: inherit; + font-size: 12.5px; +} +.main-dock-dispatch-input-row { display: flex; gap: 6px; } +.main-dock-input { + flex: 1 1 180px; + min-width: 0; + height: 32px; + padding: 0 10px; + border: 1px solid var(--border); + border-radius: 8px; + background: var(--surface); + color: var(--text); + font: inherit; + font-size: 13px; +} +.main-dock-submit { + height: 32px; + padding: 0 14px; + border: 1px solid var(--accent, var(--text)); + border-radius: 8px; + background: var(--accent, var(--text)); + color: var(--accent-fg, var(--surface)); + font-size: 12.5px; + font-weight: 500; + cursor: pointer; + flex: none; +} +.main-dock-submit:disabled { opacity: 0.45; cursor: not-allowed; } + +.main-dock-task-list { list-style: none; margin: 0; padding: 0; display: grid; gap: 7px; } +.main-dock-task-row { + display: grid; + gap: 5px; + padding: 8px 10px; + border: 1px solid var(--border); + border-radius: 9px; + background: var(--surface); +} +.main-dock-task-head { + display: flex; + flex-wrap: wrap; + align-items: center; + justify-content: space-between; + gap: 6px; +} +.main-dock-task-title { font-size: 13px; font-weight: 500; color: var(--text); overflow-wrap: anywhere; } +.main-dock-task-meta { display: inline-flex; align-items: center; gap: 6px; flex: none; } +.main-dock-agent-chip { + padding: 1px 7px; + border: 1px solid var(--border); + border-radius: 999px; + color: var(--muted); + font-size: 11.5px; +} +.main-dock-pill { + padding: 1px 7px; + border-radius: 999px; + font-size: 11.5px; + font-weight: 500; + background: var(--surface-2, var(--active)); + color: var(--muted); +} +.main-dock-pill.is-waiting { + background: color-mix(in srgb, var(--warn, #b45309) 14%, transparent); + color: var(--warn, #b45309); +} +.main-dock-pill.is-running { + background: var(--loopx-blue-soft); + color: var(--loopx-blue); +} +.main-dock-pill.is-done { + background: var(--surface-2, var(--active)); + color: var(--text); +} +.main-dock-pill.is-error { + background: rgba(192, 57, 43, 0.12); + color: #b42318; +} +.main-dock-task-summary { + margin: 0; + font-size: 12px; + color: var(--muted); + line-height: 1.45; + overflow-wrap: anywhere; + display: -webkit-box; + -webkit-line-clamp: 3; + -webkit-box-orient: vertical; + overflow: hidden; +} +.main-dock-task-actions { display: flex; gap: 6px; } +.main-dock-todos .goal-tasks { margin: 0; } + +@media (max-width: 640px) { + .main-dock-goal-tag { display: none; } + .main-dock-tray-body { max-height: 48vh; } +} diff --git a/apps/workbench/packages/web/src/sidebar.ts b/apps/workbench/packages/web/src/sidebar.ts index 623587d958..cd34e215c5 100644 --- a/apps/workbench/packages/web/src/sidebar.ts +++ b/apps/workbench/packages/web/src/sidebar.ts @@ -2,6 +2,7 @@ import type { Attention } from '@calli/extension-api'; import type { AgentInfo, ExternalSession, Section, Thread } from './api'; import { folderName } from './paths'; +import { goalOf } from './loopx/launch'; import type { AgentMarkInfo } from './thread-cache'; import { t } from './i18n'; @@ -125,8 +126,17 @@ export function withExternalSessions(threads: Thread[], external: ExternalSessio .sort((a, b) => (a.updatedAt < b.updatedAt ? 1 : a.updatedAt > b.updatedAt ? -1 : 0)); } -/** Whether a row (a thread, or a session not yet a thread) is a LoopX Goal conversation. */ -export const isLoopxRow = (thread: Thread): boolean => Boolean(thread.external ? thread.external.loopx : thread.loopxInfo); +/** Whether a row (a thread, or a session not yet a thread) is a LoopX Goal conversation (main conversation). */ +export const isLoopxRow = (thread: Thread): boolean => + Boolean(thread.external ? thread.external.loopx : (thread.loopxInfo || goalOf(thread))); + +export type SidebarKindFilter = 'all' | 'main' | 'ordinary'; + +export function filterThreadsByKind(threads: Thread[], filter: SidebarKindFilter): Thread[] { + if (filter === 'main') return threads.filter(isLoopxRow); + if (filter === 'ordinary') return threads.filter((thread) => !isLoopxRow(thread)); + return threads; +} /** A thread appears exactly once: under "pinned" if pinned, else under its section if it has one, * else under its project (working directory). Threads keep the order they arrive in. @@ -193,6 +203,7 @@ export function locateThreadInSidebar( selectedId: string | null, members?: Map, forks?: Map, + dispatched?: Map, ): SidebarLocation | null { if (!selectedId) return null; const matchIn = (list: Thread[]): { parallelParentId: string | null } | null => { @@ -200,7 +211,8 @@ export function locateThreadInSidebar( if (thread.id === selectedId) return { parallelParentId: null }; const inTeam = members?.get(thread.id)?.some((m) => m.id === selectedId) ?? false; const inFork = forks?.get(thread.id)?.some((f) => f.thread.id === selectedId) ?? false; - if (inTeam || inFork) return { parallelParentId: thread.id }; + const inDispatched = dispatched?.get(thread.id)?.some((d) => d.id === selectedId) ?? false; + if (inTeam || inFork || inDispatched) return { parallelParentId: thread.id }; } return null; }; diff --git a/apps/workbench/packages/web/test/main-conversations.test.ts b/apps/workbench/packages/web/test/main-conversations.test.ts new file mode 100644 index 0000000000..3480758204 --- /dev/null +++ b/apps/workbench/packages/web/test/main-conversations.test.ts @@ -0,0 +1,302 @@ +import assert from 'node:assert/strict'; +import { test } from 'node:test'; +import { registerHooks } from 'node:module'; +import * as React from 'react'; +import { createElement } from 'react'; +import { act, create, type ReactTestRenderer } from 'react-test-renderer'; + +(globalThis as unknown as { React: typeof React }).React = React; + +registerHooks({ + load(url, context, next) { + if (url.endsWith('.svg') || url.endsWith('.css')) { + return { format: 'module', source: 'export default ""', shortCircuit: true }; + } + return next(url, context); + }, +}); + +const { filterThreadsByKind, isLoopxRow } = await import('../src/sidebar.js'); +const { MainConversationDock, filterMainDockApprovalCards } = await import('../src/components/MainConversationDock.js'); +import type { Api, AgentInfo, StewardSurfaceSnapshot, StewardTaskRecord, Thread } from '../src/api.js'; + +const tick = () => new Promise((resolve) => setImmediate(resolve)); + +function makeThread(overrides: Partial & { id: string; title: string }): Thread { + return { + agent: 'claude', + cwd: '/tmp/proj', + cwdReal: '/tmp/proj', + agentSessionId: null, + status: 'idle', + pinned: false, + permissionMode: 'auto_edit', + model: null, + effort: null, + archivedAt: null, + sectionId: null, + forkedFrom: null, + unread: false, + preview: null, + terminalActivity: false, + waiting: false, + queued: [], + resumeCommand: null, + createdAt: '2026-12-03T10:00:00Z', + updatedAt: '2026-12-03T10:00:00Z', + ...overrides, + }; +} + +test('filterThreadsByKind distinguishes Goal main conversations (new, legacy, external) from ordinary legacy threads', () => { + const newMain = makeThread({ + id: 'th-main-new', + title: 'Goal A', + loopxInfo: { goalId: 'goal-a', goalTitle: 'Goal A', basis: 'workbench', source: 'launch' }, + }); + const legacyGoal = makeThread({ + id: 'th-main-legacy', + title: 'Legacy Goal', + loopxInfo: { goalId: 'goal-legacy', goalTitle: 'Legacy Goal', basis: 'core', source: 'join' }, + }); + const externalGoal = makeThread({ + id: 'ext:codex:s1', + title: 'External Goal Session', + external: { + agent: 'codex', + sessionId: 's1', + cwd: '/tmp/proj', + title: 'External Goal Session', + updatedAt: '2026-12-03T10:00:00Z', + loopx: { goalId: 'goal-ext', goalTitle: 'External Goal', basis: 'core', source: 'scan' }, + }, + }); + const ordinary = makeThread({ id: 'th-ordinary', title: 'Ordinary Chat' }); + + const all = [newMain, legacyGoal, externalGoal, ordinary]; + assert.equal(isLoopxRow(newMain), true); + assert.equal(isLoopxRow(legacyGoal), true); + assert.equal(isLoopxRow(externalGoal), true); + assert.equal(isLoopxRow(ordinary), false); + + assert.deepEqual(filterThreadsByKind(all, 'all').map((x) => x.id), ['th-main-new', 'th-main-legacy', 'ext:codex:s1', 'th-ordinary']); + assert.deepEqual(filterThreadsByKind(all, 'main').map((x) => x.id), ['th-main-new', 'th-main-legacy', 'ext:codex:s1']); + assert.deepEqual(filterThreadsByKind(all, 'ordinary').map((x) => x.id), ['th-ordinary']); +}); + +test('filterMainDockApprovalCards keeps only actionable approvals/inputs/plans/Core actions', () => { + const snapshot: StewardSurfaceSnapshot = { + generatedAt: '2026-12-03T10:00:00Z', + counts: { needsYou: 3, coreActions: 0, inProgress: 0, stewardReviewing: 0, openConcerns: 0, dueFollowups: 0 }, + inlineCards: [ + { + id: 'approval:ap-1', + kind: 'thread_approval', + approvalId: 'ap-1', + threadId: 'child-1', + threadTitle: 'Child Worker', + title: 'Run npm install', + options: [{ optionId: 'allow', name: 'Allow', kind: 'allow_once' }], + }, + { + id: 'concern:c-1', + kind: 'concern_report', + concernId: 'c-1', + title: 'Concern', + reportText: 'Info only', + reportEvidence: null, + targetThreadId: 'child-1', + closedAt: null, + }, + { + id: 'input:in-1', + kind: 'thread_input', + inputId: 'in-1', + threadId: 'child-1', + threadTitle: 'Child Worker', + inputKind: 'question', + title: 'Pick port', + questions: [], + }, + ], + inProgress: [], + stewardReviewing: [], + concerns: [], + followups: [], + }; + assert.deepEqual(filterMainDockApprovalCards(snapshot).map((c) => c.id), ['approval:ap-1', 'input:in-1']); +}); + +test('MainConversationDock isolates matters on switch, forwards scoped queries, and handles duplicate 404 approval gracefully', async () => { + Object.assign(globalThis, { IS_REACT_ACT_ENVIRONMENT: true }); + + const surfaceCalls: Array<{ goalId?: string | null; parentThreadId?: string | null }> = []; + const taskCalls: Array<{ goalId?: string; parentThreadId?: string }> = []; + const decideCalls: Array<{ id: string; optionId?: string }> = []; + const openedThreads: string[] = []; + let changedCount = 0; + + const surfaceByGoal: Record = { + 'goal-a': { + generatedAt: '2026-12-03T10:00:00Z', + counts: { needsYou: 1, coreActions: 0, inProgress: 1, stewardReviewing: 0, openConcerns: 0, dueFollowups: 0 }, + inlineCards: [ + { + id: 'approval:ap-a', + kind: 'thread_approval', + approvalId: 'ap-a', + threadId: 'child-a', + threadTitle: 'Child A', + title: 'npm install lodash', + options: [ + { optionId: 'allow', name: 'Allow', kind: 'allow_once' }, + { optionId: 'reject', name: 'Reject', kind: 'reject_once' }, + ], + }, + ], + inProgress: [], + stewardReviewing: [], + concerns: [], + followups: [], + }, + 'goal-b': { + generatedAt: '2026-12-03T10:00:00Z', + counts: { needsYou: 0, coreActions: 0, inProgress: 0, stewardReviewing: 0, openConcerns: 0, dueFollowups: 0 }, + inlineCards: [], + inProgress: [], + stewardReviewing: [], + concerns: [], + followups: [], + }, + }; + + const tasksByGoal: Record = { + 'goal-a': [ + { + id: 'task-a1', + planId: 'plan-a', + title: 'Install deps in A', + objective: 'approve install', + doneWhen: ['installed'], + readonly: false, + ownerStep: null, + agent: 'claude', + model: null, + effort: null, + permissionMode: 'ask', + sourceCwd: '/tmp/proj', + resolvedCwd: '/tmp/proj', + lockDir: null, + workspacePolicy: 'none', + workspaceResolved: { path: '/tmp/proj', worktree: null, queued: false, queuedBehindTaskId: null, queuePosition: null }, + threadId: 'child-a', + status: 'running', + lastTurnId: 't1', + returnRoute: { channel: 'main_conversation', goalId: 'goal-a', parentThreadId: 'th-a', originId: 'th-a' }, + resultSummary: null, + queueSeq: null, + errorMessage: null, + createdAt: '2026-12-03T10:00:00Z', + updatedAt: '2026-12-03T10:00:00Z', + startedAt: '2026-12-03T10:00:00Z', + settledAt: null, + promotedGoalId: null, + promotedAt: null, + supervisionFenced: false, + }, + ], + 'goal-b': [], + }; + + const { ApiError } = await import('../src/api.js'); + const fakeApi = { + demo: false, + stewardSurface: async (opts?: { goalId?: string | null; parentThreadId?: string | null }) => { + surfaceCalls.push({ goalId: opts?.goalId, parentThreadId: opts?.parentThreadId }); + return surfaceByGoal[opts?.goalId ?? ''] ?? surfaceByGoal['goal-b']!; + }, + stewardTasks: async (opts?: { goalId?: string; parentThreadId?: string }) => { + taskCalls.push({ goalId: opts?.goalId, parentThreadId: opts?.parentThreadId }); + return { tasks: tasksByGoal[opts?.goalId ?? ''] ?? [] }; + }, + decide: async (approvalId: string, body: { optionId?: string }) => { + decideCalls.push({ id: approvalId, optionId: body.optionId }); + // Simulate duplicate / already-resolved approval returning 404. + throw new ApiError('approval_not_found', {}, 404); + }, + } as unknown as Api; + + const agents: AgentInfo[] = [ + { id: 'claude', label: 'Claude', available: true, capabilities: { resume: true, approvals: true, permissionModes: ['ask', 'auto_edit', 'full_access'], effortLevels: [], images: false, deleteSession: false, history: true, quota: false, fork: false, forkAt: false, forkInto: false } }, + ]; + const threadA = makeThread({ id: 'th-a', title: 'Matter A', loopxInfo: { goalId: 'goal-a', goalTitle: 'Matter A', basis: 'workbench', source: 'launch' } }); + const threadB = makeThread({ id: 'th-b', title: 'Matter B', loopxInfo: { goalId: 'goal-b', goalTitle: 'Matter B', basis: 'workbench', source: 'launch' } }); + const childA = makeThread({ id: 'child-a', title: 'Child A', waiting: true }); + + let renderer!: ReactTestRenderer; + await act(async () => { + renderer = create( + createElement(MainConversationDock, { + api: fakeApi, + token: 'tok', + thread: threadA, + goalId: 'goal-a', + agents, + threads: [threadA, threadB, childA], + goal: undefined, + attention: undefined, + refreshTick: 0, + onOpenThread: (id) => openedThreads.push(id), + onChanged: () => { changedCount += 1; }, + }), + ); + await tick(); + }); + + // Scoped queries were called strictly with Matter A's goalId & threadId. + assert.deepEqual(surfaceCalls[0], { goalId: 'goal-a', parentThreadId: 'th-a' }); + assert.deepEqual(taskCalls[0], { goalId: 'goal-a', parentThreadId: 'th-a' }); + + // Approval banner appears for Matter A with direct jump to child thread. + const banner = renderer.root.findByProps({ 'data-testid': 'main-dock-approval-banner' }); + assert.ok(banner); + + // Open approvals tray and click inline Allow -> 404 reconciles cleanly without crashing. + const tabApprovals = renderer.root.findByProps({ 'data-testid': 'main-dock-tab-approvals' }); + await act(async () => { + tabApprovals.props.onClick(); + await tick(); + }); + const allowBtn = renderer.root.findAllByType('button').find((b) => b.children.join('') === 'Allow'); + assert.ok(allowBtn); + await act(async () => { + await allowBtn!.props.onClick(); + await tick(); + }); + assert.equal(decideCalls.length, 1); + assert.equal(changedCount, 1); + + // Switch to Matter B -> Matter A's approval banner and cards disappear immediately. + await act(async () => { + renderer.update( + createElement(MainConversationDock, { + api: fakeApi, + token: 'tok', + thread: threadB, + goalId: 'goal-b', + agents, + threads: [threadA, threadB, childA], + goal: undefined, + attention: undefined, + refreshTick: 0, + onOpenThread: (id) => openedThreads.push(id), + onChanged: () => { changedCount += 1; }, + }), + ); + await tick(); + }); + + assert.equal(renderer.root.findAllByProps({ 'data-testid': 'main-dock-approval-banner' }).length, 0); + assert.deepEqual(surfaceCalls.at(-1), { goalId: 'goal-b', parentThreadId: 'th-b' }); + renderer.unmount(); +}); From ae6c3f2112c61ccd93e84ffbb78290e5bf295ada Mon Sep 17 00:00:00 2001 From: maxliux5 <5958865+maxliux5@users.noreply.github.com> Date: Fri, 4 Dec 2026 10:27:47 +0800 Subject: [PATCH 2/7] feat(workbench): refine loop UI with scoped supervision entry, inline task cards, and dock cleanup Signed-off-by: maxliux5 <5958865+maxliux5@users.noreply.github.com> --- .../docs/main-conversations-design.md | 32 +- .../e2e/test/main-conversations.spec.mjs | 427 +++++++-- apps/workbench/packages/web/src/App.tsx | 58 +- apps/workbench/packages/web/src/api.ts | 66 +- .../src/components/LoopInlineTaskCards.tsx | 92 ++ .../web/src/components/LoopSupervisionBar.tsx | 250 ++++++ .../src/components/MainConversationDock.tsx | 821 +++++++++++------- .../packages/web/src/components/Sidebar.tsx | 7 +- .../packages/web/src/i18n/locales/en.ts | 90 +- .../packages/web/src/i18n/locales/ja.ts | 82 +- .../packages/web/src/i18n/locales/zh.ts | 84 +- .../packages/web/src/loopx/loopx.css | 381 +++++++- .../packages/web/src/loopx/supervision.ts | 607 +++++++++++++ .../web/test/main-conversations.test.ts | 606 +++++++++++-- 14 files changed, 3059 insertions(+), 544 deletions(-) create mode 100644 apps/workbench/packages/web/src/components/LoopInlineTaskCards.tsx create mode 100644 apps/workbench/packages/web/src/components/LoopSupervisionBar.tsx create mode 100644 apps/workbench/packages/web/src/loopx/supervision.ts diff --git a/apps/workbench/docs/main-conversations-design.md b/apps/workbench/docs/main-conversations-design.md index 2b28e95703..7957eeff8d 100644 --- a/apps/workbench/docs/main-conversations-design.md +++ b/apps/workbench/docs/main-conversations-design.md @@ -7,14 +7,14 @@ ### 1.1 主对话即真实 LoopX Goal 会话 - **归属实体**:主对话不新建平行的 `conversation_kind` 线程表,而是直接绑定真实 LoopX Goal(`LoopxBindings` 的 `/loopx-threads.json` 与线程 `loopx` / `loopxInfo` 投影,携带稳定 `goalId`、`workspace` 与 `permission`)。 -- **免手选 LoopX**: - - 侧栏一级入口新增 **「开始一件事」**(`Sidebar.tsx`、`⌘K` 命令面板及折叠侧栏顶栏按钮同步提供),同时移除旧输入框上的手选 `` 按钮。 - - 点击「开始一件事」即进入 `draftMain` 状态:自动清理 `draftTeam` 与无项目 `scratch`、优先选中支持 Goal 的 Agent、在输入栏保留必要的 ``(`read_only` / `workspace_auto`)与 ``(支持当前项目及既有「新建项目」流程)。 - - 发送首条消息时,自动走既有 `POST /api/loopx/launch/preview` → `` → `POST /api/loopx/launch/apply` 创建真实 LoopX Goal 并绑定主对话线程。 +- **免手选 LoopX(定名小写 `loop`)**: + - 侧栏一级入口提供 **「新 loop」**(`Sidebar.tsx`、`⌘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)` 归类,侧栏支持 **全部 / 主对话 / 普通** 三态筛选(持久化在 `localStorage`),刷新、重开后归属稳定。 + - 历史普通会话、历史 Goal 会话与扫描到的本机 Goal 会话直接通过 `isLoopxRow(thread)` 归类,侧栏支持 **全部 / loop / 普通** 三态筛选(持久化在 `localStorage`),刷新、重开后归属稳定。 ## 2. 复用的既有服务与最小扩展边界 @@ -26,12 +26,24 @@ | 权限审核汇聚与跳转 | `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. 交互结构(参考 Persona Dock) +## 3. 交互结构(`loop` 顶部督办、内联任务卡与底部状态栏) -主对话线程在输入框上方挂载 ``(仅对真实 Goal 会话渲染): -1. **待审核提醒条**:当本事项存在子 Agent 权限请求、等待输入或 Core Action 提案时,以克制的琥珀态单行提示浮现,提供「前往审核」直达子线程 `` 或「查看审核」展开抽屉。 -2. **单行胶囊条**:`待审核 N`、`派工 N`、`待办 N` 三个 30px 单色胶囊 + 右侧当前 Goal 标识;同一时间仅展开一个可滚动抽屉,`Esc` 关闭抽屉且不中断正在进行的对话轮次。 -3. **侧栏折叠与返回**:由主对话派出的活跃子线程自动折叠在该主对话行下方(复用意图一致的并行子行抽屉);子线程等待审核时父行同步亮起等待圆点;打开子线程后顶栏显示「← 主对话 · 标题」。 +`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` 任务事件与实际状态验收。 + - **真实状态与权限边界**:分子与分母严格同源(仅统计当前可督办子任务集合中的已授权数,`active <= eligible`);全量授权且全局已开启时顶栏切为「督办已生效」状态按钮而不再重复突出「帮我督办」主按钮;明确区分全局「管家自动督办」开关(未开启时仅记录本 `loop` 子任务授权、不虚报自动巡检已运行,并提供「前往通用设置」引导,绝不静默改动全局开关影响其他项目);只读子任务仅授予 `['retry', 'continue']` 不扩写权限;存在待审批/待确认项时停在审批前,绝不自动放行审批;连点去重、同授权幂等、切 `loop` 互不阻塞/不串回执;撤销仅撤销本 `loop` 任务授权。 +2. **对话流内联子任务卡**(``): + - 直接在 `loop` 对话流中呈现真实 `StewardTaskRecord` 卡片(相对时间不折行、Agent 芯片、只读/已授权督办真实芯片、状态点与点击直达子会话 `↗`),通过 `cleanReadableSummary()` 过滤原始 closeout 模板与内部派工 UUID(无可读摘要时隐藏摘要片段),不伪造未知字段(后端未持久化新建/续接唤醒模式故不虚构该角标): + - `waiting` / `awaiting_approval` → `需要你`(蓝点) + - `running` → `工作中`(琥珀点);`queued_workspace` → `排队中` + - `idle` 且位于 `stewardReviewing` → `待验收` + - `failed` / `cancelled` → `已中断`(红 `!` + 真实错误信息) + - `user_intervened` → `已接管`;其余 `idle` / `completed` → `已完成` +3. **底部精简状态筛选栏**(``): + - 合并重复审批入口:提醒条仅保留单个「去处理」按钮打开「要你处理」抽屉,抽屉内每条审批提供真实裁决按钮 + 单个子会话跳转链接。 + - 胶囊条改为手机友好的 **要你处理 N / 进行中 N / 已完成 N / 待办 N**,移除输入框旁重复的 Goal 标题芯片;手动派工表单默认收起在「进行中」抽屉右上角「手动派工」按钮后;派工在途状态、输入与错误按 `(thread.id, goalId)` 隔离(修复 PR #10072 评审意见 #1);`Esc` 关闭抽屉且不中断正在进行的对话轮次。 +4. **侧栏折叠与返回**:由 `loop` 派出的活跃子线程自动折叠在该 `loop` 行下方;子线程等待审核时父行同步亮起等待圆点;打开子线程后顶栏显示「← loop · 标题」。 ## 4. 归属、权限与并发边界 diff --git a/apps/workbench/packages/e2e/test/main-conversations.spec.mjs b/apps/workbench/packages/e2e/test/main-conversations.spec.mjs index 3933c19a1c..130ea23116 100644 --- a/apps/workbench/packages/e2e/test/main-conversations.spec.mjs +++ b/apps/workbench/packages/e2e/test/main-conversations.spec.mjs @@ -1,4 +1,4 @@ -// Real-browser Playwright E2E for Workbench Main Conversations (Goal-backed): +// 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'; @@ -7,25 +7,19 @@ 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 } from '../harness.mjs'; +import { startDaemon, openUi, api, launchBrowser, repoRoot } from '../harness.mjs'; function workspaceRef(root) { return `workspace-${createHash('sha256').update(root).digest('hex').slice(0, 12)}`; } -/** - * In-process synthetic LoopX Core test double implementing the exact HTTP contract used by - * LoopxService (/api/chat/projects, /api/actions/preview, /api/actions/:id/apply, /api/actions), - * GoalTasks (/api/loopx/status.json?goal_id=, /api/chat/todo/dry-run, /api/chat/todo/apply), - * and useLoopxStatus (/status.json). - */ async function startFakeCore(grantedRoot) { const ref = workspaceRef(grantedRoot); const state = { simulateDown: false, - goals: new Map(), // goalId -> { goalId, title, objective, status, workspace, agentId, todos: { user: [], agent: [] } } - proposals: new Map(), // proposalId -> proposal - todoPreviews: new Map(), // previewId -> { goalId, role, text, priority, claimedBy } + goals: new Map(), + proposals: new Map(), + todoPreviews: new Map(), seq: 0, }; @@ -68,8 +62,8 @@ async function startFakeCore(grantedRoot) { status: g.status, waiting_on: null, severity: null, - recommended_action: `继续推进 ${g.title}`, - next_action: `继续推进 ${g.title}`, + 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, @@ -95,22 +89,15 @@ async function startFakeCore(grantedRoot) { 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 === '/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 === '/api/attached-sessions') return json(200, { bindings: [] }); if (req.method === 'GET' && path === '/status.json') { - const goalFilter = url.searchParams.get('goal_id'); - return json(200, buildStatusPayload(goalFilter)); - } - if (req.method === 'GET' && path === '/api/actions') { - return json(200, { proposals: [] }); + 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])); @@ -170,11 +157,7 @@ async function startFakeCore(grantedRoot) { proposal.updated_at = now; proposal.receipt = { outcome: 'goal_created', - resource_ids: { - goal_id: goalId, - managed_agent_id: null, - goal_instance_id: null, - }, + resource_ids: { goal_id: goalId, managed_agent_id: null, goal_instance_id: null }, }; return json(200, { proposal, turn: null }); } @@ -236,11 +219,9 @@ let page; const shotDir = process.env.E2E_SHOT_DIR || ''; before(async () => { - // Start daemon with a pre-created workdir so fakeCore grants that exact workdir. const workdir = join('/tmp', `loochat-main-e2e-${Date.now()}`); mkdirSync(workdir, { recursive: true }); fakeCore = await startFakeCore(workdir); - // Provide a test-double loopx CLI shim backed by fakeCore so GoalState reads return real Goal status instead of goal_not_found. const fakeLoopxCli = join(workdir, '.fake-loopx-cli.mjs'); writeFileSync( fakeLoopxCli, @@ -253,6 +234,85 @@ 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('核对风控依赖安装') && !text.includes('approve')) { + return text + '\\napprove'; + } + 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 }, ); @@ -260,6 +320,7 @@ process.stdout.write(text); { LOOCHAT_LOOPX_CORE_URL: fakeCore.url, LOOCHAT_LOOPX_CMD: `${process.execPath} ${fakeLoopxCli}`, + LOOCHAT_CLAUDE_ACP_BIN: naturalAcpShim, FAKE_ACP_VISIBLE_ECHO: '1', }, { workdir }, @@ -281,19 +342,31 @@ async function snap(name, targetPage = page) { await targetPage.screenshot({ path: join(shotDir, `${name}.png`), fullPage: false }); } -test('full Main Conversation journey: start Goal without toggle, Core failure guard, filter/reload, UI + model dispatch, child ActionSheet approval, Core todos, two-matter isolation', async () => { +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'); - await sidebar.getByRole('button', { name: '开始一件事', exact: true }).waitFor({ timeout: 10_000 }); + await sidebar.getByRole('button', { name: '新 loop', exact: true }).waitFor({ timeout: 10_000 }); - // 1. Legacy entries intact; old manual is completely retired. + // 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. Legacy entries intact; old manual is retired. assert.equal(await sidebar.getByRole('button', { name: '新对话', exact: true }).isVisible(), true); assert.equal(await sidebar.getByRole('button', { name: 'LoopX 管家', exact: true }).isVisible(), true); assert.equal(await page.locator('.composer-loopx').count(), 0, 'manual LoopxToggle must be removed'); - // 2. Click 「开始一件事」 and verify Core failure shows original error without silent downgrade. - await sidebar.getByRole('button', { name: '开始一件事', exact: true }).click(); - await page.locator('.topbar-title').filter({ hasText: '开始一件事' }).waitFor({ timeout: 5_000 }); + // 2. Click 「新 loop」 and verify Core failure shows original error without silent downgrade. + await sidebar.getByRole('button', { name: '新 loop', exact: true }).click(); + 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; @@ -308,8 +381,8 @@ test('full Main Conversation journey: start Goal without toggle, Core failure gu await confirmDialog.waitFor({ state: 'detached', timeout: 5_000 }); fakeCore.state.simulateDown = false; - // 3. Create Matter A through real launch/preview -> GoalConfirm -> launch/apply. - await page.locator('.composer textarea').fill('Matter A 支付风控校验'); + // 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 }); @@ -323,9 +396,21 @@ test('full Main Conversation journey: start Goal without toggle, Core failure gu assert.ok(goalIdA && threadIdA, `expected real goalIdA & threadIdA, got ${goalIdA} / ${threadIdA}`); assert.ok(fakeCore.state.goals.has(goalIdA), 'goalIdA must exist in Core'); - // 4. Create Matter B via 「开始一件事」. - await sidebar.getByRole('button', { name: '开始一件事', exact: true }).click(); - await page.locator('.composer textarea').fill('Matter B 周报指标核对'); + // 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 「新 loop」 AND dispatch one UNGRANTED task in Loop B to test strict A/B supervision isolation. + await sidebar.getByRole('button', { name: '新 loop', exact: true }).click(); + 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 }); @@ -337,21 +422,35 @@ test('full Main Conversation journey: start Goal without toggle, Core failure gu 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('auto_edit'); + 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 「新对话」. await sidebar.getByRole('button', { name: '新对话', exact: true }).click(); await page.locator('.composer textarea').fill('普通会话兼容验证'); await page.locator('.composer textarea').press('Enter'); - await page.getByText('echo:普通会话兼容验证').waitFor({ timeout: 15_000 }); + 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 3-way sidebar filter (全部 / 主对话 / 普通) + reload persistence. + // 6. Test 3-way sidebar filter (全部 / loop / 普通) + reload persistence. const filterGroup = sidebar.locator('.sidebar-kind-filter'); - await filterGroup.getByRole('button', { name: '主对话', exact: true }).click(); + await filterGroup.getByRole('button', { name: 'loop', exact: true }).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); - // Reload page while filter is on 「主对话」 -> filter and ownership stay stable. await page.reload(); await sidebar.locator(`[data-thread-id="${threadIdA}"]`).waitFor({ timeout: 10_000 }); assert.equal(await sidebar.locator('.thread-title', { hasText: '普通会话兼容验证' }).count(), 0); @@ -363,103 +462,242 @@ test('full Main Conversation journey: start Goal without toggle, Core failure gu await filterGroup.getByRole('button', { name: '全部', exact: true }).click(); await sidebar.locator(`[data-thread-id="${threadIdA}"]`).waitFor({ timeout: 5_000 }); - // 7. Inside Matter A, dispatch a child Claude agent with ask permission + "approve install". + // 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('approve install'); + 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'); - assert.ok(childThreadIdA, 'expected spawned childThreadIdA'); + 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'); - // Wait for child's permission request to surface in Matter A's dock (both badge & approval banner/status). - await page.getByTestId('main-dock-approval-banner').waitFor({ timeout: 15_000 }); - await childRowA.locator('.main-dock-pill.is-waiting').waitFor({ timeout: 10_000 }); - // Assert neither protocol blocks nor goal_not_found errors appear in the visible conversation or Goal overview. 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'); - await snap('01-desktop-light-matter-a-approval-dispatch'); - // Capture dark-mode screenshot of the same populated Matter A view. + // Close open trays to capture clean populated desktop state (light & dark). + 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 snap('01-desktop-light-loop-a-supervise-cards'); await page.evaluate(() => document.documentElement.setAttribute('data-theme', 'dark')); - await snap('02-desktop-dark-matter-a-approval-dispatch'); + await page.waitForTimeout(100); + await snap('02-desktop-dark-loop-a-supervise-cards'); await page.evaluate(() => document.documentElement.removeAttribute('data-theme')); - // 8. Verify cross-matter isolation: Matter B sees ZERO approvals and ZERO dispatches from Matter A. + // 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, 'Matter A approval must NOT leak to Matter B'); - assert.equal(await page.getByTestId('main-dock-tray-dispatch').locator('.main-dock-task-row').count(), 0, 'Matter A dispatch must NOT leak to Matter B'); + 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 Matter A, click 「前往审核」 -> arrive on child thread's existing -> approve -> return to Matter A! + // 9. Return to Loop A -> click banner 「去处理」 -> child link -> child -> approve -> return via 「← loop · ...」! await sidebar.locator(`[data-thread-id="${threadIdA}"] button.thread-item`).click(); - await page.getByTestId('main-dock-approval-banner').waitFor({ timeout: 10_000 }); - await page.getByTestId('main-dock-approval-banner').getByRole('button', { name: '前往审核' }).click(); + 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(); - // Landed on child thread with existing ActionSheet and topbar back chip! 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('approved:allow').waitFor({ timeout: 15_000 }); + await page.getByText('已按批准结果完成风控依赖安装与回归校验。').waitFor({ timeout: 15_000 }); - // Jump back to Matter A and confirm approval prompt cleared & dispatch settled with result! 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(); - await page.locator(`[data-child-thread-id="${childThreadIdA}"] .main-dock-task-summary`, { hasText: 'approved:allow' }).waitFor({ timeout: 10_000 }); + 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(); + } - // 10. Model-driven dispatch from Matter A via real LOOCHAT_MAIN_SOCKET + LOOCHAT_MAIN_TOKEN! - await page.locator('.composer textarea').fill('model-dispatch claude 模型自派指标巡检 | check latency metrics'); + // 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.getByText('dispatched:task_', { exact: false }).waitFor({ timeout: 15_000 }); - const modelDispatchRow = page.getByTestId('main-dock-tray-dispatch').locator('.main-dock-task-row', { hasText: '模型自派指标巡检' }); - await modelDispatchRow.waitFor({ timeout: 10_000 }); - const childThreadIdModel = await modelDispatchRow.getAttribute('data-child-thread-id'); - assert.ok(childThreadIdModel && childThreadIdModel !== childThreadIdA); + 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'); - // 11. Persistent Core Goal todos directly under Main Conversation + reload + two-matter isolation! + // 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')); + 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('补齐 Matter A 支付风控单测'); + 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('补齐 Matter A 支付风控单测').first().waitFor({ timeout: 10_000 }); - await snap('03-desktop-light-matter-a-todos'); + await todosTray.getByText('补齐支付风控回归单测').first().waitFor({ timeout: 10_000 }); - // Switch to Matter B, verify Matter A todo absent, add Matter B todo. 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('补齐 Matter A 支付风控单测').count(), 0); + assert.equal(await todosTray.getByText('补齐支付风控回归单测').count(), 0); await todosTray.getByRole('button', { name: '新建任务' }).click(); - await todosTray.locator('textarea').fill('整理 Matter B 周报数据源'); + 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('整理 Matter B 周报数据源').first().waitFor({ timeout: 10_000 }); + await todosTray.getByText('核对周报指标数据源').first().waitFor({ timeout: 10_000 }); - // Reload browser and verify both Matter A & Matter B todos reopen with exact ownership! 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('补齐 Matter A 支付风控单测').waitFor({ timeout: 10_000 }); - assert.equal(await page.getByTestId('main-dock-tray-todos').getByText('整理 Matter B 周报数据源').count(), 0); + 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 verification capture. if (shotDir) { @@ -468,14 +706,21 @@ test('full Main Conversation journey: start Goal without toggle, Core failure gu 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(400); + await mobilePage.waitForTimeout(350); 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('main-dock-tab-dispatch').click(); - await mobilePage.getByTestId('main-dock-tray-dispatch').waitFor({ timeout: 5_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); - await snap('05-mobile-light-matter-a-dock', mobilePage); + // Assert