From a43020742719b2bbf94334b9c42e3f46097314a0 Mon Sep 17 00:00:00 2001 From: Yichen Jiang Date: Sun, 26 Jul 2026 14:09:31 +0800 Subject: [PATCH 001/139] feat(web): retry transient model requests --- ...2026-06-21-bounded-llm-request-recovery.md | 8 +- apps/cli/README.md | 2 +- apps/cli/cordis.yml | 3 + apps/cli/package.json | 1 + apps/web/tests/session-title.snapshot.ts | 75 ++++++++++++- apps/web/tests/smoke-real.e2e.ts | 92 ++++++++++++++++ apps/web/tests/snapshots/model-retry.json | 27 +++++ docs/config-catalog.md | 2 +- .../client/connection/src/client/fixture.ts | 57 ++++++++++ .../client/connection/tests/fixture.spec.ts | 8 ++ packages/client/runtime/README.md | 4 + packages/client/runtime/package.json | 1 + packages/client/runtime/src/client/index.ts | 2 +- .../src/client/sessions/conversation.ts | 18 +++- .../runtime/src/client/sessions/session.ts | 91 ++++++++++++---- packages/client/runtime/tests/event-script.ts | 16 +++ packages/client/runtime/tests/session.spec.ts | 66 ++++++++++++ packages/client/runtime/tsconfig.json | 3 + packages/client/ui-conversation/README.md | 2 + .../src/client/chat/ChatView.tsx | 20 +++- .../src/client/chat/MessageItem.module.css | 100 ++++++++++++++++++ .../src/client/chat/MessageItem.tsx | 64 +++++++++-- .../src/client/chat/chat-flow.ts | 17 ++- .../tests/chat-branch-tails.spec.tsx | 79 +++++++++++++- .../ui-conversation/tests/chat-view.spec.tsx | 43 +++++++- packages/llm/llm-retry/README.md | 2 +- packages/llm/llm-retry/package.json | 5 + packages/llm/llm-retry/src/index.ts | 2 + packages/llm/llm-retry/src/types.ts | 11 ++ packages/llm/llm-retry/tests/retry.spec.ts | 9 +- pnpm-lock.yaml | 6 ++ tsconfig.base.json | 1 + 32 files changed, 791 insertions(+), 46 deletions(-) create mode 100644 apps/web/tests/snapshots/model-retry.json create mode 100644 packages/llm/llm-retry/src/types.ts diff --git a/.agents/notes/implemented/architecture/2026-06-21-bounded-llm-request-recovery.md b/.agents/notes/implemented/architecture/2026-06-21-bounded-llm-request-recovery.md index 932318da4f..3ec72eb19a 100644 --- a/.agents/notes/implemented/architecture/2026-06-21-bounded-llm-request-recovery.md +++ b/.agents/notes/implemented/architecture/2026-06-21-bounded-llm-request-recovery.md @@ -68,11 +68,11 @@ For an eligible failure with budget remaining, the one-based transient retry cou The plugin owns a lifetime `AbortController` and tracks every active backoff callback. Each wait fuses the waterfall's turn signal with that lifetime signal. Effect cleanup first unregisters the listener, then aborts and awaits the active callbacks; a captured callback whose lifetime signal aborts returns `fail` and can neither retry nor enter the rest of its captured waterfall after disposal. This makes HMR disposal quiescent even though Cordis has already captured the listener. -Before sleeping, `dsh-llm-retry` appends one non-surface `llm/retry` session event containing the turn, failed step, one-based transient retry number, configured maximum, scheduled delay, and `LlmFailure`. The plugin owns the `SessionEventMap` augmentation; `dsh-session` remains generic persistence and does not absorb the optional policy's vocabulary. The event says what was scheduled, not that the next request completed; cancellation during the delay is subsequently visible on `turn/end`. The event ships only with a production renderer and replay/snapshot coverage, because its purpose is operational state rather than trace collection. +Before sleeping, `dsh-llm-retry` appends one non-surface `llm/retry` session event containing the turn, failed step, one-based transient retry number, configured maximum, scheduled delay, and `LlmFailure`. The plugin owns the `SessionEventMap` augmentation and exports the payload through its browser-safe `./types` subpath; `dsh-session` remains generic persistence and does not absorb the optional policy's vocabulary. The event says what was scheduled, not that the next request completed; cancellation during the delay is subsequently visible on `turn/end`. The event ships with production renderers and replay/snapshot coverage, because its purpose is operational state rather than trace collection. The listener calls `next()` for a non-transient code, an exhausted policy budget, or an over-cap provider delay. This preserves composition with context-overflow recovery and later policy plugins. It returns `{ action: 'retry' }` only after the delay completes under both signals; turn cancellation and plugin disposal return `fail`, after which the loop's cancellation/disposal checks remain authoritative. -The agent-spine demo bundle loads the plugin so the shared stdio/TUI, one-shot CLI, and ACP example compositions use the same bounded policy. Library consumers retain explicit plugin composition: omitting the plugin leaves `agent/request-error` at its current fail default. +The agent-spine demo bundle loads the plugin so the shared stdio/TUI, one-shot CLI, and ACP example compositions use the same bounded policy. The shipped Web/headless composition also loads it, so browser and command-line requests share the TUI defaults. Library consumers retain explicit plugin composition: omitting the plugin leaves `agent/request-error` at its current fail default. ### Make one layer own visible attempts @@ -90,7 +90,7 @@ Boundary tests prove termination at both actual transports. The hand-written ada ### Keep attempts separate in the existing log -A failed attempt may leave `assistant/chunk` events in its closed step, but it never appends `assistant/message` and never dispatches a tool. A retry opens the next numbered step, reconstructs the request from the durable surface, and produces its own chunks. UIs may render live chunks while a step is open, then mark or clear that transient view when `llm/retry` identifies the failed step or `turn/end` records terminal failure; message derivation continues to ignore the failed chunks. +A failed attempt may leave `assistant/chunk` events in its closed step, but it never appends `assistant/message` and never dispatches a tool. A retry opens the next numbered step, reconstructs the request from the durable surface, and produces its own chunks. TUI and Web render live chunks while a step is open, then clear that transient view and retain replayable status when `llm/retry` identifies the failed step. Web projects consecutive same-turn retry events into one stable row updated to the latest attempt, counts its delay down in ceiling-rounded seconds with a one-second floor, animates only while unresolved, and keeps exact latest failure details collapsed behind the row. Message derivation continues to ignore the failed chunks, and Web applies the same projection during history rebuild so refreshing cannot resurrect discarded partials or duplicate retry rows. If recovery is exhausted, the final failure is stored once on `turn/end.reason` with the structured facts. If transient recovery continues, `llm/retry` is the durable home for that attempt's failure and delay. No standalone final-error event or response-id vocabulary is added. @@ -124,7 +124,7 @@ If recovery is exhausted, the final failure is stored once on `turn/end.reason` - Pure unit tests cover transient-code selection, exponential backoff and jitter bounds, valid and over-cap `Retry-After`, exhausted budgets, deterministic timer/random seams, and abort during backoff. - Real agent-loop tests cover failure before chunks, partial chunks then failure, thrown and in-band failures, retry to success in a new step, exhaustion to structured `turn/end.reason`, and composition with `dsh-compact-basic` context-overflow recovery. - The partial-chunk integration test proves failed chunks remain attributed to the failed step, no assistant message or tool side effect is committed for that step, and the successful retry has distinct provenance. -- The plugin-owned `llm/retry` event is non-surface, survives JSONL and SQLite round trips, is ignored by message derivation, and drives TUI retraction plus scheduled-retry rendering. Keyless snapshots cover scheduling, cancellation, success, and exhaustion; ACP automation snapshots confirm that a discarded attempt stays off the wire while the recovered reply is emitted. +- The plugin-owned `llm/retry` event is non-surface, survives JSONL and SQLite round trips, is ignored by message derivation, and drives TUI and Web retraction plus scheduled-retry rendering. Keyless UI snapshots cover Web scheduling and success, a real Web composition test covers partial transport failure through recovery, and ACP automation snapshots confirm that a discarded attempt stays off the wire while the recovered reply is emitted. - Idle-watchdog tests prove the stable signal is rearmed only while `next()` is outstanding, disarmed during consumer think time and in `finally`, and classified separately from a total-call deadline and an earlier caller abort; adapter tests prove the signal stops the underlying request rather than merely detaching it. - Direct `ctx.llm.stream()` callers remain single-attempt and receive the same structured failure facts. diff --git a/apps/cli/README.md b/apps/cli/README.md index 2afd9c346b..301544d1ab 100644 --- a/apps/cli/README.md +++ b/apps/cli/README.md @@ -10,7 +10,7 @@ The TUI surface: - tells the agent where its own source lives: after boot it adds a prompt section naming this harness checkout, resolved from the launcher's real path so it holds under a PATH symlink and an arbitrary cwd, so the self-referential `cordis` toolset can read and modify it; - applies the personal overlay from `~/.dsh` (see [app-boot's Personal config](../../packages/ui/app-boot/README.md#personal-config)): `.env` fills environment gaps (ambient > project `.env` > personal `.env`), `config.yaml` patches the booted tree. -The Web and headless surfaces boot one shared composition (`cordis.yml`): both treat the invoking directory as the default project and Workspace root, create named Workspaces beneath that root unless `--workspace-root ` overrides it, load applicable `AGENTS.md`/`CLAUDE.md` instructions into each agent-loop request prefix with a 65,536-byte render budget, and opt into first-message model titles. Headless differs only in listening on an OS-assigned port (parallel `dsh -p` runs never collide; the stderr-printed URL opens the live session in a browser). Both need the frontend dist and client bundles built (`pnpm run build && pnpm run build:web`). +The Web and headless surfaces boot one shared composition (`cordis.yml`): both treat the invoking directory as the default project and Workspace root, create named Workspaces beneath that root unless `--workspace-root ` overrides it, load applicable `AGENTS.md`/`CLAUDE.md` instructions into each agent-loop request prefix with a 65,536-byte render budget, opt into first-message model titles, and use the same bounded transient model-request retry policy as the TUI. Headless differs only in listening on an OS-assigned port (parallel `dsh -p` runs never collide; the stderr-printed URL opens the live session in a browser). Both need the frontend dist and client bundles built (`pnpm run build && pnpm run build:web`). ## Install (developer machine) diff --git a/apps/cli/cordis.yml b/apps/cli/cordis.yml index b89df77c46..4e42b1c725 100644 --- a/apps/cli/cordis.yml +++ b/apps/cli/cordis.yml @@ -59,6 +59,9 @@ config: agents: [] +- id: llm-retry + name: '@deepseek-ai/dsh-llm-retry' + # The native DeepSeek adapter; reads the key/base-url the boot's layered # .env loading (cwd then $DSH_HOME) left in the environment. - id: llm-deepseek diff --git a/apps/cli/package.json b/apps/cli/package.json index e1c07f90b5..6cf696f542 100644 --- a/apps/cli/package.json +++ b/apps/cli/package.json @@ -41,6 +41,7 @@ "@deepseek-ai/dsh-host-webserver": "workspace:^", "@deepseek-ai/dsh-llm": "workspace:^", "@deepseek-ai/dsh-llm-deepseek": "workspace:^", + "@deepseek-ai/dsh-llm-retry": "workspace:^", "@deepseek-ai/dsh-paths": "workspace:^", "@deepseek-ai/dsh-session": "workspace:^", "@deepseek-ai/dsh-session-persistence-jsonl": "workspace:^", diff --git a/apps/web/tests/session-title.snapshot.ts b/apps/web/tests/session-title.snapshot.ts index c1616bb724..c24fd12a63 100644 --- a/apps/web/tests/session-title.snapshot.ts +++ b/apps/web/tests/session-title.snapshot.ts @@ -25,6 +25,9 @@ const bundles = new Map(PLUGINS.map(plugin => [ interface FixtureTiming { appendTitle(id: string, title: string): void + beginModelRetry(id: string): void + scheduleModelRetry(id: string, retry?: number, delayMs?: number): void + completeModelRetry(id: string): void } interface FixtureWindow extends Window { @@ -78,7 +81,7 @@ function titleSurfaces(label: string): { sidebar: string; breadcrumb: string; do return { sidebar, breadcrumb, documentTitle: document.title } } -it('projects initial and revised durable titles through the built nine-plugin fixture app', async () => { +function bootFixtureApp(): void { const root = document.querySelector('#root') if (root === null) throw new Error('snapshot root missing') act(() => { @@ -92,18 +95,26 @@ it('projects initial and revised durable titles through the built nine-plugin fi void entry.run() unmount = () => { entry.dispose() } }) +} +async function selectFixtureSession(): Promise { const tree = await screen.findByRole('tree', { name: 'Sessions' }, { timeout: 10_000 }) const projectCount = await within(tree).findByText('4 sessions') const projectRow = projectCount.closest('[role="treeitem"]') if (projectRow === null) throw new Error('fixture project row missing') fireEvent.click(projectRow) - const initialLabel = 'Fixture 历史会话' - const initialRowLabel = await screen.findByText(initialLabel) + const initialRowLabel = await screen.findByText('Fixture 历史会话') const initialRow = initialRowLabel.closest('[role="treeitem"]') if (initialRow === null) throw new Error('fixture session row missing') fireEvent.click(initialRow) +} + +it('projects initial and revised durable titles through the built nine-plugin fixture app', async () => { + bootFixtureApp() + await selectFixtureSession() + + const initialLabel = 'Fixture 历史会话' await waitFor(() => { expect(document.title).toBe(`${initialLabel} — DeepSeek Harness`) }) const initial = titleSurfaces(initialLabel) @@ -116,3 +127,61 @@ it('projects initial and revised durable titles through the built nine-plugin fi await expect(`${JSON.stringify({ initial, revised }, null, 2)}\n`) .toMatchFileSnapshot('./snapshots/session-title.json') }) + +it('retracts a failed stream at llm/retry and retains the durable notice after recovery', async () => { + bootFixtureApp() + await selectFixtureSession() + const timing = (globalThis as Record).__fxTiming as FixtureTiming + + act(() => { timing.beginModelRetry('fx-alpha') }) + const partial = await screen.findByText('应撤回的半截回复') + const beforeRetry = { partial: partial.textContent } + + act(() => { timing.scheduleModelRetry('fx-alpha') }) + const firstNotice = await screen.findByRole('status') + await waitFor(() => { expect(screen.queryByText('应撤回的半截回复')).toBeNull() }) + const disclosure = firstNotice.closest('details') + if (disclosure === null) throw new Error('retry disclosure missing') + const firstRetry = { + notice: firstNotice.textContent, + rows: screen.getAllByRole('status').length, + } + + act(() => { timing.scheduleModelRetry('fx-alpha', 2, 1_500) }) + const notice = screen.getByRole('status') + await waitFor(() => { expect(notice.textContent).toContain('(2/2)') }) + const latestDisclosure = notice.closest('details') + const summary = notice.closest('summary') + if (latestDisclosure === null || summary === null) throw new Error('latest retry disclosure missing') + await waitFor(() => { expect(screen.queryByText('第 2 次应撤回的回复')).toBeNull() }) + const scheduled = { + partialVisible: screen.queryByText('应撤回的半截回复') !== null + || screen.queryByText('第 2 次应撤回的回复') !== null, + notice: notice.textContent, + rows: screen.getAllByRole('status').length, + reusedDisclosure: latestDisclosure === disclosure, + detailsOpen: latestDisclosure.open, + animated: latestDisclosure.dataset.active === 'true', + } + fireEvent.click(summary) + const expanded = { + detailsOpen: latestDisclosure.open, + delay: screen.getByText('重试延迟:').parentElement?.textContent, + failure: screen.getByText('失败原因:').parentElement?.textContent, + } + + act(() => { timing.completeModelRetry('fx-alpha') }) + const recovered = await screen.findByText('重试后的完整回复') + await waitFor(() => { expect(screen.getByRole('status').textContent).toContain('已重试') }) + const completedNotice = screen.getByRole('status') + const completedDisclosure = completedNotice.closest('details') + if (completedDisclosure === null) throw new Error('completed retry disclosure missing') + const completed = { + recovered: recovered.textContent, + retryNoticeStillVisible: completedNotice.textContent, + animated: completedDisclosure.dataset.active === 'true', + } + + await expect(`${JSON.stringify({ beforeRetry, firstRetry, scheduled, expanded, completed }, null, 2)}\n`) + .toMatchFileSnapshot('./snapshots/model-retry.json') +}) diff --git a/apps/web/tests/smoke-real.e2e.ts b/apps/web/tests/smoke-real.e2e.ts index a3d511df16..eb6ae6d26a 100644 --- a/apps/web/tests/smoke-real.e2e.ts +++ b/apps/web/tests/smoke-real.e2e.ts @@ -271,6 +271,98 @@ describe('dsh web keyless CLI smoke', () => { rmSync(workspace, { recursive: true, force: true }) } }) + + it('retries a partial transport failure through the shipped Web composition', async () => { + requireDist() + const workspace = mkdtempSync(join(tmpdir(), 'dsh-web-retry-')) + const promptMarker = 'WEB_RETRY_REQUEST' + const recoveredMarker = 'WEB_RETRY_RECOVERED' + let mainAttempts = 0 + const provider = createServer((request, response) => { + let body = '' + request.setEncoding('utf8') + request.on('data', (chunk: string) => { body += chunk }) + request.on('end', () => { + const parsed = JSON.parse(body) as { max_tokens?: number; messages?: unknown[] } + const titleRequest = parsed.max_tokens === 64 + const mainRequest = !titleRequest && body.includes(promptMarker) + response.writeHead(200, { 'content-type': 'text/event-stream' }) + if (!mainRequest) { + response.end([ + 'data: {"choices":[{"delta":{"content":"Web retry title"}}]}', + 'data: {"choices":[{"delta":{"content":""},"finish_reason":"stop"}],"usage":{"prompt_tokens":1,"completion_tokens":1}}', + 'data: [DONE]', + '', + ].join('\n\n')) + return + } + mainAttempts++ + if (mainAttempts === 1) { + response.write('data: {"choices":[{"delta":{"content":"WEB_RETRY_DISCARDED"}}]}\n\n') + setTimeout(() => { response.destroy() }, 20) + return + } + response.end([ + `data: {"choices":[{"delta":{"content":"${recoveredMarker}"}}]}`, + 'data: {"choices":[{"delta":{"content":""},"finish_reason":"stop"}],"usage":{"prompt_tokens":3,"completion_tokens":1}}', + 'data: [DONE]', + '', + ].join('\n\n')) + }) + }) + await new Promise(resolve => provider.listen(0, '127.0.0.1', resolve)) + const address = provider.address() + if (address === null || typeof address === 'string') throw new Error('mock provider did not bind a TCP port') + const tsxLoader = pathToFileURL(createRequire(join(REPO_ROOT, 'package.json')).resolve('tsx')).href + const child = spawn( + process.execPath, + ['--import', tsxLoader, join(REPO_ROOT, 'apps/cli/src/bin.ts'), 'web', '--port', '0'], + { + cwd: workspace, + env: { + ...process.env, + DEEPSEEK_API_KEY: 'keyless-web-retry', + DEEPSEEK_BASE_URL: `http://127.0.0.1:${address.port}`, + DSH_HOME: join(workspace, '.dsh'), + TSX_TSCONFIG_PATH: join(REPO_ROOT, 'tsconfig.json'), + }, + stdio: ['ignore', 'pipe', 'pipe'], + }, + ) + try { + const baseUrl = await waitForReadyLine(child) + const created = await rpc<{ sessionId: string }>(baseUrl, 'session.create', {}) + await rpc<{ accepted: true }>(baseUrl, 'session.prompt', { + sessionId: created.sessionId, + mode: 'queue', + content: [{ type: 'text', text: promptMarker }], + }) + let page: HistoryPage | undefined + await expect.poll(async () => { + page = await history(baseUrl, created.sessionId) + return hasAssistantMarker(page, recoveredMarker) + }, { timeout: 20_000 }).toBe(true) + if (page === undefined) throw new Error('retry history was not observed') + const retry = page.events.find(({ event }) => event.type === 'llm/retry')?.event + expect(mainAttempts).toBe(2) + expect(retry?.data).toMatchObject({ + turn: 1, + step: 1, + retry: 1, + maxRetries: 2, + failure: { code: 'TRANSPORT' }, + }) + expect(JSON.stringify(page.events)).toContain('WEB_RETRY_DISCARDED') + } finally { + const closed = child.exitCode === null + ? new Promise((resolveClose) => { child.once('close', () => { resolveClose() }) }) + : Promise.resolve() + if (child.exitCode === null) child.kill('SIGTERM') + await closed + await new Promise(resolveClose => provider.close(() => { resolveClose() })) + rmSync(workspace, { recursive: true, force: true }) + } + }, 30_000) }) describe.skipIf(!process.env.DEEPSEEK_API_KEY || notReady.length > 0)('web smoke (real host, real key, W5)', () => { diff --git a/apps/web/tests/snapshots/model-retry.json b/apps/web/tests/snapshots/model-retry.json new file mode 100644 index 0000000000..df2ce854da --- /dev/null +++ b/apps/web/tests/snapshots/model-retry.json @@ -0,0 +1,27 @@ +{ + "beforeRetry": { + "partial": "应撤回的半截回复" + }, + "firstRetry": { + "notice": "正在重试模型请求(1/2) · 1s", + "rows": 1 + }, + "scheduled": { + "partialVisible": false, + "notice": "正在重试模型请求(2/2) · 2s", + "rows": 1, + "reusedDisclosure": true, + "detailsOpen": false, + "animated": true + }, + "expanded": { + "detailsOpen": true, + "delay": "重试延迟:1500ms", + "failure": "失败原因:连接被重置" + }, + "completed": { + "recovered": "重试后的完整回复", + "retryNoticeStillVisible": "已重试模型请求(2/2) · 2s", + "animated": false + } +} diff --git a/docs/config-catalog.md b/docs/config-catalog.md index 6c7627aca4..7793fa5236 100644 --- a/docs/config-catalog.md +++ b/docs/config-catalog.md @@ -708,7 +708,7 @@ export interface Config { } ``` -Source: [`packages/llm/llm-retry/src/index.ts:39`](../packages/llm/llm-retry/src/index.ts) +Source: [`packages/llm/llm-retry/src/index.ts:41`](../packages/llm/llm-retry/src/index.ts) ## `@deepseek-ai/dsh-lsp-local` diff --git a/packages/client/connection/src/client/fixture.ts b/packages/client/connection/src/client/fixture.ts index 53c18dca5c..24ad94451d 100644 --- a/packages/client/connection/src/client/fixture.ts +++ b/packages/client/connection/src/client/fixture.ts @@ -425,6 +425,8 @@ export function createFixtureApi(options: FixtureOptions = {}): ApiProxy { let failNextHistory = false /** Force-enders for currently open stream generators (timing hook: simulated connection loss). */ const streamBreakers = new Set<() => void>() + /** Retry scenarios opened by timing hooks and completed in a later browser assertion phase. */ + const retryScenarios = new Map() // Timing-acceptance hooks (browser test backdoor): the in-memory fixture is ideally timed, which // is exactly what masked the open-window and reconnect-gap bugs (audit S1/S3). These let @@ -448,6 +450,61 @@ export function createFixtureApi(options: FixtureOptions = {}): ApiProxy { const messageSeqs = log.filter(event => event.type === 'user/message').map(event => event.seq) append(sid(id), { type: 'session/title', data: { title, messageSeqs, source: { kind: 'provider', provider: 'fixture' } } }) }, + /** Open one failed model step whose partial remains visible until llm/retry arrives. */ + beginModelRetry(id: string): void { + const sessionId = sid(id) + const turn = nextTurn.get(sessionId) ?? 0 + nextTurn.set(sessionId, turn + 1) + retryScenarios.set(sessionId, { turn, failedStep: 0 }) + setRunning(sessionId, true) + append(sessionId, { type: 'turn/start', data: { turn, trigger: { kind: 'message', source: { kind: 'user' } } } }) + append(sessionId, { type: 'user/message', surfaceOp: 'append', data: { content: text('请重试这个请求'), source: { kind: 'user' } } }) + append(sessionId, { type: 'step/start', data: { turn, step: 0 } }) + append(sessionId, { type: 'assistant/chunk', data: { turn, step: 0, chunk: { type: 'block-start', index: 0, blockType: 'text' } } }) + append(sessionId, { type: 'assistant/chunk', data: { turn, step: 0, chunk: { type: 'text-delta', index: 0, text: '应撤回的半截回复' } } }) + append(sessionId, { type: 'step/end', data: { turn, step: 0 } }) + }, + /** Record one retry decision, synthesizing the later failed step when needed. */ + scheduleModelRetry(id: string, retry = 1, delayMs = 450): void { + const sessionId = sid(id) + const scenario = retryScenarios.get(sessionId) + if (scenario === undefined) throw new Error(`fixture: no model retry scenario for ${id}`) + const failedStep = retry - 1 + if (failedStep > scenario.failedStep) { + append(sessionId, { type: 'step/start', data: { turn: scenario.turn, step: failedStep } }) + append(sessionId, { type: 'assistant/chunk', data: { turn: scenario.turn, step: failedStep, chunk: { type: 'block-start', index: 0, blockType: 'text' } } }) + append(sessionId, { type: 'assistant/chunk', data: { turn: scenario.turn, step: failedStep, chunk: { type: 'text-delta', index: 0, text: `第 ${String(retry)} 次应撤回的回复` } } }) + append(sessionId, { type: 'step/end', data: { turn: scenario.turn, step: failedStep } }) + scenario.failedStep = failedStep + } + append(sessionId, { + type: 'llm/retry', + data: { + turn: scenario.turn, step: failedStep, retry, maxRetries: 2, delayMs, + failure: { code: 'TRANSPORT', message: '连接被重置' }, + }, + }) + }, + /** Finish the timing-hook retry with a finalized response on the next step. */ + completeModelRetry(id: string): void { + const sessionId = sid(id) + const scenario = retryScenarios.get(sessionId) + if (scenario === undefined) throw new Error(`fixture: no model retry scenario for ${id}`) + retryScenarios.delete(sessionId) + const step = scenario.failedStep + 1 + append(sessionId, { type: 'step/start', data: { turn: scenario.turn, step } }) + append(sessionId, { + type: 'assistant/message', + surfaceOp: 'append', + data: { + turn: scenario.turn, step, content: text('重试后的完整回复'), + provenance: { provider: 'fixture', model: 'fx-1' }, + }, + }) + append(sessionId, { type: 'step/end', data: { turn: scenario.turn, step } }) + append(sessionId, { type: 'turn/end', data: { turn: scenario.turn, reason: { kind: 'completed' } } }) + setRunning(sessionId, false) + }, /** Log append WITHOUT the mux emit: a frame lost in transit — history still serves it, the client must repull. */ appendSilent(id: string, msg: string): void { const log = logOf(sid(id)) diff --git a/packages/client/connection/tests/fixture.spec.ts b/packages/client/connection/tests/fixture.spec.ts index 16fa4b4ed6..e7912dc34b 100644 --- a/packages/client/connection/tests/fixture.spec.ts +++ b/packages/client/connection/tests/fixture.spec.ts @@ -19,6 +19,9 @@ interface TimingHooks { failNextHistory(): void appendUser(id: string, msg: string): void appendTitle(id: string, title: string): void + beginModelRetry(id: string): void + scheduleModelRetry(id: string, retry?: number, delayMs?: number): void + completeModelRetry(id: string): void appendSilent(id: string, msg: string): void breakStreams(): void } @@ -489,9 +492,14 @@ describe('createFixtureApi', () => { hooks.appendSilent('fx-alpha', '静默丢帧') hooks.appendUser('fx-alpha', '正常直播') hooks.appendTitle('fx-alpha', 'Fixture 修订标题') + hooks.beginModelRetry('fx-alpha') + hooks.scheduleModelRetry('fx-alpha') + hooks.completeModelRetry('fx-alpha') await vi.waitFor(() => { expect(seen.some(f => f.type === 'session/event' && JSON.stringify(f.event.data).includes('正常直播'))).toBe(true) expect(seen.some(f => f.type === 'session/title' && f.title === 'Fixture 修订标题')).toBe(true) + expect(seen.some(f => f.type === 'session/event' && (f.event as { type: string }).type === 'llm/retry')).toBe(true) + expect(seen.some(f => f.type === 'session/event' && JSON.stringify(f.event.data).includes('重试后的完整回复'))).toBe(true) }) expect(seen.some(f => f.type === 'session/event' && JSON.stringify(f.event.data).includes('静默丢帧'))).toBe(false) const rawTitleIndex = seen.findIndex(f => f.type === 'session/event' && (f.event as { type: string }).type === 'session/title') diff --git a/packages/client/runtime/README.md b/packages/client/runtime/README.md index 6b697cbed9..4c09bfd6e8 100644 --- a/packages/client/runtime/README.md +++ b/packages/client/runtime/README.md @@ -16,6 +16,10 @@ SlotsService gives the renderer separate bare observables for `useSessions` and `SessionManager` retains the latest validated `session/title` control snapshot independently of list and session-instance arrival. Newer event seqs replace older snapshots, title timestamps contribute to list recency, and a subscription baseline discards any retained title beyond its `lastSeq` before the optional folded title arrives. Explicit session removal also clears the retained title. The client-facing `SessionSummary.title` is therefore only the actual durable title; `displayTitle` is always present and falls back through the cwd basename and session id. A cold persisted session keeps that fallback until opening or resuming it causes the host to fold and project its log-backed title. +## Model retry projection + +The Session object validates plugin-owned `llm/retry` payloads at the event wire boundary. A valid event removes the matching failed step's streaming partial and inserts a durable retry notice at the event's sequence position. Window rebuild and history replay apply the same projection, so logged chunks from the discarded attempt never reappear as an interrupted reply after refresh. A terminal turn without `llm/retry` retains the existing behavior: visible unfinalized output is frozen as an interrupted assistant node. + ## Model Experience None, as the client runtime hosts browser-side services and the session object layer; nothing here reaches a model request. diff --git a/packages/client/runtime/package.json b/packages/client/runtime/package.json index 4bd95595c1..d4dfa8b526 100644 --- a/packages/client/runtime/package.json +++ b/packages/client/runtime/package.json @@ -35,6 +35,7 @@ "@deepseek-ai/dsh-client-ui-slots": "workspace:^", "@deepseek-ai/dsh-host-apiproxy": "workspace:^", "@deepseek-ai/dsh-llm": "workspace:^", + "@deepseek-ai/dsh-llm-retry": "workspace:^", "@deepseek-ai/dsh-session": "workspace:^", "immer": "^10.1.1", "react": "^18.2.0", diff --git a/packages/client/runtime/src/client/index.ts b/packages/client/runtime/src/client/index.ts index 830d1b8249..bea041e422 100644 --- a/packages/client/runtime/src/client/index.ts +++ b/packages/client/runtime/src/client/index.ts @@ -25,7 +25,7 @@ export type { } from './contract/store.ts' export type { AssistantBlock, AssistantMessageNode, ComposerPhase, ContextMessageNode, ConversationNode, - ConversationSnapshot, PendingPrompt, RunningToolCall, SessionIntentSnapshot, SessionIntentTarget, + ConversationSnapshot, ModelRetryNode, PendingPrompt, RunningToolCall, SessionIntentSnapshot, SessionIntentTarget, SteeringMessageNode, ToolResultNode, UnknownSurfaceNode, UserMessageNode, } from './sessions/conversation.ts' export { PendingWait } from './sessions/pending.ts' diff --git a/packages/client/runtime/src/client/sessions/conversation.ts b/packages/client/runtime/src/client/sessions/conversation.ts index 78d1eeabf5..886168b581 100644 --- a/packages/client/runtime/src/client/sessions/conversation.ts +++ b/packages/client/runtime/src/client/sessions/conversation.ts @@ -4,6 +4,7 @@ // string here (narrow to real brands when convenient). import type { ContentBlock } from '@deepseek-ai/dsh-llm/types' +import type { LlmRetryEventData } from '@deepseek-ai/dsh-llm-retry/types' import type { RpcError, SessionId, ToolCallView, ToolResultView, WorkspaceId, } from '@deepseek-ai/dsh-client-connection/client' @@ -87,6 +88,20 @@ export interface ContextMessageNode { meta?: unknown } +/** Durable notice that a closed failed step is waiting for a model-request retry. */ +export interface ModelRetryNode { + kind: 'model-retry' + seq: number + /** Unix epoch ms from the llm/retry session event. */ + time: number + turn: number + step: number + retry: number + maxRetries: number + delayMs: number + failure: LlmRetryEventData['failure'] +} + /** A tool result paired (when in-window) with its call head. */ export interface ToolResultNode { kind: 'tool-result' @@ -124,6 +139,7 @@ export type ConversationNode = | AssistantMessageNode | SteeringMessageNode | ContextMessageNode + | ModelRetryNode | ToolResultNode | UnknownSurfaceNode @@ -206,7 +222,7 @@ export interface PendingPrompt { /** The immutable snapshot contract Session hands to uSES (see the web client architecture RFC). */ export interface ConversationSnapshot { sessionId: SessionId - /** Surface fold product (finalized conversation nodes in surface order). */ + /** Finalized surface events and durable operational notices in event order. */ nodes: readonly ConversationNode[] /** Fold degradation flag (cross-window replace defense): when true, nodes come from the lenient linear scan. */ foldDegraded: boolean diff --git a/packages/client/runtime/src/client/sessions/session.ts b/packages/client/runtime/src/client/sessions/session.ts index 396d0aa798..d3fc31659b 100644 --- a/packages/client/runtime/src/client/sessions/session.ts +++ b/packages/client/runtime/src/client/sessions/session.ts @@ -1,6 +1,7 @@ // Sessions remain resident after creation so they continue consuming mux frames off-screen. import type { ContentBlock } from '@deepseek-ai/dsh-llm/types' +import type { LlmRetryEventData } from '@deepseek-ai/dsh-llm-retry/types' import type { SessionEvent } from '@deepseek-ai/dsh-session/types' import type { HistoryEntry, IApiClient, MuxFrame, RpcError, RpcId, RpcResult, @@ -52,9 +53,9 @@ export class Session implements ObservableSnapshot { private readonly foldAdapter = new FoldAdapter() private partial: PartialAccumulator | null = null private openCalls = new Map() - /** Interrupted-turn terminal nodes (frozen partial text / aborted tool cards), merged into the flow by seq. - * Derived from window events (turn/end sweep) — rebuilt by rebuildDerivedFromWindow like partial/openCalls. */ - private frozenNodes: ConversationNode[] = [] + /** Operational notices and interrupted-turn terminal nodes merged into the flow by seq. + * Derived from window events — rebuilt by rebuildDerivedFromWindow like partial/openCalls. */ + private derivedNodes: ConversationNode[] = [] private pending = new Map() // Revision counters preserve array identity when derived content is unchanged, so // React.memo children survive unrelated snapshot swaps (chunk storms must not re-render every @@ -64,8 +65,8 @@ export class Session implements ObservableSnapshot { private callsCache: { rev: number; value: RunningToolCall[] } | null = null private pendingRev = 0 private pendingCache: { rev: number; value: PendingInteraction[] } | null = null - private frozenRev = 0 - private nodesCache: { folded: readonly ConversationNode[]; frozenRev: number; value: readonly ConversationNode[] } | null = null + private derivedRev = 0 + private nodesCache: { folded: readonly ConversationNode[]; derivedRev: number; value: readonly ConversationNode[] } | null = null private running = false /** * Sticky send marker, private input of the composerPhase derivation: set @@ -609,8 +610,27 @@ export class Session implements ObservableSnapshot { } /** Per-event side effects (right column of the §A.9 dispatch table): - * chunk accumulation / partial clear on finalize / openCalls add-remove. */ + * chunk/retry projection and openCalls add-remove. */ private applyEventSideEffects(event: SessionEvent, view?: ToolEventView): void { + const eventType: string = event.type + if (eventType === 'llm/retry') { + const data = parseRetryEventData(event.data) + if (data === null) { + console.error(`[web-runtime] ignored malformed llm/retry event at seq ${event.seq}`) + return + } + if (this.partial !== null && this.partial.turn === data.turn && this.partial.step === data.step) { + this.partial = null + } + this.derivedNodes.push({ + kind: 'model-retry', + seq: event.seq, + time: event.time, + ...data, + }) + this.derivedRev++ + return + } switch (event.type) { case 'assistant/chunk': { const { turn, step, chunk } = event.data @@ -649,12 +669,12 @@ export class Session implements ObservableSnapshot { const visible = blocks.some(b => (b.kind === 'text' || b.kind === 'reasoning' ? b.text !== '' : true)) if (visible) { // Fractional seq: strictly after every event of this turn (all < turn/end seq), before the next turn. - this.frozenNodes.push({ + this.derivedNodes.push({ kind: 'assistant', seq: event.seq - 0.9, time: event.time, turn: this.partial.turn, step: this.partial.step, blocks, interrupted: true, }) - this.frozenRev++ + this.derivedRev++ } this.partial = null } @@ -664,7 +684,7 @@ export class Session implements ObservableSnapshot { this.openCalls.delete(callId) this.callsRev++ // The spinner card becomes an interrupted terminal card (never vanishes mid-flow). - this.frozenNodes.push({ + this.derivedNodes.push({ kind: 'tool-result', seq: event.seq - 0.8 + callOffset++ * 0.01, time: event.time, callId, call: { name: call.name, argsRaw: call.argsRaw }, @@ -672,7 +692,7 @@ export class Session implements ObservableSnapshot { content: [], isError: true, error: { name: 'Interrupted', code: 'interrupted' }, callView: call.callView, resultView: null, }) - this.frozenRev++ + this.derivedRev++ } return } @@ -681,15 +701,15 @@ export class Session implements ObservableSnapshot { } } - /** Re-derive state (partial/openCalls/frozenNodes) from raw window events after a rebuild — keeps + /** Re-derive state (partial/openCalls/derivedNodes) from raw window events after a rebuild — keeps * paging/stitching consistent, and makes the live freeze and the history replay converge on the - * same interrupted nodes (chunks are logged, so the replayed sweep re-freezes identical text). */ + * same retry notices and interrupted nodes. */ private rebuildDerivedFromWindow(): void { this.partial = null this.openCalls.clear() this.callsRev++ - this.frozenNodes = [] - this.frozenRev++ + this.derivedNodes = [] + this.derivedRev++ for (let i = 0; i < this.events.length; i++) { const event = this.events[i] /* v8 ignore next -- dense-array guard: i stays within events.length, so the undefined arm needs a sparse array no caller builds. */ @@ -704,17 +724,17 @@ export class Session implements ObservableSnapshot { private buildSnapshot(): ConversationSnapshot { const { nodes: folded, degraded } = this.foldAdapter.nodes() - // Frozen interrupted nodes ride fractional seqs: a stable merge keeps them in flow order. - // The merged array is cached on (folded reference, frozenRev) so an unchanged flow keeps its + // Derived nodes use their event seq or a nearby fractional seq: a stable merge keeps flow order. + // The merged array is cached on (folded reference, derivedRev) so an unchanged flow keeps its // reference across snapshot swaps (§A.9.4). let nodes: readonly ConversationNode[] - if (this.nodesCache !== null && this.nodesCache.folded === folded && this.nodesCache.frozenRev === this.frozenRev) { + if (this.nodesCache !== null && this.nodesCache.folded === folded && this.nodesCache.derivedRev === this.derivedRev) { nodes = this.nodesCache.value } else { - nodes = this.frozenNodes.length === 0 + nodes = this.derivedNodes.length === 0 ? folded - : [...folded, ...this.frozenNodes].sort((a, b) => a.seq - b.seq) - this.nodesCache = { folded, frozenRev: this.frozenRev, value: nodes } + : [...folded, ...this.derivedNodes].sort((a, b) => a.seq - b.seq) + this.nodesCache = { folded, derivedRev: this.derivedRev, value: nodes } } if (this.callsCache === null || this.callsCache.rev !== this.callsRev) { this.callsCache = { rev: this.callsRev, value: [...this.openCalls.values()] } @@ -752,6 +772,37 @@ function rpcErrorMessage(error: RpcError): string { return `${error.code}: ${error.message}` } +/** Validate the plugin-owned payload at the session-event wire boundary. */ +function parseRetryEventData(value: unknown): LlmRetryEventData | null { + if (value === null || typeof value !== 'object') return null + const data = value as Record + const failure = data.failure + if (failure === null || typeof failure !== 'object') return null + const failureData = failure as Record + if (!nonNegativeInteger(data.turn) + || !nonNegativeInteger(data.step) + || !positiveInteger(data.retry) + || !positiveInteger(data.maxRetries) + || data.retry > data.maxRetries + || typeof data.delayMs !== 'number' + || !Number.isFinite(data.delayMs) + || data.delayMs < 0 + || typeof failureData.message !== 'string' + || typeof failureData.code !== 'string') return null + const optionalNumbers = [failureData.status, failureData.providerRetryAfterMs] + if (optionalNumbers.some(item => item !== undefined && (typeof item !== 'number' || !Number.isFinite(item)))) return null + if (failureData.requestId !== undefined && typeof failureData.requestId !== 'string') return null + return data as unknown as LlmRetryEventData +} + +function nonNegativeInteger(value: unknown): value is number { + return typeof value === 'number' && Number.isInteger(value) && value >= 0 +} + +function positiveInteger(value: unknown): value is number { + return nonNegativeInteger(value) && value > 0 +} + /** * The composerPhase judgment — the single site that knows the predicate * (consumers switch on the result, never re-derive). Monotone per session diff --git a/packages/client/runtime/tests/event-script.ts b/packages/client/runtime/tests/event-script.ts index b567800c9b..b9d6556a40 100644 --- a/packages/client/runtime/tests/event-script.ts +++ b/packages/client/runtime/tests/event-script.ts @@ -28,6 +28,22 @@ export const ev = { at(seq, { type: 'tool/result', surfaceOp: 'append', data: { turn, step, callId, content: text(body), isError: false } }), stepEnd: (seq: number, turn: number, step = 0): SessionEvent => at(seq, { type: 'step/end', data: { turn, step } }), + retry: ( + seq: number, + turn: number, + step = 0, + retry = 1, + maxRetries = 2, + delayMs = 500, + message = 'temporary transport failure', + ): SessionEvent => + at(seq, { + type: 'llm/retry', + data: { + turn, step, retry, maxRetries, delayMs, + failure: { code: 'TRANSPORT', message }, + }, + }), turnEnd: (seq: number, turn: number, reason: 'completed' | 'cancelled' = 'completed'): SessionEvent => at(seq, { type: 'turn/end', data: { turn, reason: { kind: reason } } }), } diff --git a/packages/client/runtime/tests/session.spec.ts b/packages/client/runtime/tests/session.spec.ts index 136709b20c..320fee9f05 100644 --- a/packages/client/runtime/tests/session.spec.ts +++ b/packages/client/runtime/tests/session.spec.ts @@ -119,6 +119,72 @@ describe('live event path', () => { expect((last as { interrupted?: true }).interrupted).toBeUndefined() }) + it('retracts the failed step partial on retry and keeps a replayable notice before the recovered response', async () => { + const { session } = await opened() + const feed = (event: SessionEvent) => { session.handleMuxEnvelope('r' as never, { type: 'session/event', sessionId: SID, event }) } + const retryTurn = [ + ev.turnStart(6, 1), + ev.user(7, '请重试'), + ev.stepStart(8, 1), + ev.chunkStart(9, 1), + ev.chunkText(10, 1, '不完整回复'), + ev.stepEnd(11, 1), + ev.retry(12, 1, 0, 1, 2, 450, '连接被重置'), + ev.stepStart(13, 1, 1), + ev.assistant(14, 1, '完整回复', 1), + ev.stepEnd(15, 1, 1), + ev.turnEnd(16, 1), + ] + for (const event of retryTurn.slice(0, 7)) feed(event) + + let snapshot = session.getSnapshot() + expect(snapshot.partial).toBeNull() + expect(snapshot.nodes.at(-1)).toMatchObject({ + kind: 'model-retry', + turn: 1, + step: 0, + retry: 1, + maxRetries: 2, + delayMs: 450, + failure: { code: 'TRANSPORT', message: '连接被重置' }, + }) + expect(JSON.stringify(snapshot.nodes)).not.toContain('不完整回复') + + for (const event of retryTurn.slice(7)) feed(event) + snapshot = session.getSnapshot() + expect(snapshot.nodes.slice(-2).map(node => node.kind)).toEqual(['model-retry', 'assistant']) + expect(snapshot.nodes.at(-1)).toMatchObject({ kind: 'assistant', blocks: [{ kind: 'text', text: '完整回复' }] }) + + const replay = makeSession() + replay.api.onHistory = () => histResponse([...plainTurn(0, 0, 'a', 'b'), ...retryTurn]) + await replay.session.open() + expect(replay.session.getSnapshot().nodes).toEqual(snapshot.nodes) + expect(replay.session.getSnapshot().partial).toBeNull() + }) + + it('ignores malformed retry payloads without retracting the current partial', async () => { + const { session } = await opened() + const feed = (event: SessionEvent) => { session.handleMuxEnvelope('r' as never, { type: 'session/event', sessionId: SID, event }) } + feed(ev.turnStart(6, 1)) + feed(ev.chunkStart(7, 1)) + feed(ev.chunkText(8, 1, '仍在生成')) + const errorSpy = vi.spyOn(console, 'error').mockImplementation(() => undefined) + try { + feed(at(9, { + type: 'llm/retry', + data: { + turn: 1, step: 0, retry: 3, maxRetries: 2, delayMs: 500, + failure: { code: 'TRANSPORT', message: 'bad budget' }, + }, + })) + expect(session.getSnapshot().partial?.blocks).toEqual([{ kind: 'text', text: '仍在生成' }]) + expect(session.getSnapshot().nodes.filter(node => node.kind === 'model-retry')).toEqual([]) + expect(errorSpy).toHaveBeenCalledWith('[web-runtime] ignored malformed llm/retry event at seq 9') + } finally { + errorSpy.mockRestore() + } + }) + it('freezes an unfinalized partial into an interrupted node on turn/end (cancel path)', async () => { const { session } = await opened() const feed = (event: SessionEvent) => { session.handleMuxEnvelope('r' as never, { type: 'session/event', sessionId: SID, event }) } diff --git a/packages/client/runtime/tsconfig.json b/packages/client/runtime/tsconfig.json index 2e22ea1013..fb75d70312 100644 --- a/packages/client/runtime/tsconfig.json +++ b/packages/client/runtime/tsconfig.json @@ -26,6 +26,9 @@ { "path": "../../llm/llm" }, + { + "path": "../../llm/llm-retry" + }, { "path": "../../support/invariants" } diff --git a/packages/client/ui-conversation/README.md b/packages/client/ui-conversation/README.md index 0711adcccb..6be40ddb91 100644 --- a/packages/client/ui-conversation/README.md +++ b/packages/client/ui-conversation/README.md @@ -8,6 +8,8 @@ The view ring IS a slot: the conversation registration declares the `'conversati Generic tool rows classify the built-in bash, read, search, write, and edit names into dedicated visual variants. The filesystem variants render the edit icon and `Write · ` or `Edit · ` summary while retaining the shared row-to-details interaction. +The chat flow projects consecutive model-retry nodes from one turn into one stable, muted status row updated to the latest attempt; every retry event remains in the runtime snapshot and session log. Its frontend countdown derives from the scheduled delay, rounds remaining time up to seconds, and has a one-second floor. The latest unresolved retry uses a left-to-right text shimmer, then settles to a static completed label. Activating the row reveals the latest exact retry delay and failure message. The client runtime removes each failed step's streaming tail before its retry node arrives, while the status remains visible after a later attempt succeeds. + Tool rows are slots too — the standalone tool ring (`ToolViewRegistry`/`ctx.toolviews`/outlet) is retired. The chat entry declares the keyed `'conversation.chat.toolview'` hole (session scope; the key space is runtime-open); its render site dispatches per row via `entryKey: toolName` with `GenericToolCard` as the call-site `fallback`. The owner payload is the uniform `ToolRowOwnerProps` (`callId`/`toolName`/`block`/`openDetails`) and `ToolRowProps` pre-composes it with the session standard kit. A registrant is a plain plugin: `ctx.slots.register({ name: 'conversation.chat.toolview', key: '', inject? }, Row)` with `inject: ['slots', 'conversation']` as the load-order seam (apply mounts ConversationService after the chat registration, so the service being present guarantees the slot is declared); session differentiation happens inside the component (`useSessions` reading `parentId` — the bash sample is the third-party-posture exemplar). Trajectory/waterfall toolview slots share this shape and land with their own render sites (RendersCheck rejects a declaration nobody renders). Per-session UI state (selection, ordinary composer draft, active view) lives in the declared chat store (`stores.ts` `createChatStore`): apply constructs one handle and passes it to the conversation, chat-view, and details registrations, so the session slots share one instance per session (selection written by the chat view, read by details) and the framework owns instance lifecycle and draft persistence. The frontend Session Intent comes from the Session list projection; after publication, any retained prompt comes from that Session's conversation snapshot. Components are pure — the framework standard kit (`useSession`/`sessionId` when session-scoped, plus global `useSessions`/`useWorkspaces`) and the store faces (`useStore`/`actions`) arrive automatically from the registration declaration; inject factories contribute plain data and callbacks for runtime Session actions, send/stop, tabs, details, and paging. diff --git a/packages/client/ui-conversation/src/client/chat/ChatView.tsx b/packages/client/ui-conversation/src/client/chat/ChatView.tsx index 8023acddde..79577d18e8 100644 --- a/packages/client/ui-conversation/src/client/chat/ChatView.tsx +++ b/packages/client/ui-conversation/src/client/chat/ChatView.tsx @@ -45,6 +45,16 @@ type RenderToolRow = ChatViewSlotProps['renderSlot'] * chat view narrows once to the runtime snapshot the binding actually feeds. */ type UseConversation = SnapshotSelectorHook +function activeRetrySeq(nodes: readonly ConversationNode[], running: boolean): number | null { + if (!running) return null + for (let index = nodes.length - 1; index >= 0; index -= 1) { + const node = nodes[index]! + if (node.kind === 'model-retry') return node.seq + if (node.kind === 'assistant' || node.kind === 'user') return null + } + return null +} + /** One tool call row (result or running): dispatches through the keyed * toolview slot with the owner payload; unregistered tools fall back to * GenericToolCard at this render site. */ @@ -115,6 +125,7 @@ function StreamingTail({ useSession, onGrow }: { /** The chat view slot entry: pure component over the composed props (tool rows render through the declared keyed hole's renderSlot share). */ export function ChatView({ useSession, useStore, renderSlot, openDetails, loadOlder }: ChatViewSlotProps) { const nodes = useSession((s) => s.nodes) + const running = useSession((s) => s.running) const runningCalls = useSession((s) => s.runningCalls) const pending = useSession((s) => s.pending) const openState = useSession((s) => s.openState) @@ -124,6 +135,7 @@ export function ChatView({ useSession, useStore, renderSlot, openDetails, loadOl const selectedCallId = useStore((s) => s.selection?.callId) const items = useMemo(() => deriveChatFlow(nodes), [nodes]) + const activeRetry = useMemo(() => activeRetrySeq(nodes, running), [nodes, running]) const listRef = useRef(null) const atBottomRef = useRef(true) @@ -220,7 +232,13 @@ export function ChatView({ useSession, useStore, renderSlot, openDetails, loadOl } /* v8 ignore next -- tool-result never reaches here: deriveChatFlow folds them into groups. */ if (node.kind === 'tool-result') return null - return + return ( + + ) } return ( diff --git a/packages/client/ui-conversation/src/client/chat/MessageItem.module.css b/packages/client/ui-conversation/src/client/chat/MessageItem.module.css index 50e560278d..870f646099 100644 --- a/packages/client/ui-conversation/src/client/chat/MessageItem.module.css +++ b/packages/client/ui-conversation/src/client/chat/MessageItem.module.css @@ -32,3 +32,103 @@ .contextRow { padding: 2px 0; } + +.retryRow { + color: var(--dsw-alias-label-tertiary); + font-size: 13px; + line-height: 20px; +} + +.retrySummary { + display: inline-flex; + align-items: center; + width: fit-content; + padding: 2px 0; + gap: 7px; + border-radius: 3px; + color: inherit; + cursor: pointer; + list-style: none; + user-select: none; +} + +.retrySummary::-webkit-details-marker { + display: none; +} + +.retrySummary::after { + width: 6px; + height: 6px; + border-right: 1.5px solid currentcolor; + border-bottom: 1.5px solid currentcolor; + content: ''; + opacity: 0.8; + transform: rotate(-45deg); + transition: transform 120ms ease; +} + +.retrySummary:hover { + color: var(--dsw-alias-label-secondary); +} + +.retrySummary:focus-visible { + outline: 1.5px solid var(--dsw-alias-button-info-fill); + outline-offset: 2px; +} + +.retryText { + color: inherit; +} + +.retryRow[data-active] .retryText { + background: + linear-gradient( + 90deg, + var(--dsw-alias-label-tertiary) 0%, + var(--dsw-alias-label-tertiary) 40%, + var(--dsw-alias-label-secondary) 50%, + var(--dsw-alias-label-tertiary) 60%, + var(--dsw-alias-label-tertiary) 100% + ); + background-position: 100% 50%; + background-size: 200% 100%; + background-clip: text; + color: transparent; + animation: retry-shimmer 1.6s ease-in-out infinite; +} + +.retryRow[open] .retrySummary::after { + transform: rotate(45deg); +} + +.retryDetails { + display: grid; + gap: 2px; + margin-top: 3px; + padding-left: 14px; + overflow-wrap: anywhere; + font-size: 12px; + line-height: 18px; +} + +.retryDetailLabel { + color: var(--dsw-alias-label-secondary); +} + +@keyframes retry-shimmer { + from { + background-position: 100% 50%; + } + + to { + background-position: 0 50%; + } +} + +@media (prefers-reduced-motion: reduce) { + .retryRow[data-active] .retryText { + background: none; + color: inherit; + animation: none; + } +} diff --git a/packages/client/ui-conversation/src/client/chat/MessageItem.tsx b/packages/client/ui-conversation/src/client/chat/MessageItem.tsx index 4bfe07d687..c1c4ac5b4f 100644 --- a/packages/client/ui-conversation/src/client/chat/MessageItem.tsx +++ b/packages/client/ui-conversation/src/client/chat/MessageItem.tsx @@ -1,17 +1,18 @@ -// MessageItem: the four simple node kinds — user bubble (right-aligned), -// steering (badged bubble), context injection and unknown-surface JSON rows. +// MessageItem: simple chat nodes — user bubble (right-aligned), steering +// (badged bubble), context injection, retry disclosure and unknown JSON rows. // Props are frozen node slices off the snapshot cache; memo holds across // streaming because unchanged nodes keep their references. -import { memo } from 'react' +import { memo, useEffect, useState } from 'react' import type { - ContextMessageNode, SteeringMessageNode, UnknownSurfaceNode, UserMessageNode, + ContextMessageNode, ModelRetryNode, SteeringMessageNode, UnknownSurfaceNode, UserMessageNode, } from '@deepseek-ai/dsh-client-runtime/client' import { JsonBlock, MessageText } from '@deepseek-ai/dsh-client-ui-primitives' import css from './MessageItem.module.css' export interface MessageItemProps { - node: UserMessageNode | SteeringMessageNode | ContextMessageNode | UnknownSurfaceNode + node: UserMessageNode | SteeringMessageNode | ContextMessageNode | ModelRetryNode | UnknownSurfaceNode + retryActive?: boolean } function contentText(content: readonly unknown[]): { text: string; rest: unknown[] } { @@ -25,7 +26,56 @@ function contentText(content: readonly unknown[]): { text: string; rest: unknown return { text: texts.join(''), rest } } -export const MessageItem = memo(function MessageItem({ node }: MessageItemProps) { +function retrySeconds(milliseconds: number): number { + return Math.max(1, Math.ceil(milliseconds / 1_000)) +} + +interface RetryCountdown { + deadline: number + seconds: number +} + +function ModelRetryItem({ node, active }: { node: ModelRetryNode; active: boolean }) { + const deadline = node.time + node.delayMs + const scheduledSeconds = retrySeconds(node.delayMs) + const [countdown, setCountdown] = useState(() => ({ + deadline, + seconds: retrySeconds(deadline - Date.now()), + })) + const remainingSeconds = countdown.deadline === deadline + ? countdown.seconds + : retrySeconds(deadline - Date.now()) + + useEffect(() => { + if (!active || retrySeconds(deadline - Date.now()) === 1) return + const timer = window.setInterval(() => { + const next = retrySeconds(deadline - Date.now()) + setCountdown(current => ( + current.deadline === deadline && current.seconds === next + ? current + : { deadline, seconds: next } + )) + if (next === 1) window.clearInterval(timer) + }, 250) + return () => { window.clearInterval(timer) } + }, [active, deadline]) + + return ( +
+ + + {active ? '正在重试' : '已重试'}模型请求({node.retry}/{node.maxRetries}) · {active ? remainingSeconds : scheduledSeconds}s + + +
+
重试延迟:{Math.round(node.delayMs)}ms
+
失败原因:{node.failure.message}
+
+
+ ) +} + +export const MessageItem = memo(function MessageItem({ node, retryActive = false }: MessageItemProps) { switch (node.kind) { case 'user': case 'steering': { @@ -46,6 +96,8 @@ export const MessageItem = memo(function MessageItem({ node }: MessageItemProps) ) + case 'model-retry': + return default: return (
diff --git a/packages/client/ui-conversation/src/client/chat/chat-flow.ts b/packages/client/ui-conversation/src/client/chat/chat-flow.ts index 8f47e334c5..39906c5aa8 100644 --- a/packages/client/ui-conversation/src/client/chat/chat-flow.ts +++ b/packages/client/ui-conversation/src/client/chat/chat-flow.ts @@ -1,7 +1,8 @@ /** * Chat flow derivation: ConversationSnapshot nodes -> render items. Tool * results group into consecutive-run tool groups (figma step-summary flow, - * VERTICAL gap10) alternating with narration; everything else passes through. + * VERTICAL gap10) alternating with narration. Consecutive retry notices from + * one turn reuse the first notice's row while projecting the latest attempt. * Item identity keys are stable across snapshots so the list parent can * subscribe to keys only while rows subscribe to content. */ @@ -15,7 +16,7 @@ export type ChatFlowItem = /** * Group finalized nodes into the step-summary flow. * @param nodes - snapshot nodes (surface order). - * @returns flow items; consecutive tool-results merged into one group keyed by the first seq. + * @returns flow items; consecutive tool results and same-turn retry notices reuse their first key. */ export function deriveChatFlow(nodes: readonly ConversationNode[]): ChatFlowItem[] { const items: ChatFlowItem[] = [] @@ -28,6 +29,18 @@ export function deriveChatFlow(nodes: readonly ConversationNode[]): ChatFlowItem } else { group.push(node) } + } else if (node.kind === 'model-retry') { + group = null + const previous = items[items.length - 1] + if ( + previous?.kind === 'node' + && previous.node.kind === 'model-retry' + && previous.node.turn === node.turn + ) { + items[items.length - 1] = { ...previous, node } + } else { + items.push({ kind: 'node', key: `n${node.seq}`, node }) + } } else { group = null items.push({ kind: 'node', key: `n${node.seq}`, node }) diff --git a/packages/client/ui-conversation/tests/chat-branch-tails.spec.tsx b/packages/client/ui-conversation/tests/chat-branch-tails.spec.tsx index be50356185..38d901dafc 100644 --- a/packages/client/ui-conversation/tests/chat-branch-tails.spec.tsx +++ b/packages/client/ui-conversation/tests/chat-branch-tails.spec.tsx @@ -5,7 +5,7 @@ // machinery specs since the tool ring dissolved into renderSlot.) import { afterEach, describe, expect, it, vi } from 'vitest' -import { cleanup, render } from '@testing-library/react' +import { act, cleanup, fireEvent, render } from '@testing-library/react' import { RpcId } from '@deepseek-ai/dsh-client-connection/client' import type { SessionId } from '@deepseek-ai/dsh-client-runtime/client' import { PendingWait } from '@deepseek-ai/dsh-client-runtime/client' @@ -15,7 +15,10 @@ import { PendingCard } from '../src/client/chat/PendingCard.tsx' import { AssistantMarkdown } from '../src/client/chat/AssistantMarkdown.tsx' import { StatsLine, type StatsLineProps } from '../src/client/chat/StatsLine.tsx' -afterEach(cleanup) +afterEach(() => { + cleanup() + vi.useRealTimers() +}) describe('MessageItem arms', () => { it('steering bubbles carry the interjection badge and non-text rest blocks', () => { @@ -41,6 +44,78 @@ describe('MessageItem arms', () => { ) expect(unknownView.getByText(/未知 surface 事件:surface\/next/)).toBeTruthy() }) + + it('collapses retry details behind the durable model retry status', () => { + vi.useFakeTimers() + vi.setSystemTime(10_000) + const view = render( + , + ) + const details = view.container.querySelector('details') + const summary = view.container.querySelector('summary') + expect(details?.open).toBe(false) + expect(details?.dataset.active).toBe('true') + expect(view.getByRole('status').textContent).toBe('正在重试模型请求(1/2) · 3s') + expect(view.getByText('重试延迟:').parentElement?.textContent).toBe('重试延迟:2500ms') + expect(view.getByText('失败原因:').parentElement?.textContent).toBe('失败原因:连接被重置') + + act(() => { vi.advanceTimersByTime(1_100) }) + expect(view.getByRole('status').textContent).toBe('正在重试模型请求(1/2) · 2s') + act(() => { vi.advanceTimersByTime(1_000) }) + expect(view.getByRole('status').textContent).toBe('正在重试模型请求(1/2) · 1s') + + view.rerender( + , + ) + expect(view.getByRole('status').textContent).toBe('正在重试模型请求(2/2) · 4s') + + if (summary === null) throw new Error('retry summary missing') + fireEvent.click(summary) + expect(details?.open).toBe(true) + + view.rerender( + , + ) + expect(details?.dataset.active).toBeUndefined() + expect(view.getByRole('status').textContent).toBe('已重试模型请求(2/2) · 4s') + }) }) describe('small branch tails', () => { diff --git a/packages/client/ui-conversation/tests/chat-view.spec.tsx b/packages/client/ui-conversation/tests/chat-view.spec.tsx index bb55fcac77..ba661b276c 100644 --- a/packages/client/ui-conversation/tests/chat-view.spec.tsx +++ b/packages/client/ui-conversation/tests/chat-view.spec.tsx @@ -7,7 +7,7 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' import { Profiler } from 'react' import { act, cleanup, fireEvent, render } from '@testing-library/react' import type { - AssistantMessageNode, ConversationNode, ConversationSnapshot, RunningToolCall, SessionId, SessionListState, ToolResultNode, UserMessageNode, WorkspaceListState, + AssistantMessageNode, ConversationNode, ConversationSnapshot, ModelRetryNode, RunningToolCall, SessionId, SessionListState, ToolResultNode, UserMessageNode, WorkspaceListState, } from '@deepseek-ai/dsh-client-runtime/client' import { bindSnapshotSelector } from '@deepseek-ai/dsh-client-web-react' import { createSnapshotStore, PendingWait } from '@deepseek-ai/dsh-client-runtime/client' @@ -59,6 +59,11 @@ const user = (seq: number, text: string): UserMessageNode => ({ const assistant = (seq: number, text: string): AssistantMessageNode => ({ kind: 'assistant', seq, time: seq * 1_000, turn: 1, step: 1, blocks: [{ kind: 'text', text }], }) +const retry = (seq: number): ModelRetryNode => ({ + kind: 'model-retry', seq, time: seq * 1_000, turn: 1, step: 0, + retry: 1, maxRetries: 2, delayMs: 450, + failure: { code: 'TRANSPORT', message: '连接被重置' }, +}) const toolResult = (seq: number, callId: string, name = 'bash'): ToolResultNode => ({ kind: 'tool-result', seq, time: seq * 1_000, callId, call: { name, argsRaw: `{"command":"cmd-${callId}","description":"run ${callId}"}` }, @@ -128,6 +133,17 @@ describe('chat-flow derivation', () => { expect(flowKeys(items)).toBe('n1|n2|g3|n5|g6') expect(flowKeys(deriveChatFlow([...nodes, toolResult(7, 'd')]))).toBe('n1|n2|g3|n5|g6') }) + + it('reuses one stable row for consecutive retries in the same turn', () => { + const first = retry(2) + const second = { ...retry(3), step: 1, retry: 2 } + const initial = deriveChatFlow([user(1, 'try'), first]) + const updated = deriveChatFlow([user(1, 'try'), first, second]) + expect(flowKeys(initial)).toBe('n1|n2') + expect(flowKeys(updated)).toBe('n1|n2') + expect(updated).toHaveLength(2) + expect(updated[1]?.kind === 'node' && updated[1].node).toBe(second) + }) }) describe('ChatView', () => { @@ -168,6 +184,31 @@ describe('ChatView', () => { expect(view.getByText('run a')).toBeTruthy() }) + it('animates only the latest unresolved model retry', () => { + const retryNode = retry(2) + const nextRetry = { ...retry(3), step: 1, retry: 2 } + const context = { + kind: 'context', seq: 4, time: 4_000, content: [], source: null, + } as const satisfies ConversationNode + const h = makeHarness({ nodes: [user(1, 'try'), retryNode], running: true }) + const view = render() + const disclosure = view.container.querySelector('details') + expect(disclosure?.dataset.active).toBe('true') + expect(view.getByRole('status').textContent).toBe('正在重试模型请求(1/2) · 1s') + + act(() => h.set({ nodes: [user(1, 'try'), retryNode, nextRetry] })) + expect(view.getAllByRole('status')).toHaveLength(1) + expect(view.container.querySelector('details')).toBe(disclosure) + expect(view.getByRole('status').textContent).toBe('正在重试模型请求(2/2) · 1s') + + act(() => h.set({ nodes: [user(1, 'try'), retryNode, nextRetry, context, assistant(5, 'done')] })) + expect(disclosure?.dataset.active).toBeUndefined() + expect(view.getByRole('status').textContent).toBe('已重试模型请求(2/2) · 1s') + + act(() => h.set({ nodes: [user(1, 'try'), retry(6)], running: false })) + expect(disclosure?.dataset.active).toBeUndefined() + }) + it('renders assistant Markdown across history, streaming, final, and interrupted states while user text stays literal', () => { const markdown = '# Rendered\n\n- **one**\n- `two`' const h = makeHarness({ nodes: [user(1, markdown), assistant(2, markdown)] }) diff --git a/packages/llm/llm-retry/README.md b/packages/llm/llm-retry/README.md index da1084ba31..8628e8aa37 100644 --- a/packages/llm/llm-retry/README.md +++ b/packages/llm/llm-retry/README.md @@ -4,7 +4,7 @@ Function plugin that retries selected transient model-request failures on the ag The default policy permits two retries for `EMPTY_RESPONSE`, `RATE_LIMIT`, `SERVER`, `TIMEOUT`, and `TRANSPORT`, using bounded exponential backoff from 500 ms to 10 seconds with 10 percent jitter. `EMPTY_RESPONSE` is the adapters' classification of a degenerate provider completion (a terminal stop with zero content blocks); the attempt produced nothing durable, so repeating it is safe. Delay bounds must fit Node's supported timer range. A valid `providerRetryAfterMs` replaces local backoff when it is within the configured cap; an over-cap instruction delegates to the next recovery policy instead. -Before waiting, the plugin appends a non-surface `llm/retry` event with the failure and scheduled delay. Cancellation and plugin disposal abort the wait; disposal drains the plugin's active backoffs, and a callback captured before disposal fails closed if invoked afterward. +Before waiting, the plugin appends a non-surface `llm/retry` event with the failure and scheduled delay. Its payload is available from the browser-safe `@deepseek-ai/dsh-llm-retry/types` subpath, so remote renderers can consume the durable status without loading the policy runtime. Cancellation and plugin disposal abort the wait; disposal drains the plugin's active backoffs, and a callback captured before disposal fails closed if invoked afterward. The separately published `./invariant` companion checks that every retry record names the current open turn and its latest closed step, has a unique step record and increasing retry number, and carries a positive bounded retry budget and non-negative bounded timer delay. Full jitter may schedule zero milliseconds at its lower boundary. diff --git a/packages/llm/llm-retry/package.json b/packages/llm/llm-retry/package.json index 6d6c27636c..757bf49730 100644 --- a/packages/llm/llm-retry/package.json +++ b/packages/llm/llm-retry/package.json @@ -15,11 +15,16 @@ "types": "./lib/types/invariant.d.ts", "default": "./lib/invariant.js" }, + "./types": { + "types": "./lib/types/types.d.ts", + "default": "./lib/types/types.js" + }, "./package.json": "./package.json" }, "files": [ "lib/index.js", "lib/invariant.js", + "lib/types/**/*.js", "lib/types/**/*.d.ts", "lib/types/**/*.d.ts.map", "src" diff --git a/packages/llm/llm-retry/src/index.ts b/packages/llm/llm-retry/src/index.ts index f37cf47e7e..ecf1be4233 100644 --- a/packages/llm/llm-retry/src/index.ts +++ b/packages/llm/llm-retry/src/index.ts @@ -26,6 +26,8 @@ declare module '@deepseek-ai/dsh-session' { } } +export type { LlmRetryEventData } from './types.ts' + export const name = 'llm-retry' export const inject = ['agents'] diff --git a/packages/llm/llm-retry/src/types.ts b/packages/llm/llm-retry/src/types.ts new file mode 100644 index 0000000000..5e3fb0322f --- /dev/null +++ b/packages/llm/llm-retry/src/types.ts @@ -0,0 +1,11 @@ +import type { LlmFailure } from '@deepseek-ai/dsh-llm/types' + +/** Durable payload recorded before one transient model-request retry wait. */ +export interface LlmRetryEventData { + turn: number + step: number + retry: number + maxRetries: number + delayMs: number + failure: LlmFailure +} diff --git a/packages/llm/llm-retry/tests/retry.spec.ts b/packages/llm/llm-retry/tests/retry.spec.ts index 284a3686dc..5ba0361cc4 100644 --- a/packages/llm/llm-retry/tests/retry.spec.ts +++ b/packages/llm/llm-retry/tests/retry.spec.ts @@ -1,10 +1,11 @@ -import { afterEach, describe, expect, it, vi } from 'vitest' +import { afterEach, describe, expect, expectTypeOf, it, vi } from 'vitest' import { Context } from 'cordis' import type { Fiber } from 'cordis' import LlmService, { CallId, EMPTY_RESPONSE_CODE, LlmAdapter, LlmError } from '@deepseek-ai/dsh-llm' import type { GenerateOptions, StreamChunk } from '@deepseek-ai/dsh-llm' import SessionStore, { SessionId } from '@deepseek-ai/dsh-session' -import type { SessionEvent } from '@deepseek-ai/dsh-session' +import type { SessionEvent, SessionEventMap } from '@deepseek-ai/dsh-session' +import type { LlmRetryEventData } from '@deepseek-ai/dsh-llm-retry/types' import SystemPrompt from '@deepseek-ai/dsh-system-prompt' import ToolRegistry, { defineContentToolFixture } from '@deepseek-ai/dsh-tools' import AgentRegistry from '@deepseek-ai/dsh-agent' @@ -15,6 +16,10 @@ import * as retry from '../src/index.ts' type ScriptEntry = Error | Iterable | AsyncIterable +it('keeps the browser-safe retry payload identical to the session event', () => { + expectTypeOf().toEqualTypeOf() +}) + class ScriptedAdapter extends LlmAdapter { readonly requests: GenerateOptions[] = [] diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 7f19dcce27..bcb6c0402b 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -179,6 +179,9 @@ importers: '@deepseek-ai/dsh-llm-deepseek': specifier: workspace:^ version: link:../../packages/llm/llm-deepseek + '@deepseek-ai/dsh-llm-retry': + specifier: workspace:^ + version: link:../../packages/llm/llm-retry '@deepseek-ai/dsh-paths': specifier: workspace:^ version: link:../../packages/util/paths @@ -782,6 +785,9 @@ importers: '@deepseek-ai/dsh-llm': specifier: workspace:^ version: link:../../llm/llm + '@deepseek-ai/dsh-llm-retry': + specifier: workspace:^ + version: link:../../llm/llm-retry '@deepseek-ai/dsh-session': specifier: workspace:^ version: link:../../core/session diff --git a/tsconfig.base.json b/tsconfig.base.json index a449a34c4e..1846e55366 100644 --- a/tsconfig.base.json +++ b/tsconfig.base.json @@ -43,6 +43,7 @@ "@deepseek-ai/dsh-session/surface": ["./packages/core/session/src/surface.ts"], "@deepseek-ai/dsh-llm/types": ["./packages/llm/llm/src/types.ts"], "@deepseek-ai/dsh-llm/brand": ["./packages/llm/llm/src/brand.ts"], + "@deepseek-ai/dsh-llm-retry/types": ["./packages/llm/llm-retry/src/types.ts"], "@deepseek-ai/dsh-tools/presentation": ["./packages/core/tools/src/presentation.ts"], "@deepseek-ai/dsh-user-approval/types": ["./packages/ui/user-approval/src/types.ts"], "@deepseek-ai/dsh-user-interaction/types": ["./packages/ui/user-interaction/src/types.ts"], From 891e9035e7e792a8c13bb91fd3f4fab342b87600 Mon Sep 17 00:00:00 2001 From: Hypatia May Date: Mon, 27 Jul 2026 12:15:06 +0800 Subject: [PATCH 002/139] feat(web): add basic past-session search (round 1) --- .../2026-07-27-web-session-search.i18n.yaml | 6 + .../feature/2026-07-27-web-session-search.md | 42 ++++ .../2026-07-27-web-session-search.zh.md | 42 ++++ apps/cli/README.i18n.yaml | 6 +- apps/cli/README.md | 2 +- apps/cli/README.zh.md | 2 +- apps/cli/cordis.yml | 7 + apps/cli/package.json | 2 + apps/web/tests/navigation-panes.e2e.ts | 62 ++--- apps/web/tests/scaffold.ts | 1 + .../search-results.expected.md | 2 + packages/client/connection/src/client/api.ts | 2 +- .../client/connection/src/client/fixture.ts | 126 +++++++++- .../client/connection/src/client/index.ts | 2 +- packages/client/connection/tests/fake-api.ts | 9 +- .../client/connection/tests/fixture.spec.ts | 35 +++ packages/client/runtime/README.i18n.yaml | 6 +- packages/client/runtime/README.md | 2 + packages/client/runtime/README.zh.md | 2 + packages/client/runtime/src/client/index.ts | 2 +- .../runtime/src/client/sessions/manager.ts | 29 ++- .../runtime/src/client/sessions/service.ts | 20 +- packages/client/runtime/tests/fake-api.ts | 9 +- packages/client/runtime/tests/manager.spec.ts | 43 ++++ .../runtime/tests/sessions-service.spec.ts | 23 ++ packages/client/ui-workspace/README.i18n.yaml | 6 +- packages/client/ui-workspace/README.md | 7 +- packages/client/ui-workspace/README.zh.md | 7 +- .../src/client/WorkspaceBrowser.module.css | 16 ++ .../src/client/WorkspaceBrowser.tsx | 159 ++++++++++-- .../ui-workspace/src/client/contract/slots.ts | 12 +- .../client/ui-workspace/src/client/index.ts | 6 + .../src/client/rows/Rows.module.css | 58 +++++ .../ui-workspace/src/client/rows/Rows.tsx | 37 ++- .../client/ui-workspace/src/client/tree.ts | 184 ++++++++------ .../client/ui-workspace/tests/apply.spec.ts | 37 ++- .../client/ui-workspace/tests/rows.spec.tsx | 23 +- .../client/ui-workspace/tests/tree.spec.ts | 172 ++++++++----- .../tests/workspace-browser.spec.tsx | 201 ++++++++++++--- packages/host/apiproxy/README.i18n.yaml | 6 +- packages/host/apiproxy/README.md | 2 + packages/host/apiproxy/README.zh.md | 2 + packages/host/apiproxy/package.json | 1 + packages/host/apiproxy/src/api-proxy.ts | 96 ++++++- packages/host/apiproxy/src/api/index.ts | 2 +- packages/host/apiproxy/src/api/rpc-map.ts | 1 + .../host/apiproxy/src/api/sessions.schema.ts | 25 +- packages/host/apiproxy/src/api/sessions.ts | 17 ++ packages/host/apiproxy/src/fetch/client.ts | 4 + packages/host/apiproxy/src/fetch/handler.ts | 5 +- .../apiproxy/tests/api-proxy-search.spec.ts | 237 ++++++++++++++++++ .../apiproxy/tests/client-handler.spec.ts | 25 ++ .../host/apiproxy/tests/fetch-carrier.spec.ts | 47 ++++ .../host/apiproxy/tests/rpc-schemas.spec.ts | 24 +- packages/host/apiproxy/tsconfig.json | 3 + pnpm-lock.yaml | 9 + 56 files changed, 1646 insertions(+), 269 deletions(-) create mode 100644 .agents/notes/implemented/feature/2026-07-27-web-session-search.i18n.yaml create mode 100644 .agents/notes/implemented/feature/2026-07-27-web-session-search.md create mode 100644 .agents/notes/implemented/feature/2026-07-27-web-session-search.zh.md create mode 100644 apps/web/tests/snapshots/navigation-panes/search-results.expected.md create mode 100644 packages/host/apiproxy/tests/api-proxy-search.spec.ts diff --git a/.agents/notes/implemented/feature/2026-07-27-web-session-search.i18n.yaml b/.agents/notes/implemented/feature/2026-07-27-web-session-search.i18n.yaml new file mode 100644 index 0000000000..31d6b377af --- /dev/null +++ b/.agents/notes/implemented/feature/2026-07-27-web-session-search.i18n.yaml @@ -0,0 +1,6 @@ +# Bilingual-pair consistency record (docs/i18n/README.md): the git blob hash of each +# side as of the last confirmed-consistent state. Both languages carry equal authority; +# after editing either side, bring the other along and re-record with: +# pnpm run verify-translation-pairing --write .agents/notes/implemented/feature/2026-07-27-web-session-search.md +2026-07-27-web-session-search.md: 3cc44ba3652415e9fa32ce67bceefc822c41059b +2026-07-27-web-session-search.zh.md: 2b6ea7a60e1b051757852ff331c0b93c48bd2b57 diff --git a/.agents/notes/implemented/feature/2026-07-27-web-session-search.md b/.agents/notes/implemented/feature/2026-07-27-web-session-search.md new file mode 100644 index 0000000000..3cc44ba365 --- /dev/null +++ b/.agents/notes/implemented/feature/2026-07-27-web-session-search.md @@ -0,0 +1,42 @@ +# Agent Note: Web past-session search + +Status: implemented + +English | [中文](2026-07-27-web-session-search.zh.md) + +## Problem + +The Web sidebar exposes session titles and Workspace membership but cannot retrieve a past conversation from words that appear only inside its messages. Scanning histories in the browser would require attaching or loading every session, duplicate the existing indexed-search service, and make cold persisted sessions both slow and easy to omit. The product also needs a predictable failure path: an unavailable derived index must not erase title matches that the client can compute locally. + +## Decision + +The shared Web/headless composition mounts [`@deepseek-ai/dsh-session-query-sqlite`](../../../../packages/session-query/session-query-sqlite/README.md) at `.sessions/session-query.db`. Opening the database does not scan logs; the first content query lazily reconciles changed live and persisted sessions. The database is a disposable derived index, separate from canonical JSONL persistence. + +The host gateway exposes `session.search` through the existing typed RPC stack. It derives the authorization set from the same visible summaries as `session.list`, passes those ids to `ctx.sessionQuery.searchSessions`, and restricts indexed matches to current-surface `user/message`, `assistant/message`, and `steering/message` events. The response is one page of at most 20 session ids and snippets; `hasMore` tells the UI to ask for a narrower query rather than exposing pagination. The carrier signal cancels superseded work. A missing query service or an indexing/query failure remains a business error and does not mutate the canonical session store. + +[`WorkspaceBrowser`](../../../../packages/client/ui-workspace/README.md) keeps metadata and content search deliberately separate. A non-blank query immediately computes case-insensitive title and Workspace substring matches from the Session list, starts a 250 ms debounced content request, aborts the preceding request when the query changes, and ignores stale completions. It merges local matches first in recency order with backend-ranked content-only matches, deduplicates by session id, and renders a flat list regardless of the normal grouping mode. Each row shows the title, Workspace, and an available one-line snippet. Selecting a row opens the Session only and preserves the query; it does not navigate to an exact event. + +Content matching inherits the SQLite backend's normalized literal token/phrase semantics. FTS5 operators are inert data, and this surface adds no typo, fuzzy, prefix, or arbitrary-substring expansion. In particular, the `unicode61` tokenizer may treat an uninterrupted Chinese sequence as one token, so a shorter query such as `搜索` is not guaranteed to match inside `会话搜索功能`. Title and Workspace matching remains ordinary client-side substring matching. + +## Failure and visibility contract + +Search never widens session visibility: cold sessions without a servable cwd are absent for the same reason they are absent from `session.list`, and the query receives only ids from that baseline. Shadowed and log-only events, tool events outside message content, errors, todos, and other trace records do not produce UI hits. + +While the first or a later content request is pending, the UI keeps immediate metadata matches and shows a history-search status. If the backend fails, the same rows remain and a warning explains that content search is unavailable. Zero merged rows produce an explicit empty state. More than 20 candidate rows produce a refine-query hint. + +## Alternatives considered + +- **Scan every session history in the browser** — rejected because it attaches transport and fold cost to the UI, misses cold logs unless they are loaded, and duplicates the semantic extraction and source reconciliation already owned by `ctx.sessionQuery`. +- **Make trigram or fuzzy search part of the first release** — rejected because it changes index size, ranking, short-query behavior, and product expectations. Trigrams also do not by themselves solve two-character queries. The first release uses the existing backend contract and leaves recall expansion as a separate measured decision. +- **Return event addresses and jump to the exact match** — rejected for this release because conversation virtualization and stable event navigation need a separate UI contract. Session-level navigation is useful without coupling search to that work. +- **Expose cursor pagination in the sidebar** — rejected in favor of a fixed top-20 surface and a narrow-query hint; this keeps the interaction and cancellation state bounded. + +## Consequences + +Past persisted conversations become discoverable without opening them first, while the host retains one visibility boundary and one semantic-index implementation. Immediate local results hide most request latency, cancellation prevents obsolete queries from repainting the list, and backend failure degrades to the behavior available before content search. + +The first content query can take longer because it pays lazy reconciliation. Search quality is token/phrase recall rather than fuzzy or arbitrary substring recall, including the documented continuous-Chinese limitation. Results are session-level, capped at 20, and have no paging or exact-message navigation. + +## Testing + +Host tests pin request validation, visible-session filtering, event/surface filters, result bounds, cancellation, and failure mapping. Runtime and UI tests pin stateless delegation, debounce/abort/stale-response behavior, local fallback, merge order, deduplication, row rendering, and navigation semantics. A keyless assembled Web test seeds an unopened persisted conversation, finds it by message content through the lazy SQLite index, captures the sidebar result, opens it, and verifies that the query remains. diff --git a/.agents/notes/implemented/feature/2026-07-27-web-session-search.zh.md b/.agents/notes/implemented/feature/2026-07-27-web-session-search.zh.md new file mode 100644 index 0000000000..2b6ea7a60e --- /dev/null +++ b/.agents/notes/implemented/feature/2026-07-27-web-session-search.zh.md @@ -0,0 +1,42 @@ +# Agent Note: Web 历史会话搜索 + +Status: implemented + +[English](2026-07-27-web-session-search.md) | 中文 + +## 问题 + +Web 侧边栏会展示会话标题及其 Workspace 归属,但无法根据只出现在消息中的词语检索历史对话。在浏览器中扫描历史记录,需要附加或加载每个会话,重复实现现有的索引搜索服务,也会让冷态持久化会话的检索既缓慢又容易遗漏。产品还需要一条可预测的故障路径:派生索引不可用时,不得抹去客户端能够在本地计算出的标题匹配结果。 + +## 决策 + +Web 与 headless 共用的组合会在 `.sessions/session-query.db` 挂载 [`@deepseek-ai/dsh-session-query-sqlite`](../../../../packages/session-query/session-query-sqlite/README.md)。打开数据库时不会扫描日志;首次内容查询会惰性对齐发生变更的实时会话与持久化会话。该数据库是可丢弃的派生索引,与规范 JSONL 持久化相互独立。 + +宿主网关通过现有的类型化 RPC 栈公开 `session.search`。它根据 `session.list` 使用的同一组可见摘要推导授权集合,将这些 id 传给 `ctx.sessionQuery.searchSessions`,并将索引匹配限制为当前 surface 中的 `user/message`、`assistant/message` 和 `steering/message` 事件。响应只包含一页,最多 20 个会话 id 及其摘要片段;`hasMore` 会指示 UI 提示用户缩小查询范围,而不是公开分页能力。载体信号会取消已被取代的工作。查询服务缺失或索引、查询失败仍作为业务错误处理,不会修改规范会话存储。 + +[`WorkspaceBrowser`](../../../../packages/client/ui-workspace/README.md) 有意将元数据搜索与内容搜索保持独立。非空白查询会立即从会话列表中计算不区分大小写的标题和 Workspace 子串匹配,在 250 ms 防抖后发起内容请求,在查询变化时中止前一请求,并忽略陈旧的完成结果。它先按新近程度排列本地匹配,再合并由后端排序且仅匹配内容的结果,按会话 id 去重;无论常规分组模式如何,最终都渲染为扁平列表。每一行显示标题、Workspace,并在存在时显示一行摘要片段。选择某一行只会打开对应会话,并保留查询条件;不会跳转至确切事件。 + +内容匹配沿用 SQLite 后端经过规范化的字面 token/短语语义。FTS5 运算符只作为数据处理,此搜索界面不提供拼写错误纠正、模糊匹配、前缀匹配或任意子串扩展。特别是,`unicode61` 分词器可能将一段连续中文视作单个 token,因此不保证 `搜索` 之类的较短查询能匹配 `会话搜索功能` 的内部片段。标题与 Workspace 匹配仍采用普通的客户端子串匹配。 + +## 故障与可见性契约 + +搜索绝不会扩大会话可见范围:没有可供服务的 cwd 的冷会话会被排除,原因与它们不出现在 `session.list` 中相同;查询只会接收这条基线提供的 id。被遮蔽事件和纯日志事件、消息内容之外的工具事件、错误、待办事项及其他追踪记录都不会产生 UI 命中结果。 + +首个或后续内容请求仍在处理期间,UI 会保留即时元数据匹配结果,并显示历史搜索状态。如果后端失败,这些行会保持不变,并显示警告说明内容搜索不可用。合并后没有任何行时,界面会显示明确的空状态。候选行超过 20 条时,界面会提示用户缩小查询范围。 + +## 曾考虑的替代方案 + +- **在浏览器中扫描每个会话的历史记录**:不予采纳,因为这会让 UI 承担传输与折叠开销;除非加载冷态日志,否则还会漏掉这些日志;并会重复实现已经由 `ctx.sessionQuery` 负责的语义提取与源对齐。 +- **首版即加入 trigram 或模糊搜索**:不予采纳,因为这会改变索引大小、排序、短查询行为与产品预期。trigram 本身也无法解决双字查询。首版沿用现有后端契约,将召回扩展留作另一项基于度量结果的决策。 +- **返回事件地址并跳转至确切匹配位置**:本版不予采纳,因为对话虚拟化与稳定的事件导航需要单独的 UI 契约。会话级导航本身已有价值,无需让搜索与这项工作耦合。 +- **在侧边栏公开游标分页**:不予采纳,改为固定显示前 20 条结果并提示缩小查询范围;这样可使交互与取消状态保持有界。 + +## 后果 + +无需预先打开,即可检索到历史持久化对话,同时宿主仍只保留一条可见性边界和一套语义索引实现。即时本地结果掩盖了大部分请求延迟,取消机制可防止已作废查询重新渲染列表,后端故障则会降级为内容搜索尚不可用时已有的行为。 + +首次内容查询可能耗时更长,因为它要承担惰性对齐的开销。搜索质量采用 token/短语召回,而不是模糊召回或任意子串召回,并受上述连续中文限制。结果粒度为会话,最多 20 条,不支持分页,也不能跳转到具体消息。 + +## 测试 + +宿主测试将请求校验、可见会话过滤、事件和 surface 过滤、结果边界、取消与故障映射固定为契约。运行时与 UI 测试将无状态委托、防抖/中止/陈旧响应行为、本地回退、合并顺序、去重、行渲染与导航语义固定为契约。无密钥的组装层 Web 测试会播种一段尚未打开的持久化对话,通过惰性 SQLite 索引按消息内容找到它,捕获侧边栏结果,打开该会话,并验证查询条件仍然保留。 diff --git a/apps/cli/README.i18n.yaml b/apps/cli/README.i18n.yaml index abe51abc2f..e78ab7b8ad 100644 --- a/apps/cli/README.i18n.yaml +++ b/apps/cli/README.i18n.yaml @@ -1,6 +1,6 @@ # Bilingual-pair consistency record (docs/i18n/README.md): the git blob hash of each # side as of the last confirmed-consistent state. Both languages carry equal authority; # after editing either side, bring the other along and re-record with: -# pnpm run verify-translation-pairing --write -README.md: 42d2a9641cf5d497c9aae45d9f60fce4498addb9 -README.zh.md: 0a62f8bb72e2cf2dbe045d28b81768bf4df800de +# pnpm run verify-translation-pairing --write apps/cli/README.md +README.md: bb3f4ee98700e4644535d1d3c05d29a9a558275d +README.zh.md: 44edea0f5b36598cfda1b61914da0b6622b973d6 diff --git a/apps/cli/README.md b/apps/cli/README.md index 42d2a9641c..bb3f4ee987 100644 --- a/apps/cli/README.md +++ b/apps/cli/README.md @@ -14,7 +14,7 @@ The TUI surface: - tells the agent where its own source lives: after boot it adds a prompt section naming this harness checkout, resolved from the launcher's real path so it holds under a PATH symlink and an arbitrary cwd, so the self-referential `cordis` toolset can read and modify it; - applies the personal overlay from `~/.dsh` (see [app-boot's Personal config](../../packages/ui/app-boot/README.md#personal-config)): `.env` fills environment gaps (ambient > project `.env` > personal `.env`), `config.yaml` patches the booted tree. -The Web and headless surfaces boot one shared composition (`cordis.yml`): both treat the invoking directory as the default project and Workspace root, create named Workspaces beneath that root unless `--workspace-root ` overrides it, load applicable `AGENTS.md`/`CLAUDE.md` instructions into each agent-loop request prefix with a 65,536-byte render budget, and opt into first-message model titles. Headless differs only in listening on an OS-assigned port (parallel `dsh -p` runs never collide; the stderr-printed URL opens the live session in a browser). Both need the frontend dist and client bundles built (`pnpm run build && pnpm run build:web`). +The Web and headless surfaces boot one shared composition (`cordis.yml`): both treat the invoking directory as the default project and Workspace root, create named Workspaces beneath that root unless `--workspace-root ` overrides it, load applicable `AGENTS.md`/`CLAUDE.md` instructions into each agent-loop request prefix with a 65,536-byte render budget, opt into first-message model titles, and mount a disposable SQLite content index at `.sessions/session-query.db`. The index is opened without scanning at boot and lazily reconciles changed live and persisted logs on the first session search. Headless differs only in listening on an OS-assigned port (parallel `dsh -p` runs never collide; the stderr-printed URL opens the live session in a browser). Both need the frontend dist and client bundles built (`pnpm run build && pnpm run build:web`). `DSH_TOOLS_MODE` selects the tool presentation mode for the whole Web/headless process: `native` (the schema default when unset), `code` (the `run_code`-only Code Mode wire), or `both`; any other value fails loud at boot through the `dsh-tools` config schema. It is a TEMPORARY seam — process-wide because Loader composition is static — and is removed once the web UI owns per-session tool-mode selection; the TUI surface ignores it (its config tree pins its own mode). diff --git a/apps/cli/README.zh.md b/apps/cli/README.zh.md index 0a62f8bb72..44edea0f5b 100644 --- a/apps/cli/README.zh.md +++ b/apps/cli/README.zh.md @@ -14,7 +14,7 @@ TUI 界面: - 告知 agent 自身源码所在位置:启动后添加一个命名此 harness checkout 的提示词段。该路径从启动器的真实路径解析,因此在 PATH 符号链接和任意 cwd 下仍然有效,使自指的 `cordis` 工具集可以读取并修改它; - 应用 `~/.dsh` 中的个人覆盖(参见 [app-boot 的个人配置](../../packages/ui/app-boot/README.md#personal-config)):`.env` 填补环境缺口(环境中已有的值 > 项目 `.env` > 个人 `.env`),`config.yaml` 则修补已启动的树。 -Web 和无头界面启动同一个共享组合(`cordis.yml`):两者都将调用目录视为默认项目和 Workspace 根目录,除非通过 `--workspace-root ` 覆盖,否则会在该根目录下创建具名 Workspace;它们会把适用的 `AGENTS.md`/`CLAUDE.md` 指令加载到每个 agent-loop 请求前缀中,渲染预算为 65,536 字节,并选用首条消息模型标题。无头界面唯一的差异是监听操作系统分配的端口(并行 `dsh -p` 运行绝不冲突;stderr 打印的 URL 会在浏览器中打开实时会话)。两者都需要先构建前端 dist 和客户端 bundle(`pnpm run build && pnpm run build:web`)。 +Web 和无头界面启动同一个共享组合(`cordis.yml`):两者都将调用目录视为默认项目和 Workspace 根目录,除非通过 `--workspace-root ` 覆盖,否则会在该根目录下创建具名 Workspace;它们会把适用的 `AGENTS.md`/`CLAUDE.md` 指令加载到每个 agent-loop 请求前缀中,渲染预算为 65,536 字节,并选用首条消息模型标题,且在 `.sessions/session-query.db` 挂载一个可丢弃的 SQLite 内容索引。该索引在启动时不经扫描即打开,并在首次会话搜索时惰性对账已更改的实时日志和持久化日志。无头界面唯一的差异是监听操作系统分配的端口(并行 `dsh -p` 运行绝不冲突;stderr 打印的 URL 会在浏览器中打开实时会话)。两者都需要先构建前端 dist 和客户端 bundle(`pnpm run build && pnpm run build:web`)。 `DSH_TOOLS_MODE` 为整个 Web/无头进程选择工具呈现模式:可选值为 `native`(未设置时的 schema 默认值)、`code`(仅含 `run_code` 的 Code Mode 协议接口)或 `both`;任何其他值都会经由 `dsh-tools` 配置 schema 在启动时明确报错。它是一个临时 seam:Loader 组合是静态的,因此该设置作用于整个进程;待 Web UI 负责逐会话工具模式选择后便会移除。TUI 界面会忽略该变量(其配置树固定了自身模式)。 diff --git a/apps/cli/cordis.yml b/apps/cli/cordis.yml index efd75c1cf5..4adb5048b8 100644 --- a/apps/cli/cordis.yml +++ b/apps/cli/cordis.yml @@ -89,6 +89,13 @@ config: root: './.sessions' +# Lazy content index for session.search. Opening the database at boot does +# not scan logs; the first search reconciles changed live/persisted sessions. +- id: session-query-sqlite + name: '@deepseek-ai/dsh-session-query-sqlite' + config: + path: './.sessions/session-query.db' + - id: storage name: '@deepseek-ai/dsh-storage' diff --git a/apps/cli/package.json b/apps/cli/package.json index e0a3a51c94..2bc160eda8 100644 --- a/apps/cli/package.json +++ b/apps/cli/package.json @@ -55,6 +55,8 @@ "@deepseek-ai/dsh-plan-mode": "workspace:^", "@deepseek-ai/dsh-session": "workspace:^", "@deepseek-ai/dsh-session-persistence-jsonl": "workspace:^", + "@deepseek-ai/dsh-session-query": "workspace:^", + "@deepseek-ai/dsh-session-query-sqlite": "workspace:^", "@deepseek-ai/dsh-session-title": "workspace:^", "@deepseek-ai/dsh-session-title-first-message-llm": "workspace:^", "@deepseek-ai/dsh-skill": "workspace:^", diff --git a/apps/web/tests/navigation-panes.e2e.ts b/apps/web/tests/navigation-panes.e2e.ts index bbae7363df..7744ad5c55 100644 --- a/apps/web/tests/navigation-panes.e2e.ts +++ b/apps/web/tests/navigation-panes.e2e.ts @@ -26,6 +26,7 @@ const SEED = join(SNAPSHOT_DIR, 'seed.jsonl') const TRAJECTORY_EXPECTED = join(SNAPSHOT_DIR, 'trajectory.expected.md') const WATERFALL_EXPECTED = join(SNAPSHOT_DIR, 'waterfall.expected.md') const DETAILS_EXPECTED = join(SNAPSHOT_DIR, 'details-open.expected.md') +const SEARCH_EXPECTED = join(SNAPSHOT_DIR, 'search-results.expected.md') const MODE = webSnapshotMode() const SEED_ID = 'navigation-panes-web-e2e' @@ -90,39 +91,39 @@ describe('web e2e: navigation & panes over a rich seeded session', () => { expect(calls.map(e => e.data.name).sort()).toEqual(['bash', 'read', 'read']) }, 400_000) - it.skipIf(MODE === 'record')('opens the seeded session and renders both turns from the log', async () => { - onTestFailed(() => saveFailureShot(page, 'web-e2e-navigation-open')) - // Expand the collapsed group row, then open the revealed session row. - const groupRow = page.locator('[role="treeitem"]').first() - await groupRow.waitFor({ timeout: 15_000 }) - await groupRow.click() - const sessionRow = page.locator('[role="treeitem"]').nth(1) - await sessionRow.waitFor({ timeout: 10_000 }) - await sessionRow.click() + it.skipIf(MODE === 'record')('finds an unopened seeded session by message content and opens it', async () => { + onTestFailed(() => saveFailureShot(page, 'web-e2e-navigation-search')) + const search = page.getByPlaceholder('搜索名称或关键词', { exact: false }) + // The cold row has not been opened, so only the persisted log can satisfy + // this query. First search lazily reconciles the SQLite content index. + await search.fill('zzzqx-no-such-session') + await page.getByText('没有匹配结果').waitFor({ timeout: 30_000 }) + await expect.poll( + () => page.getByRole('tree', { name: '搜索结果' }).getByRole('treeitem').count(), + { timeout: 10_000 }, + ).toBe(0) + + await search.fill('WATERFALL') + const resultTree = page.getByRole('tree', { name: '搜索结果' }) + const result = resultTree.getByRole('treeitem') + await expect.poll(() => result.count(), { timeout: 30_000 }).toBe(1) + await expect.poll(() => result.getByText('WATERFALL', { exact: false }).count(), { + timeout: 10_000, + }).toBeGreaterThanOrEqual(1) + const snapshot = (await captureStableAria(page, '[class*="listArea"]', scaffold.workspaceCwd)) + .split(SEED_ID).join('{{seededId}}') + await compareOrRefreshGolden(SEARCH_EXPECTED, snapshot, MODE) + + await result.click() + // Search navigation addresses the session, not a specific event, and the + // query remains until the user explicitly clears it. + await expect.poll(() => search.inputValue(), { timeout: 5_000 }).toBe('WATERFALL') await expect.poll(() => page.getByText('FIRST_DONE', { exact: true }).count(), { timeout: 15_000 }).toBeGreaterThanOrEqual(1) await expect.poll(() => page.getByRole('heading', { name: 'Navigation Summary' }).count(), { timeout: 15_000 }).toBe(1) - }, 90_000) - - it.skipIf(MODE === 'record')('filters the sidebar tree by title through the search box', async () => { - onTestFailed(() => saveFailureShot(page, 'web-e2e-navigation-search')) - // Runs after the session is open: a cold summary carries no title (the - // sidebar shows the cwd basename), and the durable title lands with the - // attach subscription's baseline — which is itself worth pinning: search - // matches the title the user sees, not a hidden cold field. - const search = page.getByPlaceholder('Search name, keywords', { exact: false }) - await expect.poll(() => page.getByText('NavScenario', { exact: false }).count(), { timeout: 15_000 }).toBeGreaterThanOrEqual(1) - // Negative: a garbage query empties the tree (group rows hide too). - await search.fill('zzzqx-no-such-session') - await expect.poll(() => page.locator('[role="treeitem"]').count(), { timeout: 10_000 }).toBe(0) - // Positive: a title word narrows to the matched session + its group, - // force-expanded by search mode (case-insensitive client-side filter). - await search.fill('navscenario') - await expect.poll(() => page.locator('[role="treeitem"]').count(), { timeout: 10_000 }).toBeGreaterThanOrEqual(2) - // Clear restores the unfiltered tree. - await page.getByRole('button', { name: 'Clear search' }).click() + await page.getByRole('button', { name: '清除搜索' }).click() await expect.poll(() => search.inputValue(), { timeout: 5_000 }).toBe('') await expect.poll(() => page.locator('[role="treeitem"]').count(), { timeout: 10_000 }).toBeGreaterThanOrEqual(1) - }, 60_000) + }, 90_000) it.skipIf(MODE === 'record')('renders the trajectory tab with turn sections and step cells', async () => { onTestFailed(() => saveFailureShot(page, 'web-e2e-navigation-trajectory')) @@ -184,7 +185,8 @@ describe('web e2e: navigation & panes over a rich seeded session', () => { expect(tripwire.pageErrors).toEqual([]) expect(tripwire.warnings).toEqual([]) await assertFixtureInventory(SNAPSHOT_DIR, [ - 'seed.jsonl', 'trajectory.expected.md', 'waterfall.expected.md', 'details-open.expected.md', + 'seed.jsonl', 'search-results.expected.md', 'trajectory.expected.md', + 'waterfall.expected.md', 'details-open.expected.md', ]) }) }) diff --git a/apps/web/tests/scaffold.ts b/apps/web/tests/scaffold.ts index 34d0e5f123..f809081d3d 100644 --- a/apps/web/tests/scaffold.ts +++ b/apps/web/tests/scaffold.ts @@ -163,6 +163,7 @@ export async function launchWebScaffold(options: LaunchOptions = {}): Promise 0 } } +/** Fixture mirror of first-party message extraction used by session-query. */ +function searchBlockText(block: ContentBlock): string[] { + switch (block.type) { + case 'text': + case 'reasoning': + return [block.text] + case 'tool-call': + return [block.name, block.arguments] + case 'tool-result': + return block.content.flatMap(searchBlockText) + default: + return [] + } +} + +/** One current-surface user/assistant/steering document, if searchable. */ +function searchEventText(event: SessionEvent): string { + if ( + event.type !== 'user/message' + && event.type !== 'assistant/message' + && event.type !== 'steering/message' + ) return '' + return event.data.content.flatMap(searchBlockText).map(part => part.trim()).filter(Boolean).join('\n') +} + +/** + * Browser-safe approximation of SQLite FTS5 unicode61 token boundaries. + * Keeping phrase matching token-based prevents the development fixture from + * promising arbitrary within-token substring behavior that production lacks. + */ +function searchTokens(value: string): string[] { + return value + .normalize('NFD') + .replace(/\p{M}+/gu, '') + .toLowerCase() + .match(/[\p{L}\p{N}\p{Co}]+/gu) ?? [] +} + +/** Count exact contiguous token-phrase occurrences in one fixture document. */ +function phraseMatchCount(document: readonly string[], phrase: readonly string[]): number { + if (phrase.length === 0 || phrase.length > document.length) return 0 + let count = 0 + for (let start = 0; start <= document.length - phrase.length; start++) { + if (phrase.every((token, offset) => document[start + offset] === token)) count++ + } + return count +} + +/** One-line fixture excerpt, bounded so the sidebar remains readable. */ +function searchSnippet(value: string): string { + const oneLine = value.replace(/\s+/gu, ' ').trim() + return oneLine.length <= 120 ? oneLine : `${oneLine.slice(0, 117)}…` +} + +interface FixtureSearchCandidate { + sessionId: SessionId + seq: number + time: number + text: string + matchCount: number + documentLength: number +} + +/** Same rank keys as session-query-sqlite's cross-session result order. */ +function compareSearchCandidates(a: FixtureSearchCandidate, b: FixtureSearchCandidate): number { + if (a.matchCount !== b.matchCount) return b.matchCount - a.matchCount + if (a.documentLength !== b.documentLength) return a.documentLength - b.documentLength + if (a.time !== b.time) return b.time - a.time + if (a.sessionId !== b.sessionId) return a.sessionId < b.sessionId ? -1 : 1 + return b.seq - a.seq +} + interface StreamConn { push(envelope: RpcRequest): void } @@ -547,6 +620,42 @@ export function createFixtureApi(options: FixtureOptions = {}): ApiProxy { return { sessions: { list: request => ok(request, { items: [...sessions].sort((a, b) => b.updatedAt - a.updatedAt) }), + search: (request, signal) => { + if (signal.aborted) { + return err(request, { + code: 'cancelled', + message: 'fixture session search was aborted', + details: {}, + }) + } + const query = searchTokens(request.payload.query) + const matches = sessions.flatMap((summary) => { + const log = logs.get(summary.sessionId) ?? [] + const current = new Set(foldSurface(log).nodes) + const best = log.flatMap((event): FixtureSearchCandidate[] => { + if (!current.has(event.seq)) return [] + const eventText = searchEventText(event) + const matchCount = phraseMatchCount(searchTokens(eventText), query) + if (matchCount === 0) return [] + return [{ + sessionId: summary.sessionId, + seq: event.seq, + time: event.time, + text: eventText, + matchCount, + documentLength: Array.from(eventText).length, + }] + }).sort(compareSearchCandidates)[0] + return best === undefined ? [] : [best] + }).sort(compareSearchCandidates) + return ok(request, { + items: matches.slice(0, 20).map(match => ({ + sessionId: match.sessionId, + snippet: searchSnippet(match.text), + })), + hasMore: matches.length > 20, + }) + }, create: async (request) => { const workspace = request.payload.workspaceId === undefined ? undefined @@ -892,20 +1001,30 @@ export class FixtureApiClient extends AbstractApiClient { protected override async callUnary( method: K, payload: RequestPayload, + signal?: AbortSignal, ): Promise>> { const request = rpcRequest(payload) const full: ClientRequest = { type: 'client-request', rpcId: request.rpcId, method, payload } this.onEnvelope(full) - const response = await this.dispatch(method, request as RpcRequest) as RpcResponse> + const response = await this.dispatch( + method, + request as RpcRequest, + signal ?? new AbortController().signal, + ) as RpcResponse> const fullResponse: ServerResponse = { type: 'server-response', rpcId: response.rpcId, result: response.result } this.onEnvelope(fullResponse) return response } /** Method-key dispatch into the in-memory contract impl (a real carrier routes by URL path instead). */ - private dispatch(method: keyof RpcMethodMap, request: RpcRequest): Promise> { + private dispatch( + method: keyof RpcMethodMap, + request: RpcRequest, + signal: AbortSignal, + ): Promise> { switch (method) { case 'session.list': return this.api.sessions.list(request) + case 'session.search': return this.api.sessions.search(request, signal) case 'session.create': return this.api.sessions.create(request) case 'session.history': return this.api.sessions.history(request) case 'session.prompt': return this.api.sessions.prompt(request) @@ -916,8 +1035,7 @@ export class FixtureApiClient extends AbstractApiClient { case 'workspace.rename': return this.api.workspace.rename(request) case 'workspace.insertSessionBefore': return this.api.workspace.insertSessionBefore(request) case 'command.list': return this.api.commands.list(request) - // The in-memory execute never blocks, so a never-aborting signal is faithful here. - case 'command.execute': return this.api.commands.execute(request, new AbortController().signal) + case 'command.execute': return this.api.commands.execute(request, signal) case 'skill.list': return this.api.skills.list(request) } } diff --git a/packages/client/connection/src/client/index.ts b/packages/client/connection/src/client/index.ts index d4505eb659..8dd7b9b1e9 100644 --- a/packages/client/connection/src/client/index.ts +++ b/packages/client/connection/src/client/index.ts @@ -11,7 +11,7 @@ import { WebApiClient } from './web-api-client.ts' // ---- Contract re-exports (browser-safe apiproxy channels + core types) ---- export type { - ApiProxy, SessionsApi, SessionSummary, HostApi, EventsApi, MuxFrame, HostFrame, + ApiProxy, SessionsApi, SessionSearchItem, SessionSummary, HostApi, EventsApi, MuxFrame, HostFrame, ApprovalResponsePayload, QuestionResponsePayload, HistoryEntry, ToolEventView, ToolCallView, ToolResultView, WorkspaceApi, WorkspaceId, WorkspaceView, CommandsApi, CommandDescriptor, CommandExecuteResult, SkillsApi, SkillEntry, diff --git a/packages/client/connection/tests/fake-api.ts b/packages/client/connection/tests/fake-api.ts index bf7295cc50..d7785697e8 100644 --- a/packages/client/connection/tests/fake-api.ts +++ b/packages/client/connection/tests/fake-api.ts @@ -3,7 +3,7 @@ // deferred-controlled timing). Streams are hand pumps: pushMux/pushHost. import type { CommandDescriptor, CommandExecuteResult, HostFrame, IApiClient, MuxFrame, - RpcRequest, RpcResponse, SessionId, SkillEntry, + RpcRequest, RpcResponse, SessionId, SessionSearchItem, SkillEntry, } from '../src/client/api.ts' import { RpcId } from '../src/client/api.ts' @@ -43,6 +43,8 @@ export class FakeApiClient implements IApiClient { // Programmable slots (defaults answer OK-empty); reassign per case. onList: (payload: unknown) => Promise> = () => Promise.resolve(ok({ items: [] })) + onSearch: (payload: unknown) => Promise> = + () => Promise.resolve(ok({ items: [], hasMore: false })) onCreate: (payload: unknown) => Promise> = () => Promise.resolve(ok({ sessionId: 'fk-new' as SessionId })) onHistory: (payload: { sessionId: SessionId; beforeSeq?: number; maxMessages?: number }) => Promise> = @@ -55,12 +57,17 @@ export class FakeApiClient implements IApiClient { private readonly muxConns: StreamConn[] = [] private readonly hostConns: StreamConn[] = [] + lastSearchSignal: AbortSignal | undefined // Parameter annotations below are local structural types on purpose: the CI // lint lane runs without built artifacts, where IApiClient's wire types // (apiproxy subpath) resolve to any and inferred params trip no-unsafe-argument. readonly sessions: IApiClient['sessions'] = { list: (payload: unknown) => this.record('session.list', payload, this.onList(payload)), + search: (payload: unknown, signal?: AbortSignal) => { + this.lastSearchSignal = signal + return this.record('session.search', payload, this.onSearch(payload)) + }, create: (payload: unknown) => this.record('session.create', payload, this.onCreate(payload)), history: (payload: { sessionId: SessionId; beforeSeq?: number; maxMessages?: number }) => this.record('session.history', payload, this.onHistory(payload)), diff --git a/packages/client/connection/tests/fixture.spec.ts b/packages/client/connection/tests/fixture.spec.ts index 0374f92b3b..9bf0173237 100644 --- a/packages/client/connection/tests/fixture.spec.ts +++ b/packages/client/connection/tests/fixture.spec.ts @@ -48,6 +48,37 @@ describe('createFixtureApi', () => { expect(response.result.value.items[1]?.parentSessionId).toBe('fx-alpha') // lineage material }) + it('searches current message text with literal unicode61-style token phrases', async () => { + const api = createFixtureApi() + const signal = new AbortController().signal + const phrase = await api.sessions.search(req({ query: 'FIXTURE 历史消息' }), signal) + expect(phrase.result).toMatchObject({ + ok: true, + value: { + items: [{ sessionId: 'fx-alpha' }], + hasMore: false, + }, + }) + if (!phrase.result.ok) throw new Error('search failed') + expect(phrase.result.value.items[0]?.snippet).toContain('fixture 历史消息') + + const substring = await api.sessions.search(req({ query: 'ixtur' }), signal) + expect(substring.result).toEqual({ + ok: true, + value: { items: [], hasMore: false }, + }) + const punctuationOnly = await api.sessions.search(req({ query: '*' }), signal) + expect(punctuationOnly.result).toEqual({ + ok: true, + value: { items: [], hasMore: false }, + }) + + const aborted = new AbortController() + aborted.abort() + await expect(api.sessions.search(req({ query: 'fixture' }), aborted.signal)) + .resolves.toMatchObject({ result: { ok: false, error: { code: 'cancelled' } } }) + }) + it('pages history backwards on message-boundary cuts with seq-contiguous stitching', async () => { const api = createFixtureApi() const tail = await api.sessions.history(req({ sessionId: sid('fx-alpha'), maxMessages: 10 })) @@ -601,6 +632,10 @@ describe('FixtureApiClient (protocol-level fake carrier)', () => { it('covers the whole unary dispatch table', async () => { const client = new FixtureApiClient() + expect((await client.sessions.search( + { query: 'fixture' }, + new AbortController().signal, + )).result.ok).toBe(true) const created = await client.sessions.create({}) if (!created.result.ok) throw new Error('create failed') const id = created.result.value.sessionId diff --git a/packages/client/runtime/README.i18n.yaml b/packages/client/runtime/README.i18n.yaml index 5e73979b0b..2e854cc6dd 100644 --- a/packages/client/runtime/README.i18n.yaml +++ b/packages/client/runtime/README.i18n.yaml @@ -1,6 +1,6 @@ # Bilingual-pair consistency record (docs/i18n/README.md): the git blob hash of each # side as of the last confirmed-consistent state. Both languages carry equal authority; # after editing either side, bring the other along and re-record with: -# pnpm run verify-translation-pairing --write -README.md: 4724ebc75d441252245a0e811a4ae34f8b529a98 -README.zh.md: 6a0076742efccaf946910c77c77a9b74194b9dc5 +# pnpm run verify-translation-pairing --write packages/client/runtime/README.md +README.md: c83e70d574b85ff1128f48725b03811411b62fe2 +README.zh.md: ab97832760bb7f147211cf430aa5c7601b4dcbd8 diff --git a/packages/client/runtime/README.md b/packages/client/runtime/README.md index 4724ebc75d..c83e70d574 100644 --- a/packages/client/runtime/README.md +++ b/packages/client/runtime/README.md @@ -10,6 +10,8 @@ Workspace and Session lists have independent monotone `pending` → `ready` base SlotsService gives the renderer separate bare observables for `useSessions` and `useWorkspaces`; web-react creates the hooks. Workspace business state does not enter `SessionListState` or an entry store. +`SessionsService.search(query, signal)` is a stateless one-shot action over the `session.search` RPC. It returns ranked session/snippet pairs without putting query, loading, or error state into the shared Session list, so each UI owner controls debounce, cancellation, stale-response suppression, and fallback presentation. + ## New Session and the blank mirror `WorkspacesService.connectWorkspace(workspaceId)` resolves the session a New Session flow lands in: it reuses the workspace's existing blank session from the list mirror (`blank && cwd == workspace.path`) or calls `session.create({workspaceId})`, returning the session id for the caller to open. `SessionSummary.blank` mirrors the host's derived empty-log bit and only ever lowers on the client: seeded by `session.list` / the `host/session-added` frame, flipped false by the first ACCEPTED local `prompt()` (on the RPC success response — acceptance proves the user message is in the host log; a rejected first prompt keeps the session blank and reusable) and by any `running: true` status frame, re-aligned by every list re-pull. List surfaces hide blank rows; the store carries every row. `SessionsService.create` accepts an optional caller-preallocated SessionId and throws `SessionCreateError` (carrying `requestedSessionId`) on failure. diff --git a/packages/client/runtime/README.zh.md b/packages/client/runtime/README.zh.md index 6a0076742e..ab97832760 100644 --- a/packages/client/runtime/README.zh.md +++ b/packages/client/runtime/README.zh.md @@ -10,6 +10,8 @@ Workspace 和 Session 列表各自具有单调的 `pending` → `ready` 基线 SlotsService 分别为 renderer 提供 `useSessions` 与 `useWorkspaces` 的裸 observable;web-react 创建 hook。Workspace 业务状态不会进入 `SessionListState` 或配置项 store。 +`SessionsService.search(query, signal)` 是基于 `session.search` RPC 的无状态单次操作。它返回经过排序的会话/snippet 对,但不会将查询条件、加载状态或错误状态写入共享 Session 列表,因此每个 UI 所有者都自行负责防抖、取消、抑制陈旧响应和回退呈现。 + ## New Session 与 blank 镜像 `WorkspacesService.connectWorkspace(workspaceId)` 解析 New Session 流程最终落入的会话:先在列表镜像中复用该 workspace 的既有空会话(`blank && cwd == workspace.path`),未命中则调用 `session.create({workspaceId})`,返回会话 id 由调用方 open。`SessionSummary.blank` 镜像主机派生的空日志位,在客户端只降不升:由 `session.list`/`host/session-added` 帧播种,本地首次**受理成功**的 `prompt()`(RPC 成功响应时——受理即证明用户消息已入主机日志;首讯被拒则会话保持 blank、保持可复用)与任何 `running: true` 状态帧翻为 false,每次列表重拉重新对齐。列表表面隐藏 blank 行;store 保留全部行。`SessionsService.create` 接受可选的、由调用方预先分配的 SessionId,失败时抛出 `SessionCreateError`(携带 `requestedSessionId`)。 diff --git a/packages/client/runtime/src/client/index.ts b/packages/client/runtime/src/client/index.ts index b1300a192c..620ccb885d 100644 --- a/packages/client/runtime/src/client/index.ts +++ b/packages/client/runtime/src/client/index.ts @@ -18,7 +18,7 @@ export type { Session } from './sessions/session.ts' export type { SessionBinding, SessionListState, SessionProvideContribution, SessionProvideDescriptor, SessionSummary, } from './sessions/service.ts' -export type { SessionListPhase } from './sessions/manager.ts' +export type { SessionListPhase, SessionSearchResultItem } from './sessions/manager.ts' export type { WorkspaceListPhase } from './workspaces/manager.ts' export type { WorkspaceListState } from './workspaces/service.ts' export type { WorkspaceId, WorkspaceView } from '@deepseek-ai/dsh-client-connection/client' diff --git a/packages/client/runtime/src/client/sessions/manager.ts b/packages/client/runtime/src/client/sessions/manager.ts index 694768ebbc..93a9b8e597 100644 --- a/packages/client/runtime/src/client/sessions/manager.ts +++ b/packages/client/runtime/src/client/sessions/manager.ts @@ -2,7 +2,10 @@ // dispatch entry + list state, constructed and held by SessionsService (one per client runtime). // List data never enters zustand; React connects via subscribe/getListSnapshot. -import type { IApiClient, HostFrame, MuxFrame, RpcError, RpcRequest, RpcResult, SessionId, SessionSummary, WorkspaceId } from '@deepseek-ai/dsh-client-connection/client' +import type { + IApiClient, HostFrame, MuxFrame, RpcError, RpcRequest, RpcResult, SessionId, + SessionSummary, WorkspaceId, +} from '@deepseek-ai/dsh-client-connection/client' // Value import from the inline-safe wire layer (not the connection plugin): // plugin-to-plugin value imports are a bundle purity error. import { transportError } from '@deepseek-ai/dsh-host-apiproxy/api' @@ -22,6 +25,12 @@ import { Session } from './session.ts' */ export type SessionListPhase = 'pending' | 'ready' +/** Request-local content hit returned to sidebar search consumers. */ +export interface SessionSearchResultItem { + sessionId: SessionId + snippet: string +} + /** Immutable session-list snapshot for useSessionList. */ export interface SessionListSnapshot { items: readonly SessionListEntry[] @@ -213,6 +222,24 @@ export class SessionManager { return this.listInflight } + /** + * Search visible session message content without adding transient query + * state to the list snapshot. + * @param query - non-blank literal phrase. + * @param signal - cancellation for superseded UI queries. + * @returns the Host result or a folded transport error. + */ + async search( + query: string, + signal: AbortSignal, + ): Promise> { + try { + return (await this.api.sessions.search({ query }, signal)).result + } catch (error: unknown) { + return transportError(error) + } + } + /** * Contract session.create; on success merge into summaries immediately (no * wait for the next refresh). A created session is blank by definition diff --git a/packages/client/runtime/src/client/sessions/service.ts b/packages/client/runtime/src/client/sessions/service.ts index ec8ddc2354..9f239a47dd 100644 --- a/packages/client/runtime/src/client/sessions/service.ts +++ b/packages/client/runtime/src/client/sessions/service.ts @@ -16,7 +16,9 @@ * survives frozen (read-only view) until the stage moves on. */ import type { Context, Fiber } from 'cordis' -import type { IApiClient, RpcError, SessionId, WorkspaceId } from '@deepseek-ai/dsh-client-connection/client' +import type { + IApiClient, RpcError, RpcResult, SessionId, WorkspaceId, +} from '@deepseek-ai/dsh-client-connection/client' import type { HostObservable, SessionMaybeProvideInfo, SessionProvideInfo, } from '@deepseek-ai/dsh-client-ui-slots' @@ -24,7 +26,7 @@ import type { SnapshotStore } from '../contract/store.ts' import { createSnapshotStore } from '../contract/store.ts' import { createScope, scopeOf as scopeTagOf } from '../agents/scope.ts' import { SessionManager } from './manager.ts' -import type { SessionListPhase } from './manager.ts' +import type { SessionListPhase, SessionSearchResultItem } from './manager.ts' import type { Session } from './session.ts' /** Session list row projected from the host list RPC plus live stream increments. */ @@ -318,6 +320,20 @@ export class SessionsService { return this.manager.refreshList() } + /** + * Search the Host's visible message-content index. Results stay + * request-local; the list snapshot remains the metadata authority. + * @param query - non-blank literal phrase. + * @param signal - cancellation for a superseded search. + * @returns bounded results or a business/transport error. + */ + search( + query: string, + signal: AbortSignal, + ): Promise> { + return this.manager.search(query, signal) + } + /** * Route a mux stream envelope into the Session object layer. * @param envelope - validated mux stream envelope. diff --git a/packages/client/runtime/tests/fake-api.ts b/packages/client/runtime/tests/fake-api.ts index dcb334f6ea..504b9431aa 100644 --- a/packages/client/runtime/tests/fake-api.ts +++ b/packages/client/runtime/tests/fake-api.ts @@ -3,7 +3,7 @@ // deferred-controlled timing). Streams are hand pumps: pushMux/pushHost. import type { ClientResponse, CommandDescriptor, CommandExecuteResult, HostFrame, IApiClient, MuxFrame, - RpcError, RpcReceipt, RpcRequest, RpcResponse, SessionId, SkillEntry, + RpcError, RpcReceipt, RpcRequest, RpcResponse, SessionId, SessionSearchItem, SkillEntry, WorkspaceId, WorkspaceView, } from '@deepseek-ai/dsh-client-connection/client' import { RpcId } from '@deepseek-ai/dsh-client-connection/client' @@ -60,6 +60,8 @@ export class FakeApiClient implements IApiClient { // Programmable slots (defaults answer OK-empty); reassign per case. onList: (payload: unknown) => Promise> = () => Promise.resolve(ok({ items: [] })) + onSearch: (payload: unknown) => Promise> = + () => Promise.resolve(ok({ items: [], hasMore: false })) onCreate: (payload: unknown) => Promise> = () => Promise.resolve(ok({ sessionId: 'fk-new' as SessionId })) onHistory: (payload: { sessionId: SessionId; beforeSeq?: number; maxMessages?: number }) => Promise> = @@ -72,12 +74,17 @@ export class FakeApiClient implements IApiClient { private readonly muxConns: StreamConn[] = [] private readonly hostConns: StreamConn[] = [] + lastSearchSignal: AbortSignal | undefined // Parameters carry local structural annotations: the CI lint lane runs // without built lib/, so IApiClient's indexed-access types collapse to any // and inferred parameters would trip no-unsafe-argument. readonly sessions: IApiClient['sessions'] = { list: (payload: unknown) => this.record('session.list', payload, this.onList(payload)), + search: (payload: unknown, signal?: AbortSignal) => { + this.lastSearchSignal = signal + return this.record('session.search', payload, this.onSearch(payload)) + }, create: (payload: unknown) => this.record('session.create', payload, this.onCreate(payload)), history: (payload: { sessionId: SessionId; beforeSeq?: number; maxMessages?: number }) => this.record('session.history', payload, this.onHistory(payload)), diff --git a/packages/client/runtime/tests/manager.spec.ts b/packages/client/runtime/tests/manager.spec.ts index ee76d885ab..5d42aa685f 100644 --- a/packages/client/runtime/tests/manager.spec.ts +++ b/packages/client/runtime/tests/manager.spec.ts @@ -194,6 +194,49 @@ describe('list lifecycle', () => { }) }) +describe('search', () => { + it('returns bounded Host results and forwards the caller signal', async () => { + const api = new FakeApiClient() + api.onSearch = () => Promise.resolve(ok({ + items: [{ sessionId: S1, snippet: 'matching excerpt' }], + hasMore: true, + })) + const manager = new SessionManager(api) + const signal = new AbortController().signal + + await expect(manager.search('exact phrase', signal)).resolves.toEqual({ + ok: true, + value: { + items: [{ sessionId: S1, snippet: 'matching excerpt' }], + hasMore: true, + }, + }) + expect(api.callsOf('session.search')).toEqual([{ query: 'exact phrase' }]) + expect(api.lastSearchSignal).toBe(signal) + }) + + it('preserves business errors and folds transport failures', async () => { + const api = new FakeApiClient() + const manager = new SessionManager(api) + api.onSearch = () => Promise.resolve(err({ + code: 'internal', + message: 'index unavailable', + details: {}, + })) + const signal = new AbortController().signal + await expect(manager.search('first', signal)).resolves.toMatchObject({ + ok: false, + error: { code: 'internal', message: 'index unavailable' }, + }) + + api.onSearch = () => Promise.reject(new Error('wire down')) + await expect(manager.search('second', signal)).resolves.toMatchObject({ + ok: false, + error: { code: 'internal', message: 'wire down' }, + }) + }) +}) + describe('host frame routing', () => { it('adds/removes/flips sessions from host frames and keeps removed instances resident', async () => { const api = new FakeApiClient() diff --git a/packages/client/runtime/tests/sessions-service.spec.ts b/packages/client/runtime/tests/sessions-service.spec.ts index 44ab4ffb4f..0d19b914b7 100644 --- a/packages/client/runtime/tests/sessions-service.spec.ts +++ b/packages/client/runtime/tests/sessions-service.spec.ts @@ -69,6 +69,29 @@ describe('list store projection', () => { }) }) +describe('search', () => { + it('delegates transient content search without changing the list snapshot', async () => { + const b = bench() + await feedList(b, [{ id: 's1' }]) + const before = b.svc.list.getSnapshot() + b.api.onSearch = () => Promise.resolve(ok({ + items: [{ sessionId: sid('s1'), snippet: 'matching excerpt' }], + hasMore: false, + })) + const signal = new AbortController().signal + + await expect(b.svc.search('needle', signal)).resolves.toEqual({ + ok: true, + value: { + items: [{ sessionId: 's1', snippet: 'matching excerpt' }], + hasMore: false, + }, + }) + expect(b.api.lastSearchSignal).toBe(signal) + expect(b.svc.list.getSnapshot()).toBe(before) + }) +}) + describe('scope tree', () => { it('mints lazily on first resolution, tags the ctx, and keeps binding identity stable', async () => { const b = bench() diff --git a/packages/client/ui-workspace/README.i18n.yaml b/packages/client/ui-workspace/README.i18n.yaml index d0f2d0a20a..f89fbee5d4 100644 --- a/packages/client/ui-workspace/README.i18n.yaml +++ b/packages/client/ui-workspace/README.i18n.yaml @@ -1,6 +1,6 @@ # Bilingual-pair consistency record (docs/i18n/README.md): the git blob hash of each # side as of the last confirmed-consistent state. Both languages carry equal authority; # after editing either side, bring the other along and re-record with: -# pnpm run verify-translation-pairing --write -README.md: e0247b3e26f617f86e9c0094afa1cbc920f02d33 -README.zh.md: 92ef463faab4b1ccda85d7f3cec1678a338d4010 +# pnpm run verify-translation-pairing --write packages/client/ui-workspace/README.md +README.md: 9cb919a1a64394d5e116d35bdddfdee738994a02 +README.zh.md: b3add7f89cb0feb7f44238b7199d0633cdfbf641 diff --git a/packages/client/ui-workspace/README.md b/packages/client/ui-workspace/README.md index e0247b3e26..9cb919a1a6 100644 --- a/packages/client/ui-workspace/README.md +++ b/packages/client/ui-workspace/README.md @@ -2,7 +2,9 @@ English | [中文](README.zh.md) -Shared Workspace picker plugin. `WorkspacePicker` is registered into the sidebar's `sidebar.workspace` slot and the page-local Session Intent hero's `conversation.empty.workspace` slot, so both surfaces use the same menu and creation modals. +Shared Workspace browser and picker plugin. `WorkspaceBrowser` fills the sidebar's `sidebar.workspaces` slot, while `WorkspacePicker` fills the page-local Session Intent hero's `conversation.hero.workspace` slot; both surfaces use the same Workspace menu and creation modals. + +The browser renders grouped or flat Session rows from the global runtime hooks and owns the Workspace create/rename and in-Workspace reorder flows. A non-blank search query replaces either browsing mode with one flat result list: case-insensitive title and Workspace substring matches appear immediately, while a 250 ms debounced Host request adds ranked current-conversation content matches and snippets. Each new query aborts the preceding request; a failed content search leaves metadata matches visible with a warning. The list is capped at 20, asks the user to narrow broader queries, and opens the selected Session without clearing the query or jumping to a specific event. The picker lists real Host Workspace entities through the global `useWorkspaces` hook. Selecting a Workspace invokes the slot owner's `onPick` callback to retarget the frontend Session object; the existing-folder and create-new actions first create a real Workspace through the object layer, then select it. Create-new disables names already present in that list, while the Host remains authoritative for concurrent or non-UI callers. The runtime Session and Workspace services own materialization. @@ -18,5 +20,6 @@ None; this package neither assembles nor sends a provider request. ## Known Limitations and Deferred Work -- **No Workspace rename/delete controls** — the picker supports selection and creation only. +- **No fuzzy content search or event deep links** — the content backend uses literal token/phrase matching, and selecting a result opens the Session rather than the matching event. +- **No Workspace delete control** — the browser supports creation and rename, while the picker supports selection and creation. - **Existing-folder entry is manual path input only** — Host creation failures are shown in the modal. diff --git a/packages/client/ui-workspace/README.zh.md b/packages/client/ui-workspace/README.zh.md index 92ef463faa..b3add7f89c 100644 --- a/packages/client/ui-workspace/README.zh.md +++ b/packages/client/ui-workspace/README.zh.md @@ -2,7 +2,9 @@ [English](README.md) | 中文 -共享 Workspace 选择器插件。`WorkspacePicker` 注册到侧边栏的 `sidebar.workspace` slot,以及页面局部 Session Intent 主视觉区的 `conversation.empty.workspace` slot,因此两个表层使用同一菜单和创建模态框。 +共享 Workspace 浏览器与选择器插件。`WorkspaceBrowser` 填充侧边栏的 `sidebar.workspaces` slot,`WorkspacePicker` 则填充页面局部 Session Intent 主视觉区的 `conversation.hero.workspace` slot;两个表层使用同一套 Workspace 菜单和创建模态框。 + +该浏览器通过全局运行时钩子将 Session 行渲染为分组或扁平形式,并负责 Workspace 创建/重命名和 Workspace 内的重排序流程。非空白查询会以单一扁平结果列表替代任一浏览模式:不区分大小写的标题和 Workspace 子串匹配项会立即显示,经 250 ms 防抖的 Host 请求则会加入经过排序的当前对话内容匹配项及其摘要片段。每次新查询都会中止前一个请求;内容搜索失败时,元数据匹配项仍会显示,同时给出警告。列表最多显示 20 条结果,并会在查询过宽时提示用户缩小范围;打开所选 Session 时既不会清除查询,也不会跳转至特定事件。 该选择器通过全局 `useWorkspaces` hook 列出真实的 Host Workspace 实体。选择 Workspace 会调用 slot owner 的 `onPick` 回调,重新定位前端 Session 对象;使用现有文件夹和新建操作时,系统会先通过对象层创建真实 Workspace,再将其选中。新建操作会禁用列表中已有的名称,而 Host 对并发或非 UI 调用方仍具有最终决定权。运行时 Session 与 Workspace 服务负责物化。 @@ -18,5 +20,6 @@ ## 已知限制与暂缓事项 -- **没有 Workspace 重命名/删除控件**:选择器仅支持选择和创建。 +- **没有模糊内容搜索或事件深链接**:内容后端采用字面 token/短语匹配,选择结果会打开 Session,而不是匹配的事件。 +- **没有 Workspace 删除控件**:浏览器支持创建和重命名,选择器支持选择和创建。 - **现有文件夹入口仅支持手动输入路径**:Host 创建失败会显示在模态框中。 diff --git a/packages/client/ui-workspace/src/client/WorkspaceBrowser.module.css b/packages/client/ui-workspace/src/client/WorkspaceBrowser.module.css index d6375cb698..96af22a309 100644 --- a/packages/client/ui-workspace/src/client/WorkspaceBrowser.module.css +++ b/packages/client/ui-workspace/src/client/WorkspaceBrowser.module.css @@ -209,6 +209,22 @@ padding-bottom: 12px; } +.list > [role='treeitem'] + [role='treeitem'] { + margin-top: 4px; +} + +.searchStatus, +.searchWarning { + padding: 10px 12px; + font-size: 12px; + line-height: 18px; + color: var(--dsw-alias-label-tertiary); +} + +.searchWarning { + color: var(--dsw-alias-label-secondary); +} + /* One workspace section: header row + expanded session run. Rows inside keep the former flat-list 4px gap as sibling margins; the inter-group breathing room (figma 133:7661 batch separator, 20px after an expanded diff --git a/packages/client/ui-workspace/src/client/WorkspaceBrowser.tsx b/packages/client/ui-workspace/src/client/WorkspaceBrowser.tsx index 0dc6485929..d703674c01 100644 --- a/packages/client/ui-workspace/src/client/WorkspaceBrowser.tsx +++ b/packages/client/ui-workspace/src/client/WorkspaceBrowser.tsx @@ -13,16 +13,20 @@ import { Button, IconCloseFill14, IconPersonalizationOutline16, IconProjectAddOutline16, IconSearchOutline16, Menu, Modal, Tooltip, } from '@deepseek-ai/dsh-client-ui-primitives' -import type { WorkspaceId, WorkspaceView } from '@deepseek-ai/dsh-client-runtime/client' +import type { + SessionSearchResultItem, WorkspaceId, WorkspaceView, +} from '@deepseek-ai/dsh-client-runtime/client' import type { WorkspaceBrowserProps } from './contract/slots.ts' import type { SessionNode } from './tree.ts' -import { deriveFlat, deriveGroups, UNGROUPED_KEY } from './tree.ts' -import { ProjectRowItem, SessionNodeItem } from './rows/Rows.tsx' +import { deriveFlat, deriveGroups, deriveSearchResults, UNGROUPED_KEY } from './tree.ts' +import { ProjectRowItem, SearchResultItem, SessionNodeItem } from './rows/Rows.tsx' import { WorkspaceCreateFlow } from './WorkspacePicker.tsx' import css from './WorkspaceBrowser.module.css' /** Column slide length (--ds-transition-duration-slow): rail-search focus waits it out — focus() forces a synchronous layout and would jank the slide. */ const EXPAND_SLIDE_MS = 300 +/** Pause between the latest keystroke and a Host content-search request. */ +const SEARCH_DEBOUNCE_MS = 250 const GROUP_BY_ITEMS = [ { type: 'label' as const, id: 'group-by', text: 'Group by' }, @@ -83,14 +87,12 @@ type SessionTreeProps = Pick< 'useSessions' | 'startSession' | 'open' | 'insertSessionBefore' > & { workspaces: readonly WorkspaceView[] - /** Live search filter owned by the browser root (the query outlives the tree). */ - query: string /** Open the browser-owned rename dialog for a real Workspace group. */ onRenameRequest: (workspaceId: WorkspaceId, currentTitle: string) => void } /** The scrolling session tree; unmounting at collapse settle drops the sessions subscription and expansion state. */ -function SessionTree({ useSessions, startSession, open, workspaces, query, onRenameRequest, insertSessionBefore }: SessionTreeProps) { +function SessionTree({ useSessions, startSession, open, workspaces, onRenameRequest, insertSessionBefore }: SessionTreeProps) { const list = useSessions((s) => s) const current = list.current const [expandedProjects, setExpandedProjects] = useState([]) @@ -106,8 +108,8 @@ function SessionTree({ useSessions, startSession, open, workspaces, query, onRen setExpandedProjects((l) => (l.includes(currentGroup) ? l : [...l, currentGroup])) }, [current, currentGroup]) const groups = useMemo( - () => deriveGroups(list, workspaces, { expandedProjects, expandedSessions, query }), - [list, workspaces, expandedProjects, expandedSessions, query], + () => deriveGroups(list, workspaces, { expandedProjects, expandedSessions }), + [list, workspaces, expandedProjects, expandedSessions], ) const now = Date.now() @@ -115,7 +117,7 @@ function SessionTree({ useSessions, startSession, open, workspaces, query, onRen
{groups.length === 0 && ( -
{query === '' ? 'No sessions yet' : 'No matches'}
+
No sessions yet
)} {groups.map(group => ( // Group section: header row + expanded session subtree. The @@ -136,10 +138,10 @@ function SessionTree({ useSessions, startSession, open, workspaces, query, onRen }} /> {group.sessions.map((node, index) => { - // Draggable: real-workspace group roots outside search. The drag + // Draggable: real-workspace group roots. The drag // never leaves its group — rows of other groups show no markers // and reject drops (visual movement confined to this section). - const draggable = group.workspaceId !== undefined && query === '' + const draggable = group.workspaceId !== undefined const sameGroupDrag = drag !== null && drag.workspaceId === group.workspaceId const dragProps = !draggable || group.workspaceId === undefined ? undefined : { start: () => { @@ -192,15 +194,15 @@ function SessionTree({ useSessions, startSession, open, workspaces, query, onRen } /** The flat "In one list" body: every session a top-level row, newest-first. */ -function FlatList({ useSessions, open, query }: Pick) { +function FlatList({ useSessions, open }: Pick) { const list = useSessions((s) => s) - const rows = useMemo(() => deriveFlat(list, { query }), [list, query]) + const rows = useMemo(() => deriveFlat(list), [list]) const now = Date.now() return (
{rows.length === 0 && ( -
{query === '' ? 'No sessions yet' : 'No matches'}
+
No sessions yet
)} {rows.map(node => ( & { + workspaces: readonly WorkspaceView[] + query: string + remote: RemoteSearchState +}) { + const list = useSessions((s) => s) + const currentRemote = remote.query === query + ? remote + : { query, status: 'loading' as const, items: [], hasMore: false } + const results = useMemo( + () => deriveSearchResults(list, workspaces, query, currentRemote), + [list, workspaces, query, currentRemote], + ) + const pending = currentRemote.status === 'loading' + const failed = currentRemote.status === 'error' + + return ( +
+
+ {results.items.map(result => ( + + ))} + {pending && ( +
正在搜索历史…
+ )} + {failed && ( +
+ 历史内容搜索暂时不可用,仍显示名称匹配。 +
+ )} + {!pending && results.items.length === 0 && ( +
没有匹配结果
+ )} + {results.hasMore && ( +
仅显示前 20 项,请缩小搜索范围。
+ )} +
+ +
+ ) +} + /** * Render the browsing region. * @param props - composed slot props (shell owner share + store + injected actions). @@ -238,12 +301,20 @@ export function WorkspaceBrowser({ renameWorkspace, insertSessionBefore, createWorkspace, + searchSessions, }: WorkspaceBrowserProps) { const workspaces = useWorkspaces(state => state.items) const groupBy = useStore(s => s.groupBy) // The query outlives the tree and the input (both wide-only) so collapsing // does not silently drop an in-progress filter. const [query, setQuery] = useState('') + const normalizedQuery = query.trim() + const [remoteSearch, setRemoteSearch] = useState({ + query: '', + status: 'idle', + items: [], + hasMore: false, + }) const searchInput = useRef(null) // Section-header + opens the picker menu (same popover in wide and rail // states; the menu anchors on this button). @@ -263,6 +334,43 @@ export function WorkspaceBrowser({ } }, [wide, searchOnExpand]) + useEffect(() => { + if (normalizedQuery === '') { + setRemoteSearch({ query: '', status: 'idle', items: [], hasMore: false }) + return + } + const controller = new AbortController() + setRemoteSearch({ + query: normalizedQuery, + status: 'loading', + items: [], + hasMore: false, + }) + const timer = window.setTimeout(() => { + searchSessions(normalizedQuery, controller.signal).then((result) => { + if (controller.signal.aborted) return + setRemoteSearch({ + query: normalizedQuery, + status: 'ready', + items: result.items, + hasMore: result.hasMore, + }) + }).catch(() => { + if (controller.signal.aborted) return + setRemoteSearch({ + query: normalizedQuery, + status: 'error', + items: [], + hasMore: false, + }) + }) + }, SEARCH_DEBOUNCE_MS) + return () => { + window.clearTimeout(timer) + controller.abort() + } + }, [normalizedQuery, searchSessions]) + // Rename dialog (browser-owned so it outlives row unmounts during collapse). const [renameTarget, setRenameTarget] = useState<{ workspaceId: WorkspaceId; currentTitle: string } | null>(null) const [renameDraft, setRenameDraft] = useState('') @@ -331,11 +439,11 @@ export function WorkspaceBrowser({ {/* Expanded: the row is a click-to-focus field (the leading icon is decorative). Rail: the icon is the region's search control. */}
{ if (wide) searchInput.current?.focus() }}> - + + ) +} + /** Pointer-position half of a row (insert line above or below). */ function rowHalf(e: { clientY: number; currentTarget: HTMLElement }): 'before' | 'after' { const rect = e.currentTarget.getBoundingClientRect() diff --git a/packages/client/ui-workspace/src/client/tree.ts b/packages/client/ui-workspace/src/client/tree.ts index c0adfadd6f..76dcfe924e 100644 --- a/packages/client/ui-workspace/src/client/tree.ts +++ b/packages/client/ui-workspace/src/client/tree.ts @@ -3,7 +3,9 @@ * Unassigned Sessions trail under Ungrouped; only the selected blank Session * remains visible. */ -import type { SessionId, SessionListState, SessionSummary, WorkspaceId, WorkspaceView } from '@deepseek-ai/dsh-client-runtime/client' +import type { + SessionId, SessionListState, SessionSearchResultItem, SessionSummary, WorkspaceId, WorkspaceView, +} from '@deepseek-ai/dsh-client-runtime/client' /** Group key for Sessions outside every Workspace. */ export const UNGROUPED_KEY = '' @@ -15,7 +17,7 @@ export const UNGROUPED_LABEL = 'Ungrouped' export interface SessionNode { id: SessionId title: string - /** Visible children, already expansion/search-filtered (empty when folded). */ + /** Visible children, already expansion-filtered (empty when folded). */ children: readonly SessionNode[] /** The session HAS children in the data (the twist renders even while folded). */ hasChildren: boolean @@ -41,11 +43,25 @@ export interface GroupNode { sessions: readonly SessionNode[] } +/** One flat search row combining list metadata with an optional content match. */ +export interface SearchResultNode { + id: SessionId + title: string + workspace: string + running: boolean + snippet?: string +} + +/** Bounded merged search projection plus the refine-query hint bit. */ +export interface SearchResultSet { + items: readonly SearchResultNode[] + hasMore: boolean +} + /** Viewing state consumed by the derivation — the component's local useState arrays, taken as-is. */ export interface TreeView { expandedProjects: readonly string[] expandedSessions: readonly string[] - query: string } interface Group { @@ -204,47 +220,15 @@ function buildVisible(g: Group, expandedSessions: ReadonlySet): SessionN return g.roots.map(walk).filter((n): n is SessionNode => n !== null) } -/** Matched sessions plus their ancestor chains (forced visible under search). */ -function searchVisible(g: Group, q: string): Set { - const visible = new Set() - for (const m of g.summaries.values()) { - if (!sessionTitle(m).toLowerCase().includes(q)) continue - let cur: SessionSummary | undefined = m - while (cur !== undefined && !visible.has(cur.id)) { - visible.add(cur.id) - cur = cur.parentId !== undefined && cur.parentId !== cur.id ? g.summaries.get(cur.parentId) : undefined - } - } - return visible -} - -function buildSearch(g: Group, visible: ReadonlySet): SessionNode[] { - const visited = new Set() - const walk = (id: SessionId): SessionNode | null => { - if (visited.has(id) || !visible.has(id)) return null - visited.add(id) - const s = g.summaries.get(id) - /* v8 ignore next -- unreachable: walked ids come from the grouped summaries. */ - if (s === undefined) return null - const kids = (g.children.get(id) ?? []).filter(kid => visible.has(kid)) - const children = kids.map(walk).filter((n): n is SessionNode => n !== null) - return sessionNode(s, children, kids.length > 0, kids.length > 0) - } - return g.roots.map(walk).filter((n): n is SessionNode => n !== null) -} - /** * Derive the nested workspace browser group structure. * - * Normal mode: every group shows; sessions populate under expanded groups, - * descending only into expanded sessions. Search mode (non-blank query, - * case-insensitive display-title substring): expansion state is ignored — - * matched sessions and their ancestor chains are forced visible, groups - * without a display-title or label hit are dropped, and a label-only hit - * keeps the bare group header. Blank sessions are excluded everywhere. + * Every group shows; sessions populate under expanded groups, descending + * only into expanded sessions. Blank sessions are excluded except for the + * selected provisional New Session row. * @param list - sessions list snapshot (`current` feeds containsCurrent). * @param workspaces - real workspaces in stable Host order. - * @param view - local expansion arrays and search query. + * @param view - local expansion arrays. * @returns group sections in render order. */ export function deriveGroups( @@ -252,7 +236,6 @@ export function deriveGroups( workspaces: readonly WorkspaceView[], view: TreeView, ): GroupNode[] { - const q = view.query.trim().toLowerCase() const expandedProjects = new Set(view.expandedProjects) const expandedSessions = new Set(view.expandedSessions) const currentGroup = list.current === undefined @@ -261,32 +244,17 @@ export function deriveGroups( ?? UNGROUPED_KEY const groups: GroupNode[] = [] for (const g of groupByWorkspace(list, workspaces)) { - if (q === '') { - const expanded = expandedProjects.has(g.key) - groups.push({ - key: g.key, - workspaceId: g.workspaceId, - cwd: g.cwd, - label: g.label, - sessionCount: g.summaries.size, - expanded, - containsCurrent: g.key === currentGroup, - sessions: expanded ? buildVisible(g, expandedSessions) : [], - }) - } else { - const visible = searchVisible(g, q) - if (visible.size === 0 && !g.label.toLowerCase().includes(q)) continue - groups.push({ - key: g.key, - workspaceId: g.workspaceId, - cwd: g.cwd, - label: g.label, - sessionCount: g.summaries.size, - expanded: visible.size > 0, - containsCurrent: g.key === currentGroup, - sessions: buildSearch(g, visible), - }) - } + const expanded = expandedProjects.has(g.key) + groups.push({ + key: g.key, + workspaceId: g.workspaceId, + cwd: g.cwd, + label: g.label, + sessionCount: g.summaries.size, + expanded, + containsCurrent: g.key === currentGroup, + sessions: expanded ? buildVisible(g, expandedSessions) : [], + }) } return groups } @@ -295,25 +263,97 @@ export function deriveGroups( * Derive the flat session list ("In one list" mode): every session — fork * children included — as a top-level row, strictly newest-first. No grouping, * no parent/child adjacency; rows reuse SessionNode with children always - * empty so the renderer stays branch-free. Search mode filters by - * case-insensitive display-title substring. + * empty so the renderer stays branch-free. * @param list - sessions list snapshot. - * @param view - the search query (expansion state does not apply). * @returns flat rows in render order. */ -export function deriveFlat(list: SessionListState, view: Pick): SessionNode[] { - const q = view.query.trim().toLowerCase() +export function deriveFlat(list: SessionListState): SessionNode[] { const rows: SessionSummary[] = [] for (const id of list.ids) { const s = list.byId[id] if (s === undefined || !sessionVisible(s, list.current)) continue - if (q !== '' && !sessionTitle(s).toLowerCase().includes(q)) continue rows.push(s) } rows.sort(byRecency) return rows.map(s => sessionNode(s, [], false, false)) } +/** Maximum rows rendered by the basic search surface. */ +const SEARCH_RESULT_LIMIT = 20 + +/** + * Merge immediate title/Workspace substring matches with ranked Host content + * matches. Local rows lead newest-first, content-only rows retain backend + * order, and duplicate sessions receive the backend snippet in place. + * @param list - session metadata authority. + * @param workspaces - Workspace membership and display labels. + * @param query - caller text; surrounding whitespace is ignored. + * @param content - ranked Host content-search page. + * @returns at most 20 deduplicated flat rows and a refine-query hint bit. + */ +export function deriveSearchResults( + list: SessionListState, + workspaces: readonly WorkspaceView[], + query: string, + content: { items: readonly SessionSearchResultItem[]; hasMore: boolean }, +): SearchResultSet { + const q = query.trim().toLowerCase() + if (q === '') return { items: [], hasMore: false } + + const workspaceBySession = new Map() + for (const workspace of workspaces) { + for (const sessionId of workspace.sessionIds) { + if (!workspaceBySession.has(sessionId)) workspaceBySession.set(sessionId, workspace.title) + } + } + const labelOf = (summary: SessionSummary): string => + workspaceBySession.get(summary.id) ?? projectLabel(summary.cwd) + const contentBySession = new Map() + for (const item of content.items) { + if (!contentBySession.has(item.sessionId)) contentBySession.set(item.sessionId, item) + } + + const local: SessionSummary[] = [] + for (const id of list.ids) { + const summary = list.byId[id] + if (summary === undefined || !sessionVisible(summary, list.current)) continue + if ( + sessionTitle(summary).toLowerCase().includes(q) + || labelOf(summary).toLowerCase().includes(q) + ) { + local.push(summary) + } + } + local.sort(byRecency) + + const ordered: SessionSummary[] = [] + const included = new Set() + const include = (summary: SessionSummary): void => { + if (included.has(summary.id)) return + included.add(summary.id) + ordered.push(summary) + } + for (const summary of local) include(summary) + for (const item of content.items) { + const summary = list.byId[item.sessionId] + if (summary !== undefined && sessionVisible(summary, list.current)) include(summary) + } + + return { + items: ordered.slice(0, SEARCH_RESULT_LIMIT).map((summary) => { + const match = contentBySession.get(summary.id) + return { + id: summary.id, + title: sessionTitle(summary), + workspace: labelOf(summary), + running: summary.running, + ...match === undefined ? {} : { snippet: match.snippet }, + } + }), + hasMore: content.hasMore || ordered.length > SEARCH_RESULT_LIMIT, + } +} + /** * Compact relative time for session rows ("now", "5min", "3h", "2d", "4mo", "1y"). * @param updatedAt - epoch ms of the session's last activity. diff --git a/packages/client/ui-workspace/tests/apply.spec.ts b/packages/client/ui-workspace/tests/apply.spec.ts index 8961ccdb83..b2a70d0f0b 100644 --- a/packages/client/ui-workspace/tests/apply.spec.ts +++ b/packages/client/ui-workspace/tests/apply.spec.ts @@ -19,11 +19,25 @@ async function bench() { const insertSessionBefore = vi.fn(async () => ({})) const open = vi.fn() const clear = vi.fn() + const search = vi.fn(async () => ({ + ok: true as const, + value: { items: [{ sessionId: 'session' as never, snippet: 'match' }], hasMore: false }, + })) ctx.provide('workspaces', { create, startSession, rename, insertSessionBefore, } as never) - ctx.provide('sessions', { open, clear } as never) - return { ctx, slots: ctx.get('slots') as SlotsService, create, startSession, rename, insertSessionBefore, open, clear } + ctx.provide('sessions', { open, clear, search } as never) + return { + ctx, + slots: ctx.get('slots') as SlotsService, + create, + startSession, + rename, + insertSessionBefore, + open, + clear, + search, + } } type HoleName = 'sidebar.workspaces' | 'conversation.hero.workspace' | 'conversation.empty.workspace' @@ -66,6 +80,12 @@ describe('ui-workspace apply', () => { expect(b.startSession).toHaveBeenLastCalledWith(undefined) browser.open('session' as never) expect(b.open).toHaveBeenCalledWith('session') + const signal = new AbortController().signal + await expect(browser.searchSessions('match', signal)).resolves.toEqual({ + items: [{ sessionId: 'session', snippet: 'match' }], + hasMore: false, + }) + expect(b.search).toHaveBeenCalledWith('match', signal) await browser.renameWorkspace('ws' as never, 'renamed') expect(b.rename).toHaveBeenCalledWith('ws', 'renamed') await browser.insertSessionBefore('ws' as never, 's1' as never, 's2' as never) @@ -78,6 +98,19 @@ describe('ui-workspace apply', () => { expect(b.create).toHaveBeenCalledWith({ path: '/tmp/project' }) }) + it('rejects the browser search callback on a runtime business error', async () => { + const b = await bench() + b.search.mockImplementationOnce(async () => ({ + ok: false, + error: { code: 'internal', message: 'index unavailable', details: {} }, + }) as never) + declare(b.slots, 'sidebar.workspaces') + await b.ctx.plugin({ inject: [...inject], apply }).await() + const browser = (b.slots.entries('sidebar.workspaces')[0]!.inject as () => WorkspaceBrowserInjected)() + await expect(browser.searchSessions('needle', new AbortController().signal)) + .rejects.toThrow('index unavailable') + }) + it('unregisters every entry on teardown', async () => { const b = await bench() declare(b.slots, 'sidebar.workspaces', 'conversation.hero.workspace', 'conversation.empty.workspace') diff --git a/packages/client/ui-workspace/tests/rows.spec.tsx b/packages/client/ui-workspace/tests/rows.spec.tsx index 70cfb36940..fc22398cb0 100644 --- a/packages/client/ui-workspace/tests/rows.spec.tsx +++ b/packages/client/ui-workspace/tests/rows.spec.tsx @@ -3,8 +3,8 @@ import { afterEach, describe, expect, it, vi } from 'vitest' import { act, cleanup, createEvent, fireEvent, render, screen } from '@testing-library/react' import type { SessionId, WorkspaceId } from '@deepseek-ai/dsh-client-runtime/client' import type { RowDragProps } from '../src/client/rows/Rows.tsx' -import { ProjectRowItem, SessionNodeItem } from '../src/client/rows/Rows.tsx' -import type { GroupNode, SessionNode } from '../src/client/tree.ts' +import { ProjectRowItem, SearchResultItem, SessionNodeItem } from '../src/client/rows/Rows.tsx' +import type { GroupNode, SearchResultNode, SessionNode } from '../src/client/tree.ts' afterEach(cleanup) @@ -38,6 +38,25 @@ function fireDrag(row: HTMLElement, kind: 'dragOver' | 'drop', clientY: number): } describe('workspace browser rows', () => { + it('renders a selected content-search row and opens only its session', () => { + const onOpen = vi.fn() + const result: SearchResultNode = { + id: sid('result'), + title: 'Result title', + workspace: 'Workspace context', + running: true, + snippet: 'matching message excerpt', + } + render() + const row = screen.getByRole('treeitem') + expect(row.getAttribute('aria-selected')).toBe('true') + expect(screen.getByText('Workspace context')).toBeTruthy() + expect(screen.getByText('matching message excerpt')).toBeTruthy() + expect(row.hasAttribute('draggable')).toBe(false) + fireEvent.click(row) + expect(onOpen).toHaveBeenCalledWith(result.id) + }) + it('renders an active Workspace and keeps its create action separate from toggling', () => { const onToggle = vi.fn() const onCreate = vi.fn() diff --git a/packages/client/ui-workspace/tests/tree.spec.ts b/packages/client/ui-workspace/tests/tree.spec.ts index 4af5d5f70c..e308c79eec 100644 --- a/packages/client/ui-workspace/tests/tree.spec.ts +++ b/packages/client/ui-workspace/tests/tree.spec.ts @@ -2,7 +2,10 @@ import { describe, expect, it } from 'vitest' import type { SessionId, SessionListState, SessionSummary, WorkspaceId, WorkspaceView, } from '@deepseek-ai/dsh-client-runtime/client' -import { deriveFlat, deriveGroups, formatRelativeTime, projectLabel, UNGROUPED_KEY, UNGROUPED_LABEL } from '../src/client/tree.ts' +import { + deriveFlat, deriveGroups, deriveSearchResults, formatRelativeTime, projectLabel, + UNGROUPED_KEY, UNGROUPED_LABEL, +} from '../src/client/tree.ts' import { createWorkspaceViewStore } from '../src/client/stores.ts' const sid = (id: string) => id as SessionId @@ -16,12 +19,12 @@ const list = (...items: SessionSummary[]): SessionListState => ({ current: undefined, phase: 'ready', }) -const workspace = (id: string, sessionIds: string[]): WorkspaceView => ({ - workspaceId: wid(id), path: `/projects/${id}`, title: id, +const workspace = (id: string, sessionIds: string[], title = id): WorkspaceView => ({ + workspaceId: wid(id), path: `/projects/${id}`, title, sessionIds: sessionIds.map(sid), createdAt: '2026-01-01T00:00:00.000Z', updatedAt: '2026-01-01T00:00:00.000Z', }) -const view = (expandedProjects: readonly string[] = [], query = '') => ({ - expandedProjects, expandedSessions: [] as string[], query, +const view = (expandedProjects: readonly string[] = []) => ({ + expandedProjects, expandedSessions: [] as string[], }) describe('deriveGroups', () => { @@ -59,21 +62,6 @@ describe('deriveGroups', () => { expect(strayGroups.map(group => group.key)).toEqual(['first']) }) - it('searches the current blank session by its New Session title', () => { - const currentBlank = { ...summary('opaque-current', 5), blank: true } - const staleBlank = { ...summary('new session stale', 4), blank: true } - const sessions = { - ...list(currentBlank, staleBlank), - current: currentBlank.id, - } - const groups = deriveGroups( - sessions, [workspace('first', ['opaque-current', 'new session stale'])], view([], 'new session'), - ) - expect(groups[0]!.sessions.map(session => session.id)).toEqual([currentBlank.id]) - expect(groups[0]!.sessions[0]!.title).toBe('New Session') - expect(groups[0]!.sessionCount).toBe(1) - }) - it('builds, sorts, expands, and cycle-guards an ungrouped session tree', () => { const parent = summary('parent', 1) const oldChild = { ...summary('old-child', 10), parentId: parent.id } @@ -87,7 +75,7 @@ describe('deriveGroups', () => { const groups = deriveGroups( list(parent, oldChild, newChild, tieB, tieA, self, orphan, cycleA, cycleB), [], - { expandedProjects: [UNGROUPED_KEY], expandedSessions: [parent.id, cycleA.id, cycleB.id], query: '' }, + { expandedProjects: [UNGROUPED_KEY], expandedSessions: [parent.id, cycleA.id, cycleB.id] }, ) expect(groups).toHaveLength(1) @@ -113,31 +101,6 @@ describe('deriveGroups', () => { expect(groups[0]!.sessions.map(node => node.id)).toEqual([sid('present')]) }) - it('searches descendants with ancestors and handles cycles, self parents, and label-only hits', () => { - const root = { ...summary('root', 1), displayTitle: 'Ancestor' } - const match = { ...summary('match', 2), displayTitle: 'Needle child', parentId: root.id } - const sibling = { ...summary('sibling', 3), displayTitle: 'Other child', parentId: root.id } - const self = { ...summary('self', 4), displayTitle: 'Needle self', parentId: sid('self') } - const orphan = { ...summary('orphan', 5), displayTitle: 'Needle orphan', parentId: sid('absent') } - const cycleA = { ...summary('cycle-a', 6), displayTitle: 'Needle cycle A', parentId: sid('cycle-b') } - const cycleB = { ...summary('cycle-b', 7), displayTitle: 'Needle cycle B', parentId: sid('cycle-a') } - const sessions = list(root, match, sibling, self, orphan, cycleA, cycleB) - const groups = deriveGroups(sessions, [workspace('project', sessions.ids)], view([], 'needle')) - - expect(groups[0]!.sessions.flatMap(node => [node.id, ...node.children.map(child => child.id)])).toEqual([ - root.id, match.id, self.id, orphan.id, cycleA.id, cycleB.id, - ]) - - const labelOnly = deriveGroups( - list(summary('hidden', 1)), - [workspace('label-hit', ['hidden']), workspace('other', [])], - view([], 'label'), - ) - expect(labelOnly).toEqual([ - expect.objectContaining({ key: 'label-hit', expanded: false, sessions: [], sessionCount: 1 }), - ]) - }) - it('marks selected Workspace and Ungrouped sessions without relying on an Intent', () => { const owned = summary('owned', 1) const loose = summary('loose', 2) @@ -155,21 +118,15 @@ describe('deriveFlat', () => { const child = { ...summary('child', 30), parentId: parent.id } const tieB = summary('tie-b', 20) const tieA = summary('tie-a', 20) - const rows = deriveFlat(list(parent, child, tieB, tieA), { query: '' }) + const rows = deriveFlat(list(parent, child, tieB, tieA)) expect(rows.map(row => row.id)).toEqual([sid('child'), sid('tie-a'), sid('tie-b'), sid('parent')]) // Rows are branch-free: no children, no expansion. expect(rows.every(row => row.children.length === 0 && !row.hasChildren && !row.expanded)).toBe(true) }) - it('search filters by case-insensitive display-title substring', () => { - const hit = { ...summary('hit', 2), displayTitle: 'Needle row' } - const miss = { ...summary('miss', 1), displayTitle: 'Other' } - expect(deriveFlat(list(hit, miss), { query: ' NEEDLE ' }).map(row => row.id)).toEqual([sid('hit')]) - }) - it('tolerates ids whose summary has not landed yet', () => { const partial: SessionListState = { ...list(summary('present', 1)), ids: [sid('ghost'), sid('present')] } - expect(deriveFlat(partial, { query: '' }).map(row => row.id)).toEqual([sid('present')]) + expect(deriveFlat(partial).map(row => row.id)).toEqual([sid('present')]) }) it('shows only the current blank session with its New Session title', () => { @@ -179,11 +136,112 @@ describe('deriveFlat', () => { ...list(summary('real', 1), currentBlank, staleBlank), current: currentBlank.id, } - const rows = deriveFlat(sessions, { query: '' }) + const rows = deriveFlat(sessions) expect(rows.map(row => row.id)).toEqual([currentBlank.id, sid('real')]) expect(rows.map(row => row.title)).toEqual(['New Session', 'real']) - expect(deriveFlat(sessions, { query: 'new session' }).map(row => row.id)).toEqual([currentBlank.id]) - expect(deriveFlat(sessions, { query: 'stale-blank' })).toEqual([]) + }) +}) + +describe('deriveSearchResults', () => { + it('merges local title/Workspace matches before ranked content hits and enriches duplicates', () => { + const titleHit = summary('title-hit', 30, '/projects/a') + titleHit.displayTitle = 'Needle title' + const workspaceHit = summary('workspace-hit', 20, '/projects/b') + workspaceHit.displayTitle = 'Ordinary title' + const contentHit = summary('content-hit', 10, '/projects/c') + const sessions = list(titleHit, workspaceHit, contentHit) + const result = deriveSearchResults( + sessions, + [ + workspace('a', ['title-hit'], 'Alpha'), + workspace('b', ['workspace-hit'], 'Needle Workspace'), + ], + ' NEEDLE ', + { + items: [ + { sessionId: contentHit.id, snippet: 'body needle excerpt' }, + { sessionId: titleHit.id, snippet: 'title session body excerpt' }, + { sessionId: sid('unknown'), snippet: 'not in session.list' }, + ], + hasMore: false, + }, + ) + + expect(result).toEqual({ + items: [ + { + id: titleHit.id, + title: 'Needle title', + workspace: 'Alpha', + running: false, + snippet: 'title session body excerpt', + }, + { + id: workspaceHit.id, + title: 'Ordinary title', + workspace: 'Needle Workspace', + running: false, + }, + { + id: contentHit.id, + title: 'content-hit', + workspace: 'c', + running: false, + snippet: 'body needle excerpt', + }, + ], + hasMore: false, + }) + }) + + it('shows only the current blank row and uses its New Session display title', () => { + const currentBlank = { ...summary('opaque-current', 5), blank: true } + const staleBlank = { ...summary('new session stale', 4), blank: true } + const sessions = { + ...list(currentBlank, staleBlank), + current: currentBlank.id, + } + const result = deriveSearchResults( + sessions, + [workspace('first', ['opaque-current', 'new session stale'])], + 'new session', + { + items: [ + { sessionId: staleBlank.id, snippet: 'stale body' }, + { sessionId: currentBlank.id, snippet: 'current body' }, + ], + hasMore: false, + }, + ) + expect(result.items).toEqual([{ + id: currentBlank.id, + title: 'New Session', + workspace: 'first', + running: false, + snippet: 'current body', + }]) + }) + + it('caps merged rows at 20 and preserves either local overflow or backend hasMore', () => { + const rows = Array.from({ length: 22 }, (_, index) => { + const item = summary(`s-${String(index).padStart(2, '0')}`, index) + item.displayTitle = `Needle ${String(index)}` + return item + }) + const overflow = deriveSearchResults(list(...rows), [], 'needle', { items: [], hasMore: false }) + expect(overflow.items).toHaveLength(20) + expect(overflow.hasMore).toBe(true) + + const backendMore = deriveSearchResults( + list(summary('body', 1)), + [], + 'needle', + { items: [{ sessionId: sid('body'), snippet: 'needle' }], hasMore: true }, + ) + expect(backendMore.items).toHaveLength(1) + expect(backendMore.hasMore).toBe(true) + expect(deriveSearchResults(list(), [], ' ', { items: [], hasMore: true })) + .toEqual({ items: [], hasMore: false }) }) }) diff --git a/packages/client/ui-workspace/tests/workspace-browser.spec.tsx b/packages/client/ui-workspace/tests/workspace-browser.spec.tsx index e9b55e7b76..bce6fe6765 100644 --- a/packages/client/ui-workspace/tests/workspace-browser.spec.tsx +++ b/packages/client/ui-workspace/tests/workspace-browser.spec.tsx @@ -53,6 +53,7 @@ function mount(overrides: Partial = {}) { actions: store.actions, startSession: vi.fn(), open: vi.fn(), + searchSessions: vi.fn(async () => ({ items: [], hasMore: false })), renameWorkspace: vi.fn(async () => {}), insertSessionBefore: vi.fn(async () => {}), createWorkspace: vi.fn(async () => workspace('created', [])), @@ -198,42 +199,168 @@ describe('WorkspaceBrowser', () => { b.store.actions.setGroupBy('flat') rerender(b, {}) expect(screen.getAllByText('New Session')).toHaveLength(1) - fireEvent.change(screen.getByPlaceholderText('Search name, keywords...'), { target: { value: 'new session' } }) + fireEvent.change(screen.getByPlaceholderText('搜索名称或关键词…'), { target: { value: 'new session' } }) expect(screen.getAllByText('New Session')).toHaveLength(1) }) - it('searches across groups, clears via the clear button, and shows the empty states', () => { - const sessions = sessionState([ - summary('needle-row', 2, { displayTitle: 'Needle row' }), - summary('other-row', 1, { displayTitle: 'Other row' }), - ]) - mount({ - useSessions: hook(sessions), - useWorkspaces: hook(workspaceState([workspace('alpha', ['needle-row', 'other-row'])])), - }) - const input = screen.getByPlaceholderText('Search name, keywords...') - fireEvent.change(input, { target: { value: 'needle' } }) - // Search forces matches visible without expansion state. - expect(screen.getByText('Needle row')).toBeTruthy() - expect(screen.queryByText('Other row')).toBeNull() - fireEvent.change(input, { target: { value: 'zzz' } }) - expect(screen.getByText('No matches')).toBeTruthy() - fireEvent.click(screen.getByRole('button', { name: 'Clear search' })) - expect(input.value).toBe('') - // Clicking the field row focuses the input (wide mode). - fireEvent.click(input.parentElement as HTMLElement) - expect(document.activeElement).toBe(input) + it('shows local metadata matches immediately, then clears back to the grouped tree', async () => { + vi.useFakeTimers() + try { + const sessions = sessionState([ + summary('needle-row', 2, { displayTitle: 'Needle row' }), + summary('other-row', 1, { displayTitle: 'Other row' }), + ]) + mount({ + useSessions: hook(sessions), + useWorkspaces: hook(workspaceState([workspace('alpha', ['needle-row', 'other-row'])])), + }) + const input = screen.getByPlaceholderText('搜索名称或关键词…') + fireEvent.change(input, { target: { value: 'needle' } }) + expect(screen.getByRole('tree', { name: '搜索结果' })).toBeTruthy() + expect(screen.getByText('Needle row')).toBeTruthy() + expect(screen.queryByText('Other row')).toBeNull() + expect(screen.getByText('正在搜索历史…')).toBeTruthy() + + fireEvent.change(input, { target: { value: 'zzz' } }) + await act(async () => { await vi.advanceTimersByTimeAsync(250) }) + expect(screen.getByText('没有匹配结果')).toBeTruthy() + fireEvent.click(screen.getByRole('button', { name: '清除搜索' })) + expect(input.value).toBe('') + expect(screen.getByRole('tree', { name: 'Sessions' })).toBeTruthy() + // Clicking the field row focuses the input (wide mode). + fireEvent.click(input.parentElement as HTMLElement) + expect(document.activeElement).toBe(input) + } finally { + vi.useRealTimers() + } }) - it('shows the no-sessions empty state in both modes', () => { - const b = mount() - expect(screen.getByText('No sessions yet')).toBeTruthy() - b.store.actions.setGroupBy('flat') - rerender(b, {}) - expect(screen.getByText('No sessions yet')).toBeTruthy() - // Flat search misses show No matches. - fireEvent.change(screen.getByPlaceholderText('Search name, keywords...'), { target: { value: 'x' } }) - expect(screen.getByText('No matches')).toBeTruthy() + it('adds Host content hits with context, shows the result bound, and opens without clearing the query', async () => { + vi.useFakeTimers() + try { + const open = vi.fn() + const searchSessions = vi.fn(async () => ({ + items: [{ sessionId: sid('body-hit'), snippet: '…the waterfall token appears here…' }], + hasMore: true, + })) + mount({ + useSessions: hook(sessionState([ + summary('body-hit', 1, { displayTitle: 'Research notes' }), + ])), + useWorkspaces: hook(workspaceState([ + workspace('research', ['body-hit'], 'Research Workspace'), + ])), + open, + searchSessions, + }) + const input = screen.getByPlaceholderText('搜索名称或关键词…') + fireEvent.change(input, { target: { value: 'waterfall token' } }) + expect(screen.getByText('正在搜索历史…')).toBeTruthy() + expect(screen.queryByText('Research notes')).toBeNull() + + await act(async () => { await vi.advanceTimersByTimeAsync(250) }) + + expect(searchSessions).toHaveBeenCalledWith('waterfall token', expect.any(AbortSignal)) + expect(screen.getByText('Research notes')).toBeTruthy() + expect(screen.getByText('Research Workspace')).toBeTruthy() + expect(screen.getByText('…the waterfall token appears here…')).toBeTruthy() + expect(screen.getByText('仅显示前 20 项,请缩小搜索范围。')).toBeTruthy() + fireEvent.click(screen.getByRole('treeitem')) + expect(open).toHaveBeenCalledWith(sid('body-hit')) + expect(input.value).toBe('waterfall token') + } finally { + vi.useRealTimers() + } + }) + + it('keeps local matches and shows a lightweight warning when Host search fails', async () => { + vi.useFakeTimers() + try { + const searchSessions = vi.fn(async () => { throw new Error('index unavailable') }) + mount({ + useSessions: hook(sessionState([ + summary('local-hit', 1, { displayTitle: 'Needle title' }), + ])), + useWorkspaces: hook(workspaceState([workspace('alpha', ['local-hit'])])), + searchSessions, + }) + fireEvent.change(screen.getByPlaceholderText('搜索名称或关键词…'), { + target: { value: 'needle' }, + }) + expect(screen.getByText('Needle title')).toBeTruthy() + await act(async () => { await vi.advanceTimersByTimeAsync(250) }) + expect(screen.getByText('Needle title')).toBeTruthy() + expect(screen.getByText('历史内容搜索暂时不可用,仍显示名称匹配。')).toBeTruthy() + expect(screen.queryByText('没有匹配结果')).toBeNull() + } finally { + vi.useRealTimers() + } + }) + + it('aborts a superseded request and ignores its stale result', async () => { + vi.useFakeTimers() + try { + let resolveFirst!: (value: { + items: { sessionId: SessionId; snippet: string }[] + hasMore: boolean + }) => void + const first = new Promise<{ + items: { sessionId: SessionId; snippet: string }[] + hasMore: boolean + }>((resolve) => { resolveFirst = resolve }) + const searchSessions = vi.fn((query: string, _signal: AbortSignal) => query === 'first' + ? first + : Promise.resolve({ + items: [{ sessionId: sid('second-hit'), snippet: 'second excerpt' }], + hasMore: false, + })) + mount({ + useSessions: hook(sessionState([ + summary('first-hit', 2, { displayTitle: 'Old result' }), + summary('second-hit', 1, { displayTitle: 'Fresh result' }), + ])), + searchSessions, + }) + const input = screen.getByPlaceholderText('搜索名称或关键词…') + fireEvent.change(input, { target: { value: 'first' } }) + await act(async () => { await vi.advanceTimersByTimeAsync(250) }) + const firstSignal = searchSessions.mock.calls[0]?.[1] as AbortSignal + expect(firstSignal.aborted).toBe(false) + + fireEvent.change(input, { target: { value: 'second' } }) + expect(firstSignal.aborted).toBe(true) + await act(async () => { await vi.advanceTimersByTimeAsync(250) }) + expect(screen.getByText('Fresh result')).toBeTruthy() + + await act(async () => { + resolveFirst({ + items: [{ sessionId: sid('first-hit'), snippet: 'stale excerpt' }], + hasMore: false, + }) + await Promise.resolve() + }) + expect(screen.queryByText('Old result')).toBeNull() + expect(screen.getByText('Fresh result')).toBeTruthy() + } finally { + vi.useRealTimers() + } + }) + + it('shows the no-sessions empty state in both modes and resolves an empty search', async () => { + vi.useFakeTimers() + try { + const b = mount() + expect(screen.getByText('No sessions yet')).toBeTruthy() + b.store.actions.setGroupBy('flat') + rerender(b, {}) + expect(screen.getByText('No sessions yet')).toBeTruthy() + fireEvent.change(screen.getByPlaceholderText('搜索名称或关键词…'), { target: { value: 'x' } }) + expect(screen.getByText('正在搜索历史…')).toBeTruthy() + await act(async () => { await vi.advanceTimersByTimeAsync(250) }) + expect(screen.getByText('没有匹配结果')).toBeTruthy() + } finally { + vi.useRealTimers() + } }) it('rail state renders icon controls that request expansion', () => { @@ -243,16 +370,16 @@ describe('WorkspaceBrowser', () => { const b = mount({ wide: false, expandSidebar }) // No wide chrome in rail state. expect(screen.queryByText('Workspaces')).toBeNull() - expect(screen.queryByPlaceholderText('Search name, keywords...')).toBeNull() - fireEvent.click(screen.getByRole('button', { name: 'Search sessions' })) + expect(screen.queryByPlaceholderText('搜索名称或关键词…')).toBeNull() + fireEvent.click(screen.getByRole('button', { name: '搜索会话' })) expect(expandSidebar).toHaveBeenCalledTimes(1) // The wide flip mounts the input and focuses it after the slide. rerender(b, { wide: true }) - const input = screen.getByPlaceholderText('Search name, keywords...') + const input = screen.getByPlaceholderText('搜索名称或关键词…') act(() => { vi.advanceTimersByTime(300) }) expect(document.activeElement).toBe(input) // Wide search button is decorative (tabIndex -1, no expand call). - fireEvent.click(screen.getByRole('button', { name: 'Search sessions' })) + fireEvent.click(screen.getByRole('button', { name: '搜索会话' })) expect(expandSidebar).toHaveBeenCalledTimes(1) } finally { vi.useRealTimers() @@ -463,8 +590,8 @@ describe('WorkspaceBrowser', () => { useSessions: hook(sessions), useWorkspaces: hook(workspaceState([workspace('alpha', ['needle-a'])])), }) - fireEvent.change(screen.getByPlaceholderText('Search name, keywords...'), { target: { value: 'needle' } }) + fireEvent.change(screen.getByPlaceholderText('搜索名称或关键词…'), { target: { value: 'needle' } }) const row = screen.getByText('Needle A').closest('[role="treeitem"]') as HTMLElement - expect(row.getAttribute('draggable')).toBe('false') + expect(row.hasAttribute('draggable')).toBe(false) }) }) diff --git a/packages/host/apiproxy/README.i18n.yaml b/packages/host/apiproxy/README.i18n.yaml index eb06e14d2d..7d323dbeea 100644 --- a/packages/host/apiproxy/README.i18n.yaml +++ b/packages/host/apiproxy/README.i18n.yaml @@ -1,6 +1,6 @@ # Bilingual-pair consistency record (docs/i18n/README.md): the git blob hash of each # side as of the last confirmed-consistent state. Both languages carry equal authority; # after editing either side, bring the other along and re-record with: -# pnpm run verify-translation-pairing --write -README.md: 43ad70fa8b865b0b80496bbb67013f24e9e3a33f -README.zh.md: cc95a7512fb872add816bf0456a93dfcf7b84c10 +# pnpm run verify-translation-pairing --write packages/host/apiproxy/README.md +README.md: deb1073c2ff9e7a533e595ee3f5537e649660e5b +README.zh.md: e3c521d5f6a09414d087e3fb142852e6d3eb0cb7 diff --git a/packages/host/apiproxy/README.md b/packages/host/apiproxy/README.md index 43ad70fa8b..deb1073c2f 100644 --- a/packages/host/apiproxy/README.md +++ b/packages/host/apiproxy/README.md @@ -14,6 +14,8 @@ The mux stream projects the latest log-backed title as a validated `session/titl Workspace and Session lists are separate reconnect baselines. `workspace.create` creates a unique name or adopts an existing directory, `session.create` accepts an optional preallocated Session id, and `host/workspace-changed` plus `host/session-added` carry committed increments in either arrival order. `SessionSummary.blank` and the `host/session-added` frame carry the derived zero-events bit: clients hide blank sessions and reuse them per workspace, flip blank on the first `host/session-status(running:true)`, and treat `session.list` as the reconnect authority; cold summaries are never blank because lazy persistence keeps never-appended sessions out of `list()`. +`session.search` is a bounded content-search projection over the sessions visible through `session.list`. The gateway passes only those session ids and current-surface user, assistant, and steering messages to the optional `ctx.sessionQuery` service, returns at most 20 session/snippet pairs plus a refine-query bit, and forwards the carrier request signal for cancellation. A deployment without the service, or a failed index/query operation, returns an `internal` business error so clients can retain metadata-only matches. + The `command.*` and `skill.*` domains expose the host command registry and skill catalog to clients. Every method addresses one session's agent by `sessionId` (a served session always has an Agent; `command.*` resumes cold sessions through the same path as `session.*`, while `skill.list` resolves the project root from the session header without touching the Agent registry). `command.execute` runs a slash-command line host-side and returns a detached result; the carrier's request signal cancels the running handler. `host/commands-changed` is the catalog invalidation frame: clients refetch `command.list` instead of diffing. ## Carrier layer (`/client` + root) diff --git a/packages/host/apiproxy/README.zh.md b/packages/host/apiproxy/README.zh.md index cc95a7512f..e3c521d5f6 100644 --- a/packages/host/apiproxy/README.zh.md +++ b/packages/host/apiproxy/README.zh.md @@ -14,6 +14,8 @@ mux 流会在每个已附加会话的订阅基线之后,以及对应的实时 Workspace 列表与 Session 列表是相互独立的重连基线。`workspace.create` 会创建唯一名称或接纳现有目录,`session.create` 接受可选的预分配 Session id,`host/workspace-changed` 与 `host/session-added` 则以任意到达顺序携带已提交的增量。`SessionSummary.blank` 与 `host/session-added` 帧携带派生的零事件位:客户端隐藏空白会话并按 workspace 复用它们,在首个 `host/session-status(running:true)` 时翻转 blank,并以 `session.list` 作为重连权威;冷会话摘要永远不是空白——惰性持久化让从未追加过事件的会话根本不出现在 `list()` 中。 +`session.search` 是以 `session.list` 所列会话为范围的有界内容搜索投影。网关仅将这些会话 id 以及当前表层中的 user、assistant 和 steering(中途引导)消息传给可选的 `ctx.sessionQuery` 服务,返回至多 20 个会话/snippet 对和一个提示细化查询的标志位,并转发载体请求信号以支持取消。部署若未挂载该服务,或索引/查询操作失败,都会返回 `internal` 业务错误,以便客户端保留仅基于元数据的匹配项。 + `command.*` 与 `skill.*` 领域向客户端暴露宿主命令注册表和技能目录。每个方法都通过 `sessionId` 寻址一个会话的 Agent(被服务的会话必有 Agent;`command.*` 经由与 `session.*` 相同的路径恢复冷会话,而 `skill.list` 从会话头解析项目根目录,不触碰 Agent 注册表)。`command.execute` 在宿主侧运行一条斜杠命令行并返回脱耦结果;载体的请求信号可取消正在运行的处理器。`host/commands-changed` 是目录失效帧:客户端重新拉取 `command.list` 而不是做差分。 ## 载体层(`/client` + 根路径) diff --git a/packages/host/apiproxy/package.json b/packages/host/apiproxy/package.json index 0c7107a1f9..c84a4c00ff 100644 --- a/packages/host/apiproxy/package.json +++ b/packages/host/apiproxy/package.json @@ -46,6 +46,7 @@ "@deepseek-ai/dsh-llm": "workspace:^", "@deepseek-ai/dsh-session": "workspace:^", "@deepseek-ai/dsh-session-persistence": "workspace:^", + "@deepseek-ai/dsh-session-query": "workspace:^", "@deepseek-ai/dsh-session-title": "workspace:^", "@deepseek-ai/dsh-skill": "workspace:^", "@deepseek-ai/dsh-tools": "workspace:^", diff --git a/packages/host/apiproxy/src/api-proxy.ts b/packages/host/apiproxy/src/api-proxy.ts index f81f5c9be8..a5055ef1d8 100644 --- a/packages/host/apiproxy/src/api-proxy.ts +++ b/packages/host/apiproxy/src/api-proxy.ts @@ -11,6 +11,7 @@ import type { Agent, AgentMessage, AgentMessageId, AgentStatus } from '@deepseek import type { ContentBlock, MessageSource } from '@deepseek-ai/dsh-llm' import type { JsonValue, Session, SessionEvent, SessionHeader, SessionId } from '@deepseek-ai/dsh-session' import type { SessionPersistence } from '@deepseek-ai/dsh-session-persistence' +import { SessionQueryError } from '@deepseek-ai/dsh-session-query' import { foldSessionTitle } from '@deepseek-ai/dsh-session-title' import type { Workspace, WorkspaceRecord } from '@deepseek-ai/dsh-workspace' import { @@ -20,8 +21,8 @@ import { // Type-only: brings the `ctx.tools` Context merge into this program (viewFor reads presenters). import type {} from '@deepseek-ai/dsh-tools' import type { - ApiProxy, HistoryEntry, HostFrame, MuxFrame, QuestionResponsePayload, SessionSummary, ToolEventView, - WorkspaceId, WorkspaceView, + ApiProxy, HistoryEntry, HostFrame, MuxFrame, QuestionResponsePayload, SessionSearchItem, + SessionSummary, ToolEventView, WorkspaceId, WorkspaceView, } from './api/index.ts' // Type-only edges: resolve `ctx.get('commands')`, the `commands/change` event, and `ctx.get('skills')`. import type {} from '@deepseek-ai/dsh-commands' @@ -37,9 +38,17 @@ import { UserInteractionError } from '@deepseek-ai/dsh-user-interaction' /** Page size when history is called without maxMessages. */ const DEFAULT_MAX_MESSAGES = 50 +/** Product contract: sidebar search returns one bounded page and no cursor. */ +const SESSION_SEARCH_LIMIT = 20 + /** Surface message event types (the pagination counting unit). */ const MESSAGE_TYPES = new Set(['user/message', 'assistant/message', 'steering/message']) +/** Read live abort state across awaits without treating it as synchronously immutable. */ +function isAborted(signal: AbortSignal): boolean { + return signal.aborted +} + /** * Message-boundary pagination: count maxMessages surface messages backwards from * the window tail; the cut is the starting seq of the oldest message group @@ -561,6 +570,26 @@ export function createApiProxy(ctx: Context, defaults: ApiProxyDefaults): ApiPro return operation } + /** + * Build the session.list baseline shared by listing and search visibility. + * Attached sessions come from memory; servable cold sessions merge from + * persistence, and the final order is newest-first. + */ + async function listVisibleSessionSummaries(): Promise { + const items = ctx.sessions.list().map((session) => { + const agent = ctx.agents.get(session.id) + return summarize(session, agent?.status === 'running') + }) + const attached = new Set(items.map(item => item.sessionId)) + const persistence = ctx.get('sessionPersistence') + if (persistence !== undefined) { + const cold = (await persistence.list()).filter(meta => !attached.has(meta.id) && meta.cwd !== undefined) + items.push(...await Promise.all(cold.map(meta => summarizeCold(persistence, meta)))) + } + items.sort((a, b) => b.updatedAt - a.updatedAt) + return items + } + return { sessions: { // Attached sessions summarize from memory; persisted-but-unattached (cold) @@ -568,18 +597,61 @@ export function createApiProxy(ctx: Context, defaults: ApiProxyDefaults): ApiPro // Legacy logs without a cwd (pre-project stance) are not served — every // session now records its project at create time. async list(request) { - const items = ctx.sessions.list().map((session) => { - const agent = ctx.agents.get(session.id) - return summarize(session, agent?.status === 'running') + return ok(request, { items: await listVisibleSessionSummaries() }) + }, + + async search(request, signal) { + const cancelled = () => err<{ items: SessionSearchItem[]; hasMore: boolean }>(request, { + code: 'cancelled', + message: 'session search was aborted', + details: {}, }) - const attached = new Set(items.map(item => item.sessionId)) - const persistence = ctx.get('sessionPersistence') - if (persistence !== undefined) { - const cold = (await persistence.list()).filter(meta => !attached.has(meta.id) && meta.cwd !== undefined) - items.push(...await Promise.all(cold.map(meta => summarizeCold(persistence, meta)))) + if (isAborted(signal)) return cancelled() + const sessionQuery = ctx.get('sessionQuery') + if (sessionQuery === undefined) { + return err(request, { + code: 'internal', + message: 'session search is unavailable: this deployment does not mount @deepseek-ai/dsh-session-query', + details: {}, + }) + } + try { + const visible = await listVisibleSessionSummaries() + if (isAborted(signal)) return cancelled() + if (visible.length === 0) return ok(request, { items: [], hasMore: false }) + const visibleIds = new Set(visible.map(item => item.sessionId)) + const page = await sessionQuery.searchSessions({ + query: request.payload.query, + sessionFilters: [{ kind: 'id', values: [...visibleIds] }], + eventFilters: [ + { kind: 'type', values: ['user/message', 'assistant/message', 'steering/message'] }, + { kind: 'surface', values: ['current'] }, + ], + limit: SESSION_SEARCH_LIMIT, + }, { signal }) + if (isAborted(signal)) return cancelled() + // The id filter is the authorization boundary. Re-check the provider + // projection before emitting it so a backend regression cannot leak + // a session that `session.list` withheld. + const authorized = page.items.filter(hit => visibleIds.has(hit.header.id)) + return ok(request, { + items: authorized.slice(0, SESSION_SEARCH_LIMIT).map(hit => ({ + sessionId: hit.header.id, + snippet: hit.bestMatch.snippet, + })), + hasMore: page.nextCursor !== undefined || authorized.length > SESSION_SEARCH_LIMIT, + }) + } catch (error: unknown) { + if ( + isAborted(signal) + || (error instanceof SessionQueryError && error.code === 'SESSION_QUERY_ABORTED') + ) return cancelled() + return err(request, { + code: 'internal', + message: `session search failed: ${String(error)}`, + details: {}, + }) } - items.sort((a, b) => b.updatedAt - a.updatedAt) - return ok(request, { items }) }, async create(request) { diff --git a/packages/host/apiproxy/src/api/index.ts b/packages/host/apiproxy/src/api/index.ts index 537b2744ef..4425e05ecf 100644 --- a/packages/host/apiproxy/src/api/index.ts +++ b/packages/host/apiproxy/src/api/index.ts @@ -25,7 +25,7 @@ export interface ApiProxy { } // ---- Domain interfaces and payload entities ---- -export type { HistoryEntry, SessionsApi, SessionSummary } from './sessions.ts' +export type { HistoryEntry, SessionSearchItem, SessionsApi, SessionSummary } from './sessions.ts' export type { HostApi } from './host.ts' export type { WorkspaceApi, WorkspaceId, WorkspaceView } from './workspace.ts' export type { CommandsApi, CommandDescriptor, CommandExecuteResult } from './commands.ts' diff --git a/packages/host/apiproxy/src/api/rpc-map.ts b/packages/host/apiproxy/src/api/rpc-map.ts index abe992584c..8f136de494 100644 --- a/packages/host/apiproxy/src/api/rpc-map.ts +++ b/packages/host/apiproxy/src/api/rpc-map.ts @@ -18,6 +18,7 @@ import type { RpcResponse } from './rpc.ts' */ export interface RpcMethodMap { 'session.list': SessionsApi['list'] + 'session.search': SessionsApi['search'] 'session.create': SessionsApi['create'] 'session.history': SessionsApi['history'] 'session.prompt': SessionsApi['prompt'] diff --git a/packages/host/apiproxy/src/api/sessions.schema.ts b/packages/host/apiproxy/src/api/sessions.schema.ts index 12ebd4182d..4db9ac32c4 100644 --- a/packages/host/apiproxy/src/api/sessions.schema.ts +++ b/packages/host/apiproxy/src/api/sessions.schema.ts @@ -9,7 +9,7 @@ import { z } from 'zod' import type { SessionEvent, SessionId } from '@deepseek-ai/dsh-session/types' import type { RequestPayload, ResponseValue } from './rpc-map.ts' import type { Wire } from './rpc.schema.ts' -import type { HistoryEntry, SessionSummary } from './sessions.ts' +import type { HistoryEntry, SessionSearchItem, SessionSummary } from './sessions.ts' import type { ToolEventView } from './events.ts' import type { WorkspaceId } from './workspace.ts' @@ -54,6 +54,29 @@ export const sessionListValueSchema = z.object({ items: z.array(sessionSummarySchema), }) satisfies z.ZodType>> +/** Fixed wire bound for one interactive sidebar query. */ +const SESSION_SEARCH_QUERY_MAX_CHARS = 500 +/** Product response bound validated independently by every client carrier. */ +const SESSION_SEARCH_RESULT_LIMIT = 20 + +/** session.search request payload. */ +export const sessionSearchRequestSchema = z.object({ + query: z.string().trim().min(1).max(SESSION_SEARCH_QUERY_MAX_CHARS) + .refine(query => !query.includes('\0'), { message: 'search query must not contain NUL' }), +}) satisfies z.ZodType>> + +/** One session.search result. */ +export const sessionSearchItemSchema = z.object({ + sessionId: sessionIdSchema, + snippet: z.string(), +}) satisfies z.ZodType> + +/** session.search response value. */ +export const sessionSearchValueSchema = z.object({ + items: z.array(sessionSearchItemSchema).max(SESSION_SEARCH_RESULT_LIMIT), + hasMore: z.boolean(), +}) satisfies z.ZodType>> + /** session.create request payload (at most one of workspaceId / cwd). */ export const sessionCreateRequestSchema = z.object({ workspaceId: workspaceIdSchema.optional(), diff --git a/packages/host/apiproxy/src/api/sessions.ts b/packages/host/apiproxy/src/api/sessions.ts index 2552b5d5a3..7f62eea93f 100644 --- a/packages/host/apiproxy/src/api/sessions.ts +++ b/packages/host/apiproxy/src/api/sessions.ts @@ -53,11 +53,28 @@ export interface SessionSummary { cwd?: string } +/** One session-content search result; display metadata stays owned by `session.list`. */ +export interface SessionSearchItem { + sessionId: SessionId + /** Plain-text excerpt around the strongest matching visible message. */ + snippet: string +} + /** Session-domain unary methods (the map keys session.* of RpcMethodMap). */ export interface SessionsApi { /** Lists persisted sessions (updatedAt descending). v1 returns everything; cursor is a reserved seat, unimplemented. */ list(request: RpcRequest<{ cursor?: string }>): Promise> + /** + * Searches the current user/assistant/steering message surface across + * sessions visible to `list`. Results contain at most 20 sessions and carry + * no continuation cursor; `hasMore` asks the client to refine the query. + */ + search( + request: RpcRequest<{ query: string }>, + signal: AbortSignal, + ): Promise> + /** * Creates a real session and its idle agent. At most one of `workspaceId` / * `cwd` is accepted; an omitted project uses the Host cwd. A caller may diff --git a/packages/host/apiproxy/src/fetch/client.ts b/packages/host/apiproxy/src/fetch/client.ts index 0424ba7a4f..b967e5b80c 100644 --- a/packages/host/apiproxy/src/fetch/client.ts +++ b/packages/host/apiproxy/src/fetch/client.ts @@ -20,6 +20,7 @@ import { sessionHistoryValueSchema, sessionListValueSchema, sessionPromptValueSchema, + sessionSearchValueSchema, } from '../api/sessions.schema.ts' import { workspaceCreateValueSchema, @@ -48,6 +49,7 @@ import { skillListValueSchema } from '../api/skills.schema.ts' export interface IApiClient { sessions: { list(payload: RequestPayload<'session.list'>, signal?: AbortSignal): Promise>> + search(payload: RequestPayload<'session.search'>, signal?: AbortSignal): Promise>> create(payload: RequestPayload<'session.create'>, signal?: AbortSignal): Promise>> history(payload: RequestPayload<'session.history'>, signal?: AbortSignal): Promise>> prompt(payload: RequestPayload<'session.prompt'>, signal?: AbortSignal): Promise>> @@ -83,6 +85,7 @@ export interface IApiClient { */ const UNARY_VALUE_SCHEMAS: { [K in keyof RpcMethodMap]: z.ZodType>> } = { 'session.list': sessionListValueSchema, + 'session.search': sessionSearchValueSchema, 'session.create': sessionCreateValueSchema, 'session.history': sessionHistoryValueSchema, 'session.prompt': sessionPromptValueSchema, @@ -271,6 +274,7 @@ export abstract class AbstractApiClient implements IApiClient { readonly sessions: IApiClient['sessions'] = { list: (payload, signal) => this.callUnary('session.list', payload, signal), + search: (payload, signal) => this.callUnary('session.search', payload, signal), create: (payload, signal) => this.callUnary('session.create', payload, signal), history: (payload, signal) => this.callUnary('session.history', payload, signal), prompt: (payload, signal) => this.callUnary('session.prompt', payload, signal), diff --git a/packages/host/apiproxy/src/fetch/handler.ts b/packages/host/apiproxy/src/fetch/handler.ts index b79980d63e..4115f77fa0 100644 --- a/packages/host/apiproxy/src/fetch/handler.ts +++ b/packages/host/apiproxy/src/fetch/handler.ts @@ -20,6 +20,7 @@ import { sessionHistoryRequestSchema, sessionListRequestSchema, sessionPromptRequestSchema, + sessionSearchRequestSchema, } from '../api/sessions.schema.ts' import { hostDescribeRequestSchema } from '../api/host.schema.ts' import { @@ -38,7 +39,8 @@ import { skillListRequestSchema } from '../api/skills.schema.ts' * Schemas anchor to the Wire<> widening (the repo-wide exactOptionalPropertyTypes accommodation * documented on Wire); the dispatch point carries the one Wire→exact cast. * Every invoke receives the carrier Request's signal; methods whose contract - * declares a signal parameter (command.execute) forward it, the rest ignore it. + * declares a signal parameter (session.search and command.execute) forward it, + * the rest ignore it. */ type UnaryRoutes = { [K in keyof RpcMethodMap]: { @@ -49,6 +51,7 @@ type UnaryRoutes = { const UNARY_ROUTES: UnaryRoutes = { 'session.list': { schema: sessionListRequestSchema, invoke: (api, r) => api.sessions.list(r) }, + 'session.search': { schema: sessionSearchRequestSchema, invoke: (api, r, signal) => api.sessions.search(r, signal) }, 'session.create': { schema: sessionCreateRequestSchema, invoke: (api, r) => api.sessions.create(r) }, 'session.history': { schema: sessionHistoryRequestSchema, invoke: (api, r) => api.sessions.history(r) }, 'session.prompt': { schema: sessionPromptRequestSchema, invoke: (api, r) => api.sessions.prompt(r) }, diff --git a/packages/host/apiproxy/tests/api-proxy-search.spec.ts b/packages/host/apiproxy/tests/api-proxy-search.spec.ts new file mode 100644 index 0000000000..5f8060a696 --- /dev/null +++ b/packages/host/apiproxy/tests/api-proxy-search.spec.ts @@ -0,0 +1,237 @@ +/** + * Host session.search projection: list-equivalent visibility, fixed message + * filters and result bound, cancellation mapping, and unavailable/failure + * behavior. + */ + +import { describe, expect, it, vi } from 'vitest' +import { Context } from 'cordis' +import AgentRegistry from '@deepseek-ai/dsh-agent' +import SessionStore from '@deepseek-ai/dsh-session' +import type { SessionHeader, SessionId } from '@deepseek-ai/dsh-session' +import UserInteractionService from '@deepseek-ai/dsh-user-interaction' +import { + SessionQueryError, + type SessionSearchHit, + type SessionSearchRequest, +} from '@deepseek-ai/dsh-session-query' +import type { RpcRequest } from '@deepseek-ai/dsh-host-apiproxy/api' +import { RpcId } from '@deepseek-ai/dsh-host-apiproxy/api' +import { createApiProxy } from '@deepseek-ai/dsh-host-apiproxy' + +const sid = (value: string): SessionId => value as SessionId +const defaults = { provider: 'p', model: 'm', cwd: '/tmp', workspaceRoot: '/tmp' } + +function request(query: string): RpcRequest<{ query: string }> { + return { rpcId: RpcId(`search-${query}`), payload: { query } } +} + +function header(id: string, cwd: string | null = '/project'): SessionHeader { + return { + version: 0, + id: sid(id), + createdAt: 100, + ...(cwd === null ? {} : { cwd }), + } +} + +function hit(id: string, index = 0): SessionSearchHit { + const session = header(id) + return { + header: session, + live: true, + persisted: false, + bestMatch: { + sessionId: session.id, + seq: index, + type: 'user/message', + time: 200 + index, + surface: 'current', + snippet: `match ${index}`, + }, + } +} + +async function baseContext(): Promise { + const ctx = new Context() + await ctx.plugin(SessionStore) + await ctx.plugin(AgentRegistry) + await ctx.plugin(UserInteractionService) + return ctx +} + +describe('session.search', () => { + it('searches only list-visible ids and current conversation-message events', async () => { + const ctx = await baseContext() + const live = ctx.sessions.create(sid('live'), { meta: header('live', '/live') }) + live.append('user/message', { + content: [{ type: 'text', text: 'live text' }], + source: { kind: 'user' }, + }, { surfaceOp: 'append' }) + const cold = header('cold', '/cold') + const legacy = header('legacy', null) + ctx.provide('sessionPersistence', { + list: () => Promise.resolve([cold, legacy]), + locate: () => undefined, + } as never) + + const searchSessions = vi.fn(( + _request: SessionSearchRequest, + _exec?: { signal?: AbortSignal }, + ) => Promise.resolve({ + items: [ + { + header: legacy, + live: false, + persisted: true, + bestMatch: { + sessionId: legacy.id, + seq: 3, + type: 'user/message' as const, + time: 190, + surface: 'current' as const, + snippet: 'must remain hidden', + }, + }, + { + header: cold, + live: false, + persisted: true, + bestMatch: { + sessionId: cold.id, + seq: 4, + type: 'assistant/message' as const, + time: 200, + surface: 'current' as const, + snippet: 'the matching answer', + }, + }, + ], + nextCursor: 'more' as never, + })) + ctx.provide('sessionQuery', { searchSessions } as never) + const api = createApiProxy(ctx, defaults) + const signal = new AbortController().signal + + const response = await api.sessions.search(request('matching answer'), signal) + + expect(response.result).toEqual({ + ok: true, + value: { + items: [{ sessionId: 'cold', snippet: 'the matching answer' }], + hasMore: true, + }, + }) + expect(searchSessions).toHaveBeenCalledOnce() + const [query, exec] = searchSessions.mock.calls[0] as unknown as [ + SessionSearchRequest, + { signal: AbortSignal }, + ] + expect(query).toEqual({ + query: 'matching answer', + sessionFilters: [{ kind: 'id', values: ['live', 'cold'] }], + eventFilters: [ + { + kind: 'type', + values: ['user/message', 'assistant/message', 'steering/message'], + }, + { kind: 'surface', values: ['current'] }, + ], + limit: 20, + }) + expect(exec.signal).toBe(signal) + }) + + it('returns an empty page without invoking the index when no session is visible', async () => { + const ctx = await baseContext() + const searchSessions = vi.fn() + ctx.provide('sessionQuery', { searchSessions } as never) + const api = createApiProxy(ctx, defaults) + + const response = await api.sessions.search( + request('anything'), + new AbortController().signal, + ) + + expect(response.result).toEqual({ + ok: true, + value: { items: [], hasMore: false }, + }) + expect(searchSessions).not.toHaveBeenCalled() + }) + + it('enforces the 20-item Host boundary even if a provider overproduces', async () => { + const ctx = await baseContext() + const items = Array.from({ length: 21 }, (_, index) => hit(`visible-${index}`, index)) + for (const item of items) { + ctx.sessions.create(item.header.id, { meta: item.header }) + } + ctx.provide('sessionQuery', { + searchSessions: () => Promise.resolve({ items }), + } as never) + const response = await createApiProxy(ctx, defaults).sessions.search( + request('match'), + new AbortController().signal, + ) + + expect(response.result).toMatchObject({ + ok: true, + value: { hasMore: true }, + }) + if (!response.result.ok) throw new Error('unreachable') + expect(response.result.value.items).toHaveLength(20) + expect(response.result.value.items.at(-1)?.sessionId).toBe('visible-19') + }) + + it('maps missing composition, query cancellation, and provider failure', async () => { + const missingCtx = await baseContext() + missingCtx.sessions.create(sid('visible'), { meta: header('visible') }) + const missingApi = createApiProxy(missingCtx, defaults) + const preAborted = new AbortController() + preAborted.abort() + const cancelledBeforeLookup = await missingApi.sessions.search( + request('cancel-before-lookup'), + preAborted.signal, + ) + expect(cancelledBeforeLookup.result).toMatchObject({ + ok: false, + error: { code: 'cancelled' }, + }) + + const missing = await missingApi.sessions.search( + request('needle'), + new AbortController().signal, + ) + expect(missing.result.ok).toBe(false) + if (missing.result.ok) throw new Error('unreachable') + expect(missing.result.error.code).toBe('internal') + expect(missing.result.error.message).toContain('does not mount') + + const ctx = await baseContext() + ctx.sessions.create(sid('visible'), { meta: header('visible') }) + const aborted = new SessionQueryError('provider stopped', 'SESSION_QUERY_ABORTED') + const searchSessions = vi.fn() + .mockRejectedValueOnce(aborted) + .mockRejectedValueOnce(new Error('database unavailable')) + ctx.provide('sessionQuery', { searchSessions } as never) + const api = createApiProxy(ctx, defaults) + + const cancelled = await api.sessions.search( + request('first'), + new AbortController().signal, + ) + expect(cancelled.result).toMatchObject({ + ok: false, + error: { code: 'cancelled' }, + }) + + const failed = await api.sessions.search( + request('second'), + new AbortController().signal, + ) + expect(failed.result.ok).toBe(false) + if (failed.result.ok) throw new Error('unreachable') + expect(failed.result.error.code).toBe('internal') + expect(failed.result.error.message).toContain('database unavailable') + }) +}) diff --git a/packages/host/apiproxy/tests/client-handler.spec.ts b/packages/host/apiproxy/tests/client-handler.spec.ts index a9a5eac9ba..fe583b7351 100644 --- a/packages/host/apiproxy/tests/client-handler.spec.ts +++ b/packages/host/apiproxy/tests/client-handler.spec.ts @@ -29,6 +29,7 @@ function scriptedApi(overrides: { return { sessions: { list: r => ok(r, { items: [] }), + search: r => ok(r, { items: [], hasMore: false }), create: r => ok(r, { sessionId: sid('s-new') }), history: r => ok(r, { events: [], hasMore: false }), prompt: r => ok(r, { accepted: true as const }), @@ -76,6 +77,30 @@ describe('unary round trip', () => { expect(response.result).toEqual({ ok: true, value: { items: [{ sessionId: 's1', updatedAt: 7, running: false, blank: false }] } }) }) + it('round-trips a trimmed session search query and its bounded result metadata', async () => { + let seen: RpcRequest<{ query: string }> | undefined + const api = scriptedApi({ + sessions: { + search: (request) => { + seen = request + return ok(request, { + items: [{ sessionId: sid('s1'), snippet: 'matching message text' }], + hasMore: true, + }) + }, + }, + }) + const response = await client(api).sessions.search({ query: ' message text ' }) + expect(seen?.payload).toEqual({ query: 'message text' }) + expect(response.result).toEqual({ + ok: true, + value: { + items: [{ sessionId: 's1', snippet: 'matching message text' }], + hasMore: true, + }, + }) + }) + it('routes workspace rename and insertSessionBefore through the wire', async () => { const api = scriptedApi() const c = client(api) diff --git a/packages/host/apiproxy/tests/fetch-carrier.spec.ts b/packages/host/apiproxy/tests/fetch-carrier.spec.ts index e8d65d2a62..1d9bd00122 100644 --- a/packages/host/apiproxy/tests/fetch-carrier.spec.ts +++ b/packages/host/apiproxy/tests/fetch-carrier.spec.ts @@ -21,6 +21,26 @@ function fakeApi(overrides: Partial<{ muxFrames: MuxFrame[]; hostFrames: HostFra if (overrides.crashOn === 'session.list') throw new Error('impl crashed') return { rpcId: request.rpcId, result: { ok: true, value: { items: [] } } } }, + async search(request, signal) { + if (request.payload.query === 'hang') { + if (!signal.aborted) { + await new Promise((resolve) => { + signal.addEventListener('abort', () => { resolve() }, { once: true }) + }) + } + return { + rpcId: request.rpcId, + result: { ok: false, error: { code: 'cancelled', message: 'aborted', details: {} } }, + } + } + return { + rpcId: request.rpcId, + result: { + ok: true, + value: { items: [{ sessionId: 's1' as never, snippet: 'fixture match' }], hasMore: false }, + }, + } + }, async create(request) { return { rpcId: request.rpcId, result: { ok: true, value: { sessionId: 's-new' as never } } } }, @@ -124,6 +144,10 @@ describe('unary round trip (handler ⇄ client, no network)', () => { it('covers create/prompt/cancel/describe passthrough', async () => { const c = client() + expect((await c.sessions.search({ query: 'fixture' })).result).toEqual({ + ok: true, + value: { items: [{ sessionId: 's1', snippet: 'fixture match' }], hasMore: false }, + }) expect((await c.sessions.create({})).result.ok).toBe(true) expect((await c.sessions.prompt({ sessionId: 's' as never, mode: 'queue', content: [{ type: 'text', text: 'x' }] })).result.ok).toBe(true) expect((await c.sessions.cancel({ sessionId: 's' as never })).result.ok).toBe(true) @@ -155,6 +179,29 @@ describe('unary round trip (handler ⇄ client, no network)', () => { expect(parsed.rpcId).toBe('r-sig') expect(parsed.result.error?.code).toBe('cancelled') }) + + it('propagates the carrier Request signal into session.search', async () => { + const handler = toFetchHandler(fakeApi()) + const controller = new AbortController() + const body = JSON.stringify({ + type: 'client-request', + rpcId: 'r-search-sig', + method: 'session.search', + payload: { query: 'hang' }, + }) + const pending = handler.fetch(new Request( + 'http://x/api/session.search', + { method: 'POST', body, signal: controller.signal }, + )) + controller.abort() + const response = await pending + const parsed = await response.json() as { + rpcId: string + result: { error?: { code: string } } + } + expect(parsed.rpcId).toBe('r-search-sig') + expect(parsed.result.error?.code).toBe('cancelled') + }) }) describe('handler carrier-layer statuses', () => { diff --git a/packages/host/apiproxy/tests/rpc-schemas.spec.ts b/packages/host/apiproxy/tests/rpc-schemas.spec.ts index 02ca8dec22..1261959260 100644 --- a/packages/host/apiproxy/tests/rpc-schemas.spec.ts +++ b/packages/host/apiproxy/tests/rpc-schemas.spec.ts @@ -9,7 +9,7 @@ import { contentBlockSchema, sessionCancelRequestSchema, sessionCancelValueSchema, sessionCreateRequestSchema, sessionCreateValueSchema, sessionEventSchema, sessionHistoryRequestSchema, sessionHistoryValueSchema, sessionIdSchema, sessionListRequestSchema, sessionListValueSchema, sessionPromptRequestSchema, - sessionPromptValueSchema, sessionSummarySchema, + sessionPromptValueSchema, sessionSearchRequestSchema, sessionSearchValueSchema, sessionSummarySchema, } from '../src/api/sessions.schema.ts' import { hostDescribeRequestSchema, hostDescribeValueSchema } from '../src/api/host.schema.ts' import { @@ -121,6 +121,28 @@ describe('sessions domain schemas', () => { expect(sessionListRequestSchema.parse({})).toEqual({}) expect(sessionListRequestSchema.parse({ cursor: 'c' }).cursor).toBe('c') expect(sessionListValueSchema.parse({ items: [] }).items).toEqual([]) + expect(sessionSearchRequestSchema.parse({ query: ' exact phrase ' })).toEqual({ query: 'exact phrase' }) + expect(() => sessionSearchRequestSchema.parse({ query: ' ' })).toThrow() + expect(() => sessionSearchRequestSchema.parse({ query: 'bad\0query' })).toThrow(/NUL/) + expect(() => sessionSearchRequestSchema.parse({ query: 'x'.repeat(501) })).toThrow() + expect(sessionSearchValueSchema.parse({ + items: [{ sessionId: 's1', snippet: 'matching text' }], + hasMore: true, + })).toEqual({ + items: [{ sessionId: 's1', snippet: 'matching text' }], + hasMore: true, + }) + expect(() => sessionSearchValueSchema.parse({ + items: [{ sessionId: '', snippet: 'matching text' }], + hasMore: false, + })).toThrow() + expect(() => sessionSearchValueSchema.parse({ + items: Array.from( + { length: 21 }, + (_, index) => ({ sessionId: `s${index}`, snippet: 'matching text' }), + ), + hasMore: true, + })).toThrow() expect(sessionCreateRequestSchema.parse({ cwd: '/w' }).cwd).toBe('/w') // The refine's both-sides branch: workspaceId alone passes, workspaceId+cwd rejects. expect(sessionCreateRequestSchema.parse({ workspaceId: 'w1', sessionId: 's1' }).sessionId).toBe('s1') diff --git a/packages/host/apiproxy/tsconfig.json b/packages/host/apiproxy/tsconfig.json index f5aabb1cf8..6327c74f5e 100644 --- a/packages/host/apiproxy/tsconfig.json +++ b/packages/host/apiproxy/tsconfig.json @@ -32,6 +32,9 @@ { "path": "../../session-persistence/session-persistence" }, + { + "path": "../../session-query/session-query" + }, { "path": "../../session-title/session-title" }, diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index a2e7b31fe0..80dfdc102a 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -221,6 +221,12 @@ importers: '@deepseek-ai/dsh-session-persistence-jsonl': specifier: workspace:^ version: link:../../packages/session-persistence/session-persistence-jsonl + '@deepseek-ai/dsh-session-query': + specifier: workspace:^ + version: link:../../packages/session-query/session-query + '@deepseek-ai/dsh-session-query-sqlite': + specifier: workspace:^ + version: link:../../packages/session-query/session-query-sqlite '@deepseek-ai/dsh-session-title': specifier: workspace:^ version: link:../../packages/session-title/session-title @@ -2559,6 +2565,9 @@ importers: '@deepseek-ai/dsh-session-persistence': specifier: workspace:^ version: link:../../session-persistence/session-persistence + '@deepseek-ai/dsh-session-query': + specifier: workspace:^ + version: link:../../session-query/session-query '@deepseek-ai/dsh-session-title': specifier: workspace:^ version: link:../../session-title/session-title From 222096e3cf50ea1fbe182f129caa96e942fa540d Mon Sep 17 00:00:00 2001 From: Hypatia May Date: Mon, 27 Jul 2026 12:27:11 +0800 Subject: [PATCH 003/139] fix(web): validate search hit provenance (round 2) --- .../lifecycle-chrome/hero.expected.md | 4 +- packages/host/apiproxy/src/api-proxy.ts | 12 ++++-- .../apiproxy/tests/api-proxy-search.spec.ts | 37 +++++++++++++++++++ 3 files changed, 47 insertions(+), 6 deletions(-) diff --git a/apps/web/tests/snapshots/lifecycle-chrome/hero.expected.md b/apps/web/tests/snapshots/lifecycle-chrome/hero.expected.md index f280e35fc6..39fc49c023 100644 --- a/apps/web/tests/snapshots/lifecycle-chrome/hero.expected.md +++ b/apps/web/tests/snapshots/lifecycle-chrome/hero.expected.md @@ -8,9 +8,9 @@ - img - button "Create workspace": - img -- button "Search sessions": +- button "搜索会话": - img -- textbox "Search name, keywords..." +- textbox "搜索名称或关键词…" - tree "Sessions": - treeitem "workspace 1 session" [expanded]: - img diff --git a/packages/host/apiproxy/src/api-proxy.ts b/packages/host/apiproxy/src/api-proxy.ts index a5055ef1d8..d6456acc67 100644 --- a/packages/host/apiproxy/src/api-proxy.ts +++ b/packages/host/apiproxy/src/api-proxy.ts @@ -630,10 +630,14 @@ export function createApiProxy(ctx: Context, defaults: ApiProxyDefaults): ApiPro limit: SESSION_SEARCH_LIMIT, }, { signal }) if (isAborted(signal)) return cancelled() - // The id filter is the authorization boundary. Re-check the provider - // projection before emitting it so a backend regression cannot leak - // a session that `session.list` withheld. - const authorized = page.items.filter(hit => visibleIds.has(hit.header.id)) + // The filters are the authorization boundary. Re-check the complete + // provider provenance before emitting its snippet so a backend + // regression cannot pair an allowed header with excluded content. + const authorized = page.items.filter(hit => + visibleIds.has(hit.header.id) + && hit.bestMatch.sessionId === hit.header.id + && hit.bestMatch.surface === 'current' + && MESSAGE_TYPES.has(hit.bestMatch.type)) return ok(request, { items: authorized.slice(0, SESSION_SEARCH_LIMIT).map(hit => ({ sessionId: hit.header.id, diff --git a/packages/host/apiproxy/tests/api-proxy-search.spec.ts b/packages/host/apiproxy/tests/api-proxy-search.spec.ts index 5f8060a696..fcb29fdbcc 100644 --- a/packages/host/apiproxy/tests/api-proxy-search.spec.ts +++ b/packages/host/apiproxy/tests/api-proxy-search.spec.ts @@ -160,6 +160,43 @@ describe('session.search', () => { expect(searchSessions).not.toHaveBeenCalled() }) + it('rejects snippets whose provider provenance violates the Host filters', async () => { + const ctx = await baseContext() + const visible = hit('visible') + ctx.sessions.create(visible.header.id, { meta: visible.header }) + const withBestMatch = ( + index: number, + bestMatch: Partial, + ): SessionSearchHit => { + const base = hit('visible', index) + return { ...base, bestMatch: { ...base.bestMatch, ...bestMatch } } + } + ctx.provide('sessionQuery', { + searchSessions: () => Promise.resolve({ + items: [ + withBestMatch(0, { sessionId: sid('hidden') }), + withBestMatch(1, { surface: 'shadowed' }), + withBestMatch(2, { type: 'tool/result' }), + withBestMatch(3, { type: 'steering/message', snippet: 'allowed snippet' }), + ], + nextCursor: 'more', + }), + } as never) + + const response = await createApiProxy(ctx, defaults).sessions.search( + request('match'), + new AbortController().signal, + ) + + expect(response.result).toEqual({ + ok: true, + value: { + items: [{ sessionId: 'visible', snippet: 'allowed snippet' }], + hasMore: true, + }, + }) + }) + it('enforces the 20-item Host boundary even if a provider overproduces', async () => { const ctx = await baseContext() const items = Array.from({ length: 21 }, (_, index) => hit(`visible-${index}`, index)) From 31215687f9e0a8eb390c1be26cb738e3555d01ef Mon Sep 17 00:00:00 2001 From: Hypatia May Date: Mon, 27 Jul 2026 12:42:46 +0800 Subject: [PATCH 004/139] fix(web): honor search ownership and cancellation --- .../2026-07-27-web-session-search.i18n.yaml | 4 +-- .../feature/2026-07-27-web-session-search.md | 4 +-- .../2026-07-27-web-session-search.zh.md | 4 +-- apps/cli/README.i18n.yaml | 4 +-- apps/cli/README.md | 2 +- apps/cli/README.zh.md | 2 +- apps/cli/cordis.yml | 8 +++-- packages/host/apiproxy/src/api-proxy.ts | 31 ++++++++++++++--- .../apiproxy/tests/api-proxy-search.spec.ts | 34 +++++++++++++++++++ 9 files changed, 75 insertions(+), 18 deletions(-) diff --git a/.agents/notes/implemented/feature/2026-07-27-web-session-search.i18n.yaml b/.agents/notes/implemented/feature/2026-07-27-web-session-search.i18n.yaml index 31d6b377af..1aa4dd3109 100644 --- a/.agents/notes/implemented/feature/2026-07-27-web-session-search.i18n.yaml +++ b/.agents/notes/implemented/feature/2026-07-27-web-session-search.i18n.yaml @@ -2,5 +2,5 @@ # side as of the last confirmed-consistent state. Both languages carry equal authority; # after editing either side, bring the other along and re-record with: # pnpm run verify-translation-pairing --write .agents/notes/implemented/feature/2026-07-27-web-session-search.md -2026-07-27-web-session-search.md: 3cc44ba3652415e9fa32ce67bceefc822c41059b -2026-07-27-web-session-search.zh.md: 2b6ea7a60e1b051757852ff331c0b93c48bd2b57 +2026-07-27-web-session-search.md: 421922d25bc61c1813a515e8439af0c7956b2efb +2026-07-27-web-session-search.zh.md: 04035e74fae718dbf65b294b4293d368ecc89cf7 diff --git a/.agents/notes/implemented/feature/2026-07-27-web-session-search.md b/.agents/notes/implemented/feature/2026-07-27-web-session-search.md index 3cc44ba365..421922d25b 100644 --- a/.agents/notes/implemented/feature/2026-07-27-web-session-search.md +++ b/.agents/notes/implemented/feature/2026-07-27-web-session-search.md @@ -10,9 +10,9 @@ The Web sidebar exposes session titles and Workspace membership but cannot retri ## Decision -The shared Web/headless composition mounts [`@deepseek-ai/dsh-session-query-sqlite`](../../../../packages/session-query/session-query-sqlite/README.md) at `.sessions/session-query.db`. Opening the database does not scan logs; the first content query lazily reconciles changed live and persisted sessions. The database is a disposable derived index, separate from canonical JSONL persistence. +The shared Web/headless composition mounts [`@deepseek-ai/dsh-session-query-sqlite`](../../../../packages/session-query/session-query-sqlite/README.md) at a process-owned `.sessions/session-query-.db` path. Process scoping preserves the SQLite backend's single-owner contract when multiple CLI or Web processes run from the same directory. Opening the database does not scan logs; the first content query lazily reconciles changed live and persisted sessions. The database is a disposable derived index, separate from canonical JSONL persistence. -The host gateway exposes `session.search` through the existing typed RPC stack. It derives the authorization set from the same visible summaries as `session.list`, passes those ids to `ctx.sessionQuery.searchSessions`, and restricts indexed matches to current-surface `user/message`, `assistant/message`, and `steering/message` events. The response is one page of at most 20 session ids and snippets; `hasMore` tells the UI to ask for a narrower query rather than exposing pagination. The carrier signal cancels superseded work. A missing query service or an indexing/query failure remains a business error and does not mutate the canonical session store. +The host gateway exposes `session.search` through the existing typed RPC stack. It derives the authorization set from the same visible summaries as `session.list`, passes those ids to `ctx.sessionQuery.searchSessions`, and restricts indexed matches to current-surface `user/message`, `assistant/message`, and `steering/message` events. The response is one page of at most 20 session ids and snippets; `hasMore` tells the UI to ask for a narrower query rather than exposing pagination. The carrier signal cancels superseded work, including the persistence listing and bounded batches of cold-session metadata stats that build the visibility set. A missing query service or an indexing/query failure remains a business error and does not mutate the canonical session store. [`WorkspaceBrowser`](../../../../packages/client/ui-workspace/README.md) keeps metadata and content search deliberately separate. A non-blank query immediately computes case-insensitive title and Workspace substring matches from the Session list, starts a 250 ms debounced content request, aborts the preceding request when the query changes, and ignores stale completions. It merges local matches first in recency order with backend-ranked content-only matches, deduplicates by session id, and renders a flat list regardless of the normal grouping mode. Each row shows the title, Workspace, and an available one-line snippet. Selecting a row opens the Session only and preserves the query; it does not navigate to an exact event. diff --git a/.agents/notes/implemented/feature/2026-07-27-web-session-search.zh.md b/.agents/notes/implemented/feature/2026-07-27-web-session-search.zh.md index 2b6ea7a60e..04035e74fa 100644 --- a/.agents/notes/implemented/feature/2026-07-27-web-session-search.zh.md +++ b/.agents/notes/implemented/feature/2026-07-27-web-session-search.zh.md @@ -10,9 +10,9 @@ Web 侧边栏会展示会话标题及其 Workspace 归属,但无法根据只 ## 决策 -Web 与 headless 共用的组合会在 `.sessions/session-query.db` 挂载 [`@deepseek-ai/dsh-session-query-sqlite`](../../../../packages/session-query/session-query-sqlite/README.md)。打开数据库时不会扫描日志;首次内容查询会惰性对齐发生变更的实时会话与持久化会话。该数据库是可丢弃的派生索引,与规范 JSONL 持久化相互独立。 +Web 与 headless 共用的组合会在由单一进程拥有的 `.sessions/session-query-.db` 路径挂载 [`@deepseek-ai/dsh-session-query-sqlite`](../../../../packages/session-query/session-query-sqlite/README.md)。当多个 CLI 或 Web 进程从同一目录运行时,进程级隔离可维持 SQLite 后端的单一所有者契约。打开数据库时不会扫描日志;首次内容查询会惰性对齐发生变更的实时会话与持久化会话。该数据库是可丢弃的派生索引,与规范 JSONL 持久化相互独立。 -宿主网关通过现有的类型化 RPC 栈公开 `session.search`。它根据 `session.list` 使用的同一组可见摘要推导授权集合,将这些 id 传给 `ctx.sessionQuery.searchSessions`,并将索引匹配限制为当前 surface 中的 `user/message`、`assistant/message` 和 `steering/message` 事件。响应只包含一页,最多 20 个会话 id 及其摘要片段;`hasMore` 会指示 UI 提示用户缩小查询范围,而不是公开分页能力。载体信号会取消已被取代的工作。查询服务缺失或索引、查询失败仍作为业务错误处理,不会修改规范会话存储。 +宿主网关通过现有的类型化 RPC 栈公开 `session.search`。它根据 `session.list` 使用的同一组可见摘要推导授权集合,将这些 id 传给 `ctx.sessionQuery.searchSessions`,并将索引匹配限制为当前 surface 中的 `user/message`、`assistant/message` 和 `steering/message` 事件。响应只包含一页,最多 20 个会话 id 及其摘要片段;`hasMore` 会指示 UI 提示用户缩小查询范围,而不是公开分页能力。载体信号会取消已被取代的工作,包括持久化列表枚举和构建可见集合时分批受限执行的冷会话元数据 stat。查询服务缺失或索引、查询失败仍作为业务错误处理,不会修改规范会话存储。 [`WorkspaceBrowser`](../../../../packages/client/ui-workspace/README.md) 有意将元数据搜索与内容搜索保持独立。非空白查询会立即从会话列表中计算不区分大小写的标题和 Workspace 子串匹配,在 250 ms 防抖后发起内容请求,在查询变化时中止前一请求,并忽略陈旧的完成结果。它先按新近程度排列本地匹配,再合并由后端排序且仅匹配内容的结果,按会话 id 去重;无论常规分组模式如何,最终都渲染为扁平列表。每一行显示标题、Workspace,并在存在时显示一行摘要片段。选择某一行只会打开对应会话,并保留查询条件;不会跳转至确切事件。 diff --git a/apps/cli/README.i18n.yaml b/apps/cli/README.i18n.yaml index e78ab7b8ad..5e6fb13cd9 100644 --- a/apps/cli/README.i18n.yaml +++ b/apps/cli/README.i18n.yaml @@ -2,5 +2,5 @@ # side as of the last confirmed-consistent state. Both languages carry equal authority; # after editing either side, bring the other along and re-record with: # pnpm run verify-translation-pairing --write apps/cli/README.md -README.md: bb3f4ee98700e4644535d1d3c05d29a9a558275d -README.zh.md: 44edea0f5b36598cfda1b61914da0b6622b973d6 +README.md: c1d76e42a6788f48c4dd01bbf71281e1081a411c +README.zh.md: 69bd88ca8fc7086c94017ac7d25ebd55e8585427 diff --git a/apps/cli/README.md b/apps/cli/README.md index bb3f4ee987..c1d76e42a6 100644 --- a/apps/cli/README.md +++ b/apps/cli/README.md @@ -14,7 +14,7 @@ The TUI surface: - tells the agent where its own source lives: after boot it adds a prompt section naming this harness checkout, resolved from the launcher's real path so it holds under a PATH symlink and an arbitrary cwd, so the self-referential `cordis` toolset can read and modify it; - applies the personal overlay from `~/.dsh` (see [app-boot's Personal config](../../packages/ui/app-boot/README.md#personal-config)): `.env` fills environment gaps (ambient > project `.env` > personal `.env`), `config.yaml` patches the booted tree. -The Web and headless surfaces boot one shared composition (`cordis.yml`): both treat the invoking directory as the default project and Workspace root, create named Workspaces beneath that root unless `--workspace-root ` overrides it, load applicable `AGENTS.md`/`CLAUDE.md` instructions into each agent-loop request prefix with a 65,536-byte render budget, opt into first-message model titles, and mount a disposable SQLite content index at `.sessions/session-query.db`. The index is opened without scanning at boot and lazily reconciles changed live and persisted logs on the first session search. Headless differs only in listening on an OS-assigned port (parallel `dsh -p` runs never collide; the stderr-printed URL opens the live session in a browser). Both need the frontend dist and client bundles built (`pnpm run build && pnpm run build:web`). +The Web and headless surfaces boot one shared composition (`cordis.yml`): both treat the invoking directory as the default project and Workspace root, create named Workspaces beneath that root unless `--workspace-root ` overrides it, load applicable `AGENTS.md`/`CLAUDE.md` instructions into each agent-loop request prefix with a 65,536-byte render budget, opt into first-message model titles, and mount a disposable, process-owned SQLite content index at `.sessions/session-query-.db`. The process-specific path preserves the backend's single-owner contract across parallel invocations. The index is opened without scanning at boot and lazily reconciles changed live and persisted logs on the first session search. Headless differs only in listening on an OS-assigned port (parallel `dsh -p` runs never collide; the stderr-printed URL opens the live session in a browser). Both need the frontend dist and client bundles built (`pnpm run build && pnpm run build:web`). `DSH_TOOLS_MODE` selects the tool presentation mode for the whole Web/headless process: `native` (the schema default when unset), `code` (the `run_code`-only Code Mode wire), or `both`; any other value fails loud at boot through the `dsh-tools` config schema. It is a TEMPORARY seam — process-wide because Loader composition is static — and is removed once the web UI owns per-session tool-mode selection; the TUI surface ignores it (its config tree pins its own mode). diff --git a/apps/cli/README.zh.md b/apps/cli/README.zh.md index 44edea0f5b..69bd88ca8f 100644 --- a/apps/cli/README.zh.md +++ b/apps/cli/README.zh.md @@ -14,7 +14,7 @@ TUI 界面: - 告知 agent 自身源码所在位置:启动后添加一个命名此 harness checkout 的提示词段。该路径从启动器的真实路径解析,因此在 PATH 符号链接和任意 cwd 下仍然有效,使自指的 `cordis` 工具集可以读取并修改它; - 应用 `~/.dsh` 中的个人覆盖(参见 [app-boot 的个人配置](../../packages/ui/app-boot/README.md#personal-config)):`.env` 填补环境缺口(环境中已有的值 > 项目 `.env` > 个人 `.env`),`config.yaml` 则修补已启动的树。 -Web 和无头界面启动同一个共享组合(`cordis.yml`):两者都将调用目录视为默认项目和 Workspace 根目录,除非通过 `--workspace-root ` 覆盖,否则会在该根目录下创建具名 Workspace;它们会把适用的 `AGENTS.md`/`CLAUDE.md` 指令加载到每个 agent-loop 请求前缀中,渲染预算为 65,536 字节,并选用首条消息模型标题,且在 `.sessions/session-query.db` 挂载一个可丢弃的 SQLite 内容索引。该索引在启动时不经扫描即打开,并在首次会话搜索时惰性对账已更改的实时日志和持久化日志。无头界面唯一的差异是监听操作系统分配的端口(并行 `dsh -p` 运行绝不冲突;stderr 打印的 URL 会在浏览器中打开实时会话)。两者都需要先构建前端 dist 和客户端 bundle(`pnpm run build && pnpm run build:web`)。 +Web 和无头界面启动同一个共享组合(`cordis.yml`):两者都将调用目录视为默认项目和 Workspace 根目录,除非通过 `--workspace-root ` 覆盖,否则会在该根目录下创建具名 Workspace;它们会把适用的 `AGENTS.md`/`CLAUDE.md` 指令加载到每个 agent-loop 请求前缀中,渲染预算为 65,536 字节,并选用首条消息模型标题,且在 `.sessions/session-query-.db` 挂载一个可丢弃、由单一进程拥有的 SQLite 内容索引。该进程专属路径可在并行调用时维持后端的单一所有者契约。该索引在启动时不经扫描即打开,并在首次会话搜索时惰性对账已更改的实时日志和持久化日志。无头界面唯一的差异是监听操作系统分配的端口(并行 `dsh -p` 运行绝不冲突;stderr 打印的 URL 会在浏览器中打开实时会话)。两者都需要先构建前端 dist 和客户端 bundle(`pnpm run build && pnpm run build:web`)。 `DSH_TOOLS_MODE` 为整个 Web/无头进程选择工具呈现模式:可选值为 `native`(未设置时的 schema 默认值)、`code`(仅含 `run_code` 的 Code Mode 协议接口)或 `both`;任何其他值都会经由 `dsh-tools` 配置 schema 在启动时明确报错。它是一个临时 seam:Loader 组合是静态的,因此该设置作用于整个进程;待 Web UI 负责逐会话工具模式选择后便会移除。TUI 界面会忽略该变量(其配置树固定了自身模式)。 diff --git a/apps/cli/cordis.yml b/apps/cli/cordis.yml index 4adb5048b8..be9303344d 100644 --- a/apps/cli/cordis.yml +++ b/apps/cli/cordis.yml @@ -89,12 +89,14 @@ config: root: './.sessions' -# Lazy content index for session.search. Opening the database at boot does -# not scan logs; the first search reconciles changed live/persisted sessions. +# Lazy, process-owned content index for session.search. Opening the database +# at boot does not scan logs; the first search reconciles changed +# live/persisted sessions. The pid prevents concurrent dsh processes in the +# same cwd from sharing one unsupported SQLite owner path. - id: session-query-sqlite name: '@deepseek-ai/dsh-session-query-sqlite' config: - path: './.sessions/session-query.db' + path: !!js "'./.sessions/session-query-' + process.pid + '.db'" - id: storage name: '@deepseek-ai/dsh-storage' diff --git a/packages/host/apiproxy/src/api-proxy.ts b/packages/host/apiproxy/src/api-proxy.ts index d6456acc67..367479e698 100644 --- a/packages/host/apiproxy/src/api-proxy.ts +++ b/packages/host/apiproxy/src/api-proxy.ts @@ -41,6 +41,9 @@ const DEFAULT_MAX_MESSAGES = 50 /** Product contract: sidebar search returns one bounded page and no cursor. */ const SESSION_SEARCH_LIMIT = 20 +/** Bound cold-log stat fan-out so an aborted search stops launching new work. */ +const COLD_SUMMARY_BATCH_SIZE = 16 + /** Surface message event types (the pagination counting unit). */ const MESSAGE_TYPES = new Set(['user/message', 'assistant/message', 'steering/message']) @@ -170,15 +173,22 @@ function summarize(session: Session, running: boolean): SessionSummary { * updatedAt is the log file's mtime; backends without a per-session file * (locate() undefined) fall back to the header's createdAt. */ -async function summarizeCold(persistence: SessionPersistence, meta: SessionHeader): Promise { +async function summarizeCold( + persistence: SessionPersistence, + meta: SessionHeader, + signal?: AbortSignal, +): Promise { + signal?.throwIfAborted() let updatedAt = meta.createdAt const location = persistence.locate(meta) + signal?.throwIfAborted() if (location !== undefined) { try { updatedAt = (await stat(location.path)).mtimeMs } catch { // The log vanished between list() and stat() (concurrent cleanup); createdAt stands in. } + signal?.throwIfAborted() } return { sessionId: meta.id, @@ -575,16 +585,27 @@ export function createApiProxy(ctx: Context, defaults: ApiProxyDefaults): ApiPro * Attached sessions come from memory; servable cold sessions merge from * persistence, and the final order is newest-first. */ - async function listVisibleSessionSummaries(): Promise { + async function listVisibleSessionSummaries(signal?: AbortSignal): Promise { + signal?.throwIfAborted() const items = ctx.sessions.list().map((session) => { const agent = ctx.agents.get(session.id) return summarize(session, agent?.status === 'running') }) + signal?.throwIfAborted() const attached = new Set(items.map(item => item.sessionId)) const persistence = ctx.get('sessionPersistence') if (persistence !== undefined) { - const cold = (await persistence.list()).filter(meta => !attached.has(meta.id) && meta.cwd !== undefined) - items.push(...await Promise.all(cold.map(meta => summarizeCold(persistence, meta)))) + const cold = (await persistence.list(signal)) + .filter(meta => !attached.has(meta.id) && meta.cwd !== undefined) + signal?.throwIfAborted() + for (let offset = 0; offset < cold.length; offset += COLD_SUMMARY_BATCH_SIZE) { + signal?.throwIfAborted() + const batch = cold.slice(offset, offset + COLD_SUMMARY_BATCH_SIZE) + items.push(...await Promise.all( + batch.map(meta => summarizeCold(persistence, meta, signal)), + )) + signal?.throwIfAborted() + } } items.sort((a, b) => b.updatedAt - a.updatedAt) return items @@ -616,7 +637,7 @@ export function createApiProxy(ctx: Context, defaults: ApiProxyDefaults): ApiPro }) } try { - const visible = await listVisibleSessionSummaries() + const visible = await listVisibleSessionSummaries(signal) if (isAborted(signal)) return cancelled() if (visible.length === 0) return ok(request, { items: [], hasMore: false }) const visibleIds = new Set(visible.map(item => item.sessionId)) diff --git a/packages/host/apiproxy/tests/api-proxy-search.spec.ts b/packages/host/apiproxy/tests/api-proxy-search.spec.ts index fcb29fdbcc..99f40a5949 100644 --- a/packages/host/apiproxy/tests/api-proxy-search.spec.ts +++ b/packages/host/apiproxy/tests/api-proxy-search.spec.ts @@ -220,6 +220,40 @@ describe('session.search', () => { expect(response.result.value.items.at(-1)?.sessionId).toBe('visible-19') }) + it('propagates cancellation through visible-session collection and stops cold-summary work', async () => { + const ctx = await baseContext() + const controller = new AbortController() + const cold = Array.from({ length: 32 }, (_, index) => header(`cold-${index}`, `/cold-${index}`)) + const list = vi.fn((signal?: AbortSignal) => { + expect(signal).toBe(controller.signal) + return Promise.resolve(cold) + }) + let locateCalls = 0 + ctx.provide('sessionPersistence', { + list, + locate: () => { + locateCalls++ + controller.abort() + return undefined + }, + } as never) + const searchSessions = vi.fn() + ctx.provide('sessionQuery', { searchSessions } as never) + + const response = await createApiProxy(ctx, defaults).sessions.search( + request('cancel-during-visibility'), + controller.signal, + ) + + expect(response.result).toMatchObject({ + ok: false, + error: { code: 'cancelled' }, + }) + expect(list).toHaveBeenCalledOnce() + expect(locateCalls).toBe(1) + expect(searchSessions).not.toHaveBeenCalled() + }) + it('maps missing composition, query cancellation, and provider failure', async () => { const missingCtx = await baseContext() missingCtx.sessions.create(sid('visible'), { meta: header('visible') }) From bd42204e53d38af428c7c5985207dc91503a36bf Mon Sep 17 00:00:00 2001 From: Hypatia May Date: Mon, 27 Jul 2026 12:51:47 +0800 Subject: [PATCH 005/139] fix(cli): keep search index ephemeral --- .../feature/2026-07-27-web-session-search.i18n.yaml | 4 ++-- .../implemented/feature/2026-07-27-web-session-search.md | 2 +- .../feature/2026-07-27-web-session-search.zh.md | 2 +- apps/cli/README.i18n.yaml | 4 ++-- apps/cli/README.md | 2 +- apps/cli/README.zh.md | 2 +- apps/cli/cordis.yml | 9 ++++----- apps/web/tests/scaffold.ts | 2 +- docs/config-catalog.md | 6 +++--- packages/session-query/session-query-sqlite/src/index.ts | 6 +++--- 10 files changed, 19 insertions(+), 20 deletions(-) diff --git a/.agents/notes/implemented/feature/2026-07-27-web-session-search.i18n.yaml b/.agents/notes/implemented/feature/2026-07-27-web-session-search.i18n.yaml index 1aa4dd3109..1dfb037886 100644 --- a/.agents/notes/implemented/feature/2026-07-27-web-session-search.i18n.yaml +++ b/.agents/notes/implemented/feature/2026-07-27-web-session-search.i18n.yaml @@ -2,5 +2,5 @@ # side as of the last confirmed-consistent state. Both languages carry equal authority; # after editing either side, bring the other along and re-record with: # pnpm run verify-translation-pairing --write .agents/notes/implemented/feature/2026-07-27-web-session-search.md -2026-07-27-web-session-search.md: 421922d25bc61c1813a515e8439af0c7956b2efb -2026-07-27-web-session-search.zh.md: 04035e74fae718dbf65b294b4293d368ecc89cf7 +2026-07-27-web-session-search.md: 8791d02249cc310e768712b3967dcfead3a950e0 +2026-07-27-web-session-search.zh.md: 737f91fbe2c00ac5aa75fb6c30b8b22f80b0854f diff --git a/.agents/notes/implemented/feature/2026-07-27-web-session-search.md b/.agents/notes/implemented/feature/2026-07-27-web-session-search.md index 421922d25b..8791d02249 100644 --- a/.agents/notes/implemented/feature/2026-07-27-web-session-search.md +++ b/.agents/notes/implemented/feature/2026-07-27-web-session-search.md @@ -10,7 +10,7 @@ The Web sidebar exposes session titles and Workspace membership but cannot retri ## Decision -The shared Web/headless composition mounts [`@deepseek-ai/dsh-session-query-sqlite`](../../../../packages/session-query/session-query-sqlite/README.md) at a process-owned `.sessions/session-query-.db` path. Process scoping preserves the SQLite backend's single-owner contract when multiple CLI or Web processes run from the same directory. Opening the database does not scan logs; the first content query lazily reconciles changed live and persisted sessions. The database is a disposable derived index, separate from canonical JSONL persistence. +The shared Web/headless composition mounts [`@deepseek-ai/dsh-session-query-sqlite`](../../../../packages/session-query/session-query-sqlite/README.md) with an in-memory database. Each service instance owns one connection-private index, preserving the SQLite backend's single-owner contract across parallel CLI or Web invocations without leaving process-scoped derived files behind. The database starts empty; the first content query of each invocation lazily reconciles live and persisted sessions. It remains a disposable derived index, separate from canonical JSONL persistence. The host gateway exposes `session.search` through the existing typed RPC stack. It derives the authorization set from the same visible summaries as `session.list`, passes those ids to `ctx.sessionQuery.searchSessions`, and restricts indexed matches to current-surface `user/message`, `assistant/message`, and `steering/message` events. The response is one page of at most 20 session ids and snippets; `hasMore` tells the UI to ask for a narrower query rather than exposing pagination. The carrier signal cancels superseded work, including the persistence listing and bounded batches of cold-session metadata stats that build the visibility set. A missing query service or an indexing/query failure remains a business error and does not mutate the canonical session store. diff --git a/.agents/notes/implemented/feature/2026-07-27-web-session-search.zh.md b/.agents/notes/implemented/feature/2026-07-27-web-session-search.zh.md index 04035e74fa..737f91fbe2 100644 --- a/.agents/notes/implemented/feature/2026-07-27-web-session-search.zh.md +++ b/.agents/notes/implemented/feature/2026-07-27-web-session-search.zh.md @@ -10,7 +10,7 @@ Web 侧边栏会展示会话标题及其 Workspace 归属,但无法根据只 ## 决策 -Web 与 headless 共用的组合会在由单一进程拥有的 `.sessions/session-query-.db` 路径挂载 [`@deepseek-ai/dsh-session-query-sqlite`](../../../../packages/session-query/session-query-sqlite/README.md)。当多个 CLI 或 Web 进程从同一目录运行时,进程级隔离可维持 SQLite 后端的单一所有者契约。打开数据库时不会扫描日志;首次内容查询会惰性对齐发生变更的实时会话与持久化会话。该数据库是可丢弃的派生索引,与规范 JSONL 持久化相互独立。 +Web 与 headless 共用的组合会使用内存数据库挂载 [`@deepseek-ai/dsh-session-query-sqlite`](../../../../packages/session-query/session-query-sqlite/README.md)。每个服务实例都独占一个连接私有索引,因此并行 CLI 或 Web 调用可维持 SQLite 后端的单一所有者契约,又不会留下进程级派生文件。数据库从空状态启动;每次调用的首次内容查询会惰性对齐实时会话与持久化会话。它仍是与规范 JSONL 持久化相互独立的可丢弃派生索引。 宿主网关通过现有的类型化 RPC 栈公开 `session.search`。它根据 `session.list` 使用的同一组可见摘要推导授权集合,将这些 id 传给 `ctx.sessionQuery.searchSessions`,并将索引匹配限制为当前 surface 中的 `user/message`、`assistant/message` 和 `steering/message` 事件。响应只包含一页,最多 20 个会话 id 及其摘要片段;`hasMore` 会指示 UI 提示用户缩小查询范围,而不是公开分页能力。载体信号会取消已被取代的工作,包括持久化列表枚举和构建可见集合时分批受限执行的冷会话元数据 stat。查询服务缺失或索引、查询失败仍作为业务错误处理,不会修改规范会话存储。 diff --git a/apps/cli/README.i18n.yaml b/apps/cli/README.i18n.yaml index 5e6fb13cd9..9a5db218c0 100644 --- a/apps/cli/README.i18n.yaml +++ b/apps/cli/README.i18n.yaml @@ -2,5 +2,5 @@ # side as of the last confirmed-consistent state. Both languages carry equal authority; # after editing either side, bring the other along and re-record with: # pnpm run verify-translation-pairing --write apps/cli/README.md -README.md: c1d76e42a6788f48c4dd01bbf71281e1081a411c -README.zh.md: 69bd88ca8fc7086c94017ac7d25ebd55e8585427 +README.md: 0c4ff8d36a89e234512f42d130774fe3717968b9 +README.zh.md: 7e116ecb32061060816f27279a5d3b555a584f6b diff --git a/apps/cli/README.md b/apps/cli/README.md index c1d76e42a6..0c4ff8d36a 100644 --- a/apps/cli/README.md +++ b/apps/cli/README.md @@ -14,7 +14,7 @@ The TUI surface: - tells the agent where its own source lives: after boot it adds a prompt section naming this harness checkout, resolved from the launcher's real path so it holds under a PATH symlink and an arbitrary cwd, so the self-referential `cordis` toolset can read and modify it; - applies the personal overlay from `~/.dsh` (see [app-boot's Personal config](../../packages/ui/app-boot/README.md#personal-config)): `.env` fills environment gaps (ambient > project `.env` > personal `.env`), `config.yaml` patches the booted tree. -The Web and headless surfaces boot one shared composition (`cordis.yml`): both treat the invoking directory as the default project and Workspace root, create named Workspaces beneath that root unless `--workspace-root ` overrides it, load applicable `AGENTS.md`/`CLAUDE.md` instructions into each agent-loop request prefix with a 65,536-byte render budget, opt into first-message model titles, and mount a disposable, process-owned SQLite content index at `.sessions/session-query-.db`. The process-specific path preserves the backend's single-owner contract across parallel invocations. The index is opened without scanning at boot and lazily reconciles changed live and persisted logs on the first session search. Headless differs only in listening on an OS-assigned port (parallel `dsh -p` runs never collide; the stderr-printed URL opens the live session in a browser). Both need the frontend dist and client bundles built (`pnpm run build && pnpm run build:web`). +The Web and headless surfaces boot one shared composition (`cordis.yml`): both treat the invoking directory as the default project and Workspace root, create named Workspaces beneath that root unless `--workspace-root ` overrides it, load applicable `AGENTS.md`/`CLAUDE.md` instructions into each agent-loop request prefix with a 65,536-byte render budget, opt into first-message model titles, and mount a disposable in-memory SQLite content index. Each service instance owns its database, so parallel invocations neither share unsupported SQLite state nor leave derived index files behind. The index starts empty and lazily reconciles live and persisted logs on the first session search of each invocation. Headless differs only in listening on an OS-assigned port (parallel `dsh -p` runs never collide; the stderr-printed URL opens the live session in a browser). Both need the frontend dist and client bundles built (`pnpm run build && pnpm run build:web`). `DSH_TOOLS_MODE` selects the tool presentation mode for the whole Web/headless process: `native` (the schema default when unset), `code` (the `run_code`-only Code Mode wire), or `both`; any other value fails loud at boot through the `dsh-tools` config schema. It is a TEMPORARY seam — process-wide because Loader composition is static — and is removed once the web UI owns per-session tool-mode selection; the TUI surface ignores it (its config tree pins its own mode). diff --git a/apps/cli/README.zh.md b/apps/cli/README.zh.md index 69bd88ca8f..7e116ecb32 100644 --- a/apps/cli/README.zh.md +++ b/apps/cli/README.zh.md @@ -14,7 +14,7 @@ TUI 界面: - 告知 agent 自身源码所在位置:启动后添加一个命名此 harness checkout 的提示词段。该路径从启动器的真实路径解析,因此在 PATH 符号链接和任意 cwd 下仍然有效,使自指的 `cordis` 工具集可以读取并修改它; - 应用 `~/.dsh` 中的个人覆盖(参见 [app-boot 的个人配置](../../packages/ui/app-boot/README.md#personal-config)):`.env` 填补环境缺口(环境中已有的值 > 项目 `.env` > 个人 `.env`),`config.yaml` 则修补已启动的树。 -Web 和无头界面启动同一个共享组合(`cordis.yml`):两者都将调用目录视为默认项目和 Workspace 根目录,除非通过 `--workspace-root ` 覆盖,否则会在该根目录下创建具名 Workspace;它们会把适用的 `AGENTS.md`/`CLAUDE.md` 指令加载到每个 agent-loop 请求前缀中,渲染预算为 65,536 字节,并选用首条消息模型标题,且在 `.sessions/session-query-.db` 挂载一个可丢弃、由单一进程拥有的 SQLite 内容索引。该进程专属路径可在并行调用时维持后端的单一所有者契约。该索引在启动时不经扫描即打开,并在首次会话搜索时惰性对账已更改的实时日志和持久化日志。无头界面唯一的差异是监听操作系统分配的端口(并行 `dsh -p` 运行绝不冲突;stderr 打印的 URL 会在浏览器中打开实时会话)。两者都需要先构建前端 dist 和客户端 bundle(`pnpm run build && pnpm run build:web`)。 +Web 和无头界面启动同一个共享组合(`cordis.yml`):两者都将调用目录视为默认项目和 Workspace 根目录,除非通过 `--workspace-root ` 覆盖,否则会在该根目录下创建具名 Workspace;它们会把适用的 `AGENTS.md`/`CLAUDE.md` 指令加载到每个 agent-loop 请求前缀中,渲染预算为 65,536 字节,并选用首条消息模型标题,且挂载一个可丢弃的内存 SQLite 内容索引。每个服务实例独占自己的数据库,因此并行调用既不会共享不受支持的 SQLite 状态,也不会留下派生索引文件。该索引从空状态启动,并在每次调用的首次会话搜索时惰性对账实时日志与持久化日志。无头界面唯一的差异是监听操作系统分配的端口(并行 `dsh -p` 运行绝不冲突;stderr 打印的 URL 会在浏览器中打开实时会话)。两者都需要先构建前端 dist 和客户端 bundle(`pnpm run build && pnpm run build:web`)。 `DSH_TOOLS_MODE` 为整个 Web/无头进程选择工具呈现模式:可选值为 `native`(未设置时的 schema 默认值)、`code`(仅含 `run_code` 的 Code Mode 协议接口)或 `both`;任何其他值都会经由 `dsh-tools` 配置 schema 在启动时明确报错。它是一个临时 seam:Loader 组合是静态的,因此该设置作用于整个进程;待 Web UI 负责逐会话工具模式选择后便会移除。TUI 界面会忽略该变量(其配置树固定了自身模式)。 diff --git a/apps/cli/cordis.yml b/apps/cli/cordis.yml index be9303344d..35979b274f 100644 --- a/apps/cli/cordis.yml +++ b/apps/cli/cordis.yml @@ -89,14 +89,13 @@ config: root: './.sessions' -# Lazy, process-owned content index for session.search. Opening the database -# at boot does not scan logs; the first search reconciles changed -# live/persisted sessions. The pid prevents concurrent dsh processes in the -# same cwd from sharing one unsupported SQLite owner path. +# Lazy, service-owned content index for session.search. The in-memory database +# cannot be shared across processes or leak derived files across invocations; +# the first search reconciles changed live/persisted sessions for this boot. - id: session-query-sqlite name: '@deepseek-ai/dsh-session-query-sqlite' config: - path: !!js "'./.sessions/session-query-' + process.pid + '.db'" + path: ':memory:' - id: storage name: '@deepseek-ai/dsh-storage' diff --git a/apps/web/tests/scaffold.ts b/apps/web/tests/scaffold.ts index f809081d3d..eb61619de0 100644 --- a/apps/web/tests/scaffold.ts +++ b/apps/web/tests/scaffold.ts @@ -163,7 +163,7 @@ export async function launchWebScaffold(options: LaunchOptions = {}): Promise Date: Mon, 27 Jul 2026 13:05:59 +0800 Subject: [PATCH 006/139] fix(web): support large search corpora (round 4) --- .../2026-07-27-web-session-search.i18n.yaml | 4 +- .../feature/2026-07-27-web-session-search.md | 2 +- .../2026-07-27-web-session-search.zh.md | 2 +- packages/host/apiproxy/README.i18n.yaml | 4 +- packages/host/apiproxy/README.md | 2 +- packages/host/apiproxy/README.zh.md | 2 +- packages/host/apiproxy/src/api-proxy.ts | 69 ++++++++++++------- .../apiproxy/tests/api-proxy-search.spec.ts | 50 ++++++++++++-- 8 files changed, 96 insertions(+), 39 deletions(-) diff --git a/.agents/notes/implemented/feature/2026-07-27-web-session-search.i18n.yaml b/.agents/notes/implemented/feature/2026-07-27-web-session-search.i18n.yaml index 1dfb037886..721f0f9483 100644 --- a/.agents/notes/implemented/feature/2026-07-27-web-session-search.i18n.yaml +++ b/.agents/notes/implemented/feature/2026-07-27-web-session-search.i18n.yaml @@ -2,5 +2,5 @@ # side as of the last confirmed-consistent state. Both languages carry equal authority; # after editing either side, bring the other along and re-record with: # pnpm run verify-translation-pairing --write .agents/notes/implemented/feature/2026-07-27-web-session-search.md -2026-07-27-web-session-search.md: 8791d02249cc310e768712b3967dcfead3a950e0 -2026-07-27-web-session-search.zh.md: 737f91fbe2c00ac5aa75fb6c30b8b22f80b0854f +2026-07-27-web-session-search.md: e3219f865aa3f13cdb7e806570ef6134dd5bd448 +2026-07-27-web-session-search.zh.md: 27d0efee5d218c2e737fb7378d3fd71c6b13e4ce diff --git a/.agents/notes/implemented/feature/2026-07-27-web-session-search.md b/.agents/notes/implemented/feature/2026-07-27-web-session-search.md index 8791d02249..e3219f865a 100644 --- a/.agents/notes/implemented/feature/2026-07-27-web-session-search.md +++ b/.agents/notes/implemented/feature/2026-07-27-web-session-search.md @@ -12,7 +12,7 @@ The Web sidebar exposes session titles and Workspace membership but cannot retri The shared Web/headless composition mounts [`@deepseek-ai/dsh-session-query-sqlite`](../../../../packages/session-query/session-query-sqlite/README.md) with an in-memory database. Each service instance owns one connection-private index, preserving the SQLite backend's single-owner contract across parallel CLI or Web invocations without leaving process-scoped derived files behind. The database starts empty; the first content query of each invocation lazily reconciles live and persisted sessions. It remains a disposable derived index, separate from canonical JSONL persistence. -The host gateway exposes `session.search` through the existing typed RPC stack. It derives the authorization set from the same visible summaries as `session.list`, passes those ids to `ctx.sessionQuery.searchSessions`, and restricts indexed matches to current-surface `user/message`, `assistant/message`, and `steering/message` events. The response is one page of at most 20 session ids and snippets; `hasMore` tells the UI to ask for a narrower query rather than exposing pagination. The carrier signal cancels superseded work, including the persistence listing and bounded batches of cold-session metadata stats that build the visibility set. A missing query service or an indexing/query failure remains a business error and does not mutate the canonical session store. +The host gateway exposes `session.search` through the existing typed RPC stack. It derives the authorization set from the same visible summaries as `session.list`, asks `ctx.sessionQuery.searchSessions` for globally ranked current-surface `user/message`, `assistant/message`, and `steering/message` matches, and consumes provider pages until it has 20 authorized sessions plus one lookahead or exhausts the stream. Every hit's session id, best-match session id, surface, and event type are revalidated before its snippet leaves the Host. Keeping the potentially large authorization set out of SQLite bindings avoids the portable variable ceiling while preserving global ranking. The response remains one bounded page; `hasMore` tells the UI to ask for a narrower query rather than exposing pagination. The carrier signal cancels superseded work, including persistence listing, bounded batches of cold-session metadata stats, and each provider page. A missing query service or an indexing/query failure remains a business error and does not mutate the canonical session store. [`WorkspaceBrowser`](../../../../packages/client/ui-workspace/README.md) keeps metadata and content search deliberately separate. A non-blank query immediately computes case-insensitive title and Workspace substring matches from the Session list, starts a 250 ms debounced content request, aborts the preceding request when the query changes, and ignores stale completions. It merges local matches first in recency order with backend-ranked content-only matches, deduplicates by session id, and renders a flat list regardless of the normal grouping mode. Each row shows the title, Workspace, and an available one-line snippet. Selecting a row opens the Session only and preserves the query; it does not navigate to an exact event. diff --git a/.agents/notes/implemented/feature/2026-07-27-web-session-search.zh.md b/.agents/notes/implemented/feature/2026-07-27-web-session-search.zh.md index 737f91fbe2..27d0efee5d 100644 --- a/.agents/notes/implemented/feature/2026-07-27-web-session-search.zh.md +++ b/.agents/notes/implemented/feature/2026-07-27-web-session-search.zh.md @@ -12,7 +12,7 @@ Web 侧边栏会展示会话标题及其 Workspace 归属,但无法根据只 Web 与 headless 共用的组合会使用内存数据库挂载 [`@deepseek-ai/dsh-session-query-sqlite`](../../../../packages/session-query/session-query-sqlite/README.md)。每个服务实例都独占一个连接私有索引,因此并行 CLI 或 Web 调用可维持 SQLite 后端的单一所有者契约,又不会留下进程级派生文件。数据库从空状态启动;每次调用的首次内容查询会惰性对齐实时会话与持久化会话。它仍是与规范 JSONL 持久化相互独立的可丢弃派生索引。 -宿主网关通过现有的类型化 RPC 栈公开 `session.search`。它根据 `session.list` 使用的同一组可见摘要推导授权集合,将这些 id 传给 `ctx.sessionQuery.searchSessions`,并将索引匹配限制为当前 surface 中的 `user/message`、`assistant/message` 和 `steering/message` 事件。响应只包含一页,最多 20 个会话 id 及其摘要片段;`hasMore` 会指示 UI 提示用户缩小查询范围,而不是公开分页能力。载体信号会取消已被取代的工作,包括持久化列表枚举和构建可见集合时分批受限执行的冷会话元数据 stat。查询服务缺失或索引、查询失败仍作为业务错误处理,不会修改规范会话存储。 +宿主网关通过现有的类型化 RPC 栈公开 `session.search`。它根据 `session.list` 使用的同一组可见摘要推导授权集合,向 `ctx.sessionQuery.searchSessions` 请求全局排序后的当前 surface `user/message`、`assistant/message` 和 `steering/message` 匹配项,并持续消费提供方分页,直到获得 20 个已授权会话及一个前瞻项,或结果流耗尽。每个命中的会话 id、最佳匹配会话 id、surface 和事件类型都会经过重新校验,其 snippet 才能离开宿主。将可能很大的授权集合排除在 SQLite 绑定之外,可避开可移植变量上限,同时保持全局排序。响应仍只有一个有界页面;`hasMore` 会指示 UI 提示用户缩小查询范围,而不是公开分页能力。载体信号会取消已被取代的工作,包括持久化列表枚举、分批受限执行的冷会话元数据 stat,以及每一页提供方搜索。查询服务缺失或索引、查询失败仍作为业务错误处理,不会修改规范会话存储。 [`WorkspaceBrowser`](../../../../packages/client/ui-workspace/README.md) 有意将元数据搜索与内容搜索保持独立。非空白查询会立即从会话列表中计算不区分大小写的标题和 Workspace 子串匹配,在 250 ms 防抖后发起内容请求,在查询变化时中止前一请求,并忽略陈旧的完成结果。它先按新近程度排列本地匹配,再合并由后端排序且仅匹配内容的结果,按会话 id 去重;无论常规分组模式如何,最终都渲染为扁平列表。每一行显示标题、Workspace,并在存在时显示一行摘要片段。选择某一行只会打开对应会话,并保留查询条件;不会跳转至确切事件。 diff --git a/packages/host/apiproxy/README.i18n.yaml b/packages/host/apiproxy/README.i18n.yaml index 7d323dbeea..5079e05965 100644 --- a/packages/host/apiproxy/README.i18n.yaml +++ b/packages/host/apiproxy/README.i18n.yaml @@ -2,5 +2,5 @@ # side as of the last confirmed-consistent state. Both languages carry equal authority; # after editing either side, bring the other along and re-record with: # pnpm run verify-translation-pairing --write packages/host/apiproxy/README.md -README.md: deb1073c2ff9e7a533e595ee3f5537e649660e5b -README.zh.md: e3c521d5f6a09414d087e3fb142852e6d3eb0cb7 +README.md: b9f0fcd8506afda733774868d78fe6e851b4fe2a +README.zh.md: c57990b029b8d1e143396bb13718dbed165e2b47 diff --git a/packages/host/apiproxy/README.md b/packages/host/apiproxy/README.md index deb1073c2f..b9f0fcd850 100644 --- a/packages/host/apiproxy/README.md +++ b/packages/host/apiproxy/README.md @@ -14,7 +14,7 @@ The mux stream projects the latest log-backed title as a validated `session/titl Workspace and Session lists are separate reconnect baselines. `workspace.create` creates a unique name or adopts an existing directory, `session.create` accepts an optional preallocated Session id, and `host/workspace-changed` plus `host/session-added` carry committed increments in either arrival order. `SessionSummary.blank` and the `host/session-added` frame carry the derived zero-events bit: clients hide blank sessions and reuse them per workspace, flip blank on the first `host/session-status(running:true)`, and treat `session.list` as the reconnect authority; cold summaries are never blank because lazy persistence keeps never-appended sessions out of `list()`. -`session.search` is a bounded content-search projection over the sessions visible through `session.list`. The gateway passes only those session ids and current-surface user, assistant, and steering messages to the optional `ctx.sessionQuery` service, returns at most 20 session/snippet pairs plus a refine-query bit, and forwards the carrier request signal for cancellation. A deployment without the service, or a failed index/query operation, returns an `internal` business error so clients can retain metadata-only matches. +`session.search` is a bounded content-search projection over the sessions visible through `session.list`. The gateway asks the optional `ctx.sessionQuery` service for globally ranked current-surface user, assistant, and steering matches, pages that stream until it has at most 20 visible session/snippet pairs plus one lookahead, and revalidates every hit against the list-derived authorization set before returning it. Keeping the authorization set in Host memory avoids SQLite's variable ceiling for large valid corpora without weakening visibility or ranking. The carrier request signal cancels persistence listing, cold-summary collection, and every search page. A deployment without the service, or a failed index/query operation, returns an `internal` business error so clients can retain metadata-only matches. The `command.*` and `skill.*` domains expose the host command registry and skill catalog to clients. Every method addresses one session's agent by `sessionId` (a served session always has an Agent; `command.*` resumes cold sessions through the same path as `session.*`, while `skill.list` resolves the project root from the session header without touching the Agent registry). `command.execute` runs a slash-command line host-side and returns a detached result; the carrier's request signal cancels the running handler. `host/commands-changed` is the catalog invalidation frame: clients refetch `command.list` instead of diffing. diff --git a/packages/host/apiproxy/README.zh.md b/packages/host/apiproxy/README.zh.md index e3c521d5f6..c57990b029 100644 --- a/packages/host/apiproxy/README.zh.md +++ b/packages/host/apiproxy/README.zh.md @@ -14,7 +14,7 @@ mux 流会在每个已附加会话的订阅基线之后,以及对应的实时 Workspace 列表与 Session 列表是相互独立的重连基线。`workspace.create` 会创建唯一名称或接纳现有目录,`session.create` 接受可选的预分配 Session id,`host/workspace-changed` 与 `host/session-added` 则以任意到达顺序携带已提交的增量。`SessionSummary.blank` 与 `host/session-added` 帧携带派生的零事件位:客户端隐藏空白会话并按 workspace 复用它们,在首个 `host/session-status(running:true)` 时翻转 blank,并以 `session.list` 作为重连权威;冷会话摘要永远不是空白——惰性持久化让从未追加过事件的会话根本不出现在 `list()` 中。 -`session.search` 是以 `session.list` 所列会话为范围的有界内容搜索投影。网关仅将这些会话 id 以及当前表层中的 user、assistant 和 steering(中途引导)消息传给可选的 `ctx.sessionQuery` 服务,返回至多 20 个会话/snippet 对和一个提示细化查询的标志位,并转发载体请求信号以支持取消。部署若未挂载该服务,或索引/查询操作失败,都会返回 `internal` 业务错误,以便客户端保留仅基于元数据的匹配项。 +`session.search` 是以 `session.list` 所列会话为范围的有界内容搜索投影。网关向可选的 `ctx.sessionQuery` 服务请求全局排序后的当前 surface user、assistant 和 steering(中途引导)匹配项,对该结果流分页,直到获得至多 20 个可见会话/snippet 对及一个前瞻项,并在返回前依据从列表推导的授权集合重新校验每个命中。将授权集合保留在宿主内存中,可在不削弱可见性或排序的前提下避开有效大型语料库的 SQLite 变量上限。载体请求信号可取消持久化列表枚举、冷会话摘要收集和每一页搜索。部署若未挂载该服务,或索引/查询操作失败,都会返回 `internal` 业务错误,以便客户端保留仅基于元数据的匹配项。 `command.*` 与 `skill.*` 领域向客户端暴露宿主命令注册表和技能目录。每个方法都通过 `sessionId` 寻址一个会话的 Agent(被服务的会话必有 Agent;`command.*` 经由与 `session.*` 相同的路径恢复冷会话,而 `skill.list` 从会话头解析项目根目录,不触碰 Agent 注册表)。`command.execute` 在宿主侧运行一条斜杠命令行并返回脱耦结果;载体的请求信号可取消正在运行的处理器。`host/commands-changed` 是目录失效帧:客户端重新拉取 `command.list` 而不是做差分。 diff --git a/packages/host/apiproxy/src/api-proxy.ts b/packages/host/apiproxy/src/api-proxy.ts index 367479e698..c9329feea8 100644 --- a/packages/host/apiproxy/src/api-proxy.ts +++ b/packages/host/apiproxy/src/api-proxy.ts @@ -11,7 +11,7 @@ import type { Agent, AgentMessage, AgentMessageId, AgentStatus } from '@deepseek import type { ContentBlock, MessageSource } from '@deepseek-ai/dsh-llm' import type { JsonValue, Session, SessionEvent, SessionHeader, SessionId } from '@deepseek-ai/dsh-session' import type { SessionPersistence } from '@deepseek-ai/dsh-session-persistence' -import { SessionQueryError } from '@deepseek-ai/dsh-session-query' +import { SessionQueryError, type SessionSearchCursor } from '@deepseek-ai/dsh-session-query' import { foldSessionTitle } from '@deepseek-ai/dsh-session-title' import type { Workspace, WorkspaceRecord } from '@deepseek-ai/dsh-workspace' import { @@ -641,30 +641,51 @@ export function createApiProxy(ctx: Context, defaults: ApiProxyDefaults): ApiPro if (isAborted(signal)) return cancelled() if (visible.length === 0) return ok(request, { items: [], hasMore: false }) const visibleIds = new Set(visible.map(item => item.sessionId)) - const page = await sessionQuery.searchSessions({ - query: request.payload.query, - sessionFilters: [{ kind: 'id', values: [...visibleIds] }], - eventFilters: [ - { kind: 'type', values: ['user/message', 'assistant/message', 'steering/message'] }, - { kind: 'surface', values: ['current'] }, - ], - limit: SESSION_SEARCH_LIMIT, - }, { signal }) - if (isAborted(signal)) return cancelled() - // The filters are the authorization boundary. Re-check the complete - // provider provenance before emitting its snippet so a backend - // regression cannot pair an allowed header with excluded content. - const authorized = page.items.filter(hit => - visibleIds.has(hit.header.id) - && hit.bestMatch.sessionId === hit.header.id - && hit.bestMatch.surface === 'current' - && MESSAGE_TYPES.has(hit.bestMatch.type)) + const authorized: SessionSearchItem[] = [] + const acceptedIds = new Set() + const seenCursors = new Set() + let cursor: SessionSearchCursor | undefined + while (authorized.length <= SESSION_SEARCH_LIMIT) { + if (isAborted(signal)) return cancelled() + const page = await sessionQuery.searchSessions({ + query: request.payload.query, + eventFilters: [ + { kind: 'type', values: ['user/message', 'assistant/message', 'steering/message'] }, + { kind: 'surface', values: ['current'] }, + ], + limit: SESSION_SEARCH_LIMIT, + ...cursor === undefined ? {} : { cursor }, + }, { signal }) + if (isAborted(signal)) return cancelled() + // Host visibility is the authorization boundary. Consume the + // provider's globally ranked stream rather than binding every + // visible id into one SQLite statement, then re-check complete + // provenance before emitting any snippet. + for (const hit of page.items) { + if ( + !visibleIds.has(hit.header.id) + || hit.bestMatch.sessionId !== hit.header.id + || hit.bestMatch.surface !== 'current' + || !MESSAGE_TYPES.has(hit.bestMatch.type) + || acceptedIds.has(hit.header.id) + ) continue + acceptedIds.add(hit.header.id) + authorized.push({ + sessionId: hit.header.id, + snippet: hit.bestMatch.snippet, + }) + if (authorized.length > SESSION_SEARCH_LIMIT) break + } + if (authorized.length > SESSION_SEARCH_LIMIT || page.nextCursor === undefined) break + if (seenCursors.has(page.nextCursor)) { + throw new Error('session search provider repeated a continuation cursor') + } + seenCursors.add(page.nextCursor) + cursor = page.nextCursor + } return ok(request, { - items: authorized.slice(0, SESSION_SEARCH_LIMIT).map(hit => ({ - sessionId: hit.header.id, - snippet: hit.bestMatch.snippet, - })), - hasMore: page.nextCursor !== undefined || authorized.length > SESSION_SEARCH_LIMIT, + items: authorized.slice(0, SESSION_SEARCH_LIMIT), + hasMore: authorized.length > SESSION_SEARCH_LIMIT, }) } catch (error: unknown) { if ( diff --git a/packages/host/apiproxy/tests/api-proxy-search.spec.ts b/packages/host/apiproxy/tests/api-proxy-search.spec.ts index 99f40a5949..5138398fe3 100644 --- a/packages/host/apiproxy/tests/api-proxy-search.spec.ts +++ b/packages/host/apiproxy/tests/api-proxy-search.spec.ts @@ -107,7 +107,6 @@ describe('session.search', () => { }, }, ], - nextCursor: 'more' as never, })) ctx.provide('sessionQuery', { searchSessions } as never) const api = createApiProxy(ctx, defaults) @@ -119,7 +118,7 @@ describe('session.search', () => { ok: true, value: { items: [{ sessionId: 'cold', snippet: 'the matching answer' }], - hasMore: true, + hasMore: false, }, }) expect(searchSessions).toHaveBeenCalledOnce() @@ -129,7 +128,6 @@ describe('session.search', () => { ] expect(query).toEqual({ query: 'matching answer', - sessionFilters: [{ kind: 'id', values: ['live', 'cold'] }], eventFilters: [ { kind: 'type', @@ -179,7 +177,6 @@ describe('session.search', () => { withBestMatch(2, { type: 'tool/result' }), withBestMatch(3, { type: 'steering/message', snippet: 'allowed snippet' }), ], - nextCursor: 'more', }), } as never) @@ -192,19 +189,25 @@ describe('session.search', () => { ok: true, value: { items: [{ sessionId: 'visible', snippet: 'allowed snippet' }], - hasMore: true, + hasMore: false, }, }) }) - it('enforces the 20-item Host boundary even if a provider overproduces', async () => { + it('pages the globally ranked stream until the 20-item Host boundary is known', async () => { const ctx = await baseContext() const items = Array.from({ length: 21 }, (_, index) => hit(`visible-${index}`, index)) for (const item of items) { ctx.sessions.create(item.header.id, { meta: item.header }) } + const searchSessions = vi.fn() + .mockResolvedValueOnce({ + items: [hit('hidden-ranked-first'), ...items.slice(0, 19)], + nextCursor: 'page-2', + }) + .mockResolvedValueOnce({ items: items.slice(19) }) ctx.provide('sessionQuery', { - searchSessions: () => Promise.resolve({ items }), + searchSessions, } as never) const response = await createApiProxy(ctx, defaults).sessions.search( request('match'), @@ -218,6 +221,39 @@ describe('session.search', () => { if (!response.result.ok) throw new Error('unreachable') expect(response.result.value.items).toHaveLength(20) expect(response.result.value.items.at(-1)?.sessionId).toBe('visible-19') + expect(searchSessions).toHaveBeenCalledTimes(2) + expect(searchSessions.mock.calls[1]?.[0]).toMatchObject({ cursor: 'page-2' }) + }) + + it('keeps visibility sets above SQLite variable limits out of provider bindings', async () => { + const ctx = await baseContext() + const cold = Array.from( + { length: 32_751 }, + (_, index) => header(`cold-${index}`, `/cold-${index}`), + ) + ctx.provide('sessionPersistence', { + list: () => Promise.resolve(cold), + locate: () => undefined, + } as never) + const searchSessions = vi.fn(() => Promise.resolve({ + items: [hit('cold-32750')], + })) + ctx.provide('sessionQuery', { searchSessions } as never) + + const response = await createApiProxy(ctx, defaults).sessions.search( + request('large corpus'), + new AbortController().signal, + ) + + expect(response.result).toEqual({ + ok: true, + value: { + items: [{ sessionId: 'cold-32750', snippet: 'match 0' }], + hasMore: false, + }, + }) + expect(searchSessions).toHaveBeenCalledOnce() + expect(searchSessions.mock.calls[0]?.[0]).not.toHaveProperty('sessionFilters') }) it('propagates cancellation through visible-session collection and stops cold-summary work', async () => { From 30503c3b0308752d9f915e8af631d76a1fed754d Mon Sep 17 00:00:00 2001 From: Hypatia May Date: Mon, 27 Jul 2026 13:07:23 +0800 Subject: [PATCH 007/139] test(web): type large-corpus search mock (round 5) --- packages/host/apiproxy/tests/api-proxy-search.spec.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/packages/host/apiproxy/tests/api-proxy-search.spec.ts b/packages/host/apiproxy/tests/api-proxy-search.spec.ts index 5138398fe3..05e33fb08f 100644 --- a/packages/host/apiproxy/tests/api-proxy-search.spec.ts +++ b/packages/host/apiproxy/tests/api-proxy-search.spec.ts @@ -235,7 +235,7 @@ describe('session.search', () => { list: () => Promise.resolve(cold), locate: () => undefined, } as never) - const searchSessions = vi.fn(() => Promise.resolve({ + const searchSessions = vi.fn((_request: SessionSearchRequest) => Promise.resolve({ items: [hit('cold-32750')], })) ctx.provide('sessionQuery', { searchSessions } as never) From a8c28be1ba345bda3e8a90847ca992edcda0668e Mon Sep 17 00:00:00 2001 From: Hypatia May Date: Mon, 27 Jul 2026 13:18:05 +0800 Subject: [PATCH 008/139] fix(web): bound search provider work (round 6) --- .../2026-07-27-web-session-search.i18n.yaml | 4 +- .../feature/2026-07-27-web-session-search.md | 8 +- .../2026-07-27-web-session-search.zh.md | 8 +- packages/host/apiproxy/README.i18n.yaml | 4 +- packages/host/apiproxy/README.md | 2 +- packages/host/apiproxy/README.zh.md | 2 +- packages/host/apiproxy/src/api-proxy.ts | 15 +++ .../apiproxy/tests/api-proxy-search.spec.ts | 122 ++++++++++++++++++ 8 files changed, 151 insertions(+), 14 deletions(-) diff --git a/.agents/notes/implemented/feature/2026-07-27-web-session-search.i18n.yaml b/.agents/notes/implemented/feature/2026-07-27-web-session-search.i18n.yaml index 721f0f9483..c7ce4dcdd1 100644 --- a/.agents/notes/implemented/feature/2026-07-27-web-session-search.i18n.yaml +++ b/.agents/notes/implemented/feature/2026-07-27-web-session-search.i18n.yaml @@ -2,5 +2,5 @@ # side as of the last confirmed-consistent state. Both languages carry equal authority; # after editing either side, bring the other along and re-record with: # pnpm run verify-translation-pairing --write .agents/notes/implemented/feature/2026-07-27-web-session-search.md -2026-07-27-web-session-search.md: e3219f865aa3f13cdb7e806570ef6134dd5bd448 -2026-07-27-web-session-search.zh.md: 27d0efee5d218c2e737fb7378d3fd71c6b13e4ce +2026-07-27-web-session-search.md: 2e82c9cb0d453ce6e863f8c436cb793979d17a64 +2026-07-27-web-session-search.zh.md: 010b29f80098bce518354992f23cd499e63e0b04 diff --git a/.agents/notes/implemented/feature/2026-07-27-web-session-search.md b/.agents/notes/implemented/feature/2026-07-27-web-session-search.md index e3219f865a..2e82c9cb0d 100644 --- a/.agents/notes/implemented/feature/2026-07-27-web-session-search.md +++ b/.agents/notes/implemented/feature/2026-07-27-web-session-search.md @@ -12,7 +12,7 @@ The Web sidebar exposes session titles and Workspace membership but cannot retri The shared Web/headless composition mounts [`@deepseek-ai/dsh-session-query-sqlite`](../../../../packages/session-query/session-query-sqlite/README.md) with an in-memory database. Each service instance owns one connection-private index, preserving the SQLite backend's single-owner contract across parallel CLI or Web invocations without leaving process-scoped derived files behind. The database starts empty; the first content query of each invocation lazily reconciles live and persisted sessions. It remains a disposable derived index, separate from canonical JSONL persistence. -The host gateway exposes `session.search` through the existing typed RPC stack. It derives the authorization set from the same visible summaries as `session.list`, asks `ctx.sessionQuery.searchSessions` for globally ranked current-surface `user/message`, `assistant/message`, and `steering/message` matches, and consumes provider pages until it has 20 authorized sessions plus one lookahead or exhausts the stream. Every hit's session id, best-match session id, surface, and event type are revalidated before its snippet leaves the Host. Keeping the potentially large authorization set out of SQLite bindings avoids the portable variable ceiling while preserving global ranking. The response remains one bounded page; `hasMore` tells the UI to ask for a narrower query rather than exposing pagination. The carrier signal cancels superseded work, including persistence listing, bounded batches of cold-session metadata stats, and each provider page. A missing query service or an indexing/query failure remains a business error and does not mutate the canonical session store. +The host gateway exposes `session.search` through the existing typed RPC stack. It derives the authorization set from the same visible summaries as `session.list`, asks `ctx.sessionQuery.searchSessions` for globally ranked current-surface `user/message`, `assistant/message`, and `steering/message` matches in pages capped at 20 hits, and consumes provider pages until it has 20 authorized sessions plus one lookahead or exhausts the stream. Every hit's session id, best-match session id, surface, and event type are revalidated before its snippet leaves the Host. Keeping the potentially large authorization set out of SQLite bindings avoids the portable variable ceiling while preserving global ranking. The response remains one bounded page; `hasMore` tells the UI to ask for a narrower query rather than exposing pagination. The Host makes at most 100 provider calls (2,000 inspected hits); an oversized page, a repeated continuation cursor, or a still-unexhausted stream at that budget fails closed as an `internal` business error. The carrier signal cancels superseded work, including persistence listing, bounded batches of cold-session metadata stats, and each provider page. A missing query service or an indexing/query failure remains a business error and does not mutate the canonical session store. [`WorkspaceBrowser`](../../../../packages/client/ui-workspace/README.md) keeps metadata and content search deliberately separate. A non-blank query immediately computes case-insensitive title and Workspace substring matches from the Session list, starts a 250 ms debounced content request, aborts the preceding request when the query changes, and ignores stale completions. It merges local matches first in recency order with backend-ranked content-only matches, deduplicates by session id, and renders a flat list regardless of the normal grouping mode. Each row shows the title, Workspace, and an available one-line snippet. Selecting a row opens the Session only and preserves the query; it does not navigate to an exact event. @@ -20,7 +20,7 @@ Content matching inherits the SQLite backend's normalized literal token/phrase s ## Failure and visibility contract -Search never widens session visibility: cold sessions without a servable cwd are absent for the same reason they are absent from `session.list`, and the query receives only ids from that baseline. Shadowed and log-only events, tool events outside message content, errors, todos, and other trace records do not produce UI hits. +Search never widens session visibility: cold sessions without a servable cwd are absent for the same reason they are absent from `session.list`, and only provider hits whose ids occur in that baseline can leave the Host. Shadowed and log-only events, tool events outside message content, errors, todos, and other trace records do not produce UI hits. While the first or a later content request is pending, the UI keeps immediate metadata matches and shows a history-search status. If the backend fails, the same rows remain and a warning explains that content search is unavailable. Zero merged rows produce an explicit empty state. More than 20 candidate rows produce a refine-query hint. @@ -35,8 +35,8 @@ While the first or a later content request is pending, the UI keeps immediate me Past persisted conversations become discoverable without opening them first, while the host retains one visibility boundary and one semantic-index implementation. Immediate local results hide most request latency, cancellation prevents obsolete queries from repainting the list, and backend failure degrades to the behavior available before content search. -The first content query can take longer because it pays lazy reconciliation. Search quality is token/phrase recall rather than fuzzy or arbitrary substring recall, including the documented continuous-Chinese limitation. Results are session-level, capped at 20, and have no paging or exact-message navigation. +The first content query can take longer because it pays lazy reconciliation. Search quality is token/phrase recall rather than fuzzy or arbitrary substring recall, including the documented continuous-Chinese limitation. Results are session-level, capped at 20, and have no paging or exact-message navigation. A valid but pathologically unselective provider stream that has not produced enough authorized results within its first 2,000 hits takes the metadata-only failure path instead of consuming unbounded work. ## Testing -Host tests pin request validation, visible-session filtering, event/surface filters, result bounds, cancellation, and failure mapping. Runtime and UI tests pin stateless delegation, debounce/abort/stale-response behavior, local fallback, merge order, deduplication, row rendering, and navigation semantics. A keyless assembled Web test seeds an unopened persisted conversation, finds it by message content through the lazy SQLite index, captures the sidebar result, opens it, and verifies that the query remains. +Host tests pin request validation, visible-session filtering, event/surface filters, result bounds, provider page and item budgets, cursor and cross-page deduplication behavior, continuation-page cancellation, and failure mapping. Runtime and UI tests pin stateless delegation, debounce/abort/stale-response behavior, local fallback, merge order, deduplication, row rendering, and navigation semantics. A keyless assembled Web test seeds an unopened persisted conversation, finds it by message content through the lazy SQLite index, captures the sidebar result, opens it, and verifies that the query remains. diff --git a/.agents/notes/implemented/feature/2026-07-27-web-session-search.zh.md b/.agents/notes/implemented/feature/2026-07-27-web-session-search.zh.md index 27d0efee5d..010b29f800 100644 --- a/.agents/notes/implemented/feature/2026-07-27-web-session-search.zh.md +++ b/.agents/notes/implemented/feature/2026-07-27-web-session-search.zh.md @@ -12,7 +12,7 @@ Web 侧边栏会展示会话标题及其 Workspace 归属,但无法根据只 Web 与 headless 共用的组合会使用内存数据库挂载 [`@deepseek-ai/dsh-session-query-sqlite`](../../../../packages/session-query/session-query-sqlite/README.md)。每个服务实例都独占一个连接私有索引,因此并行 CLI 或 Web 调用可维持 SQLite 后端的单一所有者契约,又不会留下进程级派生文件。数据库从空状态启动;每次调用的首次内容查询会惰性对齐实时会话与持久化会话。它仍是与规范 JSONL 持久化相互独立的可丢弃派生索引。 -宿主网关通过现有的类型化 RPC 栈公开 `session.search`。它根据 `session.list` 使用的同一组可见摘要推导授权集合,向 `ctx.sessionQuery.searchSessions` 请求全局排序后的当前 surface `user/message`、`assistant/message` 和 `steering/message` 匹配项,并持续消费提供方分页,直到获得 20 个已授权会话及一个前瞻项,或结果流耗尽。每个命中的会话 id、最佳匹配会话 id、surface 和事件类型都会经过重新校验,其 snippet 才能离开宿主。将可能很大的授权集合排除在 SQLite 绑定之外,可避开可移植变量上限,同时保持全局排序。响应仍只有一个有界页面;`hasMore` 会指示 UI 提示用户缩小查询范围,而不是公开分页能力。载体信号会取消已被取代的工作,包括持久化列表枚举、分批受限执行的冷会话元数据 stat,以及每一页提供方搜索。查询服务缺失或索引、查询失败仍作为业务错误处理,不会修改规范会话存储。 +宿主网关通过现有的类型化 RPC 栈公开 `session.search`。它根据 `session.list` 使用的同一组可见摘要推导授权集合,向 `ctx.sessionQuery.searchSessions` 请求全局排序后的当前 surface `user/message`、`assistant/message` 和 `steering/message` 匹配项(每页最多 20 个命中),并持续消费提供方分页,直到获得 20 个已授权会话及一个前瞻项,或结果流耗尽。每个命中的会话 id、最佳匹配会话 id、surface 和事件类型都会经过重新校验,其 snippet 才能离开宿主。将可能很大的授权集合排除在 SQLite 绑定之外,可避开可移植变量上限,同时保持全局排序。响应仍只有一个有界页面;`hasMore` 会指示 UI 提示用户缩小查询范围,而不是公开分页能力。宿主最多调用提供方 100 次(检查 2,000 个命中);如果单页命中数超限、续传游标重复,或用尽该预算后结果流仍未耗尽,都会直接返回 `internal` 业务错误,不返回部分结果。载体信号会取消已被取代的工作,包括持久化列表枚举、分批受限执行的冷会话元数据 stat,以及每一页提供方搜索。查询服务缺失或索引、查询失败仍作为业务错误处理,不会修改规范会话存储。 [`WorkspaceBrowser`](../../../../packages/client/ui-workspace/README.md) 有意将元数据搜索与内容搜索保持独立。非空白查询会立即从会话列表中计算不区分大小写的标题和 Workspace 子串匹配,在 250 ms 防抖后发起内容请求,在查询变化时中止前一请求,并忽略陈旧的完成结果。它先按新近程度排列本地匹配,再合并由后端排序且仅匹配内容的结果,按会话 id 去重;无论常规分组模式如何,最终都渲染为扁平列表。每一行显示标题、Workspace,并在存在时显示一行摘要片段。选择某一行只会打开对应会话,并保留查询条件;不会跳转至确切事件。 @@ -20,7 +20,7 @@ Web 与 headless 共用的组合会使用内存数据库挂载 [`@deepseek-ai/ds ## 故障与可见性契约 -搜索绝不会扩大会话可见范围:没有可供服务的 cwd 的冷会话会被排除,原因与它们不出现在 `session.list` 中相同;查询只会接收这条基线提供的 id。被遮蔽事件和纯日志事件、消息内容之外的工具事件、错误、待办事项及其他追踪记录都不会产生 UI 命中结果。 +搜索绝不会扩大会话可见范围:没有可供服务的 cwd 的冷会话会被排除,原因与它们不出现在 `session.list` 中相同;只有 id 位于这条基线中的提供方命中才能离开宿主。被遮蔽事件和纯日志事件、消息内容之外的工具事件、错误、待办事项及其他追踪记录都不会产生 UI 命中结果。 首个或后续内容请求仍在处理期间,UI 会保留即时元数据匹配结果,并显示历史搜索状态。如果后端失败,这些行会保持不变,并显示警告说明内容搜索不可用。合并后没有任何行时,界面会显示明确的空状态。候选行超过 20 条时,界面会提示用户缩小查询范围。 @@ -35,8 +35,8 @@ Web 与 headless 共用的组合会使用内存数据库挂载 [`@deepseek-ai/ds 无需预先打开,即可检索到历史持久化对话,同时宿主仍只保留一条可见性边界和一套语义索引实现。即时本地结果掩盖了大部分请求延迟,取消机制可防止已作废查询重新渲染列表,后端故障则会降级为内容搜索尚不可用时已有的行为。 -首次内容查询可能耗时更长,因为它要承担惰性对齐的开销。搜索质量采用 token/短语召回,而不是模糊召回或任意子串召回,并受上述连续中文限制。结果粒度为会话,最多 20 条,不支持分页,也不能跳转到具体消息。 +首次内容查询可能耗时更长,因为它要承担惰性对齐的开销。搜索质量采用 token/短语召回,而不是模糊召回或任意子串召回,并受上述连续中文限制。结果粒度为会话,最多 20 条,不支持分页,也不能跳转到具体消息。如果有效但选择性极差的提供方结果流在前 2,000 个命中内仍未产生足够多的已授权结果,系统会进入仅保留元数据匹配的故障路径,而不是无限制地继续处理。 ## 测试 -宿主测试将请求校验、可见会话过滤、事件和 surface 过滤、结果边界、取消与故障映射固定为契约。运行时与 UI 测试将无状态委托、防抖/中止/陈旧响应行为、本地回退、合并顺序、去重、行渲染与导航语义固定为契约。无密钥的组装层 Web 测试会播种一段尚未打开的持久化对话,通过惰性 SQLite 索引按消息内容找到它,捕获侧边栏结果,打开该会话,并验证查询条件仍然保留。 +宿主测试将请求校验、可见会话过滤、事件和 surface 过滤、结果边界、提供方页数和单页命中数预算、游标与跨页去重行为、后续页取消及故障映射固定为契约。运行时与 UI 测试将无状态委托、防抖/中止/陈旧响应行为、本地回退、合并顺序、去重、行渲染与导航语义固定为契约。无密钥的组装层 Web 测试会播种一段尚未打开的持久化对话,通过惰性 SQLite 索引按消息内容找到它,捕获侧边栏结果,打开该会话,并验证查询条件仍然保留。 diff --git a/packages/host/apiproxy/README.i18n.yaml b/packages/host/apiproxy/README.i18n.yaml index 5079e05965..b4c9f9f9fb 100644 --- a/packages/host/apiproxy/README.i18n.yaml +++ b/packages/host/apiproxy/README.i18n.yaml @@ -2,5 +2,5 @@ # side as of the last confirmed-consistent state. Both languages carry equal authority; # after editing either side, bring the other along and re-record with: # pnpm run verify-translation-pairing --write packages/host/apiproxy/README.md -README.md: b9f0fcd8506afda733774868d78fe6e851b4fe2a -README.zh.md: c57990b029b8d1e143396bb13718dbed165e2b47 +README.md: 2f062ba9b927ab62518523731d39fd7c52e07c8d +README.zh.md: 72ff415f793b4bdb2068a8240ea42baab79984dc diff --git a/packages/host/apiproxy/README.md b/packages/host/apiproxy/README.md index b9f0fcd850..2f062ba9b9 100644 --- a/packages/host/apiproxy/README.md +++ b/packages/host/apiproxy/README.md @@ -14,7 +14,7 @@ The mux stream projects the latest log-backed title as a validated `session/titl Workspace and Session lists are separate reconnect baselines. `workspace.create` creates a unique name or adopts an existing directory, `session.create` accepts an optional preallocated Session id, and `host/workspace-changed` plus `host/session-added` carry committed increments in either arrival order. `SessionSummary.blank` and the `host/session-added` frame carry the derived zero-events bit: clients hide blank sessions and reuse them per workspace, flip blank on the first `host/session-status(running:true)`, and treat `session.list` as the reconnect authority; cold summaries are never blank because lazy persistence keeps never-appended sessions out of `list()`. -`session.search` is a bounded content-search projection over the sessions visible through `session.list`. The gateway asks the optional `ctx.sessionQuery` service for globally ranked current-surface user, assistant, and steering matches, pages that stream until it has at most 20 visible session/snippet pairs plus one lookahead, and revalidates every hit against the list-derived authorization set before returning it. Keeping the authorization set in Host memory avoids SQLite's variable ceiling for large valid corpora without weakening visibility or ranking. The carrier request signal cancels persistence listing, cold-summary collection, and every search page. A deployment without the service, or a failed index/query operation, returns an `internal` business error so clients can retain metadata-only matches. +`session.search` is a bounded content-search projection over the sessions visible through `session.list`. The gateway asks the optional `ctx.sessionQuery` service for globally ranked current-surface user, assistant, and steering matches in pages capped at 20 hits, consumes that stream until it has at most 20 visible session/snippet pairs plus one lookahead, and revalidates every hit against the list-derived authorization set before returning it. It makes at most 100 provider calls (2,000 inspected hits); an oversized page, a repeated continuation cursor, or a still-unexhausted stream at that budget fails closed as an `internal` business error. Keeping the authorization set in Host memory avoids SQLite's variable ceiling for large valid corpora without weakening visibility or ranking. The carrier request signal cancels persistence listing, cold-summary collection, and every search page. A deployment without the service, or a failed index/query operation, also returns an `internal` business error so clients can retain metadata-only matches. The `command.*` and `skill.*` domains expose the host command registry and skill catalog to clients. Every method addresses one session's agent by `sessionId` (a served session always has an Agent; `command.*` resumes cold sessions through the same path as `session.*`, while `skill.list` resolves the project root from the session header without touching the Agent registry). `command.execute` runs a slash-command line host-side and returns a detached result; the carrier's request signal cancels the running handler. `host/commands-changed` is the catalog invalidation frame: clients refetch `command.list` instead of diffing. diff --git a/packages/host/apiproxy/README.zh.md b/packages/host/apiproxy/README.zh.md index c57990b029..72ff415f79 100644 --- a/packages/host/apiproxy/README.zh.md +++ b/packages/host/apiproxy/README.zh.md @@ -14,7 +14,7 @@ mux 流会在每个已附加会话的订阅基线之后,以及对应的实时 Workspace 列表与 Session 列表是相互独立的重连基线。`workspace.create` 会创建唯一名称或接纳现有目录,`session.create` 接受可选的预分配 Session id,`host/workspace-changed` 与 `host/session-added` 则以任意到达顺序携带已提交的增量。`SessionSummary.blank` 与 `host/session-added` 帧携带派生的零事件位:客户端隐藏空白会话并按 workspace 复用它们,在首个 `host/session-status(running:true)` 时翻转 blank,并以 `session.list` 作为重连权威;冷会话摘要永远不是空白——惰性持久化让从未追加过事件的会话根本不出现在 `list()` 中。 -`session.search` 是以 `session.list` 所列会话为范围的有界内容搜索投影。网关向可选的 `ctx.sessionQuery` 服务请求全局排序后的当前 surface user、assistant 和 steering(中途引导)匹配项,对该结果流分页,直到获得至多 20 个可见会话/snippet 对及一个前瞻项,并在返回前依据从列表推导的授权集合重新校验每个命中。将授权集合保留在宿主内存中,可在不削弱可见性或排序的前提下避开有效大型语料库的 SQLite 变量上限。载体请求信号可取消持久化列表枚举、冷会话摘要收集和每一页搜索。部署若未挂载该服务,或索引/查询操作失败,都会返回 `internal` 业务错误,以便客户端保留仅基于元数据的匹配项。 +`session.search` 是以 `session.list` 所列会话为范围的有界内容搜索投影。网关向可选的 `ctx.sessionQuery` 服务请求全局排序后的当前 surface user、assistant 和 steering(中途引导)匹配项,每页至多 20 个命中,并持续消费该结果流,直到获得至多 20 个可见会话/snippet 对及一个前瞻项;返回前仍会依据从列表推导的授权集合重新校验每个命中。宿主最多调用提供方 100 次(检查 2,000 个命中);如果单页命中数超限、续传游标重复,或用尽该预算后结果流仍未耗尽,都会直接返回 `internal` 业务错误,不返回部分结果。将授权集合保留在宿主内存中,可在不削弱可见性或排序的前提下避开有效大型语料库的 SQLite 变量上限。载体请求信号可取消持久化列表枚举、冷会话摘要收集和每一页搜索。部署若未挂载该服务,或索引/查询操作失败,也会返回 `internal` 业务错误,以便客户端保留仅基于元数据的匹配项。 `command.*` 与 `skill.*` 领域向客户端暴露宿主命令注册表和技能目录。每个方法都通过 `sessionId` 寻址一个会话的 Agent(被服务的会话必有 Agent;`command.*` 经由与 `session.*` 相同的路径恢复冷会话,而 `skill.list` 从会话头解析项目根目录,不触碰 Agent 注册表)。`command.execute` 在宿主侧运行一条斜杠命令行并返回脱耦结果;载体的请求信号可取消正在运行的处理器。`host/commands-changed` 是目录失效帧:客户端重新拉取 `command.list` 而不是做差分。 diff --git a/packages/host/apiproxy/src/api-proxy.ts b/packages/host/apiproxy/src/api-proxy.ts index c9329feea8..e94f71fd3f 100644 --- a/packages/host/apiproxy/src/api-proxy.ts +++ b/packages/host/apiproxy/src/api-proxy.ts @@ -41,6 +41,9 @@ const DEFAULT_MAX_MESSAGES = 50 /** Product contract: sidebar search returns one bounded page and no cursor. */ const SESSION_SEARCH_LIMIT = 20 +/** Provider work budget: at most 100 pages × 20 hits = 2,000 inspected hits. */ +const SESSION_SEARCH_PROVIDER_PAGE_LIMIT = 100 + /** Bound cold-log stat fan-out so an aborted search stops launching new work. */ const COLD_SUMMARY_BATCH_SIZE = 16 @@ -645,8 +648,15 @@ export function createApiProxy(ctx: Context, defaults: ApiProxyDefaults): ApiPro const acceptedIds = new Set() const seenCursors = new Set() let cursor: SessionSearchCursor | undefined + let providerPageCount = 0 while (authorized.length <= SESSION_SEARCH_LIMIT) { if (isAborted(signal)) return cancelled() + if (providerPageCount >= SESSION_SEARCH_PROVIDER_PAGE_LIMIT) { + throw new Error( + `session search provider exceeded the ${SESSION_SEARCH_PROVIDER_PAGE_LIMIT}-page work budget`, + ) + } + providerPageCount++ const page = await sessionQuery.searchSessions({ query: request.payload.query, eventFilters: [ @@ -657,6 +667,11 @@ export function createApiProxy(ctx: Context, defaults: ApiProxyDefaults): ApiPro ...cursor === undefined ? {} : { cursor }, }, { signal }) if (isAborted(signal)) return cancelled() + if (page.items.length > SESSION_SEARCH_LIMIT) { + throw new Error( + `session search provider returned ${page.items.length} items; maximum is ${SESSION_SEARCH_LIMIT}`, + ) + } // Host visibility is the authorization boundary. Consume the // provider's globally ranked stream rather than binding every // visible id into one SQLite statement, then re-check complete diff --git a/packages/host/apiproxy/tests/api-proxy-search.spec.ts b/packages/host/apiproxy/tests/api-proxy-search.spec.ts index 05e33fb08f..840535ba2d 100644 --- a/packages/host/apiproxy/tests/api-proxy-search.spec.ts +++ b/packages/host/apiproxy/tests/api-proxy-search.spec.ts @@ -225,6 +225,128 @@ describe('session.search', () => { expect(searchSessions.mock.calls[1]?.[0]).toMatchObject({ cursor: 'page-2' }) }) + it('fails closed after 100 provider pages with distinct continuation cursors', async () => { + const ctx = await baseContext() + ctx.sessions.create(sid('visible'), { meta: header('visible') }) + let pageNumber = 0 + const searchSessions = vi.fn((providerRequest: SessionSearchRequest) => { + pageNumber++ + expect(providerRequest.limit).toBe(20) + return Promise.resolve({ + items: [], + nextCursor: `page-${pageNumber}`, + }) + }) + ctx.provide('sessionQuery', { searchSessions } as never) + + const response = await createApiProxy(ctx, defaults).sessions.search( + request('endless-pages'), + new AbortController().signal, + ) + + expect(response.result.ok).toBe(false) + if (response.result.ok) throw new Error('unreachable') + expect(response.result.error).toMatchObject({ code: 'internal' }) + expect(response.result.error.message).toContain('100-page work budget') + expect(searchSessions).toHaveBeenCalledTimes(100) + }) + + it('rejects an oversized provider page before iterating its items', async () => { + const ctx = await baseContext() + ctx.sessions.create(sid('visible'), { meta: header('visible') }) + const oversized = new Array(21) + const iterate = vi.fn(() => oversized.values()) + Object.defineProperty(oversized, Symbol.iterator, { value: iterate }) + const searchSessions = vi.fn(() => Promise.resolve({ items: oversized })) + ctx.provide('sessionQuery', { searchSessions } as never) + + const response = await createApiProxy(ctx, defaults).sessions.search( + request('oversized-page'), + new AbortController().signal, + ) + + expect(response.result.ok).toBe(false) + if (response.result.ok) throw new Error('unreachable') + expect(response.result.error).toMatchObject({ code: 'internal' }) + expect(response.result.error.message).toContain('returned 21 items; maximum is 20') + expect(iterate).not.toHaveBeenCalled() + }) + + it('fails closed when the provider repeats a continuation cursor', async () => { + const ctx = await baseContext() + ctx.sessions.create(sid('visible'), { meta: header('visible') }) + const searchSessions = vi.fn() + .mockResolvedValueOnce({ items: [], nextCursor: 'repeated' }) + .mockResolvedValueOnce({ items: [], nextCursor: 'repeated' }) + ctx.provide('sessionQuery', { searchSessions } as never) + + const response = await createApiProxy(ctx, defaults).sessions.search( + request('repeated-cursor'), + new AbortController().signal, + ) + + expect(response.result.ok).toBe(false) + if (response.result.ok) throw new Error('unreachable') + expect(response.result.error).toMatchObject({ code: 'internal' }) + expect(response.result.error.message).toContain('repeated a continuation cursor') + expect(searchSessions).toHaveBeenCalledTimes(2) + }) + + it('does not count duplicate session ids toward the result or lookahead boundary', async () => { + const ctx = await baseContext() + const items = Array.from({ length: 21 }, (_, index) => hit(`visible-${index}`, index)) + for (const item of items) { + ctx.sessions.create(item.header.id, { meta: item.header }) + } + const searchSessions = vi.fn() + .mockResolvedValueOnce({ items: items.slice(0, 20), nextCursor: 'page-2' }) + .mockResolvedValueOnce({ items: items.slice(0, 20), nextCursor: 'page-3' }) + .mockResolvedValueOnce({ items: items.slice(20) }) + ctx.provide('sessionQuery', { searchSessions } as never) + + const response = await createApiProxy(ctx, defaults).sessions.search( + request('duplicate-pages'), + new AbortController().signal, + ) + + expect(response.result).toMatchObject({ + ok: true, + value: { hasMore: true }, + }) + if (!response.result.ok) throw new Error('unreachable') + expect(response.result.value.items.map(item => item.sessionId)).toEqual( + items.slice(0, 20).map(item => item.header.id), + ) + expect(searchSessions).toHaveBeenCalledTimes(3) + }) + + it('cancels on a continuation page and passes the carrier signal to both calls', async () => { + const ctx = await baseContext() + ctx.sessions.create(sid('visible'), { meta: header('visible') }) + const controller = new AbortController() + const searchSessions = vi.fn() + .mockResolvedValueOnce({ items: [], nextCursor: 'page-2' }) + .mockImplementationOnce(() => { + controller.abort() + return Promise.resolve({ items: [] }) + }) + ctx.provide('sessionQuery', { searchSessions } as never) + + const response = await createApiProxy(ctx, defaults).sessions.search( + request('cancel-continuation'), + controller.signal, + ) + + expect(response.result).toMatchObject({ + ok: false, + error: { code: 'cancelled' }, + }) + expect(searchSessions).toHaveBeenCalledTimes(2) + for (const call of searchSessions.mock.calls) { + expect(call[1]).toEqual({ signal: controller.signal }) + } + }) + it('keeps visibility sets above SQLite variable limits out of provider bindings', async () => { const ctx = await baseContext() const cold = Array.from( From 40b68cd8d55a7ae57de4d3b87c3afc0dfa849b5d Mon Sep 17 00:00:00 2001 From: Hypatia May Date: Mon, 27 Jul 2026 13:24:39 +0800 Subject: [PATCH 009/139] fix(web): harden paged search protocol (round 7) --- packages/host/apiproxy/src/api-proxy.ts | 29 ++++++---- .../apiproxy/tests/api-proxy-search.spec.ts | 53 +++++++++++++++++++ 2 files changed, 72 insertions(+), 10 deletions(-) diff --git a/packages/host/apiproxy/src/api-proxy.ts b/packages/host/apiproxy/src/api-proxy.ts index e94f71fd3f..8126dd432d 100644 --- a/packages/host/apiproxy/src/api-proxy.ts +++ b/packages/host/apiproxy/src/api-proxy.ts @@ -667,16 +667,23 @@ export function createApiProxy(ctx: Context, defaults: ApiProxyDefaults): ApiPro ...cursor === undefined ? {} : { cursor }, }, { signal }) if (isAborted(signal)) return cancelled() - if (page.items.length > SESSION_SEARCH_LIMIT) { + const providerItemCount = page.items.length + if (providerItemCount > SESSION_SEARCH_LIMIT) { throw new Error( - `session search provider returned ${page.items.length} items; maximum is ${SESSION_SEARCH_LIMIT}`, + `session search provider returned ${providerItemCount} items; maximum is ${SESSION_SEARCH_LIMIT}`, ) } // Host visibility is the authorization boundary. Consume the // provider's globally ranked stream rather than binding every // visible id into one SQLite statement, then re-check complete - // provenance before emitting any snippet. - for (const hit of page.items) { + // provenance before emitting any snippet. Inspect exactly the + // declared array entries so a custom iterator cannot overproduce. + for (let itemIndex = 0; itemIndex < providerItemCount; itemIndex++) { + const hit = page.items[itemIndex] + if (hit === undefined) { + throw new Error(`session search provider omitted item at index ${itemIndex}`) + } + if (authorized.length > SESSION_SEARCH_LIMIT) continue if ( !visibleIds.has(hit.header.id) || hit.bestMatch.sessionId !== hit.header.id @@ -689,14 +696,16 @@ export function createApiProxy(ctx: Context, defaults: ApiProxyDefaults): ApiPro sessionId: hit.header.id, snippet: hit.bestMatch.snippet, }) - if (authorized.length > SESSION_SEARCH_LIMIT) break } - if (authorized.length > SESSION_SEARCH_LIMIT || page.nextCursor === undefined) break - if (seenCursors.has(page.nextCursor)) { - throw new Error('session search provider repeated a continuation cursor') + const nextCursor = page.nextCursor + if (nextCursor !== undefined) { + if (seenCursors.has(nextCursor)) { + throw new Error('session search provider repeated a continuation cursor') + } + seenCursors.add(nextCursor) } - seenCursors.add(page.nextCursor) - cursor = page.nextCursor + if (authorized.length > SESSION_SEARCH_LIMIT || nextCursor === undefined) break + cursor = nextCursor } return ok(request, { items: authorized.slice(0, SESSION_SEARCH_LIMIT), diff --git a/packages/host/apiproxy/tests/api-proxy-search.spec.ts b/packages/host/apiproxy/tests/api-proxy-search.spec.ts index 840535ba2d..734ddfc499 100644 --- a/packages/host/apiproxy/tests/api-proxy-search.spec.ts +++ b/packages/host/apiproxy/tests/api-proxy-search.spec.ts @@ -272,6 +272,33 @@ describe('session.search', () => { expect(iterate).not.toHaveBeenCalled() }) + it('inspects only numerically stored items when a compliant page overrides iteration', async () => { + const ctx = await baseContext() + const visible = Array.from({ length: 21 }, (_, index) => hit(`visible-${index}`, index)) + for (const item of visible) { + ctx.sessions.create(item.header.id, { meta: item.header }) + } + const stored = visible.slice(0, 1) + const iterate = vi.fn(() => visible.values()) + Object.defineProperty(stored, Symbol.iterator, { value: iterate }) + const searchSessions = vi.fn(() => Promise.resolve({ items: stored })) + ctx.provide('sessionQuery', { searchSessions } as never) + + const response = await createApiProxy(ctx, defaults).sessions.search( + request('custom-iterator'), + new AbortController().signal, + ) + + expect(response.result).toEqual({ + ok: true, + value: { + items: [{ sessionId: 'visible-0', snippet: 'match 0' }], + hasMore: false, + }, + }) + expect(iterate).not.toHaveBeenCalled() + }) + it('fails closed when the provider repeats a continuation cursor', async () => { const ctx = await baseContext() ctx.sessions.create(sid('visible'), { meta: header('visible') }) @@ -292,6 +319,32 @@ describe('session.search', () => { expect(searchSessions).toHaveBeenCalledTimes(2) }) + it('validates a repeated cursor before accepting the authorized lookahead', async () => { + const ctx = await baseContext() + const items = Array.from({ length: 21 }, (_, index) => hit(`visible-${index}`, index)) + for (const item of items) { + ctx.sessions.create(item.header.id, { meta: item.header }) + } + const searchSessions = vi.fn() + .mockResolvedValueOnce({ items: items.slice(0, 20), nextCursor: 'repeated' }) + .mockResolvedValueOnce({ items: items.slice(20), nextCursor: 'repeated' }) + ctx.provide('sessionQuery', { searchSessions } as never) + + const response = await createApiProxy(ctx, defaults).sessions.search( + request('repeated-lookahead-cursor'), + new AbortController().signal, + ) + + expect(response.result).toMatchObject({ + ok: false, + error: { code: 'internal' }, + }) + expect(response.result).not.toHaveProperty('value') + if (response.result.ok) throw new Error('unreachable') + expect(response.result.error.message).toContain('repeated a continuation cursor') + expect(searchSessions).toHaveBeenCalledTimes(2) + }) + it('does not count duplicate session ids toward the result or lookahead boundary', async () => { const ctx = await baseContext() const items = Array.from({ length: 21 }, (_, index) => hit(`visible-${index}`, index)) From ba2925c7041bac2976c362c1a5bec379b2c0af3f Mon Sep 17 00:00:00 2001 From: Hypatia May Date: Mon, 27 Jul 2026 14:02:35 +0800 Subject: [PATCH 010/139] fix(web): converge search runtime boundaries (round 8) --- .../2026-07-27-web-session-search.i18n.yaml | 4 +- .../feature/2026-07-27-web-session-search.md | 8 +- .../2026-07-27-web-session-search.zh.md | 8 +- apps/cli/README.i18n.yaml | 4 +- apps/cli/README.md | 2 +- apps/cli/README.zh.md | 2 +- apps/cli/cordis.yml | 7 +- docs/config-catalog.md | 7 +- packages/host/apiproxy/README.i18n.yaml | 4 +- packages/host/apiproxy/README.md | 4 +- packages/host/apiproxy/README.zh.md | 4 +- packages/host/apiproxy/src/api-proxy.ts | 76 +++++-- .../apiproxy/tests/api-proxy-search.spec.ts | 202 +++++++++++++++++- .../session-query-sqlite/README.i18n.yaml | 6 +- .../session-query-sqlite/README.md | 3 + .../session-query-sqlite/README.zh.md | 3 + .../session-query-sqlite/src/index.ts | 30 ++- .../session-query-sqlite/src/schema.ts | 3 +- .../tests/lazy-open.compat.spec.ts | 45 ++++ .../session-query-sqlite/tests/sqlite.spec.ts | 96 ++++++++- scripts/run-gates.ts | 5 + 21 files changed, 469 insertions(+), 54 deletions(-) create mode 100644 packages/session-query/session-query-sqlite/tests/lazy-open.compat.spec.ts diff --git a/.agents/notes/implemented/feature/2026-07-27-web-session-search.i18n.yaml b/.agents/notes/implemented/feature/2026-07-27-web-session-search.i18n.yaml index c7ce4dcdd1..6124b31fb4 100644 --- a/.agents/notes/implemented/feature/2026-07-27-web-session-search.i18n.yaml +++ b/.agents/notes/implemented/feature/2026-07-27-web-session-search.i18n.yaml @@ -2,5 +2,5 @@ # side as of the last confirmed-consistent state. Both languages carry equal authority; # after editing either side, bring the other along and re-record with: # pnpm run verify-translation-pairing --write .agents/notes/implemented/feature/2026-07-27-web-session-search.md -2026-07-27-web-session-search.md: 2e82c9cb0d453ce6e863f8c436cb793979d17a64 -2026-07-27-web-session-search.zh.md: 010b29f80098bce518354992f23cd499e63e0b04 +2026-07-27-web-session-search.md: 8992fdf046c1256ab61278cf5189ba56df8b4ecd +2026-07-27-web-session-search.zh.md: 764e9f3363ae321c55e401cc52b35dcba790a0b4 diff --git a/.agents/notes/implemented/feature/2026-07-27-web-session-search.md b/.agents/notes/implemented/feature/2026-07-27-web-session-search.md index 2e82c9cb0d..8992fdf046 100644 --- a/.agents/notes/implemented/feature/2026-07-27-web-session-search.md +++ b/.agents/notes/implemented/feature/2026-07-27-web-session-search.md @@ -10,9 +10,9 @@ The Web sidebar exposes session titles and Workspace membership but cannot retri ## Decision -The shared Web/headless composition mounts [`@deepseek-ai/dsh-session-query-sqlite`](../../../../packages/session-query/session-query-sqlite/README.md) with an in-memory database. Each service instance owns one connection-private index, preserving the SQLite backend's single-owner contract across parallel CLI or Web invocations without leaving process-scoped derived files behind. The database starts empty; the first content query of each invocation lazily reconciles live and persisted sessions. It remains a disposable derived index, separate from canonical JSONL persistence. +The shared Web/headless composition mounts [`@deepseek-ai/dsh-session-query-sqlite`](../../../../packages/session-query/session-query-sqlite/README.md) with `openAt: first-search` and an in-memory database. The service is ACTIVE at boot, while its `node:sqlite` module and connection-private handle open only on the first content query. This keeps Node 22 startup output free of SQLite's experimental warning before search is used without promising to suppress the warning when search first imports the module. Each service instance owns its index, preserving the SQLite backend's single-owner contract across parallel CLI or Web invocations without leaving process-scoped derived files behind. The database starts empty and lazily reconciles live and persisted sessions on that first query. It remains a disposable derived index, separate from canonical JSONL persistence. -The host gateway exposes `session.search` through the existing typed RPC stack. It derives the authorization set from the same visible summaries as `session.list`, asks `ctx.sessionQuery.searchSessions` for globally ranked current-surface `user/message`, `assistant/message`, and `steering/message` matches in pages capped at 20 hits, and consumes provider pages until it has 20 authorized sessions plus one lookahead or exhausts the stream. Every hit's session id, best-match session id, surface, and event type are revalidated before its snippet leaves the Host. Keeping the potentially large authorization set out of SQLite bindings avoids the portable variable ceiling while preserving global ranking. The response remains one bounded page; `hasMore` tells the UI to ask for a narrower query rather than exposing pagination. The Host makes at most 100 provider calls (2,000 inspected hits); an oversized page, a repeated continuation cursor, or a still-unexhausted stream at that budget fails closed as an `internal` business error. The carrier signal cancels superseded work, including persistence listing, bounded batches of cold-session metadata stats, and each provider page. A missing query service or an indexing/query failure remains a business error and does not mutate the canonical session store. +The host gateway exposes `session.search` through the existing typed RPC stack. It derives the authorization set from the same visible summaries as `session.list`, asks `ctx.sessionQuery.searchSessions` for globally ranked current-surface `user/message`, `assistant/message`, and `steering/message` matches in pages capped at 20 hits, and consumes provider pages until it has 20 authorized sessions plus one lookahead or exhausts the stream. Every hit's session id, best-match session id, surface, event type, and snippet type are revalidated before its snippet leaves the Host, and emitted snippets contain at most 240 Unicode code points. Keeping the potentially large authorization set out of SQLite bindings avoids the portable variable ceiling while preserving global ranking. The response remains one bounded page; `hasMore` tells the UI to ask for a narrower query rather than exposing pagination. A stale continuation discards the current attempt's partial results, deduplication entries, and cursors, then restarts from the first page against the original visibility snapshot. Those retries share the limit of 100 provider calls (and therefore at most 2,000 inspected hits); an oversized page, a repeated continuation cursor, or a still-unexhausted stream at that call budget fails closed as an `internal` business error. The carrier signal cancels superseded work, including persistence listing, bounded batches of cold-session metadata stats, and each provider call, and wins over a concurrent stale rejection. A missing query service or an unrecovered indexing/query failure remains a business error and does not mutate the canonical session store. [`WorkspaceBrowser`](../../../../packages/client/ui-workspace/README.md) keeps metadata and content search deliberately separate. A non-blank query immediately computes case-insensitive title and Workspace substring matches from the Session list, starts a 250 ms debounced content request, aborts the preceding request when the query changes, and ignores stale completions. It merges local matches first in recency order with backend-ranked content-only matches, deduplicates by session id, and renders a flat list regardless of the normal grouping mode. Each row shows the title, Workspace, and an available one-line snippet. Selecting a row opens the Session only and preserves the query; it does not navigate to an exact event. @@ -35,8 +35,8 @@ While the first or a later content request is pending, the UI keeps immediate me Past persisted conversations become discoverable without opening them first, while the host retains one visibility boundary and one semantic-index implementation. Immediate local results hide most request latency, cancellation prevents obsolete queries from repainting the list, and backend failure degrades to the behavior available before content search. -The first content query can take longer because it pays lazy reconciliation. Search quality is token/phrase recall rather than fuzzy or arbitrary substring recall, including the documented continuous-Chinese limitation. Results are session-level, capped at 20, and have no paging or exact-message navigation. A valid but pathologically unselective provider stream that has not produced enough authorized results within its first 2,000 hits takes the metadata-only failure path instead of consuming unbounded work. +The first content query can take longer because it imports and opens SQLite before paying lazy reconciliation. Search quality is token/phrase recall rather than fuzzy or arbitrary substring recall, including the documented continuous-Chinese limitation. Results are session-level, capped at 20, and have no paging or exact-message navigation. A valid but pathologically unselective or repeatedly stale provider attempt that does not complete within 100 calls takes the metadata-only failure path instead of consuming unbounded work. ## Testing -Host tests pin request validation, visible-session filtering, event/surface filters, result bounds, provider page and item budgets, cursor and cross-page deduplication behavior, continuation-page cancellation, and failure mapping. Runtime and UI tests pin stateless delegation, debounce/abort/stale-response behavior, local fallback, merge order, deduplication, row rendering, and navigation semantics. A keyless assembled Web test seeds an unopened persisted conversation, finds it by message content through the lazy SQLite index, captures the sidebar result, opens it, and verifies that the query remains. +Host tests pin request validation, visible-session filtering, event/surface filters, result and snippet bounds, the shared provider-call budget, stale-generation restarts, cursor and cross-page deduplication behavior, continuation-page cancellation, and failure mapping. SQLite lifecycle tests pin eager activation, first-search opening and failure, shared readiness, and unopened disposal; a Node 22 compatibility subprocess pins warning-free mount and disposal before the first search. Runtime and UI tests pin stateless delegation, debounce/abort/stale-response behavior, local fallback, merge order, deduplication, row rendering, and navigation semantics. A keyless assembled Web test seeds an unopened persisted conversation, finds it by message content through the lazy SQLite index, captures the sidebar result, opens it, and verifies that the query remains. diff --git a/.agents/notes/implemented/feature/2026-07-27-web-session-search.zh.md b/.agents/notes/implemented/feature/2026-07-27-web-session-search.zh.md index 010b29f800..764e9f3363 100644 --- a/.agents/notes/implemented/feature/2026-07-27-web-session-search.zh.md +++ b/.agents/notes/implemented/feature/2026-07-27-web-session-search.zh.md @@ -10,9 +10,9 @@ Web 侧边栏会展示会话标题及其 Workspace 归属,但无法根据只 ## 决策 -Web 与 headless 共用的组合会使用内存数据库挂载 [`@deepseek-ai/dsh-session-query-sqlite`](../../../../packages/session-query/session-query-sqlite/README.md)。每个服务实例都独占一个连接私有索引,因此并行 CLI 或 Web 调用可维持 SQLite 后端的单一所有者契约,又不会留下进程级派生文件。数据库从空状态启动;每次调用的首次内容查询会惰性对齐实时会话与持久化会话。它仍是与规范 JSONL 持久化相互独立的可丢弃派生索引。 +Web 与 headless 共用的组合会使用 `openAt: first-search` 和内存数据库挂载 [`@deepseek-ai/dsh-session-query-sqlite`](../../../../packages/session-query/session-query-sqlite/README.md)。服务启动时处于 ACTIVE 状态,而其 `node:sqlite` 模块与连接私有句柄分别要到首次内容查询才会导入和打开。这让 Node 22 的启动输出在使用搜索前不会出现 SQLite 实验性警告,但并不承诺在首次搜索导入该模块时抑制警告。每个服务实例都独占自己的索引,因此并行 CLI 或 Web 调用可维持 SQLite 后端的单一所有者契约,又不会留下进程级派生文件。数据库从空状态启动,并在该首次查询时惰性对齐实时会话与持久化会话。它仍是与规范 JSONL 持久化相互独立的可丢弃派生索引。 -宿主网关通过现有的类型化 RPC 栈公开 `session.search`。它根据 `session.list` 使用的同一组可见摘要推导授权集合,向 `ctx.sessionQuery.searchSessions` 请求全局排序后的当前 surface `user/message`、`assistant/message` 和 `steering/message` 匹配项(每页最多 20 个命中),并持续消费提供方分页,直到获得 20 个已授权会话及一个前瞻项,或结果流耗尽。每个命中的会话 id、最佳匹配会话 id、surface 和事件类型都会经过重新校验,其 snippet 才能离开宿主。将可能很大的授权集合排除在 SQLite 绑定之外,可避开可移植变量上限,同时保持全局排序。响应仍只有一个有界页面;`hasMore` 会指示 UI 提示用户缩小查询范围,而不是公开分页能力。宿主最多调用提供方 100 次(检查 2,000 个命中);如果单页命中数超限、续传游标重复,或用尽该预算后结果流仍未耗尽,都会直接返回 `internal` 业务错误,不返回部分结果。载体信号会取消已被取代的工作,包括持久化列表枚举、分批受限执行的冷会话元数据 stat,以及每一页提供方搜索。查询服务缺失或索引、查询失败仍作为业务错误处理,不会修改规范会话存储。 +宿主网关通过现有的类型化 RPC 栈公开 `session.search`。它根据 `session.list` 使用的同一组可见摘要推导授权集合,向 `ctx.sessionQuery.searchSessions` 请求全局排序后的当前 surface `user/message`、`assistant/message` 和 `steering/message` 匹配项(每页最多 20 个命中),并持续消费提供方分页,直到获得 20 个已授权会话及一个前瞻项,或结果流耗尽。每个命中的会话 id、最佳匹配会话 id、surface、事件类型和 snippet 类型都会经过重新校验,其 snippet 才能离开宿主,且发出的 snippet 最多包含 240 个 Unicode 码点。将可能很大的授权集合排除在 SQLite 绑定之外,可避开可移植变量上限,同时保持全局排序。响应仍只有一个有界页面;`hasMore` 会指示 UI 提示用户缩小查询范围,而不是公开分页能力。陈旧的续传会丢弃当前尝试的部分结果、去重条目和游标,然后依据原始可见性快照从第一页重新开始。这些重试共用 100 次提供方调用的限制(因此最多检查 2,000 个命中);如果单页命中数超限、续传游标重复,或用尽该调用预算后结果流仍未耗尽,都会直接返回 `internal` 业务错误,不返回部分结果。载体信号会取消已被取代的工作,包括持久化列表枚举、分批受限执行的冷会话元数据 stat,以及每一次提供方调用;即使同时收到陈旧拒绝,也以取消为准。查询服务缺失或索引/查询故障无法恢复时,仍作为业务错误处理,不会修改规范会话存储。 [`WorkspaceBrowser`](../../../../packages/client/ui-workspace/README.md) 有意将元数据搜索与内容搜索保持独立。非空白查询会立即从会话列表中计算不区分大小写的标题和 Workspace 子串匹配,在 250 ms 防抖后发起内容请求,在查询变化时中止前一请求,并忽略陈旧的完成结果。它先按新近程度排列本地匹配,再合并由后端排序且仅匹配内容的结果,按会话 id 去重;无论常规分组模式如何,最终都渲染为扁平列表。每一行显示标题、Workspace,并在存在时显示一行摘要片段。选择某一行只会打开对应会话,并保留查询条件;不会跳转至确切事件。 @@ -35,8 +35,8 @@ Web 与 headless 共用的组合会使用内存数据库挂载 [`@deepseek-ai/ds 无需预先打开,即可检索到历史持久化对话,同时宿主仍只保留一条可见性边界和一套语义索引实现。即时本地结果掩盖了大部分请求延迟,取消机制可防止已作废查询重新渲染列表,后端故障则会降级为内容搜索尚不可用时已有的行为。 -首次内容查询可能耗时更长,因为它要承担惰性对齐的开销。搜索质量采用 token/短语召回,而不是模糊召回或任意子串召回,并受上述连续中文限制。结果粒度为会话,最多 20 条,不支持分页,也不能跳转到具体消息。如果有效但选择性极差的提供方结果流在前 2,000 个命中内仍未产生足够多的已授权结果,系统会进入仅保留元数据匹配的故障路径,而不是无限制地继续处理。 +首次内容查询可能耗时更长,因为它要先导入并打开 SQLite,再承担惰性对齐的开销。搜索质量采用 token/短语召回,而不是模糊召回或任意子串召回,并受上述连续中文限制。结果粒度为会话,最多 20 条,不支持分页,也不能跳转到具体消息。如果有效但选择性极差或反复陈旧的提供方尝试未能在 100 次调用内完成,系统会进入仅保留元数据匹配的故障路径,而不是无限制地继续处理。 ## 测试 -宿主测试将请求校验、可见会话过滤、事件和 surface 过滤、结果边界、提供方页数和单页命中数预算、游标与跨页去重行为、后续页取消及故障映射固定为契约。运行时与 UI 测试将无状态委托、防抖/中止/陈旧响应行为、本地回退、合并顺序、去重、行渲染与导航语义固定为契约。无密钥的组装层 Web 测试会播种一段尚未打开的持久化对话,通过惰性 SQLite 索引按消息内容找到它,捕获侧边栏结果,打开该会话,并验证查询条件仍然保留。 +宿主测试将请求校验、可见会话过滤、事件和 surface 过滤、结果与 snippet 边界、共享提供方调用预算、陈旧世代重启、游标与跨页去重行为、后续页取消及故障映射固定为契约。SQLite 生命周期测试将启动时激活、首次搜索时的打开与失败、共享就绪状态以及未打开状态下的处置固定为契约;一个 Node 22 兼容性子进程将首次搜索前无警告挂载与处置固定为契约。运行时与 UI 测试将无状态委托、防抖/中止/陈旧响应行为、本地回退、合并顺序、去重、行渲染与导航语义固定为契约。无密钥的组装层 Web 测试会播种一段尚未打开的持久化对话,通过惰性 SQLite 索引按消息内容找到它,捕获侧边栏结果,打开该会话,并验证查询条件仍然保留。 diff --git a/apps/cli/README.i18n.yaml b/apps/cli/README.i18n.yaml index 9a5db218c0..4bf441aa6a 100644 --- a/apps/cli/README.i18n.yaml +++ b/apps/cli/README.i18n.yaml @@ -2,5 +2,5 @@ # side as of the last confirmed-consistent state. Both languages carry equal authority; # after editing either side, bring the other along and re-record with: # pnpm run verify-translation-pairing --write apps/cli/README.md -README.md: 0c4ff8d36a89e234512f42d130774fe3717968b9 -README.zh.md: 7e116ecb32061060816f27279a5d3b555a584f6b +README.md: c3a3cbbdd578b0705a7e6c6d62c52dcd9cf6fa60 +README.zh.md: b755a82917e9472b6e788667a4f3387abce3397b diff --git a/apps/cli/README.md b/apps/cli/README.md index 0c4ff8d36a..c3a3cbbdd5 100644 --- a/apps/cli/README.md +++ b/apps/cli/README.md @@ -14,7 +14,7 @@ The TUI surface: - tells the agent where its own source lives: after boot it adds a prompt section naming this harness checkout, resolved from the launcher's real path so it holds under a PATH symlink and an arbitrary cwd, so the self-referential `cordis` toolset can read and modify it; - applies the personal overlay from `~/.dsh` (see [app-boot's Personal config](../../packages/ui/app-boot/README.md#personal-config)): `.env` fills environment gaps (ambient > project `.env` > personal `.env`), `config.yaml` patches the booted tree. -The Web and headless surfaces boot one shared composition (`cordis.yml`): both treat the invoking directory as the default project and Workspace root, create named Workspaces beneath that root unless `--workspace-root ` overrides it, load applicable `AGENTS.md`/`CLAUDE.md` instructions into each agent-loop request prefix with a 65,536-byte render budget, opt into first-message model titles, and mount a disposable in-memory SQLite content index. Each service instance owns its database, so parallel invocations neither share unsupported SQLite state nor leave derived index files behind. The index starts empty and lazily reconciles live and persisted logs on the first session search of each invocation. Headless differs only in listening on an OS-assigned port (parallel `dsh -p` runs never collide; the stderr-printed URL opens the live session in a browser). Both need the frontend dist and client bundles built (`pnpm run build && pnpm run build:web`). +The Web and headless surfaces boot one shared composition (`cordis.yml`): both treat the invoking directory as the default project and Workspace root, create named Workspaces beneath that root unless `--workspace-root ` overrides it, load applicable `AGENTS.md`/`CLAUDE.md` instructions into each agent-loop request prefix with a 65,536-byte render budget, opt into first-message model titles, and mount a disposable in-memory SQLite content-index service. That service is ACTIVE at boot, while its `node:sqlite` module and database handle open only on the first content search. This keeps Node 22 startup output free of SQLite's experimental warning before search is used; the first actual search may still emit the runtime warning. Each service instance owns its database, so parallel invocations neither share unsupported SQLite state nor leave derived index files behind, and the first search lazily reconciles live and persisted logs. Headless differs only in listening on an OS-assigned port (parallel `dsh -p` runs never collide; the stderr-printed URL opens the live session in a browser). Both need the frontend dist and client bundles built (`pnpm run build && pnpm run build:web`). `DSH_TOOLS_MODE` selects the tool presentation mode for the whole Web/headless process: `native` (the schema default when unset), `code` (the `run_code`-only Code Mode wire), or `both`; any other value fails loud at boot through the `dsh-tools` config schema. It is a TEMPORARY seam — process-wide because Loader composition is static — and is removed once the web UI owns per-session tool-mode selection; the TUI surface ignores it (its config tree pins its own mode). diff --git a/apps/cli/README.zh.md b/apps/cli/README.zh.md index 7e116ecb32..b755a82917 100644 --- a/apps/cli/README.zh.md +++ b/apps/cli/README.zh.md @@ -14,7 +14,7 @@ TUI 界面: - 告知 agent 自身源码所在位置:启动后添加一个命名此 harness checkout 的提示词段。该路径从启动器的真实路径解析,因此在 PATH 符号链接和任意 cwd 下仍然有效,使自指的 `cordis` 工具集可以读取并修改它; - 应用 `~/.dsh` 中的个人覆盖(参见 [app-boot 的个人配置](../../packages/ui/app-boot/README.md#personal-config)):`.env` 填补环境缺口(环境中已有的值 > 项目 `.env` > 个人 `.env`),`config.yaml` 则修补已启动的树。 -Web 和无头界面启动同一个共享组合(`cordis.yml`):两者都将调用目录视为默认项目和 Workspace 根目录,除非通过 `--workspace-root ` 覆盖,否则会在该根目录下创建具名 Workspace;它们会把适用的 `AGENTS.md`/`CLAUDE.md` 指令加载到每个 agent-loop 请求前缀中,渲染预算为 65,536 字节,并选用首条消息模型标题,且挂载一个可丢弃的内存 SQLite 内容索引。每个服务实例独占自己的数据库,因此并行调用既不会共享不受支持的 SQLite 状态,也不会留下派生索引文件。该索引从空状态启动,并在每次调用的首次会话搜索时惰性对账实时日志与持久化日志。无头界面唯一的差异是监听操作系统分配的端口(并行 `dsh -p` 运行绝不冲突;stderr 打印的 URL 会在浏览器中打开实时会话)。两者都需要先构建前端 dist 和客户端 bundle(`pnpm run build && pnpm run build:web`)。 +Web 和无头界面启动同一个共享组合(`cordis.yml`):两者都将调用目录视为默认项目和 Workspace 根目录,除非通过 `--workspace-root ` 覆盖,否则会在该根目录下创建具名 Workspace;它们会把适用的 `AGENTS.md`/`CLAUDE.md` 指令加载到每个 agent-loop 请求前缀中,渲染预算为 65,536 字节,并选用首条消息模型标题,且挂载一个可丢弃的内存 SQLite 内容索引服务。该服务在启动时处于 ACTIVE 状态,但其 `node:sqlite` 模块与数据库句柄分别要到首次内容搜索才会导入和打开。这样可使 Node 22 在尚未使用搜索时的启动输出不出现 SQLite 实验性警告;首次实际搜索仍可能发出运行时警告。每个服务实例独占自己的数据库,因此并行调用既不会共享不受支持的 SQLite 状态,也不会留下派生索引文件,首次搜索还会惰性对账实时日志与持久化日志。无头界面唯一的差异是监听操作系统分配的端口(并行 `dsh -p` 运行绝不冲突;stderr 打印的 URL 会在浏览器中打开实时会话)。两者都需要先构建前端 dist 和客户端 bundle(`pnpm run build && pnpm run build:web`)。 `DSH_TOOLS_MODE` 为整个 Web/无头进程选择工具呈现模式:可选值为 `native`(未设置时的 schema 默认值)、`code`(仅含 `run_code` 的 Code Mode 协议接口)或 `both`;任何其他值都会经由 `dsh-tools` 配置 schema 在启动时明确报错。它是一个临时 seam:Loader 组合是静态的,因此该设置作用于整个进程;待 Web UI 负责逐会话工具模式选择后便会移除。TUI 界面会忽略该变量(其配置树固定了自身模式)。 diff --git a/apps/cli/cordis.yml b/apps/cli/cordis.yml index 35979b274f..96e4716c4d 100644 --- a/apps/cli/cordis.yml +++ b/apps/cli/cordis.yml @@ -89,13 +89,14 @@ config: root: './.sessions' -# Lazy, service-owned content index for session.search. The in-memory database -# cannot be shared across processes or leak derived files across invocations; -# the first search reconciles changed live/persisted sessions for this boot. +# The service activates at boot, while first-search defers the node:sqlite +# import and in-memory handle so Node 22 startup stays quiet until content +# search actually uses SQLite. That search then reconciles this boot's sources. - id: session-query-sqlite name: '@deepseek-ai/dsh-session-query-sqlite' config: path: ':memory:' + openAt: first-search - id: storage name: '@deepseek-ai/dsh-storage' diff --git a/docs/config-catalog.md b/docs/config-catalog.md index a69d5f1978..5b7415aec3 100644 --- a/docs/config-catalog.md +++ b/docs/config-catalog.md @@ -1057,6 +1057,8 @@ export interface Config extends SessionQueryConfig { * POSIX filesystems; existing modes are preserved. */ path: string + /** Open the SQLite module and handle at service activation or the first search. Defaults to `startup`. */ + openAt?: OpenAt /** SQLite journal mode. Defaults to `wal`. */ journalMode?: JournalMode /** Page size when a request omits `limit`. At most `Number.MAX_SAFE_INTEGER - 1`; defaults to 20. */ @@ -1069,13 +1071,16 @@ export interface Config extends SessionQueryConfig { persistedInspectConcurrency?: number } +/** SQLite module/handle opening phase. */ +export type OpenAt = 'startup' | 'first-search' + /** Supported SQLite journal modes. */ export type JournalMode = 'wal' | 'delete' | 'truncate' | 'persist' ``` Depends on: [`SessionQueryConfig`](../packages/session-query/session-query/src/index.ts) -Source: [`packages/session-query/session-query-sqlite/src/index.ts:76`](../packages/session-query/session-query-sqlite/src/index.ts) +Source: [`packages/session-query/session-query-sqlite/src/index.ts:79`](../packages/session-query/session-query-sqlite/src/index.ts) ## `@deepseek-ai/dsh-session-reference` diff --git a/packages/host/apiproxy/README.i18n.yaml b/packages/host/apiproxy/README.i18n.yaml index b4c9f9f9fb..39a555e071 100644 --- a/packages/host/apiproxy/README.i18n.yaml +++ b/packages/host/apiproxy/README.i18n.yaml @@ -2,5 +2,5 @@ # side as of the last confirmed-consistent state. Both languages carry equal authority; # after editing either side, bring the other along and re-record with: # pnpm run verify-translation-pairing --write packages/host/apiproxy/README.md -README.md: 2f062ba9b927ab62518523731d39fd7c52e07c8d -README.zh.md: 72ff415f793b4bdb2068a8240ea42baab79984dc +README.md: e61de41a14294b8c1601e5be8cab19fdf780916d +README.zh.md: 7e49ad49aaa9356412f90b37237b06ce65776e1c diff --git a/packages/host/apiproxy/README.md b/packages/host/apiproxy/README.md index 2f062ba9b9..e61de41a14 100644 --- a/packages/host/apiproxy/README.md +++ b/packages/host/apiproxy/README.md @@ -14,7 +14,9 @@ The mux stream projects the latest log-backed title as a validated `session/titl Workspace and Session lists are separate reconnect baselines. `workspace.create` creates a unique name or adopts an existing directory, `session.create` accepts an optional preallocated Session id, and `host/workspace-changed` plus `host/session-added` carry committed increments in either arrival order. `SessionSummary.blank` and the `host/session-added` frame carry the derived zero-events bit: clients hide blank sessions and reuse them per workspace, flip blank on the first `host/session-status(running:true)`, and treat `session.list` as the reconnect authority; cold summaries are never blank because lazy persistence keeps never-appended sessions out of `list()`. -`session.search` is a bounded content-search projection over the sessions visible through `session.list`. The gateway asks the optional `ctx.sessionQuery` service for globally ranked current-surface user, assistant, and steering matches in pages capped at 20 hits, consumes that stream until it has at most 20 visible session/snippet pairs plus one lookahead, and revalidates every hit against the list-derived authorization set before returning it. It makes at most 100 provider calls (2,000 inspected hits); an oversized page, a repeated continuation cursor, or a still-unexhausted stream at that budget fails closed as an `internal` business error. Keeping the authorization set in Host memory avoids SQLite's variable ceiling for large valid corpora without weakening visibility or ranking. The carrier request signal cancels persistence listing, cold-summary collection, and every search page. A deployment without the service, or a failed index/query operation, also returns an `internal` business error so clients can retain metadata-only matches. +`session.search` is a bounded content-search projection over the sessions visible through `session.list`. The gateway asks the optional `ctx.sessionQuery` service for globally ranked current-surface user, assistant, and steering matches in pages capped at 20 hits, consumes that stream until it has at most 20 visible session/snippet pairs plus one lookahead, and revalidates every hit against the list-derived authorization set before returning it. Returned snippets contain at most 240 Unicode code points; a malformed non-string provider snippet fails closed instead of crossing the RPC boundary. Keeping the authorization set in Host memory avoids SQLite's variable ceiling for large valid corpora without weakening visibility or ranking. + +A stale continuation discards every partial result, deduplication entry, and cursor from that provider attempt, then restarts at the first page against the original list-derived visibility snapshot. Stale retries share the same limit of at most 100 provider calls (and therefore at most 2,000 inspected hits); an oversized page, a repeated continuation cursor, or a still-unexhausted stream at that call budget fails closed as an `internal` business error. The carrier request signal cancels persistence listing, cold-summary collection, and every search call, including a stale rejection observed concurrently with cancellation. A deployment without the service, or any unrecovered index/query failure, also returns an `internal` business error so clients can retain metadata-only matches. The `command.*` and `skill.*` domains expose the host command registry and skill catalog to clients. Every method addresses one session's agent by `sessionId` (a served session always has an Agent; `command.*` resumes cold sessions through the same path as `session.*`, while `skill.list` resolves the project root from the session header without touching the Agent registry). `command.execute` runs a slash-command line host-side and returns a detached result; the carrier's request signal cancels the running handler. `host/commands-changed` is the catalog invalidation frame: clients refetch `command.list` instead of diffing. diff --git a/packages/host/apiproxy/README.zh.md b/packages/host/apiproxy/README.zh.md index 72ff415f79..7e49ad49aa 100644 --- a/packages/host/apiproxy/README.zh.md +++ b/packages/host/apiproxy/README.zh.md @@ -14,7 +14,9 @@ mux 流会在每个已附加会话的订阅基线之后,以及对应的实时 Workspace 列表与 Session 列表是相互独立的重连基线。`workspace.create` 会创建唯一名称或接纳现有目录,`session.create` 接受可选的预分配 Session id,`host/workspace-changed` 与 `host/session-added` 则以任意到达顺序携带已提交的增量。`SessionSummary.blank` 与 `host/session-added` 帧携带派生的零事件位:客户端隐藏空白会话并按 workspace 复用它们,在首个 `host/session-status(running:true)` 时翻转 blank,并以 `session.list` 作为重连权威;冷会话摘要永远不是空白——惰性持久化让从未追加过事件的会话根本不出现在 `list()` 中。 -`session.search` 是以 `session.list` 所列会话为范围的有界内容搜索投影。网关向可选的 `ctx.sessionQuery` 服务请求全局排序后的当前 surface user、assistant 和 steering(中途引导)匹配项,每页至多 20 个命中,并持续消费该结果流,直到获得至多 20 个可见会话/snippet 对及一个前瞻项;返回前仍会依据从列表推导的授权集合重新校验每个命中。宿主最多调用提供方 100 次(检查 2,000 个命中);如果单页命中数超限、续传游标重复,或用尽该预算后结果流仍未耗尽,都会直接返回 `internal` 业务错误,不返回部分结果。将授权集合保留在宿主内存中,可在不削弱可见性或排序的前提下避开有效大型语料库的 SQLite 变量上限。载体请求信号可取消持久化列表枚举、冷会话摘要收集和每一页搜索。部署若未挂载该服务,或索引/查询操作失败,也会返回 `internal` 业务错误,以便客户端保留仅基于元数据的匹配项。 +`session.search` 是以 `session.list` 所列会话为范围的有界内容搜索投影。网关向可选的 `ctx.sessionQuery` 服务请求全局排序后的当前 surface user、assistant 和 steering(中途引导)匹配项,每页至多 20 个命中,并持续消费该结果流,直到获得至多 20 个可见会话/snippet 对及一个前瞻项;返回前仍会依据从列表推导的授权集合重新校验每个命中。返回的 snippet 最多包含 240 个 Unicode 码点;如果提供方返回格式错误的非字符串 snippet,系统会直接失败,而不会让它越过 RPC 边界。将授权集合保留在宿主内存中,可在不削弱可见性或排序的前提下避开有效大型语料库的 SQLite 变量上限。 + +陈旧的续传会丢弃该提供方尝试中的所有部分结果、去重条目和游标,然后依据最初从列表推导的可见性快照从第一页重新开始。陈旧重试共用最多 100 次提供方调用的限制(因此最多检查 2,000 个命中);如果单页命中数超限、续传游标重复,或用尽该调用预算后结果流仍未耗尽,都会直接返回 `internal` 业务错误,不返回部分结果。载体请求信号可取消持久化列表枚举、冷会话摘要收集和每一次搜索调用;即使同时收到陈旧拒绝,也以取消为准。部署若未挂载该服务,或索引/查询故障无法恢复,也会返回 `internal` 业务错误,以便客户端保留仅基于元数据的匹配项。 `command.*` 与 `skill.*` 领域向客户端暴露宿主命令注册表和技能目录。每个方法都通过 `sessionId` 寻址一个会话的 Agent(被服务的会话必有 Agent;`command.*` 经由与 `session.*` 相同的路径恢复冷会话,而 `skill.list` 从会话头解析项目根目录,不触碰 Agent 注册表)。`command.execute` 在宿主侧运行一条斜杠命令行并返回脱耦结果;载体的请求信号可取消正在运行的处理器。`host/commands-changed` 是目录失效帧:客户端重新拉取 `command.list` 而不是做差分。 diff --git a/packages/host/apiproxy/src/api-proxy.ts b/packages/host/apiproxy/src/api-proxy.ts index 8126dd432d..f22539fefb 100644 --- a/packages/host/apiproxy/src/api-proxy.ts +++ b/packages/host/apiproxy/src/api-proxy.ts @@ -41,8 +41,11 @@ const DEFAULT_MAX_MESSAGES = 50 /** Product contract: sidebar search returns one bounded page and no cursor. */ const SESSION_SEARCH_LIMIT = 20 -/** Provider work budget: at most 100 pages × 20 hits = 2,000 inspected hits. */ -const SESSION_SEARCH_PROVIDER_PAGE_LIMIT = 100 +/** Provider work budget: at most 100 calls and 2,000 inspected hits. */ +const SESSION_SEARCH_PROVIDER_CALL_LIMIT = 100 + +/** Product contract: snippets contain at most 240 Unicode code points. */ +const SESSION_SEARCH_SNIPPET_CODE_POINT_LIMIT = 240 /** Bound cold-log stat fan-out so an aborted search stops launching new work. */ const COLD_SUMMARY_BATCH_SIZE = 16 @@ -55,6 +58,28 @@ function isAborted(signal: AbortSignal): boolean { return signal.aborted } +/** Copy at most the product-visible code-point prefix without splitting a surrogate pair. */ +function boundedSessionSearchSnippet(value: unknown): string { + if (typeof value !== 'string') { + throw new Error('session search provider returned a non-string snippet') + } + let end = 0 + for ( + let count = 0; + count < SESSION_SEARCH_SNIPPET_CODE_POINT_LIMIT && end < value.length; + count++ + ) { + const first = value.charCodeAt(end) + const hasSurrogatePair = first >= 0xD800 + && first <= 0xDBFF + && end + 1 < value.length + && value.charCodeAt(end + 1) >= 0xDC00 + && value.charCodeAt(end + 1) <= 0xDFFF + end += hasSurrogatePair ? 2 : 1 + } + return end === value.length ? value : value.slice(0, end) +} + /** * Message-boundary pagination: count maxMessages surface messages backwards from * the window tail; the cut is the starting seq of the oldest message group @@ -648,24 +673,42 @@ export function createApiProxy(ctx: Context, defaults: ApiProxyDefaults): ApiPro const acceptedIds = new Set() const seenCursors = new Set() let cursor: SessionSearchCursor | undefined - let providerPageCount = 0 + let providerCallCount = 0 while (authorized.length <= SESSION_SEARCH_LIMIT) { if (isAborted(signal)) return cancelled() - if (providerPageCount >= SESSION_SEARCH_PROVIDER_PAGE_LIMIT) { + if (providerCallCount >= SESSION_SEARCH_PROVIDER_CALL_LIMIT) { throw new Error( - `session search provider exceeded the ${SESSION_SEARCH_PROVIDER_PAGE_LIMIT}-page work budget`, + `session search provider exceeded the ${SESSION_SEARCH_PROVIDER_CALL_LIMIT}-call work budget`, ) } - providerPageCount++ - const page = await sessionQuery.searchSessions({ - query: request.payload.query, - eventFilters: [ - { kind: 'type', values: ['user/message', 'assistant/message', 'steering/message'] }, - { kind: 'surface', values: ['current'] }, - ], - limit: SESSION_SEARCH_LIMIT, - ...cursor === undefined ? {} : { cursor }, - }, { signal }) + providerCallCount++ + const requestedCursor = cursor + let page + try { + page = await sessionQuery.searchSessions({ + query: request.payload.query, + eventFilters: [ + { kind: 'type', values: ['user/message', 'assistant/message', 'steering/message'] }, + { kind: 'surface', values: ['current'] }, + ], + limit: SESSION_SEARCH_LIMIT, + ...requestedCursor === undefined ? {} : { cursor: requestedCursor }, + }, { signal }) + } catch (error: unknown) { + if (isAborted(signal)) return cancelled() + if ( + requestedCursor !== undefined + && error instanceof SessionQueryError + && error.code === 'SESSION_QUERY_STALE_CURSOR' + ) { + authorized.length = 0 + acceptedIds.clear() + seenCursors.clear() + cursor = undefined + continue + } + throw error + } if (isAborted(signal)) return cancelled() const providerItemCount = page.items.length if (providerItemCount > SESSION_SEARCH_LIMIT) { @@ -691,10 +734,11 @@ export function createApiProxy(ctx: Context, defaults: ApiProxyDefaults): ApiPro || !MESSAGE_TYPES.has(hit.bestMatch.type) || acceptedIds.has(hit.header.id) ) continue + const snippet = boundedSessionSearchSnippet(hit.bestMatch.snippet) acceptedIds.add(hit.header.id) authorized.push({ sessionId: hit.header.id, - snippet: hit.bestMatch.snippet, + snippet, }) } const nextCursor = page.nextCursor diff --git a/packages/host/apiproxy/tests/api-proxy-search.spec.ts b/packages/host/apiproxy/tests/api-proxy-search.spec.ts index 734ddfc499..0ab2d97792 100644 --- a/packages/host/apiproxy/tests/api-proxy-search.spec.ts +++ b/packages/host/apiproxy/tests/api-proxy-search.spec.ts @@ -225,7 +225,7 @@ describe('session.search', () => { expect(searchSessions.mock.calls[1]?.[0]).toMatchObject({ cursor: 'page-2' }) }) - it('fails closed after 100 provider pages with distinct continuation cursors', async () => { + it('fails closed after 100 provider calls with distinct continuation cursors', async () => { const ctx = await baseContext() ctx.sessions.create(sid('visible'), { meta: header('visible') }) let pageNumber = 0 @@ -247,10 +247,153 @@ describe('session.search', () => { expect(response.result.ok).toBe(false) if (response.result.ok) throw new Error('unreachable') expect(response.result.error).toMatchObject({ code: 'internal' }) - expect(response.result.error.message).toContain('100-page work budget') + expect(response.result.error.message).toContain('100-call work budget') expect(searchSessions).toHaveBeenCalledTimes(100) }) + it('restarts a stale continuation from one fresh generation and keeps the visibility snapshot', async () => { + const ctx = await baseContext() + const oldOnly = hit('old-only', 0) + const shared = hit('shared', 1) + const freshFirst = hit('fresh-first', 2) + const freshLast = hit('fresh-last', 3) + for (const item of [oldOnly, shared, freshFirst, freshLast]) { + ctx.sessions.create(item.header.id, { meta: item.header }) + } + const late = hit('late-visible', 4) + const stale = new SessionQueryError( + 'provider generation changed', + 'SESSION_QUERY_STALE_CURSOR', + ) + const searchSessions = vi.fn((providerRequest: SessionSearchRequest) => { + switch (searchSessions.mock.calls.length) { + case 1: + expect(providerRequest).not.toHaveProperty('cursor') + return Promise.resolve({ + items: [oldOnly, shared], + nextCursor: 'old-cursor', + }) + case 2: + expect(providerRequest.cursor).toBe('old-cursor') + ctx.sessions.create(late.header.id, { meta: late.header }) + return Promise.reject(stale) + case 3: + expect(providerRequest).not.toHaveProperty('cursor') + return Promise.resolve({ + items: [freshFirst, shared], + nextCursor: 'old-cursor', + }) + case 4: + expect(providerRequest.cursor).toBe('old-cursor') + return Promise.resolve({ items: [freshLast, late] }) + default: + return Promise.reject(new Error('unexpected provider call')) + } + }) + ctx.provide('sessionQuery', { searchSessions } as never) + + const response = await createApiProxy(ctx, defaults).sessions.search( + request('stale-restart'), + new AbortController().signal, + ) + + expect(response.result).toEqual({ + ok: true, + value: { + items: [ + { sessionId: 'fresh-first', snippet: 'match 2' }, + { sessionId: 'shared', snippet: 'match 1' }, + { sessionId: 'fresh-last', snippet: 'match 3' }, + ], + hasMore: false, + }, + }) + expect(searchSessions).toHaveBeenCalledTimes(4) + }) + + it('counts continuous stale restarts against the 100-call budget', async () => { + const ctx = await baseContext() + const partial = hit('partial') + ctx.sessions.create(partial.header.id, { meta: partial.header }) + const stale = new SessionQueryError( + 'provider generation changed', + 'SESSION_QUERY_STALE_CURSOR', + ) + const searchSessions = vi.fn((providerRequest: SessionSearchRequest) => { + if (searchSessions.mock.calls.length > 100) { + return Promise.reject(new Error('provider was called after the shared budget')) + } + if (providerRequest.cursor !== undefined) return Promise.reject(stale) + return Promise.resolve({ + items: [partial], + nextCursor: `cursor-${searchSessions.mock.calls.length}`, + }) + }) + ctx.provide('sessionQuery', { searchSessions } as never) + + const response = await createApiProxy(ctx, defaults).sessions.search( + request('stale-churn'), + new AbortController().signal, + ) + + expect(response.result.ok).toBe(false) + if (response.result.ok) throw new Error('unreachable') + expect(response.result.error.code).toBe('internal') + expect(response.result.error.message).toContain('100-call work budget') + expect(response.result).not.toHaveProperty('value') + expect(searchSessions).toHaveBeenCalledTimes(100) + }) + + it('gives abort priority over a coincident stale continuation failure', async () => { + const ctx = await baseContext() + ctx.sessions.create(sid('visible'), { meta: header('visible') }) + const controller = new AbortController() + const stale = new SessionQueryError( + 'provider generation changed', + 'SESSION_QUERY_STALE_CURSOR', + ) + const searchSessions = vi.fn() + .mockResolvedValueOnce({ items: [], nextCursor: 'stale-cursor' }) + .mockImplementationOnce(() => { + controller.abort() + return Promise.reject(stale) + }) + ctx.provide('sessionQuery', { searchSessions } as never) + + const response = await createApiProxy(ctx, defaults).sessions.search( + request('abort-stale'), + controller.signal, + ) + + expect(response.result).toMatchObject({ + ok: false, + error: { code: 'cancelled' }, + }) + expect(searchSessions).toHaveBeenCalledTimes(2) + }) + + it('does not retry a stale first-page failure', async () => { + const ctx = await baseContext() + ctx.sessions.create(sid('visible'), { meta: header('visible') }) + const searchSessions = vi.fn(() => Promise.reject(new SessionQueryError( + 'provider generation changed before paging', + 'SESSION_QUERY_STALE_CURSOR', + ))) + ctx.provide('sessionQuery', { searchSessions } as never) + + const response = await createApiProxy(ctx, defaults).sessions.search( + request('first-page-stale'), + new AbortController().signal, + ) + + expect(response.result).toMatchObject({ + ok: false, + error: { code: 'internal' }, + }) + expect(response.result).not.toHaveProperty('value') + expect(searchSessions).toHaveBeenCalledOnce() + }) + it('rejects an oversized provider page before iterating its items', async () => { const ctx = await baseContext() ctx.sessions.create(sid('visible'), { meta: header('visible') }) @@ -272,6 +415,61 @@ describe('session.search', () => { expect(iterate).not.toHaveBeenCalled() }) + it('bounds provider snippets to 240 Unicode code points without splitting astral text', async () => { + const ctx = await baseContext() + const visible = hit('visible') + ctx.sessions.create(visible.header.id, { meta: visible.header }) + const expected = `${'x'.repeat(239)}😀` + const overlong = { + ...visible, + bestMatch: { + ...visible.bestMatch, + snippet: `${expected}${'y'.repeat(10_000)}`, + }, + } + ctx.provide('sessionQuery', { + searchSessions: () => Promise.resolve({ items: [overlong] }), + } as never) + + const response = await createApiProxy(ctx, defaults).sessions.search( + request('bounded-snippet'), + new AbortController().signal, + ) + + expect(response.result).toEqual({ + ok: true, + value: { + items: [{ sessionId: 'visible', snippet: expected }], + hasMore: false, + }, + }) + }) + + it('fails closed when the provider returns a non-string snippet', async () => { + const ctx = await baseContext() + const visible = hit('visible') + ctx.sessions.create(visible.header.id, { meta: visible.header }) + ctx.provide('sessionQuery', { + searchSessions: () => Promise.resolve({ + items: [{ + ...visible, + bestMatch: { ...visible.bestMatch, snippet: 42 }, + }], + }), + } as never) + + const response = await createApiProxy(ctx, defaults).sessions.search( + request('malformed-snippet'), + new AbortController().signal, + ) + + expect(response.result.ok).toBe(false) + if (response.result.ok) throw new Error('unreachable') + expect(response.result.error.code).toBe('internal') + expect(response.result.error.message).toContain('non-string snippet') + expect(response.result).not.toHaveProperty('value') + }) + it('inspects only numerically stored items when a compliant page overrides iteration', async () => { const ctx = await baseContext() const visible = Array.from({ length: 21 }, (_, index) => hit(`visible-${index}`, index)) diff --git a/packages/session-query/session-query-sqlite/README.i18n.yaml b/packages/session-query/session-query-sqlite/README.i18n.yaml index 9c5f95f8ce..88e88cc15d 100644 --- a/packages/session-query/session-query-sqlite/README.i18n.yaml +++ b/packages/session-query/session-query-sqlite/README.i18n.yaml @@ -1,6 +1,6 @@ # Bilingual-pair consistency record (docs/i18n/README.md): the git blob hash of each # side as of the last confirmed-consistent state. Both languages carry equal authority; # after editing either side, bring the other along and re-record with: -# pnpm run verify-translation-pairing --write -README.md: ceffb3ac25bc8b5252d6cc40cd6389839dfce1e2 -README.zh.md: 4e11ae9c9b8012045a7f3bab5d5c45724e553303 +# pnpm run verify-translation-pairing --write packages/session-query/session-query-sqlite/README.md +README.md: 4bf4d979f2d2954cd6280c80bf7f5988d8121fd1 +README.zh.md: afa45ad364a92e0268cf40c90dd61b163be0e18f diff --git a/packages/session-query/session-query-sqlite/README.md b/packages/session-query/session-query-sqlite/README.md index ceffb3ac25..4bf4d979f2 100644 --- a/packages/session-query/session-query-sqlite/README.md +++ b/packages/session-query/session-query-sqlite/README.md @@ -16,6 +16,8 @@ All three surfaces (`current`, `shadowed`, and `log-only`) are searchable by def The service requires `ctx.sessions` and observes optional `ctx.sessionPersistence` dynamically. One serialized state machine compares source-qualified lightweight durable snapshot revisions, non-mutatingly inspects only new or changed logs, extracts shared semantic documents, reconciles changes transactionally, and runs the query. Session queries never invoke the persistence backend's crash-repairing `load()`; an owner attaching during inspection cannot mutate its log, and the stable-observation retry makes the result live-preferred. The TEMP live row still records persisted availability, and the durable base refreshes after that live owner detaches. Repeated queries and an unchanged same-store reopen perform no full durable-log inspection; switching stores, or observing new, changed, deleted, or externally load-repaired sources, reconciles on the next stable observation. Source or transaction failure commits nothing, and the next search retries. +`openAt: startup` is the default: service activation imports `node:sqlite`, opens the handle, and fails before publication when the index is invalid. `openAt: first-search` publishes the service as ACTIVE without importing the SQLite module or opening a handle; the first concurrent searches share one readiness promise, and disposal before any search opens nothing. This mode supports compositions that need clean Node 22 startup output by deferring SQLite's experimental warning until the first actual search; it does not suppress a warning at that point. An invalid database likewise fails the first search instead of service activation. + Persisted FTS rows live in a dedicated derived database. Connection-local TEMP tables hold live rows, which shadow the durable base for the same session and reveal it when the live owner disappears. Unmounting persistence hides durable rows without discarding the cache; remounting reconciles it. Closing or reopening the database drops every live overlay while retaining persisted rows. The database is disposable but reset is guarded: every recognized schema version rejects unknown user tables before mutating journal mode, and only a recognized incompatible schema containing derived tables rebuilds in place. An unrelated or canonical database is refused. Never point `path` at the session-persistence database. On filesystems with POSIX modes, missing directories and databases are created owner-only (`0700` and `0600` before the process umask), and SQLite sidecars inherit the database mode; existing modes are preserved. Exactly one service in one process owns a derived-index path; external writers or a second process are unsupported because generations and TEMP shadow state are connection-owned. @@ -25,6 +27,7 @@ The database is disposable but reset is guarded: every recognized schema version | Key | Default | Contract | |---|---:|---| | `path` | required | Dedicated derived-index SQLite path; `:memory:` is supported. Missing filesystem paths are created owner-only on POSIX filesystems. | +| `openAt` | `startup` | `startup` opens before service activation completes; `first-search` defers the SQLite module and handle until search. | | `journalMode` | `wal` | `wal`, `delete`, `truncate`, or `persist`. | | `defaultLimit` | `20` | Page size when a request omits `limit`; at most `Number.MAX_SAFE_INTEGER - 1`. | | `maxLimit` | `100` | Largest accepted request page size; at most `Number.MAX_SAFE_INTEGER - 1`. | diff --git a/packages/session-query/session-query-sqlite/README.zh.md b/packages/session-query/session-query-sqlite/README.zh.md index 4e11ae9c9b..afa45ad364 100644 --- a/packages/session-query/session-query-sqlite/README.zh.md +++ b/packages/session-query/session-query-sqlite/README.zh.md @@ -16,6 +16,8 @@ 该服务需要 `ctx.sessions`,并动态观察可选的 `ctx.sessionPersistence`。一个串行化状态机比较来源限定的轻量持久化快照修订,以非变更方式只检查新日志或已更改日志,提取共享语义文档,以事务方式对账变更,然后运行查询。会话查询绝不会调用持久化后端会修复崩溃的 `load()`;检查期间附加的 owner 无法修改其日志,稳定观察重试使结果优先使用实时来源。TEMP 实时行仍会记录持久化可用性,而持久基库会在该实时 owner 脱离后刷新。重复查询和未变的同存储重新打开不会执行完整持久化日志检查;切换存储,或观察到新增、已更改、已删除或经外部 load 修复的来源时,会在下次稳定观察时对账。来源或事务失败不会提交任何内容,下一次搜索会重试。 +`openAt: startup` 是默认值:服务激活会导入 `node:sqlite` 并打开句柄;如果索引无效,则会在服务发布前失败。`openAt: first-search` 会将服务以 ACTIVE 状态发布,同时不导入 SQLite 模块也不打开句柄;首批并发搜索共享同一个就绪 promise,在任何搜索前处置服务时也不会导入模块或打开句柄。此模式通过把 SQLite 的实验性警告推迟到首次实际搜索,支持需要干净 Node 22 启动输出的组合;它不会抑制届时的警告。无效数据库同样会使首次搜索失败,而不是服务激活失败。 + 持久化 FTS 行位于专用派生数据库中。连接本地 TEMP 表保存实时行,这些行会遮蔽同一会话的持久化基库,并在实时 owner 消失后使其重新可见。卸载持久化会隐藏持久行,但不会丢弃缓存;重新挂载会对账缓存。关闭或重新打开数据库会删除全部实时覆盖层,但保留持久行。 该数据库可丢弃,但 reset 受到保护:每个已识别 schema 版本都会在修改 journal mode 前拒绝未知用户表;只有包含派生表的已识别不兼容 schema 才会原地重建。不相关数据库或规范数据库将被拒绝。绝不能将 `path` 指向 session-persistence 数据库。在具有 POSIX mode 的文件系统上,缺失的目录和数据库会以仅所有者可访问的方式创建(进程 umask 前为 `0700` 和 `0600`),SQLite sidecar 继承数据库 mode;现有 mode 保持不变。每个派生索引路径在一个进程中只能由一个服务拥有;不支持外部写入者或第二个进程,因为世代和 TEMP 遮蔽状态归连接所有。 @@ -25,6 +27,7 @@ | 键 | 默认值 | 契约 | |---|---:|---| | `path` | required | 专用派生索引 SQLite 路径;支持 `:memory:`。在 POSIX 文件系统上,缺失的文件系统路径会以仅所有者可访问的方式创建。 | +| `openAt` | `startup` | `startup` 会在服务激活完成前打开;`first-search` 把 SQLite 模块与句柄推迟到搜索时再加载和打开。 | | `journalMode` | `wal` | `wal`、`delete`、`truncate` 或 `persist`。 | | `defaultLimit` | `20` | 请求省略 `limit` 时的分页大小;最多为 `Number.MAX_SAFE_INTEGER - 1`。 | | `maxLimit` | `100` | 接受的最大请求分页大小;最多为 `Number.MAX_SAFE_INTEGER - 1`。 | diff --git a/packages/session-query/session-query-sqlite/src/index.ts b/packages/session-query/session-query-sqlite/src/index.ts index 9f19108180..8e95196663 100644 --- a/packages/session-query/session-query-sqlite/src/index.ts +++ b/packages/session-query/session-query-sqlite/src/index.ts @@ -5,7 +5,7 @@ */ import { createHash, randomUUID } from 'node:crypto' -import { DatabaseSync } from 'node:sqlite' +import type { DatabaseSync } from 'node:sqlite' import { Context, Service, type Fiber } from 'cordis' import z from 'schemastery' import type { Session, SessionEvent, SessionHeader, SessionId } from '@deepseek-ai/dsh-session' @@ -72,6 +72,9 @@ export const SESSION_QUERY_SQLITE_SNIPPET_CHARS = 240 // One transient source change gets a retry; repeated churn fails rather than monopolizing the queue. const STABLE_OBSERVATION_ATTEMPTS = 2 +/** SQLite module/handle opening phase. */ +export type OpenAt = 'startup' | 'first-search' + /** Combined session-query configuration backed by SQLite full-text search. */ export interface Config extends SessionQueryConfig { /** @@ -80,6 +83,8 @@ export interface Config extends SessionQueryConfig { * POSIX filesystems; existing modes are preserved. */ path: string + /** Open the SQLite module and handle at service activation or the first search. Defaults to `startup`. */ + openAt?: OpenAt /** SQLite journal mode. Defaults to `wal`. */ journalMode?: JournalMode /** Page size when a request omits `limit`. At most `Number.MAX_SAFE_INTEGER - 1`; defaults to 20. */ @@ -94,6 +99,7 @@ export interface Config extends SessionQueryConfig { interface ResolvedConfig { path: string + openAt: OpenAt journalMode: JournalMode defaultLimit: number maxLimit: number @@ -175,6 +181,7 @@ export class SessionQuerySqlite extends SessionQueryService { static Config: z = z.object({ path: z.string().required(), + openAt: z.union(['startup', 'first-search'] as const).default('startup'), journalMode: z.union(['wal', 'delete', 'truncate', 'persist'] as const).default('wal'), defaultLimit: z.number().step(1).min(1).max(SQLITE_MAX_PAGE_LIMIT).default(SESSION_QUERY_SQLITE_DEFAULT_LIMIT), maxLimit: z.number().step(1).min(1).max(SQLITE_MAX_PAGE_LIMIT).default(SESSION_QUERY_SQLITE_MAX_LIMIT), @@ -191,7 +198,7 @@ export class SessionQuerySqlite extends SessionQueryService { readonly config: ResolvedConfig private readonly _instance = randomUUID() - private readonly _ready: Promise + private _ready: Promise | undefined private _db: DatabaseSync | undefined private _persistenceBinding: PersistenceBinding = { identity: Symbol() } private _lastPersistenceIdentity: symbol | undefined @@ -208,7 +215,6 @@ export class SessionQuerySqlite extends SessionQueryService { // register `ctx.sessionQuery`; keep that same validated value afterward. super(ctx, config = resolveConfig(config)) this.config = config as ResolvedConfig - this._ready = this._open() this._optionalPersistenceFiber = ctx.inject(['sessionPersistence'], (childCtx: Context) => { const service = childCtx.sessionPersistence const binding = { identity: Symbol(), service } @@ -225,9 +231,9 @@ export class SessionQuerySqlite extends SessionQueryService { ctx.effect(() => async () => this.close(), 'sessionQuerySqlite.close') } - /** Open the index before Cordis publishes this combined service as active. */ + /** Open eagerly only when activation owns the configured readiness boundary. */ protected async [Service.init](): Promise { - await this._ensureReady(undefined) + if (this.config.openAt === 'startup') await this._ensureReady(undefined) } override async searchSessions( @@ -296,10 +302,12 @@ export class SessionQuerySqlite extends SessionQueryService { private async _close(): Promise { this._closed = true await this._tail - try { - await this._ready - } catch { - // Opening already closed a partially-created handle; disposal only waits. + if (this._ready !== undefined) { + try { + await this._ready + } catch { + // Opening already closed a partially-created handle; disposal only waits. + } } this._db?.close() this._db = undefined @@ -315,6 +323,7 @@ export class SessionQuerySqlite extends SessionQueryService { } private async _ensureReady(signal: AbortSignal | undefined): Promise { + this._ready ??= this._open() try { await waitWithAbort(this._ready, signal) } catch (error: unknown) { @@ -946,6 +955,7 @@ function invalidCursor(cause: unknown): SessionQueryError { function resolveConfig(config: Config): ResolvedConfig { const resolved: ResolvedConfig = { path: config.path, + openAt: config.openAt ?? 'startup', journalMode: config.journalMode ?? 'wal', defaultLimit: config.defaultLimit ?? SESSION_QUERY_SQLITE_DEFAULT_LIMIT, maxLimit: config.maxLimit ?? SESSION_QUERY_SQLITE_MAX_LIMIT, @@ -957,6 +967,8 @@ function resolveConfig(config: Config): ResolvedConfig { if (typeof resolved.path !== 'string' || resolved.path.trim().length === 0) { throw invalidConfig('path must not be blank') } + const openPhases: readonly string[] = ['startup', 'first-search'] + if (!openPhases.includes(resolved.openAt)) throw invalidConfig('openAt is not supported') assertPageLimit('defaultLimit', resolved.defaultLimit) assertPageLimit('maxLimit', resolved.maxLimit) assertPositiveInteger('snippetChars', resolved.snippetChars) diff --git a/packages/session-query/session-query-sqlite/src/schema.ts b/packages/session-query/session-query-sqlite/src/schema.ts index 47f6374ba6..073b42d19e 100644 --- a/packages/session-query/session-query-sqlite/src/schema.ts +++ b/packages/session-query/session-query-sqlite/src/schema.ts @@ -1,6 +1,6 @@ /** SQLite schema for the disposable session full-text read model. */ -import { DatabaseSync } from 'node:sqlite' +import type { DatabaseSync } from 'node:sqlite' import { mkdir, open } from 'node:fs/promises' import { dirname, resolve } from 'node:path' @@ -49,6 +49,7 @@ export async function openSearchDatabase(path: string, journalMode: JournalMode) await mkdir(dirname(actual), { recursive: true, mode: 0o700 }) await createDatabaseFile(actual) } + const { DatabaseSync } = await import('node:sqlite') const db = new DatabaseSync(actual) try { const { application_id: applicationId } = db.prepare('PRAGMA application_id').get() as { application_id: number } diff --git a/packages/session-query/session-query-sqlite/tests/lazy-open.compat.spec.ts b/packages/session-query/session-query-sqlite/tests/lazy-open.compat.spec.ts new file mode 100644 index 0000000000..eea18805fa --- /dev/null +++ b/packages/session-query/session-query-sqlite/tests/lazy-open.compat.spec.ts @@ -0,0 +1,45 @@ +/** + * Node 22 startup-output smoke for first-search SQLite opening. + * + * The isolated subprocess omits NODE_OPTIONS so warning suppression cannot + * hide a static node:sqlite import. + */ + +import { execFile } from 'node:child_process' +import { resolve } from 'node:path' +import { promisify } from 'node:util' +import { expect, it } from 'vitest' + +const execFileAsync = promisify(execFile) +const root = resolve(import.meta.dirname, '../../../..') + +it('mounts and disposes first-search mode without a SQLite experimental warning', async () => { + const script = ` + import { Context } from 'cordis' + import SessionStore from '@deepseek-ai/dsh-session' + import SessionQuerySqlite from './packages/session-query/session-query-sqlite/src/index.ts' + + const ctx = new Context() + const sessions = await ctx.plugin(SessionStore) + const search = await ctx.plugin(SessionQuerySqlite, { + path: ':memory:', + openAt: 'first-search', + }) + await search.dispose() + await sessions.dispose() + ` + const env = { ...process.env } + delete env.NODE_OPTIONS + const { stderr } = await execFileAsync(process.execPath, [ + '--import', + 'tsx', + '--input-type=module', + '--eval', + script, + ], { + cwd: root, + env, + }) + + expect(stderr).not.toMatch(/ExperimentalWarning: SQLite/) +}) diff --git a/packages/session-query/session-query-sqlite/tests/sqlite.spec.ts b/packages/session-query/session-query-sqlite/tests/sqlite.spec.ts index 2fdd0b1e89..9251f6c7f2 100644 --- a/packages/session-query/session-query-sqlite/tests/sqlite.spec.ts +++ b/packages/session-query/session-query-sqlite/tests/sqlite.spec.ts @@ -177,16 +177,19 @@ async function liveContext(config: ConstructorParameters { - it('defaults and validates persisted inspection concurrency through its Cordis config', async () => { + it('defaults and validates opening policy and persisted inspection concurrency through its Cordis config', async () => { const defaultCtx = await liveContext() + expect((defaultCtx.sessionQuery as SessionQuerySqlite).config.openAt).toBe('startup') expect((defaultCtx.sessionQuery as SessionQuerySqlite).config.persistedInspectConcurrency) .toBe(SESSION_QUERY_DEFAULT_PERSISTED_INSPECT_CONCURRENCY) const configuredValue = 2 const configured = new SessionQuerySqlite.Config({ path: ':memory:', + openAt: 'first-search', persistedInspectConcurrency: configuredValue, }) + expect(configured.openAt).toBe('first-search') expect(configured.persistedInspectConcurrency).toBe(configuredValue) const configuredCtx = await liveContext(configured) expect((configuredCtx.sessionQuery as SessionQuerySqlite).config.persistedInspectConcurrency) @@ -198,6 +201,72 @@ describe('SQLite session search', () => { persistedInspectConcurrency, })).toThrow() } + expect(() => new SessionQuerySqlite.Config({ + path: ':memory:', + openAt: 'later' as never, + })).toThrow() + }) + + it('mounts and disposes first-search mode without opening its database', async () => { + const path = await temporaryPath('unopened.db') + const ctx = new Context() + await ctx.plugin(SessionStore) + const search = await ctx.plugin(SessionQuerySqlite, { + path, + openAt: 'first-search', + }) + + await expect(stat(path)).rejects.toMatchObject({ code: 'ENOENT' }) + await search.dispose() + await expect(stat(path)).rejects.toMatchObject({ code: 'ENOENT' }) + }) + + it('opens once on the first search and reuses readiness for later searches', async () => { + const ctx = new Context() + await ctx.plugin(SessionStore) + await ctx.plugin(SessionQuerySqlite, { + path: ':memory:', + openAt: 'first-search', + }) + const service = ctx.sessionQuery as SessionQuerySqlite + const internals = service as unknown as { _open(): Promise } + const open = vi.spyOn(internals, '_open') + + await expect(service.searchSessions({ query: 'first' })).resolves.toEqual({ items: [] }) + await expect(service.searchSessions({ query: 'second' })).resolves.toEqual({ items: [] }) + + expect(open).toHaveBeenCalledOnce() + }) + + it('shares one readiness promise across concurrent first searches', async () => { + const ctx = new Context() + await ctx.plugin(SessionStore) + await ctx.plugin(SessionQuerySqlite, { + path: ':memory:', + openAt: 'first-search', + }) + const service = ctx.sessionQuery as SessionQuerySqlite + const internals = service as unknown as { _open(): Promise } + const originalOpen = internals._open.bind(internals) + const release = Promise.withResolvers() + const started = Promise.withResolvers() + const open = vi.spyOn(internals, '_open').mockImplementation(async () => { + started.resolve(undefined) + await release.promise + await originalOpen() + }) + + const first = service.searchSessions({ query: 'first' }) + const second = service.searchSessions({ query: 'second' }) + await started.promise + expect(open).toHaveBeenCalledOnce() + release.resolve(undefined) + + await expect(Promise.all([first, second])).resolves.toEqual([ + { items: [] }, + { items: [] }, + ]) + expect(open).toHaveBeenCalledOnce() }) it('searches two-character Unicode61 tokens in live-only sessions', async () => { @@ -522,6 +591,7 @@ describe('SQLite session search', () => { { path: ':memory:', persistedInspectConcurrency: 0 }, { path: ':memory:', persistedInspectConcurrency: Number.MAX_SAFE_INTEGER + 1 }, { path: ':memory:', defaultLimit: 3, maxLimit: 2 }, + { path: ':memory:', openAt: 'later' }, { path: ':memory:', journalMode: 'memory' }, ]) { const direct = new Context() @@ -1238,6 +1308,30 @@ describe('SQLite schema, cancellation, and real persistence integration', () => } }) + it('defers an invalid database failure only in first-search mode', async () => { + const path = await temporaryPath('lazy-invalid.db') + const foreign = new DatabaseSync(path) + foreign.exec('CREATE TABLE canonical(value TEXT)') + foreign.close() + + const lazyCtx = new Context() + await lazyCtx.plugin(SessionStore) + const lazy = await lazyCtx.plugin(SessionQuerySqlite, { + path, + openAt: 'first-search', + }) + expect(lazyCtx.sessionQuery).toBeInstanceOf(SessionQuerySqlite) + await expect(lazyCtx.sessionQuery.searchSessions({ query: 'needle' })) + .rejects.toThrow(expectCode('SESSION_QUERY_INDEX_FAILED')) + await lazy.dispose() + + const eagerCtx = new Context() + await eagerCtx.plugin(SessionStore) + await expect(eagerCtx.plugin(SessionQuerySqlite, { path })) + .rejects.toThrow(expectCode('SESSION_QUERY_INDEX_FAILED')) + expect(eagerCtx.sessionQuery).toBeUndefined() + }) + it.each(['sessions', 'events'] as const)( 'forwards one exact reconciliation signal through both snapshot lists and persisted inspection for %s search', async (scope) => { diff --git a/scripts/run-gates.ts b/scripts/run-gates.ts index ae11479274..7905fcfc18 100644 --- a/scripts/run-gates.ts +++ b/scripts/run-gates.ts @@ -261,6 +261,11 @@ function nodeCompatSmokeGates(): Gate[] { 'run', 'packages/session-persistence/session-persistence-jsonl/tests/zstd.compat.spec.ts', ], { label: 'JSONL Zstandard smoke' }), + pnpmExec('session-query-lazy-open-smoke', [ + 'vitest', + 'run', + 'packages/session-query/session-query-sqlite/tests/lazy-open.compat.spec.ts', + ], { label: 'session-query lazy-open smoke' }), ] } From 0aa7f8c5cf6e682df87de52b24502b2036bc0761 Mon Sep 17 00:00:00 2001 From: Hypatia May Date: Mon, 27 Jul 2026 14:46:08 +0800 Subject: [PATCH 011/139] fix(web): converge session search boundaries (round 9) --- .../2026-07-27-web-session-search.i18n.yaml | 4 +- .../feature/2026-07-27-web-session-search.md | 6 +- .../2026-07-27-web-session-search.zh.md | 6 +- .../tests/lazy-search-startup.compat.spec.ts | 109 ++++++++++ apps/web/tests/navigation-panes.e2e.ts | 10 +- apps/web/tests/scaffold.ts | 2 +- .../lifecycle-chrome/hero.expected.md | 4 +- .../search-results.expected.md | 2 +- packages/client/connection/README.i18n.yaml | 6 +- packages/client/connection/README.md | 2 +- packages/client/connection/README.zh.md | 2 +- .../client/connection/src/client/fixture.ts | 117 ++++++++--- .../client/connection/tests/fixture.spec.ts | 17 ++ packages/client/ui-workspace/README.i18n.yaml | 4 +- packages/client/ui-workspace/README.md | 2 +- packages/client/ui-workspace/README.zh.md | 2 +- .../src/client/WorkspaceBrowser.tsx | 36 +++- .../client/ui-workspace/tests/tree.spec.ts | 2 + .../tests/workspace-browser.spec.tsx | 91 +++++++-- packages/host/apiproxy/README.i18n.yaml | 4 +- packages/host/apiproxy/README.md | 4 +- packages/host/apiproxy/README.zh.md | 4 +- packages/host/apiproxy/src/api-proxy.ts | 17 +- .../host/apiproxy/src/api/sessions.schema.ts | 25 ++- .../apiproxy/tests/api-proxy-search.spec.ts | 192 +++++++++++++++++- .../apiproxy/tests/client-handler.spec.ts | 14 ++ .../host/apiproxy/tests/rpc-schemas.spec.ts | 8 + .../tests/lazy-open.compat.spec.ts | 45 ---- scripts/run-gates.ts | 49 ++++- 29 files changed, 629 insertions(+), 157 deletions(-) create mode 100644 apps/cli/tests/lazy-search-startup.compat.spec.ts delete mode 100644 packages/session-query/session-query-sqlite/tests/lazy-open.compat.spec.ts diff --git a/.agents/notes/implemented/feature/2026-07-27-web-session-search.i18n.yaml b/.agents/notes/implemented/feature/2026-07-27-web-session-search.i18n.yaml index 6124b31fb4..c17f464bc5 100644 --- a/.agents/notes/implemented/feature/2026-07-27-web-session-search.i18n.yaml +++ b/.agents/notes/implemented/feature/2026-07-27-web-session-search.i18n.yaml @@ -2,5 +2,5 @@ # side as of the last confirmed-consistent state. Both languages carry equal authority; # after editing either side, bring the other along and re-record with: # pnpm run verify-translation-pairing --write .agents/notes/implemented/feature/2026-07-27-web-session-search.md -2026-07-27-web-session-search.md: 8992fdf046c1256ab61278cf5189ba56df8b4ecd -2026-07-27-web-session-search.zh.md: 764e9f3363ae321c55e401cc52b35dcba790a0b4 +2026-07-27-web-session-search.md: a709719a04a787d9bfcbba0d73263abd84fabcc1 +2026-07-27-web-session-search.zh.md: 980e2638e5a2a819433525c26e0f336c08384409 diff --git a/.agents/notes/implemented/feature/2026-07-27-web-session-search.md b/.agents/notes/implemented/feature/2026-07-27-web-session-search.md index 8992fdf046..a709719a04 100644 --- a/.agents/notes/implemented/feature/2026-07-27-web-session-search.md +++ b/.agents/notes/implemented/feature/2026-07-27-web-session-search.md @@ -12,9 +12,9 @@ The Web sidebar exposes session titles and Workspace membership but cannot retri The shared Web/headless composition mounts [`@deepseek-ai/dsh-session-query-sqlite`](../../../../packages/session-query/session-query-sqlite/README.md) with `openAt: first-search` and an in-memory database. The service is ACTIVE at boot, while its `node:sqlite` module and connection-private handle open only on the first content query. This keeps Node 22 startup output free of SQLite's experimental warning before search is used without promising to suppress the warning when search first imports the module. Each service instance owns its index, preserving the SQLite backend's single-owner contract across parallel CLI or Web invocations without leaving process-scoped derived files behind. The database starts empty and lazily reconciles live and persisted sessions on that first query. It remains a disposable derived index, separate from canonical JSONL persistence. -The host gateway exposes `session.search` through the existing typed RPC stack. It derives the authorization set from the same visible summaries as `session.list`, asks `ctx.sessionQuery.searchSessions` for globally ranked current-surface `user/message`, `assistant/message`, and `steering/message` matches in pages capped at 20 hits, and consumes provider pages until it has 20 authorized sessions plus one lookahead or exhausts the stream. Every hit's session id, best-match session id, surface, event type, and snippet type are revalidated before its snippet leaves the Host, and emitted snippets contain at most 240 Unicode code points. Keeping the potentially large authorization set out of SQLite bindings avoids the portable variable ceiling while preserving global ranking. The response remains one bounded page; `hasMore` tells the UI to ask for a narrower query rather than exposing pagination. A stale continuation discards the current attempt's partial results, deduplication entries, and cursors, then restarts from the first page against the original visibility snapshot. Those retries share the limit of 100 provider calls (and therefore at most 2,000 inspected hits); an oversized page, a repeated continuation cursor, or a still-unexhausted stream at that call budget fails closed as an `internal` business error. The carrier signal cancels superseded work, including persistence listing, bounded batches of cold-session metadata stats, and each provider call, and wins over a concurrent stale rejection. A missing query service or an unrecovered indexing/query failure remains a business error and does not mutate the canonical session store. +The host gateway exposes `session.search` through the existing typed RPC stack. It derives the authorization set from the same visible summaries as `session.list`, asks `ctx.sessionQuery.searchSessions` for globally ranked current-surface `user/message`, `assistant/message`, and `steering/message` matches, and consumes provider pages until it has 20 authorized sessions plus one lookahead or exhausts the stream. The first provider page requests 20 hits; a first-page `SESSION_QUERY_INVALID_LIMIT` halves that size through 10, 5, 2, and 1, retaining the learned size across continuations and stale-generation restarts. Every hit's session id, best-match session id, surface, event type, and snippet type are revalidated before its snippet leaves the Host, and emitted snippets contain at most 240 Unicode code points; the wire response schema independently enforces the same code-point bound at client parse. Keeping the potentially large authorization set out of SQLite bindings avoids the portable variable ceiling while preserving global ranking. The response remains one bounded page; `hasMore` tells the UI to ask for a narrower query rather than exposing pagination. A stale continuation discards the current attempt's partial results, deduplication entries, and cursors, then restarts from the first page against the original visibility snapshot. Limit probes and stale retries share the limit of 100 provider calls (and therefore at most 2,000 inspected hits); a page larger than its requested limit, a repeated continuation cursor, or a still-unexhausted stream at that call budget fails closed as an `internal` business error. The carrier signal cancels superseded work, including persistence listing, bounded batches of cold-session metadata stats, and each provider call, and wins over a concurrent limit or stale rejection. A missing query service or an unrecovered indexing/query failure remains a business error and does not mutate the canonical session store. -[`WorkspaceBrowser`](../../../../packages/client/ui-workspace/README.md) keeps metadata and content search deliberately separate. A non-blank query immediately computes case-insensitive title and Workspace substring matches from the Session list, starts a 250 ms debounced content request, aborts the preceding request when the query changes, and ignores stale completions. It merges local matches first in recency order with backend-ranked content-only matches, deduplicates by session id, and renders a flat list regardless of the normal grouping mode. Each row shows the title, Workspace, and an available one-line snippet. Selecting a row opens the Session only and preserves the query; it does not navigate to an exact event. +[`WorkspaceBrowser`](../../../../packages/client/ui-workspace/README.md) keeps metadata and content search deliberately separate. Its default copy is English, and its input plus defensive request path remove NUL and cap queries at the request schema's 500 UTF-16 code units without splitting a surrogate pair. A non-blank query immediately computes case-insensitive title and Workspace substring matches from the Session list, starts a 250 ms debounced content request, aborts the preceding request when the query changes, and ignores stale completions. It merges local matches first in recency order with backend-ranked content-only matches, deduplicates by session id, and renders a flat list regardless of the normal grouping mode. Each row shows the title, Workspace, and an available one-line snippet. Selecting a row opens the Session only and preserves the query; it does not navigate to an exact event. Content matching inherits the SQLite backend's normalized literal token/phrase semantics. FTS5 operators are inert data, and this surface adds no typo, fuzzy, prefix, or arbitrary-substring expansion. In particular, the `unicode61` tokenizer may treat an uninterrupted Chinese sequence as one token, so a shorter query such as `搜索` is not guaranteed to match inside `会话搜索功能`. Title and Workspace matching remains ordinary client-side substring matching. @@ -39,4 +39,4 @@ The first content query can take longer because it imports and opens SQLite befo ## Testing -Host tests pin request validation, visible-session filtering, event/surface filters, result and snippet bounds, the shared provider-call budget, stale-generation restarts, cursor and cross-page deduplication behavior, continuation-page cancellation, and failure mapping. SQLite lifecycle tests pin eager activation, first-search opening and failure, shared readiness, and unopened disposal; a Node 22 compatibility subprocess pins warning-free mount and disposal before the first search. Runtime and UI tests pin stateless delegation, debounce/abort/stale-response behavior, local fallback, merge order, deduplication, row rendering, and navigation semantics. A keyless assembled Web test seeds an unopened persisted conversation, finds it by message content through the lazy SQLite index, captures the sidebar result, opens it, and verifies that the query remains. +Host tests pin request and response validation, visible-session filtering, event/surface filters, result and snippet bounds, adaptive provider limits inside the shared call budget, learned-limit stale restarts, cursor and cross-page deduplication behavior, cancellation precedence, and failure mapping. SQLite lifecycle tests pin eager activation, first-search opening and failure, shared readiness, and unopened disposal; the Node 22 compatibility gate builds the CLI and Web artifacts, boots the shipped `dsh web`/`AppCLIEntry` composition under plain Node with ambient warning suppression removed and an isolated temporary home/provider environment, waits for settled startup, and disposes it through the shipped signal path. Fixture, runtime, and UI tests pin match-centered bounded snippets, stateless delegation, the 500-code-unit query boundary, debounce/abort/stale-response behavior, local fallback, merge order, deduplication, English copy, row rendering, and navigation semantics. A keyless assembled Web test preserves the lazy-open config while seeding an unopened persisted conversation, finds it by message content through the SQLite index, captures the sidebar result, opens it, and verifies that the query remains. diff --git a/.agents/notes/implemented/feature/2026-07-27-web-session-search.zh.md b/.agents/notes/implemented/feature/2026-07-27-web-session-search.zh.md index 764e9f3363..980e2638e5 100644 --- a/.agents/notes/implemented/feature/2026-07-27-web-session-search.zh.md +++ b/.agents/notes/implemented/feature/2026-07-27-web-session-search.zh.md @@ -12,9 +12,9 @@ Web 侧边栏会展示会话标题及其 Workspace 归属,但无法根据只 Web 与 headless 共用的组合会使用 `openAt: first-search` 和内存数据库挂载 [`@deepseek-ai/dsh-session-query-sqlite`](../../../../packages/session-query/session-query-sqlite/README.md)。服务启动时处于 ACTIVE 状态,而其 `node:sqlite` 模块与连接私有句柄分别要到首次内容查询才会导入和打开。这让 Node 22 的启动输出在使用搜索前不会出现 SQLite 实验性警告,但并不承诺在首次搜索导入该模块时抑制警告。每个服务实例都独占自己的索引,因此并行 CLI 或 Web 调用可维持 SQLite 后端的单一所有者契约,又不会留下进程级派生文件。数据库从空状态启动,并在该首次查询时惰性对齐实时会话与持久化会话。它仍是与规范 JSONL 持久化相互独立的可丢弃派生索引。 -宿主网关通过现有的类型化 RPC 栈公开 `session.search`。它根据 `session.list` 使用的同一组可见摘要推导授权集合,向 `ctx.sessionQuery.searchSessions` 请求全局排序后的当前 surface `user/message`、`assistant/message` 和 `steering/message` 匹配项(每页最多 20 个命中),并持续消费提供方分页,直到获得 20 个已授权会话及一个前瞻项,或结果流耗尽。每个命中的会话 id、最佳匹配会话 id、surface、事件类型和 snippet 类型都会经过重新校验,其 snippet 才能离开宿主,且发出的 snippet 最多包含 240 个 Unicode 码点。将可能很大的授权集合排除在 SQLite 绑定之外,可避开可移植变量上限,同时保持全局排序。响应仍只有一个有界页面;`hasMore` 会指示 UI 提示用户缩小查询范围,而不是公开分页能力。陈旧的续传会丢弃当前尝试的部分结果、去重条目和游标,然后依据原始可见性快照从第一页重新开始。这些重试共用 100 次提供方调用的限制(因此最多检查 2,000 个命中);如果单页命中数超限、续传游标重复,或用尽该调用预算后结果流仍未耗尽,都会直接返回 `internal` 业务错误,不返回部分结果。载体信号会取消已被取代的工作,包括持久化列表枚举、分批受限执行的冷会话元数据 stat,以及每一次提供方调用;即使同时收到陈旧拒绝,也以取消为准。查询服务缺失或索引/查询故障无法恢复时,仍作为业务错误处理,不会修改规范会话存储。 +宿主网关通过现有的类型化 RPC 栈公开 `session.search`。它根据 `session.list` 使用的同一组可见摘要推导授权集合,向 `ctx.sessionQuery.searchSessions` 请求全局排序后的当前 surface `user/message`、`assistant/message` 和 `steering/message` 匹配项,并持续消费提供方分页,直到获得 20 个已授权会话及一个前瞻项,或结果流耗尽。首个提供方页面请求 20 个命中;如果第一页返回 `SESSION_QUERY_INVALID_LIMIT`,页面大小会依次折半为 10、5、2、1,并在续传和陈旧世代重启中沿用探测所得的大小。每个命中的会话 id、最佳匹配会话 id、surface、事件类型和 snippet 类型都会经过重新校验,其 snippet 才能离开宿主,且发出的 snippet 最多包含 240 个 Unicode 码点;传输响应 schema 会在客户端解析时独立强制执行相同的码点上限。将可能很大的授权集合排除在 SQLite 绑定之外,可避开可移植变量上限,同时保持全局排序。响应仍只有一个有界页面;`hasMore` 会指示 UI 提示用户缩小查询范围,而不是公开分页能力。陈旧的续传会丢弃当前尝试的部分结果、去重条目和游标,然后依据原始可见性快照从第一页重新开始。上限探测与陈旧重试共用 100 次提供方调用的限制(因此最多检查 2,000 个命中);如果某页命中数超过其请求的上限、续传游标重复,或用尽该调用预算后结果流仍未耗尽,都会直接返回 `internal` 业务错误,不返回部分结果。载体信号会取消已被取代的工作,包括持久化列表枚举、分批受限执行的冷会话元数据 stat,以及每一次提供方调用;即使同时收到上限拒绝或陈旧拒绝,也以取消为准。查询服务缺失或索引/查询故障无法恢复时,仍作为业务错误处理,不会修改规范会话存储。 -[`WorkspaceBrowser`](../../../../packages/client/ui-workspace/README.md) 有意将元数据搜索与内容搜索保持独立。非空白查询会立即从会话列表中计算不区分大小写的标题和 Workspace 子串匹配,在 250 ms 防抖后发起内容请求,在查询变化时中止前一请求,并忽略陈旧的完成结果。它先按新近程度排列本地匹配,再合并由后端排序且仅匹配内容的结果,按会话 id 去重;无论常规分组模式如何,最终都渲染为扁平列表。每一行显示标题、Workspace,并在存在时显示一行摘要片段。选择某一行只会打开对应会话,并保留查询条件;不会跳转至确切事件。 +[`WorkspaceBrowser`](../../../../packages/client/ui-workspace/README.md) 有意将元数据搜索与内容搜索保持独立。其默认界面文案为英文;输入框及防御性请求路径会移除 NUL,将查询限制在请求 schema 规定的 500 个 UTF-16 code unit 内且不会拆分 surrogate pair。非空白查询会立即从会话列表中计算不区分大小写的标题和 Workspace 子串匹配,在 250 ms 防抖后发起内容请求,在查询变化时中止前一请求,并忽略陈旧的完成结果。它先按新近程度排列本地匹配,再合并由后端排序且仅匹配内容的结果,按会话 id 去重;无论常规分组模式如何,最终都渲染为扁平列表。每一行显示标题、Workspace,并在存在时显示一行摘要片段。选择某一行只会打开对应会话,并保留查询条件;不会跳转至确切事件。 内容匹配沿用 SQLite 后端经过规范化的字面 token/短语语义。FTS5 运算符只作为数据处理,此搜索界面不提供拼写错误纠正、模糊匹配、前缀匹配或任意子串扩展。特别是,`unicode61` 分词器可能将一段连续中文视作单个 token,因此不保证 `搜索` 之类的较短查询能匹配 `会话搜索功能` 的内部片段。标题与 Workspace 匹配仍采用普通的客户端子串匹配。 @@ -39,4 +39,4 @@ Web 与 headless 共用的组合会使用 `openAt: first-search` 和内存数据 ## 测试 -宿主测试将请求校验、可见会话过滤、事件和 surface 过滤、结果与 snippet 边界、共享提供方调用预算、陈旧世代重启、游标与跨页去重行为、后续页取消及故障映射固定为契约。SQLite 生命周期测试将启动时激活、首次搜索时的打开与失败、共享就绪状态以及未打开状态下的处置固定为契约;一个 Node 22 兼容性子进程将首次搜索前无警告挂载与处置固定为契约。运行时与 UI 测试将无状态委托、防抖/中止/陈旧响应行为、本地回退、合并顺序、去重、行渲染与导航语义固定为契约。无密钥的组装层 Web 测试会播种一段尚未打开的持久化对话,通过惰性 SQLite 索引按消息内容找到它,捕获侧边栏结果,打开该会话,并验证查询条件仍然保留。 +宿主测试将请求与响应校验、可见会话过滤、事件和 surface 过滤、结果与 snippet 边界、共享调用预算内的自适应提供方上限、沿用探测所得上限的陈旧世代重启、游标与跨页去重行为、取消优先级及故障映射固定为契约。SQLite 生命周期测试将启动时激活、首次搜索时的打开与失败、共享就绪状态以及未打开状态下的处置固定为契约;Node 22 兼容性门禁会构建 CLI 与 Web 产物,在移除环境级警告抑制并采用隔离的临时 home/提供方环境后,以普通 Node 启动随产品交付的 `dsh web`/`AppCLIEntry` 组合,等待启动完成并稳定,再沿随产品交付的信号路径对其执行 dispose(资源释放)。fixture(测试前置数据)、运行时与 UI 测试将以匹配位置为中心的有界 snippet、无状态委托、500 个 code unit 的查询边界、防抖/中止/陈旧响应行为、本地回退、合并顺序、去重、英文文案、行渲染与导航语义固定为契约。无密钥的组装层 Web 测试会在保留惰性打开配置的同时,播种一段尚未打开的持久化对话,通过 SQLite 索引按消息内容找到它,捕获侧边栏结果,打开该会话,并验证查询条件仍然保留。 diff --git a/apps/cli/tests/lazy-search-startup.compat.spec.ts b/apps/cli/tests/lazy-search-startup.compat.spec.ts new file mode 100644 index 0000000000..96e9d24e1c --- /dev/null +++ b/apps/cli/tests/lazy-search-startup.compat.spec.ts @@ -0,0 +1,109 @@ +/** + * Node 22 startup-output smoke for the shipped Web CLI composition. + * + * The child runs built artifacts under plain Node with the real cordis.yml. + * Its URL line follows AppCLIEntry's settled boot; SIGTERM then exercises the + * shipped quiescent disposer. + */ + +import { spawn } from 'node:child_process' +import { existsSync } from 'node:fs' +import { mkdtemp, readFile, rm } from 'node:fs/promises' +import { tmpdir } from 'node:os' +import { join, resolve } from 'node:path' +import { fileURLToPath } from 'node:url' +import yaml from 'js-yaml' +import { describe, expect, it } from 'vitest' + +const repoRoot = fileURLToPath(new URL('../../../', import.meta.url)) +const builtBin = join(repoRoot, 'apps/cli/lib/bin.js') +const webDist = join(repoRoot, 'apps/web/dist/index.html') +const configPath = join(repoRoot, 'apps/cli/cordis.yml') +const requireBuiltArtifacts = process.env.DSH_REQUIRE_BUILT_CLI_SMOKE === '1' +const builtArtifactsPresent = existsSync(builtBin) && existsSync(webDist) + +interface ConfigRow { + id?: string + config?: { openAt?: unknown } +} + +const jsExprType = new yaml.Type('tag:yaml.org,2002:js', { + kind: 'scalar', + construct: value => String(value), +}) +const configSchema = yaml.JSON_SCHEMA.extend(jsExprType) + +/** Boot the built Web CLI, wait for its settled URL, then dispose through SIGTERM. */ +function runBuiltWeb(cwd: string): Promise<{ stdout: string; stderr: string; code: number }> { + return new Promise((resolveRun, rejectRun) => { + const env: NodeJS.ProcessEnv = { + ...process.env, + DEEPSEEK_API_KEY: 'dsh-cli-smoke-dummy-key', + DSH_HOME: join(cwd, '.dsh'), + } + delete env.DEEPSEEK_BASE_URL + delete env.NODE_OPTIONS + delete env.NODE_NO_WARNINGS + const child = spawn(process.execPath, [ + builtBin, + 'web', + '--host', + '127.0.0.1', + '--port', + '0', + ], { + cwd, + env, + stdio: ['ignore', 'pipe', 'pipe'], + }) + let stdout = '' + let stderr = '' + let settled = false + child.stdout.setEncoding('utf8') + child.stderr.setEncoding('utf8') + child.stdout.on('data', (chunk: string) => { + stdout += chunk + if (!settled && /dsh web: http:\/\/127\.0\.0\.1:\d+/u.test(stdout)) { + settled = true + child.kill('SIGTERM') + } + }) + child.stderr.on('data', (chunk: string) => { stderr += chunk }) + const timer = setTimeout(() => { + child.kill('SIGKILL') + rejectRun(new Error(`built Web CLI did not settle and dispose within 60s\nstdout:\n${stdout}\nstderr:\n${stderr}`)) + }, 60_000) + child.on('error', (error) => { + clearTimeout(timer) + rejectRun(error) + }) + child.on('close', (code) => { + clearTimeout(timer) + if (!settled) { + rejectRun(new Error(`built Web CLI exited before settled startup (code ${String(code)})\nstdout:\n${stdout}\nstderr:\n${stderr}`)) + return + } + resolveRun({ stdout, stderr, code: code ?? -1 }) + }) + }) +} + +describe.skipIf(!requireBuiltArtifacts && !builtArtifactsPresent)('built CLI lazy-search startup', () => { + it('boots and disposes the shipped composition without a SQLite startup warning', async () => { + expect(existsSync(builtBin), `missing built CLI ${resolve(builtBin)}; run pnpm build`).toBe(true) + expect(existsSync(webDist), `missing Web dist ${resolve(webDist)}; run pnpm run build:web`).toBe(true) + const rows = yaml.load(await readFile(configPath, 'utf8'), { schema: configSchema }) as ConfigRow[] + const searchRow = rows.find(row => row.id === 'session-query-sqlite') + expect(searchRow?.config?.openAt).toBe('first-search') + + const cwd = await mkdtemp(join(tmpdir(), 'dsh-cli-lazy-search-')) + try { + const result = await runBuiltWeb(cwd) + expect(result.stdout).toMatch(/dsh web: http:\/\/127\.0\.0\.1:\d+/u) + expect(result.code).toBe(0) + expect(result.stderr).not.toMatch(/ExperimentalWarning: SQLite/u) + } finally { + await rm(cwd, { recursive: true, force: true }) + } + }, 70_000) +}) diff --git a/apps/web/tests/navigation-panes.e2e.ts b/apps/web/tests/navigation-panes.e2e.ts index 7744ad5c55..d5acb3ee04 100644 --- a/apps/web/tests/navigation-panes.e2e.ts +++ b/apps/web/tests/navigation-panes.e2e.ts @@ -93,18 +93,18 @@ describe('web e2e: navigation & panes over a rich seeded session', () => { it.skipIf(MODE === 'record')('finds an unopened seeded session by message content and opens it', async () => { onTestFailed(() => saveFailureShot(page, 'web-e2e-navigation-search')) - const search = page.getByPlaceholder('搜索名称或关键词', { exact: false }) + const search = page.getByPlaceholder('Search names or content', { exact: false }) // The cold row has not been opened, so only the persisted log can satisfy // this query. First search lazily reconciles the SQLite content index. await search.fill('zzzqx-no-such-session') - await page.getByText('没有匹配结果').waitFor({ timeout: 30_000 }) + await page.getByText('No matching sessions').waitFor({ timeout: 30_000 }) await expect.poll( - () => page.getByRole('tree', { name: '搜索结果' }).getByRole('treeitem').count(), + () => page.getByRole('tree', { name: 'Search results' }).getByRole('treeitem').count(), { timeout: 10_000 }, ).toBe(0) await search.fill('WATERFALL') - const resultTree = page.getByRole('tree', { name: '搜索结果' }) + const resultTree = page.getByRole('tree', { name: 'Search results' }) const result = resultTree.getByRole('treeitem') await expect.poll(() => result.count(), { timeout: 30_000 }).toBe(1) await expect.poll(() => result.getByText('WATERFALL', { exact: false }).count(), { @@ -120,7 +120,7 @@ describe('web e2e: navigation & panes over a rich seeded session', () => { await expect.poll(() => search.inputValue(), { timeout: 5_000 }).toBe('WATERFALL') await expect.poll(() => page.getByText('FIRST_DONE', { exact: true }).count(), { timeout: 15_000 }).toBeGreaterThanOrEqual(1) await expect.poll(() => page.getByRole('heading', { name: 'Navigation Summary' }).count(), { timeout: 15_000 }).toBe(1) - await page.getByRole('button', { name: '清除搜索' }).click() + await page.getByRole('button', { name: 'Clear search' }).click() await expect.poll(() => search.inputValue(), { timeout: 5_000 }).toBe('') await expect.poll(() => page.locator('[role="treeitem"]').count(), { timeout: 10_000 }).toBeGreaterThanOrEqual(1) }, 90_000) diff --git a/apps/web/tests/scaffold.ts b/apps/web/tests/scaffold.ts index eb61619de0..c9390af80d 100644 --- a/apps/web/tests/scaffold.ts +++ b/apps/web/tests/scaffold.ts @@ -163,7 +163,7 @@ export async function launchWebScaffold(options: LaunchOptions = {}): Promise part.trim()).filter(Boolean).join('\n') } +interface FixtureSearchToken { + value: string + /** Inclusive code-point offset in the whitespace-normalized display text. */ + start: number + /** Exclusive code-point offset in the whitespace-normalized display text. */ + end: number +} + /** * Browser-safe approximation of SQLite FTS5 unicode61 token boundaries. * Keeping phrase matching token-based prevents the development fixture from * promising arbitrary within-token substring behavior that production lacks. */ -function searchTokens(value: string): string[] { - return value - .normalize('NFD') - .replace(/\p{M}+/gu, '') - .toLowerCase() - .match(/[\p{L}\p{N}\p{Co}]+/gu) ?? [] -} - -/** Count exact contiguous token-phrase occurrences in one fixture document. */ -function phraseMatchCount(document: readonly string[], phrase: readonly string[]): number { - if (phrase.length === 0 || phrase.length > document.length) return 0 - let count = 0 - for (let start = 0; start <= document.length - phrase.length; start++) { - if (phrase.every((token, offset) => document[start + offset] === token)) count++ +function searchTokenSpans(value: string): { text: string; tokens: FixtureSearchToken[] } { + const text = value.replace(/\s+/gu, ' ').trim() + const characters = Array.from(text) + const tokens: FixtureSearchToken[] = [] + let start: number | undefined + let raw = '' + const flush = (end: number): void => { + if (start !== undefined) { + const folded = raw.normalize('NFD').replace(/\p{M}+/gu, '').toLowerCase() + if (folded !== '') tokens.push({ value: folded, start, end }) + } + start = undefined + raw = '' } - return count + for (let index = 0; index < characters.length; index++) { + const character = characters[index] as string + const tokenBase = character.normalize('NFD').replace(/\p{M}+/gu, '') + if (tokenBase === '') { + if (start !== undefined) raw += character + continue + } + if (/^[\p{L}\p{N}\p{Co}]+$/u.test(tokenBase)) { + start ??= index + raw += character + } else { + flush(index) + } + } + flush(characters.length) + return { text, tokens } } -/** One-line fixture excerpt, bounded so the sidebar remains readable. */ -function searchSnippet(value: string): string { - const oneLine = value.replace(/\s+/gu, ' ').trim() - return oneLine.length <= 120 ? oneLine : `${oneLine.slice(0, 117)}…` +interface FixturePhraseMatch { + count: number + start: number + end: number +} + +/** Count exact contiguous token-phrase occurrences and retain the first display span. */ +function phraseMatch(document: readonly FixtureSearchToken[], phrase: readonly string[]): FixturePhraseMatch { + if (phrase.length === 0 || phrase.length > document.length) return { count: 0, start: 0, end: 0 } + let count = 0 + let firstStart = 0 + let firstEnd = 0 + for (let start = 0; start <= document.length - phrase.length; start++) { + if (!phrase.every((token, offset) => document[start + offset]?.value === token)) continue + count++ + if (count === 1) { + firstStart = document[start]?.start ?? 0 + firstEnd = document[start + phrase.length - 1]?.end ?? firstStart + } + } + return { count, start: firstStart, end: firstEnd } +} + +/** Match-centered fixture excerpt, bounded by Unicode code points for the sidebar. */ +function searchSnippet(value: string, matchStart: number, matchEnd: number): string { + const characters = Array.from(value) + if (characters.length <= 120) return value + const boundedStart = Math.min(Math.max(0, matchStart), characters.length - 1) + const boundedEnd = Math.min( + characters.length, + Math.max(boundedStart + 1, matchEnd), + ) + const center = Math.floor((boundedStart + boundedEnd) / 2) + let start = Math.min( + characters.length - 118, + Math.max(0, center - Math.floor(118 / 2)), + ) + let end = start + 118 + if (start === 0) { + end = 119 + } else if (end === characters.length) { + start = characters.length - 119 + } + return `${start > 0 ? '…' : ''}${characters.slice(start, end).join('')}${end < characters.length ? '…' : ''}` } interface FixtureSearchCandidate { @@ -342,6 +404,8 @@ interface FixtureSearchCandidate { time: number text: string matchCount: number + matchStart: number + matchEnd: number documentLength: number } @@ -628,21 +692,24 @@ export function createFixtureApi(options: FixtureOptions = {}): ApiProxy { details: {}, }) } - const query = searchTokens(request.payload.query) + const query = searchTokenSpans(request.payload.query).tokens.map(token => token.value) const matches = sessions.flatMap((summary) => { const log = logs.get(summary.sessionId) ?? [] const current = new Set(foldSurface(log).nodes) const best = log.flatMap((event): FixtureSearchCandidate[] => { if (!current.has(event.seq)) return [] const eventText = searchEventText(event) - const matchCount = phraseMatchCount(searchTokens(eventText), query) - if (matchCount === 0) return [] + const document = searchTokenSpans(eventText) + const match = phraseMatch(document.tokens, query) + if (match.count === 0) return [] return [{ sessionId: summary.sessionId, seq: event.seq, time: event.time, - text: eventText, - matchCount, + text: document.text, + matchCount: match.count, + matchStart: match.start, + matchEnd: match.end, documentLength: Array.from(eventText).length, }] }).sort(compareSearchCandidates)[0] @@ -651,7 +718,7 @@ export function createFixtureApi(options: FixtureOptions = {}): ApiProxy { return ok(request, { items: matches.slice(0, 20).map(match => ({ sessionId: match.sessionId, - snippet: searchSnippet(match.text), + snippet: searchSnippet(match.text, match.matchStart, match.matchEnd), })), hasMore: matches.length > 20, }) diff --git a/packages/client/connection/tests/fixture.spec.ts b/packages/client/connection/tests/fixture.spec.ts index 9bf0173237..71d171ee0c 100644 --- a/packages/client/connection/tests/fixture.spec.ts +++ b/packages/client/connection/tests/fixture.spec.ts @@ -62,6 +62,23 @@ describe('createFixtureApi', () => { if (!phrase.result.ok) throw new Error('search failed') expect(phrase.result.value.items[0]?.snippet).toContain('fixture 历史消息') + timing().appendUser( + 'fx-alpha', + `${'leading context '.repeat(20)}late café token${' trailing context'.repeat(20)}`, + ) + const late = await api.sessions.search(req({ query: 'LATE CAFE TOKEN' }), signal) + if (!late.result.ok) throw new Error('late search failed') + const lateSnippet = late.result.value.items[0]?.snippet ?? '' + expect(lateSnippet).toContain('late café token') + expect(lateSnippet.startsWith('…')).toBe(true) + expect(lateSnippet.endsWith('…')).toBe(true) + expect(Array.from(lateSnippet).length).toBeLessThanOrEqual(120) + + timing().appendUser('fx-alpha', 'Greek final sigma: ος') + const finalSigma = await api.sessions.search(req({ query: 'ΟΣ' }), signal) + if (!finalSigma.result.ok) throw new Error('final sigma search failed') + expect(finalSigma.result.value.items[0]?.snippet).toContain('ος') + const substring = await api.sessions.search(req({ query: 'ixtur' }), signal) expect(substring.result).toEqual({ ok: true, diff --git a/packages/client/ui-workspace/README.i18n.yaml b/packages/client/ui-workspace/README.i18n.yaml index f89fbee5d4..f2da1e952a 100644 --- a/packages/client/ui-workspace/README.i18n.yaml +++ b/packages/client/ui-workspace/README.i18n.yaml @@ -2,5 +2,5 @@ # side as of the last confirmed-consistent state. Both languages carry equal authority; # after editing either side, bring the other along and re-record with: # pnpm run verify-translation-pairing --write packages/client/ui-workspace/README.md -README.md: 9cb919a1a64394d5e116d35bdddfdee738994a02 -README.zh.md: b3add7f89cb0feb7f44238b7199d0633cdfbf641 +README.md: badcfc704b456a62a921cb93f6cf637f255fca1f +README.zh.md: 53c43f880ea4ce4f0cfbf633d32f163662e9271f diff --git a/packages/client/ui-workspace/README.md b/packages/client/ui-workspace/README.md index 9cb919a1a6..badcfc704b 100644 --- a/packages/client/ui-workspace/README.md +++ b/packages/client/ui-workspace/README.md @@ -4,7 +4,7 @@ English | [中文](README.zh.md) Shared Workspace browser and picker plugin. `WorkspaceBrowser` fills the sidebar's `sidebar.workspaces` slot, while `WorkspacePicker` fills the page-local Session Intent hero's `conversation.hero.workspace` slot; both surfaces use the same Workspace menu and creation modals. -The browser renders grouped or flat Session rows from the global runtime hooks and owns the Workspace create/rename and in-Workspace reorder flows. A non-blank search query replaces either browsing mode with one flat result list: case-insensitive title and Workspace substring matches appear immediately, while a 250 ms debounced Host request adds ranked current-conversation content matches and snippets. Each new query aborts the preceding request; a failed content search leaves metadata matches visible with a warning. The list is capped at 20, asks the user to narrow broader queries, and opens the selected Session without clearing the query or jumping to a specific event. +The browser renders grouped or flat Session rows from the global runtime hooks and owns the Workspace create/rename and in-Workspace reorder flows. A non-blank search query replaces either browsing mode with one flat result list: case-insensitive title and Workspace substring matches appear immediately, while a 250 ms debounced Host request adds ranked current-conversation content matches and snippets. The English search input and its defensive request path remove NUL, cap the query at the wire schema's 500 UTF-16 code units without splitting a surrogate pair, and preserve the existing debounce and cancellation behavior. Each new query aborts the preceding request; a failed content search leaves metadata matches visible with a warning. The list is capped at 20, asks the user to narrow broader queries, and opens the selected Session without clearing the query or jumping to a specific event. The picker lists real Host Workspace entities through the global `useWorkspaces` hook. Selecting a Workspace invokes the slot owner's `onPick` callback to retarget the frontend Session object; the existing-folder and create-new actions first create a real Workspace through the object layer, then select it. Create-new disables names already present in that list, while the Host remains authoritative for concurrent or non-UI callers. The runtime Session and Workspace services own materialization. diff --git a/packages/client/ui-workspace/README.zh.md b/packages/client/ui-workspace/README.zh.md index b3add7f89c..53c43f880e 100644 --- a/packages/client/ui-workspace/README.zh.md +++ b/packages/client/ui-workspace/README.zh.md @@ -4,7 +4,7 @@ 共享 Workspace 浏览器与选择器插件。`WorkspaceBrowser` 填充侧边栏的 `sidebar.workspaces` slot,`WorkspacePicker` 则填充页面局部 Session Intent 主视觉区的 `conversation.hero.workspace` slot;两个表层使用同一套 Workspace 菜单和创建模态框。 -该浏览器通过全局运行时钩子将 Session 行渲染为分组或扁平形式,并负责 Workspace 创建/重命名和 Workspace 内的重排序流程。非空白查询会以单一扁平结果列表替代任一浏览模式:不区分大小写的标题和 Workspace 子串匹配项会立即显示,经 250 ms 防抖的 Host 请求则会加入经过排序的当前对话内容匹配项及其摘要片段。每次新查询都会中止前一个请求;内容搜索失败时,元数据匹配项仍会显示,同时给出警告。列表最多显示 20 条结果,并会在查询过宽时提示用户缩小范围;打开所选 Session 时既不会清除查询,也不会跳转至特定事件。 +该浏览器通过全局运行时钩子将 Session 行渲染为分组或扁平形式,并负责 Workspace 创建/重命名和 Workspace 内的重排序流程。非空白查询会以单一扁平结果列表替代任一浏览模式:不区分大小写的标题和 Workspace 子串匹配项会立即显示,经 250 ms 防抖的 Host 请求则会加入经过排序的当前对话内容匹配项及其摘要片段。英文搜索输入框及其防御性请求路径会移除 NUL,将查询限制在传输 schema 规定的 500 个 UTF-16 code unit 内且不会拆分 surrogate pair,并保留现有的防抖与取消行为。每次新查询都会中止前一个请求;内容搜索失败时,元数据匹配项仍会显示,同时给出警告。列表最多显示 20 条结果,并会在查询过宽时提示用户缩小范围;打开所选 Session 时既不会清除查询,也不会跳转至特定事件。 该选择器通过全局 `useWorkspaces` hook 列出真实的 Host Workspace 实体。选择 Workspace 会调用 slot owner 的 `onPick` 回调,重新定位前端 Session 对象;使用现有文件夹和新建操作时,系统会先通过对象层创建真实 Workspace,再将其选中。新建操作会禁用列表中已有的名称,而 Host 对并发或非 UI 调用方仍具有最终决定权。运行时 Session 与 Workspace 服务负责物化。 diff --git a/packages/client/ui-workspace/src/client/WorkspaceBrowser.tsx b/packages/client/ui-workspace/src/client/WorkspaceBrowser.tsx index d703674c01..c2b73165f3 100644 --- a/packages/client/ui-workspace/src/client/WorkspaceBrowser.tsx +++ b/packages/client/ui-workspace/src/client/WorkspaceBrowser.tsx @@ -27,6 +27,19 @@ import css from './WorkspaceBrowser.module.css' const EXPAND_SLIDE_MS = 300 /** Pause between the latest keystroke and a Host content-search request. */ const SEARCH_DEBOUNCE_MS = 250 +/** `session.search` wire bound, measured in JavaScript UTF-16 code units. */ +const SEARCH_QUERY_MAX_CODE_UNITS = 500 + +/** Keep controlled input and RPC payload inside the session.search wire contract. */ +function sanitizeSearchQuery(value: string): string { + const withoutNul = value.replaceAll('\0', '') + if (withoutNul.length <= SEARCH_QUERY_MAX_CODE_UNITS) return withoutNul + let end = SEARCH_QUERY_MAX_CODE_UNITS + const last = withoutNul.charCodeAt(end - 1) + const next = withoutNul.charCodeAt(end) + if (last >= 0xD800 && last <= 0xDBFF && next >= 0xDC00 && next <= 0xDFFF) end-- + return withoutNul.slice(0, end) +} const GROUP_BY_ITEMS = [ { type: 'label' as const, id: 'group-by', text: 'Group by' }, @@ -255,7 +268,7 @@ function SearchResults({ return (
-
+
{results.items.map(result => ( ))} {pending && ( -
正在搜索历史…
+
Searching session history…
)} {failed && (
- 历史内容搜索暂时不可用,仍显示名称匹配。 + Content search is temporarily unavailable. Showing name matches.
)} {!pending && results.items.length === 0 && ( -
没有匹配结果
+
No matching sessions
)} {results.hasMore && ( -
仅显示前 20 项,请缩小搜索范围。
+
Showing the first 20 results. Narrow your search.
)}
@@ -308,7 +321,7 @@ export function WorkspaceBrowser({ // The query outlives the tree and the input (both wide-only) so collapsing // does not silently drop an in-progress filter. const [query, setQuery] = useState('') - const normalizedQuery = query.trim() + const normalizedQuery = sanitizeSearchQuery(query).trim() const [remoteSearch, setRemoteSearch] = useState({ query: '', status: 'idle', @@ -439,11 +452,11 @@ export function WorkspaceBrowser({ {/* Expanded: the row is a click-to-focus field (the leading icon is decorative). Rail: the icon is the region's search control. */}
{ if (wide) searchInput.current?.focus() }}> - + + ) : ( + {model.summary} + )} +
+ {diff !== null && ( + + )} +
+ ) +} + +/** + * The file-mutation rows as a plain registrant plugin. `inject` carries the + * load-order seam: requiring the conversation service guarantees the chat entry + * (and with it the 'conversation.chat.toolview' declaration) is registered — + * ui-conversation's apply mounts the service after the chat entry. + */ +export const fileMutationToolview = { + name: 'file-mutation-toolview', + inject: ['slots', 'conversation'], + /** + * Register the file-mutation row into the chat view's keyed toolview hole + * under both mutation tool names. + * @param ctx - registrant context (disposal rides ctx.effect inside slots.register). + */ + apply(ctx: Context): void { + ctx.slots.register({ name: 'conversation.chat.toolview', key: 'edit' }, FileMutationRow) + ctx.slots.register({ name: 'conversation.chat.toolview', key: 'write' }, FileMutationRow) + }, +} diff --git a/packages/client/ui-conversation/tests/diff-card.spec.tsx b/packages/client/ui-conversation/tests/diff-card.spec.tsx new file mode 100644 index 0000000000..77b762c38b --- /dev/null +++ b/packages/client/ui-conversation/tests/diff-card.spec.tsx @@ -0,0 +1,248 @@ +// @vitest-environment jsdom +// The diff render intent on the web side: the pure diffCardModel derivation +// over callView/resultView, and both conversation render sites that consume it +// — the chat tool row's expanded body (GenericToolCard / FileMutationRow) and +// the details panel's Output section. + +import { afterEach, describe, expect, it, vi } from 'vitest' +import { cleanup, fireEvent, render } from '@testing-library/react' +import { bindSnapshotSelector } from '@deepseek-ai/dsh-client-web-react' +import { createSnapshotStore } from '@deepseek-ai/dsh-client-runtime/client' +import type { + ConversationSnapshot, RunningToolCall, SessionId, SessionListState, ToolResultNode, WorkspaceListState, +} from '@deepseek-ai/dsh-client-runtime/client' +import type { ToolCallView, ToolResultView } from '@deepseek-ai/dsh-client-connection/client' +import type { SelectionTarget, ToolRowOwnerProps, ToolRowProps } from '@deepseek-ai/dsh-client-ui-conversation/client' +import { CHAT_DIFF_MAX_LINES, diffCardModel } from '../src/client/contract/diff-card-model.ts' +import { createChatStore } from '../src/client/stores.ts' +import { GenericToolCard } from '../src/client/chat/GenericToolCard.tsx' +import { DetailsPanel } from '../src/client/skeleton/DetailsPanel.tsx' +import { FileMutationRow } from '../src/client/toolviews/file-mutation-row.tsx' + +afterEach(cleanup) + +const SID = 's1' as SessionId + +const ARGS = '{"file_path":"notes/demo.txt","old_string":"hello","new_string":"hello fixture"}' + +/** The edit tool's own call view (a call-time diff derived from the arguments). */ +const callDiff = (over?: Partial>): ToolCallView => ({ + card: 'diff', title: 'Edit notes/demo.txt', + diffs: [{ path: 'notes/demo.txt', oldText: 'hello', newText: 'hello fixture' }], ...over, +}) + +/** The edit tool's own result view (the applied hunk diff). */ +const resultDiff = (over?: Partial>): ToolResultView => ({ + card: 'diff', title: 'Edit notes/demo.txt', + diffs: [{ path: 'notes/demo.txt', oldText: 'hello', newText: 'hello fixture' }], ...over, +}) + +const running = (over?: Partial): RunningToolCall => ({ + callId: 'c1', name: 'edit', argsRaw: ARGS, + turn: 1, step: 1, time: 1_000, callView: callDiff(), ...over, +}) + +const settled = (over?: Partial): ToolResultNode => ({ + kind: 'tool-result', seq: 10, time: 2_000, callId: 'c1', + call: { name: 'edit', argsRaw: ARGS }, + callTime: 1_000, + content: [{ type: 'text', text: 'The file notes/demo.txt has been updated successfully.' }], isError: false, + callView: callDiff(), resultView: resultDiff(), ...over, +}) + +describe('diffCardModel', () => { + it('derives a running card from the call view alone', () => { + expect(diffCardModel(running())).toEqual({ + card: { diffs: [{ path: 'notes/demo.txt', oldText: 'hello', newText: 'hello fixture' }] }, + }) + }) + + it('derives a settled card from the result view, which replaces the call-time diff', () => { + // The applied hunks (result) win over the args-derived call diff. + expect(diffCardModel(settled({ + resultView: resultDiff({ diffs: [{ path: 'notes/demo.txt', oldText: 'a', newText: 'b' }] }), + }))).toEqual({ + card: { diffs: [{ path: 'notes/demo.txt', oldText: 'a', newText: 'b' }] }, + }) + }) + + it('renders a settled diff even when the window dropped the call head', () => { + // A truncated call carries only the result view, which holds the whole change. + expect(diffCardModel(settled({ call: null, callView: null }))?.card.diffs).toHaveLength(1) + }) + + it('returns null for every non-diff call: no views, generic views, unknown cards', () => { + expect(diffCardModel(running({ callView: null }))).toBeNull() + expect(diffCardModel(settled({ callView: null, resultView: null }))).toBeNull() + expect(diffCardModel(running({ callView: { card: 'generic', title: 'read x' } }))).toBeNull() + // A generic result settles a diff call on the generic path (write/edit's + // own execution-error arm). + expect(diffCardModel(settled({ resultView: { card: 'generic' } }))).toBeNull() + // A card tag this UI version does not know arrives over the wire; the + // documented generic-card default takes it, not a crash. + const future = { card: 'chart', title: 'plot' } as unknown as ToolCallView + expect(diffCardModel(running({ callView: future }))).toBeNull() + expect(diffCardModel(settled({ + callView: future, resultView: { card: 'chart' } as unknown as ToolResultView, + }))).toBeNull() + }) +}) + +describe('chat row diff body', () => { + const ownerProps = (block: RunningToolCall | ToolResultNode): ToolRowOwnerProps => ({ + callId: 'c1', toolName: 'edit', block, openFile: vi.fn(), + }) + + it('the expanded body is the applied diff, capped tighter than the panel', () => { + expect(CHAT_DIFF_MAX_LINES).toBeLessThan(16) + const view = render() + // Collapsed: the summary row (path) only, no diff body. + expect(view.queryByText('hello fixture')).toBeNull() + // The path link is not the expand control; the leading toggle is. + fireEvent.click(view.container.querySelector('button[aria-expanded]')!) + expect(view.container.querySelector('[data-diff]')).not.toBeNull() + expect(view.getByText('hello fixture')).toBeTruthy() + }) + + it('a running diff call expands to its intended change', () => { + const view = render() + fireEvent.click(view.container.querySelector('button[aria-expanded]')!) + expect(view.container.querySelector('[data-diff]')).not.toBeNull() + }) + + it('a non-diff call keeps the args-JSON text body', () => { + // A non-file tool name so the row is not single-file (no path link), and its + // args body is the fallback the diff card must not have replaced. + const view = render() + fireEvent.click(view.container.querySelector('button[aria-expanded]')!) + expect(view.container.querySelector('[data-diff]')).toBeNull() + expect(view.getByText(/"foo"/)).toBeTruthy() + }) +}) + +describe('FileMutationRow diff card', () => { + const list = () => createSnapshotStore({ + ids: [SID], + byId: { [SID]: { id: SID, displayTitle: 'r', running: false, blank: false, waitingApproval: false, updatedAt: 0, cwd: '/w/app' } }, + current: SID, + phase: 'ready', + }) + + const rowProps = (block: RunningToolCall | ToolResultNode, toolName = 'edit'): ToolRowProps => ({ + callId: 'c1', toolName, block, openFile: vi.fn(), cwd: '/w/app', + sessionId: SID, useSessions: bindSnapshotSelector(list()), + } as unknown as ToolRowProps) + + it('renders the applied diff under the summary row, without an expand gesture', () => { + const view = render() + // The diff card is resident (no expand toggle needed). + expect(view.container.querySelector('[data-diff]')).not.toBeNull() + expect(view.getByText('hello fixture')).toBeTruthy() + expect(view.getByText('复制')).toBeTruthy() + }) + + it('the summary is a path link that opens through the host, cwd-resolved', () => { + const openFile = vi.fn() + const view = render() + fireEvent.click(view.getByRole('button', { name: 'notes/demo.txt' })) + expect(openFile).toHaveBeenCalledWith('/w/app/notes/demo.txt') + }) + + it('registers under write too, rendering a create as an added-only diff', () => { + const writeArgs = '{"file_path":"notes/new.txt","content":"hello fixture\\n"}' + const view = render() + expect(view.getByText('└ +1 -0 · 1 file')).toBeTruthy() + }) + + it('reflects the run state on its leading slot', () => { + const runningView = render() + expect(runningView.container.querySelector('[data-state="running"]')).not.toBeNull() + cleanup() + const errorView = render() + expect(errorView.container.querySelector('[data-state="error"]')).not.toBeNull() + }) + + it('a mutation call with no diff view renders the summary row alone', () => { + const view = render() + expect(view.container.querySelector('[data-diff]')).toBeNull() + }) +}) + +describe('DetailsPanel diff Output section', () => { + function mount(snapshot: ConversationSnapshot, selection: SelectionTarget | null, cwd?: string) { + localStorage.clear() + const chat = createChatStore().create() + if (selection !== null) chat.actions.select(selection) + const sessions = createSnapshotStore(cwd === undefined + ? { ids: [], byId: {}, current: undefined, phase: 'ready' } + : { + ids: [SID], + byId: { [SID]: { id: SID, displayTitle: 'r', running: false, blank: false, waitingApproval: false, updatedAt: 0, cwd } }, + current: SID, + phase: 'ready', + }) + const workspaces = createSnapshotStore({ + items: [], state: 'idle', phase: 'ready', error: null, + baselinesReady: true, recentWorkspaceId: undefined, + }) + return render( + snapshot, subscribe: () => () => {} })} + useSessions={bindSnapshotSelector(sessions)} + useWorkspaces={bindSnapshotSelector(workspaces)} + useInput={(() => { throw new Error('unused') })} + inputActions={{ setDraft: () => {}, submit: () => {} }} + useProjection={(() => undefined)} + useStore={bindSnapshotSelector(chat)} + actions={chat.actions} + closeDetails={vi.fn()} + />, + ) + } + + function snapshot(over: Partial = {}): ConversationSnapshot { + return { + sessionId: SID, nodes: [], foldDegraded: false, partial: null, runningCalls: [], codeDispatches: new Map(), + pending: [], queue: [], running: false, composerPhase: 'active', removed: false, + openState: 'open', openError: null, hasMore: false, loadingOlder: false, + promptError: null, blank: false, lastAgentError: null, ...over, + } + } + + const target: SelectionTarget = { turnSeq: 10, callId: 'c1', toolName: 'edit' } + + it('renders the applied diff at full height, keeping the JSON Input section', () => { + const view = mount(snapshot({ nodes: [settled()] }), target) + expect(view.getByText(/"file_path"/)).toBeTruthy() + expect(view.container.querySelector('[data-diff]')).not.toBeNull() + expect(view.getByText('hello fixture')).toBeTruthy() + }) + + it('a running diff call renders its intended change, not the 运行中… placeholder', () => { + const view = mount(snapshot({ runningCalls: [running()] }), target) + expect(view.container.querySelector('[data-diff]')).not.toBeNull() + expect(view.queryByText('运行中…')).toBeNull() + }) + + it('a non-diff result keeps the flattened pre', () => { + const view = mount(snapshot({ + nodes: [settled({ + callView: null, resultView: null, + content: [{ type: 'text', text: 'permission denied' }], + })], + }), target) + expect(view.container.querySelector('[data-diff]')).toBeNull() + expect(view.getByText('Output').closest('section')?.querySelector('pre')?.textContent).toBe('permission denied') + }) +}) diff --git a/packages/client/ui-primitives/README.i18n.yaml b/packages/client/ui-primitives/README.i18n.yaml index b5e4b5c078..ba6010f6c7 100644 --- a/packages/client/ui-primitives/README.i18n.yaml +++ b/packages/client/ui-primitives/README.i18n.yaml @@ -2,5 +2,5 @@ # side as of the last confirmed-consistent state. Both languages carry equal authority; # after editing either side, bring the other along and re-record with: # pnpm run verify-translation-pairing --write packages/client/ui-primitives/README.md -README.md: 0ef3c20f848b3d331c007911d0837f11cd72c024 -README.zh.md: af94551bfb9e12dbadcef6a96a54f9bf7ea71299 +README.md: 58c8ddcf0343216979ffdae7749c5368e26c45e5 +README.zh.md: 2d775f6591d3e2f5305cd517a38effb2cf25becf diff --git a/packages/client/ui-primitives/README.md b/packages/client/ui-primitives/README.md index 0ef3c20f84..58c8ddcf03 100644 --- a/packages/client/ui-primitives/README.md +++ b/packages/client/ui-primitives/README.md @@ -2,7 +2,7 @@ English | [中文](README.zh.md) -Pure React atoms (zero cordis): StateDot, ic_ds_* icons, Button/Pill/Menu/Modal/Input, the markdown family (MessageText/MarkdownText/JsonBlock), the read-only JsonTree inspector, the `useAnchoredMaxHeight` hook that clamps a bottom-anchored overlay to the viewport space above its anchor (re-measured on resize, scroll, and a caller-supplied dependency), and TerminalBlock. Contract: api-contracts v3 §8. +Pure React atoms (zero cordis): StateDot, ic_ds_* icons, Button/Pill/Menu/Modal/Input, the markdown family (MessageText/MarkdownText/JsonBlock), the read-only JsonTree inspector, the `useAnchoredMaxHeight` hook that clamps a bottom-anchored overlay to the viewport space above its anchor (re-measured on resize, scroll, and a caller-supplied dependency), TerminalBlock, and DiffBlock. Contract: api-contracts v3 §8. ## Markdown rendering @@ -12,6 +12,10 @@ Pure React atoms (zero cordis): StateDot, ic_ds_* icons, Button/Pill/Menu/Modal/ `TerminalBlock` renders a shell command as a terminal surface: one prompt row per line of the command (the shortened `cwd` label on the first row only, since the view knows one working directory and a `cd` moves later lines elsewhere, then that line), the command's output, a status pill for a non-zero exit code or a terminating signal, and a copy control that writes the raw `output` prop. A run-state `StateDot` marks the call once, on the first row, out of flow in a gutter the card reserves as its own left padding, so the dot sits inside the card box yet left of the prompt text. It reaches three of `StateDot`'s states — the chase while `running`, red for the same exit status that renders the pill, green otherwise — so a card states whether its command is still running rather than leaving that to be inferred from the presence of output; it carries one visually hidden text label because `StateDot` is `aria-hidden`. One dot regardless of line count is deliberate: the exit status is the whole call's, so a dot per line would claim a per-line outcome the view does not carry. Command text is `white-space: pre`, so repeated spaces, tabs, and an indented continuation render verbatim while the row stays single-line and ellipsizes. ANSI escape sequences are parsed with the `anser` runtime dependency into React spans; cursor movements replay into a per-line column buffer before inert controls are stripped, since carriage return and backspace only MOVE the cursor: `100%` + CR + `OK` alone shows `OK0%`, while the `\x1b[K` a spinner writes with its redraw erases the tail so `100%\r\x1b[KOK` shows `OK`. Erase-in-line is honored in all three parameter forms, the cursor advances by terminal columns (8-column tab stops, two for emoji and CJK, none for a combining mark), and SGR state is normalized per cell as a terminal stores it, threading across lines and closing at the state the line ended in; basic-16 foreground colors map onto `--dsw-*` tokens, while 256-palette and truecolor values pass through as literal rgb. Output keeps `white-space: pre` with horizontal scrolling, so column-aligned output holds its alignment instead of soft-wrapping, and collapses to a head slice plus a tail slice past `maxLines` (default 16, the TUI transcript's split arithmetic) behind an expand button. Rationale: [the web terminal card note](../../../.agents/notes/implemented/feature/2026-07-28-web-terminal-card.md). +## Diff rendering + +`DiffBlock` renders a file mutation as an inline diff surface: one bold path header per file, the removed lines (`- `, error token) above the added lines (`+ `, success token), a `⋯` gap before a same-file second hunk, and a dim `└ +A -R · N file(s)` footer. Lines are `white-space: pre` with horizontal scrolling, so a source line holds its indentation instead of soft-wrapping, and the body collapses to a head slice plus a tail slice past `maxLines` (default 16, `TerminalBlock`'s split arithmetic) behind an expand button. A create (`oldText: null`) has no removed side. The copy control writes the prefixed diff text (path headers, `- `/`+ ` lines, the gap) so a multi-file copy stays attributable, and floats in the top-right corner rather than on a banner row of its own. Geometry mirrors `CodeBlock`/`TerminalBlock`. The `+`/`-` block form mirrors the TUI transcript's diff card so a diff reads the same across front ends. Rationale: [the web diff card note](../../../.agents/notes/implemented/feature/2026-07-30-web-diff-card.md). + ## Model Experience None, as the package renders pure React atoms in the browser; nothing here reaches a model request. diff --git a/packages/client/ui-primitives/README.zh.md b/packages/client/ui-primitives/README.zh.md index af94551bfb..2d775f6591 100644 --- a/packages/client/ui-primitives/README.zh.md +++ b/packages/client/ui-primitives/README.zh.md @@ -2,7 +2,7 @@ [English](README.md) | 中文 -纯 React 原子组件(零 cordis):StateDot、ic_ds_* 图标、Button/Pill/Menu/Modal/Input、markdown 家族(MessageText/MarkdownText/JsonBlock)、只读 JsonTree 检查器、`useAnchoredMaxHeight` hook(把底部锚定的浮层高度收敛到锚点上方的视口空间,并在 resize、scroll 与调用方提供的依赖变化时重新测量),以及 TerminalBlock。契约:api-contracts v3 §8。 +纯 React 原子组件(零 cordis):StateDot、ic_ds_* 图标、Button/Pill/Menu/Modal/Input、markdown 家族(MessageText/MarkdownText/JsonBlock)、只读 JsonTree 检查器、`useAnchoredMaxHeight` hook(把底部锚定的浮层高度收敛到锚点上方的视口空间,并在 resize、scroll 与调用方提供的依赖变化时重新测量)、TerminalBlock,以及 DiffBlock。契约:api-contracts v3 §8。 ## Markdown 渲染 @@ -11,6 +11,10 @@ `TerminalBlock` 将一条 shell 命令渲染为终端表层:命令的每一行各占一个提示行(缩短后的 `cwd` 标签只出现在第一行,因为视图只知道一个工作目录,而一个 `cd` 就会让后面的行去到别处,标签之后是该行)、命令输出、非零退出码或终止信号对应的状态胶囊,以及写入原始 `output` prop 的复制控件。一枚运行状态 `StateDot` 为整次调用标记一次,位于第一行,以脱离文档流的方式落在卡片以自身左内边距预留的落区中,因此它位于卡片盒之内、提示文字之左。它用到 `StateDot` 的三种状态——`running` 期间为追逐动画,与渲染状态胶囊相同的退出状态为红色,其余为绿色——因此卡片直接陈述其命令是否仍在运行,而不是让人从有无输出中推断;由于 `StateDot` 是 `aria-hidden`,它携带一处视觉隐藏的文本标签。无论多少行都只有一枚状态点是有意为之:退出状态属于整次调用,因此每行一枚就会声称一个视图并不携带的逐行结果。命令文本使用 `white-space: pre`,因此重复空格、制表符与缩进续行都原样呈现,同时该行仍保持单行并以省略号截断。ANSI 转义序列通过运行时依赖 `anser` 解析为 React span;光标移动在剥除无显示意义控制符之前先重放进逐行的列缓冲,因为回车与退格**只移动**光标:单是 `100%` 加回车再加 `OK` 显示为 `OK0%`,而 spinner 随重绘写出的 `\x1b[K` 会擦掉尾巴,因此 `100%\r\x1b[KOK` 显示为 `OK`。行内擦除的三种参数形式都被遵循,光标按终端列推进(8 列制表位;emoji 与 CJK 占两列;组合标记不占列),SGR 状态按单元格归一化存储,与终端一致,并跨行延续、在行结束时的状态处收束;基础 16 色前景色映射到 `--dsw-*` token,而 256 色板与真彩色值按字面 rgb 透传。输出保持 `white-space: pre` 并支持横向滚动,因此按列对齐的输出保留其对齐而不会软换行;超过 `maxLines`(默认 16,与 TUI 转录相同的切分算法)时折叠为头部切片加尾部切片,由展开按钮控制。原理:[Web 终端卡片笔记](../../../.agents/notes/implemented/feature/2026-07-28-web-terminal-card.md)。 +## Diff 渲染 + +`DiffBlock` 将一次文件改动渲染为内联 diff 表层:每个文件一个粗体路径头、删除行(`- `,error token)在新增行(`+ `,success token)之上、同文件第二个 hunk 前一个 `⋯` gap,以及暗色 `└ +A -R · N file(s)` 页脚。各行使用 `white-space: pre` 并横向滚动,因此源码行保留其缩进而不软换行;超过 `maxLines`(默认 16,与 `TerminalBlock` 相同的切分算法)时折叠为头部切片加尾部切片,由展开按钮控制。新建(`oldText: null`)没有删除侧。复制控件写入带前缀的 diff 文本(路径头、`- `/`+ ` 行、gap),使多文件复制保持可归属,并浮在右上角而非占据自己的 banner 行。几何镜像 `CodeBlock`/`TerminalBlock`。`+`/`-` 块形式镜像 TUI 转录的 diff 卡片,使 diff 在两个前端读起来一致。原理:[Web diff 卡片笔记](../../../.agents/notes/implemented/feature/2026-07-30-web-diff-card.md)。 + ## 模型体验 无。该包(package)在浏览器中渲染纯 React 原子组件;这里没有任何内容进入模型请求。 diff --git a/packages/client/ui-primitives/src/DiffBlock.module.css b/packages/client/ui-primitives/src/DiffBlock.module.css new file mode 100644 index 0000000000..8794dbb87e --- /dev/null +++ b/packages/client/ui-primitives/src/DiffBlock.module.css @@ -0,0 +1,103 @@ +/* Geometry mirrors CodeBlock/TerminalBlock (12px radius, code-block surface + + banner row, markdown code-block font) so a diff card reads as one family with + a fenced block and a terminal card. The deliberate divergence, shared with + TerminalBlock: the body keeps `white-space: pre` and scrolls horizontally, + because folding a source line destroys the indentation a diff is read by. */ + +.block { + --dsl-diff-radius: 12px; + --dsl-diff-line-height: 22px; + + position: relative; + margin: 16px 0; + color: var(--dsw-alias-label-primary); + background: var(--dsw-alias-markdown-code-block); + border-radius: var(--dsl-diff-radius); +} + +/* The copy control floats in the top-right corner over the body, so the card + has no empty banner row above its first diff line (the TUI diff card has no + banner either — only the footer). The block is position: relative, so this + anchors to the card. */ +.copyButton { + position: absolute; + top: 8px; + right: 12px; + z-index: 1; + background-color: transparent; + border: none; + padding: 0; + margin: 0; + color: var(--dsw-alias-label-secondary); + cursor: pointer; + font: var(--dsw-font-xs-13); +} + +.body { + padding: 12px 14px; + font: var(--dsw-font-markdown-code-block); + overflow-x: auto; + overflow-y: hidden; +} + +/* No wrapping, no word-break: a diff is read by its indentation. */ +.line { + min-height: var(--dsl-diff-line-height); + white-space: pre; +} + +/* A file header: the path in the primary tone, set apart by weight. */ +.path { + color: var(--dsw-alias-label-primary); + font-weight: 600; +} + +/* A same-file second hunk's separator (a scattered edit), in the dim tone. */ +.gap { + color: var(--dsw-alias-label-tertiary); +} + +/* The diff's own meaning-carrying colors: removed on the error token, added on + the success token. A `- `/`+ ` prefix is drawn here so a copied line and the + shown line agree, and so the sign reads without relying on color alone. */ +.del::before { + content: '- '; + color: var(--dsw-alias-state-error-primary); +} + +.del { + color: var(--dsw-alias-state-error-primary); +} + +.add::before { + content: '+ '; + color: var(--dsw-alias-state-success-primary); +} + +.add { + color: var(--dsw-alias-state-success-primary); +} + +.expand { + display: block; + width: 100%; + padding: 0; + border: none; + background-color: transparent; + color: var(--dsw-alias-label-tertiary); + cursor: pointer; + font: inherit; + text-align: left; +} + +.expand:hover { + color: var(--dsw-alias-label-secondary); +} + +/* The change summary, dim under the body: `└ +A -R · N file(s)`, the same + footer the TUI transcript's diff card draws. */ +.footer { + padding: 0 14px 12px; + font: var(--dsw-font-markdown-code-block); + color: var(--dsw-alias-label-tertiary); +} diff --git a/packages/client/ui-primitives/src/DiffBlock.tsx b/packages/client/ui-primitives/src/DiffBlock.tsx new file mode 100644 index 0000000000..ab1700b7b5 --- /dev/null +++ b/packages/client/ui-primitives/src/DiffBlock.tsx @@ -0,0 +1,171 @@ +// DiffBlock: the inline-diff surface for a file mutation (write/edit) — a copy +// control over one or more per-file hunks, each a bold path header followed by +// the removed block (`-`, error color) and the added block (`+`, success +// color), with a dim `└ +A -R · N file(s)` footer. The +/- block form mirrors +// the TUI transcript's diff card (packages/ui/tui: diffLines) so a diff reads +// the same across front ends: the removed side is the old text in full, the +// added side the new text in full. Output never soft-wraps — an aligned source +// line keeps its indentation and scrolls horizontally instead of folding. +// Colors resolve through --dsw-* tokens; geometry mirrors CodeBlock. + +import { useCallback, useMemo, useState } from 'react' +import clsx from 'clsx' +import { writeClipboard } from './clipboard.ts' +import css from './DiffBlock.module.css' + +/** + * Output lines shown before the height cap collapses the middle. Matches + * {@link DEFAULT_TERMINAL_MAX_LINES} so a diff card and a terminal card cut a + * long body at the same place. + */ +export const DEFAULT_DIFF_MAX_LINES = 16 + +/** + * One file's change, in the shape {@link DiffBlock} draws. Structurally the + * render-intent contract's `FileDiff`, redeclared here so this primitive stays + * free of the tool contract (the terminal card's decoupling, applied to diffs). + */ +export interface DiffHunk { + /** The changed file's path (as the tool operated on it; the bridge relativizes it). */ + path: string + /** Prior content, or `null` for a new file / an overwrite (nothing on the removed side). */ + oldText: string | null + /** Content after the change (the added side). */ + newText: string +} + +export interface DiffBlockProps { + /** One entry per applied hunk, in file order; empty renders nothing. */ + diffs: DiffHunk[] + /** Height cap in body lines before the middle collapses (default {@link DEFAULT_DIFF_MAX_LINES}). */ + maxLines?: number | undefined + /** Extra class merged onto the wrapper (callers position; this component draws). */ + className?: string | undefined +} + +/** A single rendered body line and its role, so the height cap slices a flat list. */ +interface DiffRow { + kind: 'path' | 'del' | 'add' | 'gap' + text: string +} + +/** The dim class per row kind (path/gap chrome vs the diff's own +/- colors). */ +const ROW_CLASS: Record = { + path: css.path, + del: css.del, + add: css.add, + gap: css.gap, +} + +/** + * Flatten the hunks into the body's rows plus the footer counts. A path header + * opens each new file; a same-file second hunk (a scattered edit) opens with a + * `⋯` gap instead of repeating the path. Every old-side line counts toward + * `removed` and every new-side line toward `added`, the same per-side line count + * the TUI footer draws, so the two front ends agree on a change's size. + * @param diffs - the hunks to render. + * @returns the body rows, the +/- totals, and the distinct-file count. + */ +function buildRows(diffs: DiffHunk[]): { rows: DiffRow[]; added: number; removed: number; files: number } { + const rows: DiffRow[] = [] + const paths = new Set() + let added = 0 + let removed = 0 + let prevPath: string | undefined + for (const diff of diffs) { + paths.add(diff.path) + if (diff.path !== prevPath) rows.push({ kind: 'path', text: diff.path }) + else rows.push({ kind: 'gap', text: '⋯' }) + prevPath = diff.path + if (diff.oldText !== null) { + for (const line of diff.oldText.split('\n')) { + rows.push({ kind: 'del', text: line }) + removed++ + } + } + for (const line of diff.newText.split('\n')) { + rows.push({ kind: 'add', text: line }) + added++ + } + } + return { rows, added, removed, files: paths.size } +} + +/** + * The diff text a reader copies: each row's `-`/`+`/path/gap prefix and its + * content, exactly what the card shows. The removed and added blocks are the + * change; the path headers keep a multi-file copy attributable. + * @param rows - the flattened body rows. + * @returns the diff as plain text. + */ +function copyText(rows: DiffRow[]): string { + return rows.map((row) => { + switch (row.kind) { + case 'del': return `- ${row.text}` + case 'add': return `+ ${row.text}` + case 'gap': return row.text + default: return row.text + } + }).join('\n') +} + +/** + * Render a file mutation as an inline diff surface. + * @param props - see {@link DiffBlockProps}. + * @returns the diff block element. + */ +export function DiffBlock({ diffs, maxLines = DEFAULT_DIFF_MAX_LINES, className }: DiffBlockProps) { + const { rows, added, removed, files } = useMemo(() => buildRows(diffs), [diffs]) + const [expanded, setExpanded] = useState(false) + const [copied, setCopied] = useState(false) + + const onCopy = useCallback(() => { + if (copied) return + void writeClipboard(copyText(rows)).then((ok) => { + if (!ok) return + setCopied(true) + window.setTimeout(() => { setCopied(false) }, 1000) + }) + }, [copied, rows]) + + const onToggle = useCallback(() => { setExpanded(value => !value) }, []) + + if (rows.length === 0) return null + + const hidden = rows.length - maxLines + const capped = hidden > 0 && !expanded + // Same split arithmetic as TerminalBlock and the TUI transcript's collapsed + // card, so a body's head and tail slices agree across the front ends. + const headLines = Math.ceil(maxLines / 2) + const tailLines = maxLines - headLines + const head = capped ? rows.slice(0, headLines) : rows + const tail = capped ? rows.slice(rows.length - tailLines) : [] + + return ( +
+ +
+ {head.map((row, index) => ( +
{row.text}
+ ))} + {hidden > 0 && ( + + )} + {tail.map((row, index) => ( +
{row.text}
+ ))} +
+
└ +{added} -{removed} · {files} file{files === 1 ? '' : 's'}
+
+ ) +} diff --git a/packages/client/ui-primitives/src/index.ts b/packages/client/ui-primitives/src/index.ts index aa674f7a1a..fc0d08b76e 100644 --- a/packages/client/ui-primitives/src/index.ts +++ b/packages/client/ui-primitives/src/index.ts @@ -22,6 +22,8 @@ export { JsonTree } from './JsonTree.tsx' export type { JsonTreeProps } from './JsonTree.tsx' export { TerminalBlock, DEFAULT_TERMINAL_MAX_LINES } from './TerminalBlock.tsx' export type { TerminalBlockProps } from './TerminalBlock.tsx' +export { DiffBlock, DEFAULT_DIFF_MAX_LINES } from './DiffBlock.tsx' +export type { DiffBlockProps, DiffHunk } from './DiffBlock.tsx' export { CodeBlock } from './markdown/CodeBlock.tsx' export { JsonBlock } from './markdown/JsonBlock.tsx' export { MarkdownText } from './markdown/MarkdownText.tsx' diff --git a/packages/client/ui-primitives/tests/diff-block.spec.tsx b/packages/client/ui-primitives/tests/diff-block.spec.tsx new file mode 100644 index 0000000000..d732a13315 --- /dev/null +++ b/packages/client/ui-primitives/tests/diff-block.spec.tsx @@ -0,0 +1,162 @@ +// @vitest-environment jsdom +// DiffBlock: the per-file hunk rows (path header, removed block, added block), +// the same-file second-hunk gap separator, the `+A -R · N file(s)` footer and +// its singular/plural, the head/tail height cap and its expand control, the +// empty-diffs null render, and the copy control writing the prefixed diff text +// on both the accepted and the refused clipboard paths. writeClipboard's own +// return contract is pinned in terminal-block.spec.tsx (the shared seam), so +// only its DOM consequence is asserted here. + +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' +import { act, cleanup, fireEvent, render, screen } from '@testing-library/react' +import { DEFAULT_DIFF_MAX_LINES, DiffBlock, type DiffHunk } from '../src/index.ts' + +afterEach(cleanup) + +beforeEach(() => { + vi.useRealTimers() +}) + +/** The rendered body rows, one string per visible line (CSS-module class prefix). */ +function bodyRows(container: HTMLElement): string[] { + return [...container.querySelectorAll('[class*="_line_"]')].map(row => row.textContent ?? '') +} + +/** Only the changed rows (add/del), excluding the path header and gap chrome. */ +function changeRows(container: HTMLElement): string[] { + return [...container.querySelectorAll('[class*="_del_"], [class*="_add_"]')].map(row => row.textContent ?? '') +} + +/** `count` numbered added lines as one hunk's newText. */ +function added(count: number): string { + return Array.from({ length: count }, (_v, i) => `line ${i + 1}`).join('\n') +} + +describe('DiffBlock structure', () => { + it('renders a create as a path header and an added block (no removed side)', () => { + const diffs: DiffHunk[] = [{ path: 'notes/new.txt', oldText: null, newText: 'hello\nworld' }] + const { container } = render() + expect(screen.getByText('notes/new.txt')).toBeTruthy() + // No removed rows: both change lines are added. + expect(changeRows(container)).toEqual(['hello', 'world']) + expect(container.querySelectorAll('[class*="_del_"]').length).toBe(0) + expect(container.querySelectorAll('[class*="_add_"]').length).toBe(2) + }) + + it('renders an edit as a removed block above an added block', () => { + const diffs: DiffHunk[] = [{ path: 'a.ts', oldText: 'old', newText: 'new' }] + const { container } = render() + expect(container.querySelectorAll('[class*="_del_"]').length).toBe(1) + expect(container.querySelectorAll('[class*="_add_"]').length).toBe(1) + expect(changeRows(container)).toEqual(['old', 'new']) + }) + + it('opens a same-file second hunk with a gap instead of repeating the path', () => { + const diffs: DiffHunk[] = [ + { path: 'a.ts', oldText: 'x', newText: 'y' }, + { path: 'a.ts', oldText: 'p', newText: 'q' }, + ] + const { container } = render() + // One path header, one gap row. + expect(container.querySelectorAll('[class*="_path_"]').length).toBe(1) + expect(container.querySelectorAll('[class*="_gap_"]').length).toBe(1) + }) + + it('opens a new file with its own path header', () => { + const diffs: DiffHunk[] = [ + { path: 'a.ts', oldText: 'x', newText: 'y' }, + { path: 'b.ts', oldText: 'p', newText: 'q' }, + ] + const { container } = render() + expect(container.querySelectorAll('[class*="_path_"]').length).toBe(2) + expect(container.querySelectorAll('[class*="_gap_"]').length).toBe(0) + }) + + it('renders nothing for empty diffs', () => { + const { container } = render() + expect(container.firstChild).toBeNull() + }) +}) + +describe('DiffBlock footer', () => { + it('counts added and removed lines and one file', () => { + const diffs: DiffHunk[] = [{ path: 'a.ts', oldText: 'a\nb', newText: 'c' }] + render() + expect(screen.getByText('└ +1 -2 · 1 file')).toBeTruthy() + }) + + it('pluralizes the distinct-file count', () => { + const diffs: DiffHunk[] = [ + { path: 'a.ts', oldText: null, newText: 'x' }, + { path: 'b.ts', oldText: null, newText: 'y' }, + ] + render() + expect(screen.getByText('└ +2 -0 · 2 files')).toBeTruthy() + }) +}) + +describe('DiffBlock height cap', () => { + it('shows head and tail with an expand control past the cap, then all lines expanded', () => { + // One added line over the default cap forces the collapse. + const diffs: DiffHunk[] = [{ path: 'a.ts', oldText: null, newText: added(DEFAULT_DIFF_MAX_LINES) }] + // The path header counts as a row, so a body of maxLines added lines plus + // the header is one over the cap. + const { container } = render() + const toggle = screen.getByRole('button', { name: /展开其余/ }) + expect(toggle.getAttribute('aria-expanded')).toBe('false') + // Collapsed shows fewer rows than the full body. + const collapsedCount = bodyRows(container).length + expect(collapsedCount).toBeLessThan(DEFAULT_DIFF_MAX_LINES + 1) + fireEvent.click(toggle) + expect(screen.getByRole('button', { name: '收起差异' }).getAttribute('aria-expanded')).toBe('true') + expect(bodyRows(container).length).toBeGreaterThan(collapsedCount) + }) + + it('shows no expand control at or under the cap', () => { + const diffs: DiffHunk[] = [{ path: 'a.ts', oldText: null, newText: added(4) }] + render() + expect(screen.queryByRole('button', { name: /展开其余|收起差异/ })).toBeNull() + }) +}) + +describe('DiffBlock copy', () => { + it('copies the prefixed diff text and flips the label on success', async () => { + vi.useFakeTimers() + const writeText = vi.fn().mockResolvedValue(undefined) + Object.defineProperty(navigator, 'clipboard', { configurable: true, value: { writeText } }) + const diffs: DiffHunk[] = [ + { path: 'a.ts', oldText: 'old', newText: 'new' }, + { path: 'a.ts', oldText: 'p', newText: 'q' }, + ] + render() + const copy = screen.getByRole('button', { name: '复制' }) + await act(async () => { fireEvent.click(copy) }) + // Path header, del/add prefixes, and the same-file gap all reach the clipboard. + expect(writeText).toHaveBeenCalledWith('a.ts\n- old\n+ new\n⋯\n- p\n+ q') + expect(screen.getByRole('button', { name: '复制成功' })).toBeTruthy() + await act(async () => { await vi.advanceTimersByTimeAsync(1000) }) + expect(screen.getByRole('button', { name: '复制' })).toBeTruthy() + }) + + it('keeps the label on a refused clipboard write', async () => { + Object.defineProperty(navigator, 'clipboard', { + configurable: true, + value: { writeText: vi.fn().mockRejectedValue(new Error('denied')) }, + }) + render() + const copy = screen.getByRole('button', { name: '复制' }) + await act(async () => { fireEvent.click(copy) }) + expect(screen.getByRole('button', { name: '复制' })).toBeTruthy() + }) + + it('ignores a second click while the copied label is showing', async () => { + vi.useFakeTimers() + const writeText = vi.fn().mockResolvedValue(undefined) + Object.defineProperty(navigator, 'clipboard', { configurable: true, value: { writeText } }) + render() + const copy = screen.getByRole('button', { name: '复制' }) + await act(async () => { fireEvent.click(copy) }) + await act(async () => { fireEvent.click(screen.getByRole('button', { name: '复制成功' })) }) + expect(writeText).toHaveBeenCalledTimes(1) + }) +}) From d7e46bea355d6246cfc9e0c3bd2c8696b7464da8 Mon Sep 17 00:00:00 2001 From: Chinesezjc Date: Thu, 30 Jul 2026 16:45:00 +0800 Subject: [PATCH 024/139] test(web): update chat-apply keyed-entry assertion for the file-mutation rows The diff card registers edit and write into the keyed toolview hole, so the mounted-entry set is now ['bash', 'edit', 'write', 'todo_write']. --- .../client/ui-conversation/tests/chat-apply.spec.tsx | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/packages/client/ui-conversation/tests/chat-apply.spec.tsx b/packages/client/ui-conversation/tests/chat-apply.spec.tsx index d7b9125b34..33f8af938d 100644 --- a/packages/client/ui-conversation/tests/chat-apply.spec.tsx +++ b/packages/client/ui-conversation/tests/chat-apply.spec.tsx @@ -80,12 +80,13 @@ describe('apply wiring', () => { await b.runtime.dispose() }) - it('mounts the bash sample and the todo row as keyed entries through the load-order seam', async () => { + it('mounts the bash sample, the file-mutation rows, and the todo row as keyed entries through the load-order seam', async () => { const b = await bench() - // Both registrant plugins' inject: ['slots', 'conversation'] resolved — the - // service being present implies the chat entry declared the hole first. + // Each registrant plugin's inject: ['slots', 'conversation'] resolved — the + // service being present implies the chat entry declared the hole first. The + // file-mutation registrant claims both write and edit for the diff card. const entries = b.slots.entries('conversation.chat.toolview') - expect(entries.map(e => e.options.key)).toEqual(['bash', 'todo_write']) + expect(entries.map(e => e.options.key)).toEqual(['bash', 'edit', 'write', 'todo_write']) // Stats stick with the composer (not inside ChatView). expect(b.slots.entries('conversation.composer.dock').map(e => e.options.id)).toEqual(['stats']) await b.runtime.dispose() From 4d3e324467e2722da7c01d327200c3393d171e18 Mon Sep 17 00:00:00 2001 From: NI0317 Date: Thu, 30 Jul 2026 16:47:27 +0800 Subject: [PATCH 025/139] docs: preserve established README voice --- ...-07-22-product-first-root-readme.i18n.yaml | 4 +- .../2026-07-22-product-first-root-readme.md | 18 ++- ...2026-07-22-product-first-root-readme.zh.md | 18 ++- README.i18n.yaml | 4 +- README.md | 110 ++++++++++++------ README.zh.md | 98 +++++++++++----- .../request-response.expected.json | 4 +- 7 files changed, 162 insertions(+), 94 deletions(-) diff --git a/.agents/notes/implemented/process/2026-07-22-product-first-root-readme.i18n.yaml b/.agents/notes/implemented/process/2026-07-22-product-first-root-readme.i18n.yaml index bd424e628d..92ca6f87e6 100644 --- a/.agents/notes/implemented/process/2026-07-22-product-first-root-readme.i18n.yaml +++ b/.agents/notes/implemented/process/2026-07-22-product-first-root-readme.i18n.yaml @@ -2,5 +2,5 @@ # side as of the last confirmed-consistent state. Both languages carry equal authority; # after editing either side, bring the other along and re-record with: # pnpm run verify-translation-pairing --write .agents/notes/implemented/process/2026-07-22-product-first-root-readme.md -2026-07-22-product-first-root-readme.md: bed7d3b49c58a59fa0f6d6637c9852b9fb615b63 -2026-07-22-product-first-root-readme.zh.md: fbfb726b2c1a821b323de2fbf419dc97920a6878 +2026-07-22-product-first-root-readme.md: eeef25702b9d1ce87353d620e52ae661455d9b99 +2026-07-22-product-first-root-readme.zh.md: c4026484132772e3783492aaa0e368027ae15574 diff --git a/.agents/notes/implemented/process/2026-07-22-product-first-root-readme.md b/.agents/notes/implemented/process/2026-07-22-product-first-root-readme.md index bed7d3b49c..eeef25702b 100644 --- a/.agents/notes/implemented/process/2026-07-22-product-first-root-readme.md +++ b/.agents/notes/implemented/process/2026-07-22-product-first-root-readme.md @@ -6,30 +6,28 @@ English | [中文](2026-07-22-product-first-root-readme.zh.md) ## Problem -The root README is the repository's product front door, but a product-only coding-agent description hides the SDK and current runtime breadth, while an SDK-first package inventory delays the shortest path to a working agent. Commands, capability claims, and entry-point descriptions also drift when the README is treated as general marketing instead of a maintained product contract. +The root README is the repository's product front door. Its product-first structure and established voice remain useful, but concrete entry points and capability claims drift as the runtime grows. Rewriting sections whose facts remain correct increases the review surface and discards language that already works. ## Decision -The root README defines DeepSeek Harness as a plugin-native coding-agent runtime that ships both a composable SDK and the assembled `dsh` agent. It separates mission from shipped facts and leads with the supported one-line installer. +The root README preserves its existing structure, order, and wording wherever the underlying fact remains correct. A refresh changes only stale claims and adds material needed to represent shipped surfaces; it does not use repository growth as a reason to reframe the whole page. -A note before the installer thanks early users, states plainly that the internal preview remains unfinished, has a low overall level of completion, and falls below the experience the team wants to deliver. It invites direct reports of failures, confusion, and friction, assigning those shortcomings to the product rather than the user, while the adjacent pre-release warning keeps the compatibility boundary explicit. +A note before installation thanks internal testers, states that features and experience remain unfinished, and asks for direct reports of failures, confusion, and friction through the WeCom group. The technical pre-release statement remains in its existing development position. -The README names the TUI, Web, headless, ACP, and Python/JSON-RPC entry points with commands or owning links. It summarizes capabilities by coding, orchestration, and operational families, while stating that each composition selects its own plugins. Exhaustive package and service inventories stay in the generated graphs and package-group documentation. +The user-surface section adds the ACP automation server and Python/JSON-RPC SDK beside the existing Web, TUI, and headless entries. The capability paragraph keeps its compact inventory style while adding the shipped PTY, LSP, web, goal, planning, task, sandbox, approval, session-query, and telemetry families and stating that compositions select subsets. One adjacent bullet records the authoritative-session-log rule because persistence, replay, queries, telemetry, and interfaces depend on it. -Plugin-native is the organizing principle rather than a slogan: the README ties replaceable services and typed events to composition through `cordis.yml`, and ties model-visible behavior, persistence, replay, queries, telemetry, and UI projections to the authoritative session log. Detailed contracts remain with the architecture, CLI, examples, cookbook, and generated catalogs. - -The English and Chinese README sides share the same technical structure. Their community sections point to the primary channel for each language audience. The documentation website keeps its separate user-guide landing page; the repository README is not added to that projection. +Detailed package and service inventories remain at their owning documentation. The English and Chinese README sides share the same technical structure, while their community sections continue to point to the primary channel for each language audience. The documentation website keeps its separate user-guide landing page. ## Alternatives considered -**Present only the assembled coding agent.** This gives the shortest product pitch but makes the SDK, alternate front doors, and replaceable runtime seams look incidental even though they are shipped repository surfaces. +**Rewrite the README around a new product narrative.** A complete rewrite can make every current surface prominent, but it replaces accurate, reviewed copy and creates unnecessary churn. Current facts fit the established product-first structure. **Present the repository as an SDK and package catalog.** This exposes implementation breadth immediately but makes a new reader reconstruct the product from package names. The package map and generated capability graph remain the authoritative inventories. **Use a long marketing page with screenshots, badges, and duplicated tutorials.** Rich media can demonstrate a stable product journey, but it ages separately from commands and source contracts. The root stays compact and links to runnable examples and owned guides. -**Project the root README as the documentation website home page.** A single landing page avoids two narratives, but the website's user guide and the repository's developer/product front door have different navigation and maintenance needs. They remain separate sources linked to the same architecture and guides. +**Project the root README as the documentation website home page.** A single landing page avoids two narratives, but the website's user guide and the repository's product/developer front door have different navigation and maintenance needs. ## Consequences -A new reader can install or choose a runtime surface before learning the package topology, while an SDK reader can see the extension model without a generated catalog being copied into prose. The README must change with any affected command, entry point, pre-release boundary, or high-level capability family, and each claim remains reviewable against source or an owning document. +Reviewers can distinguish factual refreshes from editorial rewrites, and future updates retain established wording unless its meaning becomes false or incomplete. The README must still change with affected commands, entry points, pre-release boundaries, or high-level capability families, while exhaustive detail remains linked rather than copied. diff --git a/.agents/notes/implemented/process/2026-07-22-product-first-root-readme.zh.md b/.agents/notes/implemented/process/2026-07-22-product-first-root-readme.zh.md index fbfb726b2c..c402648413 100644 --- a/.agents/notes/implemented/process/2026-07-22-product-first-root-readme.zh.md +++ b/.agents/notes/implemented/process/2026-07-22-product-first-root-readme.zh.md @@ -6,30 +6,28 @@ Status: implemented ## 问题 -根 README 是仓库的产品入口,但仅以产品视角描述 coding agent(编程智能体)会掩盖 SDK 与当前运行时的广度,而以 SDK 为先的包(package)清单则会把启动可运行 agent 的最短路径放到后面。如果把 README 当作通用营销文案,而非持续维护的产品契约,命令、能力声明和入口描述也会逐渐漂移。 +根 README 是仓库的产品入口。其产品优先的结构和既有语气仍然有效,但随着运行时不断扩展,具体入口和能力声明会逐渐陈旧。重写事实仍然正确的章节,会扩大评审范围,也会丢弃已经行之有效的措辞。 ## 决策 -根 README 将 DeepSeek Harness 定义为以插件为原生构成单元的 coding agent 运行时,同时交付可组合的 SDK 与组装完成的 `dsh` agent。它将使命定位与已交付事实分开,并首先给出受支持的单行安装命令。 +只要背后的事实仍然正确,根 README 就保留既有结构、顺序和措辞。刷新时只修正陈旧声明,并补充呈现已交付内容所需的信息;不会因为仓库规模增长就重构整篇叙事。 -安装命令之前的一则说明感谢早期用户,坦率说明内测版本仍未完成、整体完成度还很低,距离团队希望交付的体验还有差距,并邀请用户直接反馈故障、困惑和所有不顺手之处。它明确这些不足是产品的问题,而非用户的问题;紧接其后的预发布提醒则清楚说明兼容性边界。 +安装说明之前的一则文字感谢内测用户,说明功能和体验仍待完善,并邀请大家通过企业微信群直接反馈失败、困惑和不顺手之处。技术性的预发布声明仍保留在原有的开发章节位置。 -README 列出 TUI、Web、Headless、ACP(Agent Client Protocol)以及 Python/JSON-RPC 入口,并为每个入口提供命令或归属文档链接。它按编码、编排和运维三个类别概述能力,同时说明每种组合都自行选择插件。包与服务的完整清单仍由生成图和包分组文档维护。 +用户入口章节在已有的 Web、TUI 和 Headless 入口旁补充 ACP(Agent Client Protocol)自动化服务器和 Python/JSON-RPC SDK。能力段落沿用简洁清单的写法,补充已经交付的 PTY、LSP、Web、目标、规划、任务、沙箱、审批、会话查询和遥测等能力类别,并说明不同组合只选用其中一部分。相邻的一条列表项说明权威会话日志规则,因为持久化、回放、查询、遥测和各类接口都依赖它。 -以插件为原生构成单元是 README 的组织原则,而非一句口号:README 通过 `cordis.yml` 将可替换服务、类型化事件与组合方式关联起来,并明确面向模型的行为、持久化、回放、查询、遥测和 UI 投影都以权威会话日志为基础。详细契约仍由架构文档、CLI(命令行界面)、示例、实操手册(cookbook)和生成目录各自维护。 - -中英文 README 采用相同的技术结构。两侧的社区章节分别指向各自语言受众的主要交流渠道。文档网站继续使用独立的用户指南首页;仓库 README 不加入该投影。 +包(package)与服务的完整清单仍由各自的归属文档维护。中英文 README 采用相同的技术结构,但社区章节仍分别指向各自语言受众的主要交流渠道。文档网站继续使用独立的用户指南首页。 ## 考虑过的替代方案 -**只展示组装完成的 coding agent。** 这样能给出最简短的产品介绍,但会让 SDK、其他入口和可替换的运行时 seam 显得无足轻重,尽管它们都是仓库中已经交付的组成部分。 +**围绕新的产品叙事重写 README。** 完整重写能够突出所有现有入口和能力,但也会替换准确且已经过评审的文案,造成不必要的变动。现有事实能够纳入既有的产品优先结构。 **将仓库呈现为 SDK 和包清单。** 这样能立即展现实现广度,却会迫使新读者从包名反推出产品。包索引与生成的能力图仍是权威清单。 **使用包含截图、徽章和重复教程的长篇营销页面。** 富媒体能够展示稳定的产品使用路径,但其内容会独立于命令和源码契约而逐渐陈旧。根 README 保持紧凑,并链接到可运行示例和各自维护的指南。 -**将根 README 投影为文档网站首页。** 使用同一个首页可以避免两套叙事,但文档网站的用户指南与仓库面向开发者和产品的入口在导航和维护需求上并不相同。两者继续作为独立来源,并链接到相同的架构文档和指南。 +**将根 README 投影为文档网站首页。** 使用同一个首页可以避免两套叙事,但文档网站的用户指南与仓库面向产品和开发者的入口在导航和维护需求上并不相同。 ## 结果 -新读者可以在了解包拓扑之前完成安装或选择运行时入口,SDK 读者也能理解扩展模型,而无需把生成目录复制进正文。任何受影响的命令、入口、预发布边界或高层能力类别发生变化时,README 都必须同步更新;每项声明都可以依据源码或归属文档进行评审核验。 +评审者可以区分事实更新与编辑性重写;今后的更新会保留既有措辞,除非其含义已经不再正确或完整。受影响的命令、入口、预发布边界或高层能力类别发生变化时,README 仍须同步更新;完整细节则继续以链接方式提供,而不是复制到正文。 diff --git a/README.i18n.yaml b/README.i18n.yaml index 7bf728a630..5dd6ee3ce5 100644 --- a/README.i18n.yaml +++ b/README.i18n.yaml @@ -2,5 +2,5 @@ # side as of the last confirmed-consistent state. Both languages carry equal authority; # after editing either side, bring the other along and re-record with: # pnpm run verify-translation-pairing --write README.md -README.md: 169722e07c9505c457a0ab7dbdca4e22f1178c92 -README.zh.md: d67e21daa58d203c42eab5e01414e688f2c8d1d3 +README.md: ad76366274086248cb4ea0be786ccc6fd0a51296 +README.zh.md: ae6244743fa2af136be17ea8e2b386fe6b1ec48d diff --git a/README.md b/README.md index 169722e07c..ad76366274 100644 --- a/README.md +++ b/README.md @@ -2,68 +2,102 @@ English | [中文](README.zh.md) -DeepSeek Harness is an open-source, plugin-native runtime for coding agents. This repository ships both the composable SDK and `dsh`, a working agent assembled from the same packages. +DeepSeek Harness (`dsh`) is an open-source coding agent built on the DeepSeek Harness SDK. -**Mission.** Build capable agent products without hard-wiring product choices into one loop. Models, tools, policy, storage, context, interfaces, and even the loop are [Cordis plugins](docs/architecture.md); the session log is the authoritative record from which model history, persistence, replay, queries, telemetry, and UIs derive. +It uses an architecture where **everything is a plugin**. ## Before you begin, thank you -Thank you for taking the time to try DeepSeek Harness. +Thank you for making time to try DeepSeek Harness. -This version is for internal testing only. Overall, it is still far from complete and nowhere near what we want to deliver. Some features are unfinished, and some parts will feel rough. What we learn from real use may also lead us to rethink the designs we have today. +This version is still in internal testing. Some features remain unfinished, and parts of the experience may feel rough. -We will keep working carefully on it, and we sincerely want direct feedback—especially about the moments when it fails, confuses you, or gets in your way. If it does not help you, or makes your work harder, please leave a message in our WeCom group and tell us plainly. +“As one cuts and files, as one carves and polishes.” Products grow through repeated encounters with real use and candid feedback. The problems you uncover in practice may lead us to re-examine, or even discard, existing designs. -> **Pre-release notice:** Package APIs, configuration, and persisted formats may change without compatibility shims until the first tagged release. +We especially want to hear about moments of failure, confusion, or friction. If DeepSeek Harness does not help—or instead makes your work harder—please leave a message in our WeCom group and tell us about your experience. Every report will help us refine it. -## Start in one command +## Install + +Install `dsh` with one command: ```sh curl -fsSL https://raw.githubusercontent.com/deepseek-harness/deepseek-harness/master/scripts/install.sh | sh ``` -The installer requires `git` and Node `^22.19 || >=24`, offers to install `pnpm`, prompts for a DeepSeek API key, and launches the TUI in the current directory. It keeps managed checkouts under `~/.dsh/source`; run the same command again to update. [`scripts/install.sh`](scripts/install.sh) documents alternate locations and non-interactive options. +The installer requires `git` and Node `^22.19 || >=24`, offers to install `pnpm` when it is missing, and prompts for a DeepSeek API key. -## Choose a surface +The installer keeps every checkout under `~/.dsh/source`: the master clone at `~/.dsh/source/master` and each install's staging checkout as a git worktree `~/.dsh/source/staging-`. The stable symlink `~/.dsh/source/current` points at the active staging worktree, and `dsh` in `~/.local/bin` links to `current/bin/dsh`, so an upgrade repoints one symlink and the `dsh` on PATH never moves. Re-running the command adds a fresh staging worktree from an updated master and repoints `current` at it. See [`scripts/install.sh`](scripts/install.sh) for alternate install locations and other options. -| Surface | Entry point | -|---|---| -| Full-screen TUI | `dsh` | -| Browser UI | `pnpm run demo:web` from a source checkout, or `dsh web` from a built checkout | -| One-shot headless task | `pnpm run demo:headless "summarize this workspace"`, or `dsh -p "summarize this workspace"` from a built checkout | -| ACP automation server | `pnpm run demo:acp` from a source checkout | -| Python / JSON-RPC SDK | [`python/`](python/README.md) with its bundled runtime | +## Use DeepSeek Harness -The one-line installer launches the source-running TUI without a build. The `dsh web` and `dsh -p` entries additionally need the frontend and client bundles from `pnpm run build`; `pnpm run demo:web` performs that build itself. The TUI, Web, and headless entries use the invoking directory as the workspace. See the [`dsh` CLI contract](apps/cli/README.md) for configuration, resume, provider, and workspace details; the [examples](examples/README.md) show the thinner ACP, JSON-RPC, Code Mode, and self-referential compositions. +### Web UI -## What ships - -Capabilities are selected by composition. The repository's shipped plugins cover: - -- **Coding:** filesystem read/write/edit and search, shell and persistent PTY execution, LSP navigation, web search/fetch, reusable skills, and model-written Code Mode programs. -- **Orchestration:** subagents, background tasks, worker-thread workflows, same-session goals, plan state, todos, and user questions. -- **Operations:** workspace sandboxing and approvals, session persistence/resume/fork/query, compaction and spill, projections, titles, and OpenTelemetry export. - -Anything visible to the model must be reconstructable from the session log. That makes alternate UIs, persistence backends, replay, and operational tooling consumers of one event stream instead of parallel sources of truth. - -## Extend the harness - -A swappable capability normally separates its interface, implementation, and consumer. Add or replace a provider behind a service such as `ctx.llm`, `ctx.fs`, `ctx.pty`, `ctx.web`, or `ctx.subagents`; register model-facing behavior through `ctx.tools`; attach policy and request shaping through typed events; compose the result in `cordis.yml` without forking the agent loop. - -Start with the [first-plugin guide](docs/user/develop/basic/index.md) and [extension cookbook](docs/cookbook/extension-cookbook.md). Use the [architecture](docs/architecture.md) for the system map, the generated [capability graph](docs/capability-seams.md) for current service relationships, and the [package map](packages/README.md) when you need ownership details. - -## Develop +For the recommended local interface, build the frontend after installation and after each update, then start the Web UI. Resolve the running checkout from the `dsh` launcher so the command holds regardless of which staging worktree is current (the launcher resolves through the stable `current` symlink): ```sh -pnpm install -pnpm run demo:tui +dsh_bin=$(cd "$(dirname "$(command -v dsh)")" && pwd -P)/$(basename "$(command -v dsh)") +while [ -L "$dsh_bin" ]; do + link=$(readlink "$dsh_bin") + case $link in /*) dsh_bin=$link ;; *) dsh_bin=$(cd "$(dirname "$dsh_bin")" && cd "$(dirname "$link")" && pwd -P)/$(basename "$link") ;; esac +done +dsh_dir=$(cd "$(dirname "$dsh_bin")/.." && pwd -P) +pnpm --dir "$dsh_dir" run build && pnpm --dir "$dsh_dir" run build:web +dsh web ``` -Set `DEEPSEEK_API_KEY` in the environment or root `.env`. The [development guide](docs/development.md) owns setup and validation; read the [architecture](docs/architecture.md) before changing `packages/`, and follow [AGENTS.md](AGENTS.md) when working in this repository. +The Web UI is served at `http://127.0.0.1:3080` by default. + +### TUI + +Start the full-screen terminal interface: + +```sh +dsh +``` + +### Headless + +Run one task, print the final answer, and exit: + +```sh +dsh -p "summarize this workspace" +``` + +### Automation and SDKs + +From a source checkout, start the ACP automation server: + +```sh +pnpm run demo:acp +``` + +The [Python SDK](python/README.md) drives a bundled JSON-RPC runtime. The [examples](examples/README.md) cover the runnable TUI, headless, ACP, JSON-RPC, Code Mode, and self-referential compositions. + +## Why DeepSeek Harness + +Built-in capabilities cover file reading, editing, and search; shell and persistent PTY execution; reusable skills; task tracking, goals, plans, todos, and background tasks; subagents and workflows; sandboxing and approvals; persistent, resumable, forkable, and queryable sessions; LSP and web access; context compaction; and telemetry. Each composition selects the subset appropriate to its surface. The TUI also includes Plan Mode. + +- **Everything is a plugin.** Models, tools, policies, storage, context management, and interfaces are composable [Cordis plugins](docs/user/develop/basic/index.md), so deployments can extend or replace behavior without forking the agent loop. See the [architecture](docs/architecture.md) for the underlying design. +- **Runs are reconstructable.** Anything visible to the model is logged in the authoritative session stream; persistence, resume/fork/query, replay, telemetry, and UIs derive from the same events. See the [session-log architecture](docs/architecture.md#session-log). +- **Code Mode (opt-in).** It exposes a `run_code` tool and a generated TypeScript SDK; only program output re-enters model context. See [Code Mode](packages/core/tools/README.md#code-mode). +- **Self-referential Cordis tools are opt-in.** They let the agent inspect its live runtime and mount or unmount plugins while it runs. See the [Cordis tools](packages/cordis/tool-cordis/README.md). ## Community -Follow DeepSeek Harness on X for project updates. +Follow DeepSeek Harness on Twitter for project updates. + +## Development + +```sh +pnpm install +pnpm run test:coverage +``` + +Start with the [development guide](docs/development.md) and read the [architecture](docs/architecture.md) before changing packages. + +For agents, follow [AGENTS.md](AGENTS.md). + +DeepSeek Harness is currently pre-release. ## License diff --git a/README.zh.md b/README.zh.md index d67e21daa5..ae6244743f 100644 --- a/README.zh.md +++ b/README.zh.md @@ -2,68 +2,106 @@ [English](README.md) | 中文 -DeepSeek Harness 是一个面向 coding agent(智能体)的开源、插件原生运行时。本仓库同时提供可组合的 SDK,以及由同一组包(package)组装而成、可直接运行的 agent `dsh`。 +DeepSeek Harness(`dsh`)是一款基于 DeepSeek Harness SDK 构建的开源 coding agent(编程智能体)。 -**使命。** 构建能力强大的 agent 产品,而不把产品选择硬编码到单一循环中。模型、工具、策略、存储、上下文、接口,乃至循环本身,都是 [Cordis 插件](docs/architecture.md);会话日志是权威记录,模型历史、持久化、回放、查询、遥测和 UI 均从中派生。 +它采用了**一切皆插件**的架构。 ## 使用前,想先说声谢谢 -感谢你愿意花时间试用 DeepSeek Harness。 +感谢您愿意拨冗试用 DeepSeek Harness。 -目前版本仅供内测,整体完成度不高,也远没有达到我们想交付的样子。有些功能还没做完,有些地方用起来会很粗糙。真实使用中暴露出来的问题,也可能让我们推翻现在的设计。 +目前的版本仍处于内部测试阶段,有些功能仍待完善,有些体验难免粗粝。 -我们会继续认真打磨,也真诚希望听到直接的反馈——尤其是那些失败、困惑或不顺手的时刻。如果它没有帮到你,或者反而给工作添了麻烦,可以在企业微信群中留言,向我们反馈。 +“如切如磋,如琢如磨。”产品的成长,离不开一次次真实的碰撞与坦诚的反馈。您在真实使用中暴露的问题,也可能促使我们重新审视,甚至推翻已有的设计。 -> **预发布说明:** 在首个带标签的版本发布之前,包 API、配置和持久化格式可能直接变更,不提供兼容层。 +我们尤其希望听见那些失败、困惑与不顺手的时刻——如果它未能帮到您,甚至反而为工作平添了麻烦,请在企业微信群中留言,将使用感受告诉我们。每一条反馈,都会帮助我们把它打磨得更好。 -## 一条命令开始 +## 安装 + +使用一条命令安装 `dsh`: ```sh curl -fsSL https://raw.githubusercontent.com/deepseek-harness/deepseek-harness/master/scripts/install.sh | sh ``` -安装器要求系统已安装 `git` 和 Node `^22.19 || >=24`,可代为安装 `pnpm`,会提示输入 DeepSeek API 密钥,并在当前目录启动 TUI。它把受管检出放在 `~/.dsh/source` 下;再次运行同一命令即可更新。其他安装位置和非交互选项见 [`scripts/install.sh`](scripts/install.sh)。 +安装器要求系统已安装 `git` 和 Node `^22.19 || >=24`,缺少 `pnpm` 时可代为安装,并会提示输入 DeepSeek API 密钥。 -## 选择使用方式 +安装器会把所有检出都放在 `~/.dsh/source` 下:master 克隆位于 `~/.dsh/source/master`,每次安装的 staging 检出是一个 git worktree `~/.dsh/source/staging-<时间戳>`。稳定符号链接 `~/.dsh/source/current` 指向当前生效的 staging worktree,`~/.local/bin` 中的 `dsh` 链接到 `current/bin/dsh`,因此升级只需重指一个符号链接,PATH 上的 `dsh` 从不移动。再次运行该命令会基于更新后的 master 新增一个 staging worktree,并把 `current` 重指到它。其他安装位置和选项见 [`scripts/install.sh`](scripts/install.sh)。 -| 使用方式 | 入口 | -|---|---| -| 全屏 TUI | `dsh` | -| 浏览器 UI | 在源码检出中运行 `pnpm run demo:web`,或在已构建的检出中运行 `dsh web` | -| 一次性无头任务 | 运行 `pnpm run demo:headless "summarize this workspace"`,或在已构建的检出中运行 `dsh -p "summarize this workspace"` | -| ACP(Agent Client Protocol)自动化服务器 | 在源码检出中运行 `pnpm run demo:acp` | -| Python / JSON-RPC SDK | [`python/`](python/README.md) 及其自带的运行时 | +## 使用 DeepSeek Harness -一行安装命令可直接启动从源码运行的 TUI,无需构建。`dsh web` 和 `dsh -p` 入口还需要先通过 `pnpm run build` 生成前端与客户端构建产物;`pnpm run demo:web` 会自行执行该构建。TUI、Web 和无头入口都把调用命令时的目录用作工作区。配置、会话恢复、提供方及工作区细节见 [`dsh` CLI(命令行界面)契约](apps/cli/README.md);[示例](examples/README.md)展示了更精简的 ACP、JSON-RPC、Code Mode 和自指组合。 +### Web UI -## 当前提供的能力 +推荐在本地使用 Web UI。安装完成后以及每次更新后,请先构建前端,再启动 Web UI。通过 `dsh` 启动器解析当前运行的检出,这样无论当前是哪个 staging worktree,命令都成立(启动器会经由稳定的 `current` 符号链接解析): -能力由组合决定。本仓库交付的插件涵盖: +```sh +dsh_bin=$(cd "$(dirname "$(command -v dsh)")" && pwd -P)/$(basename "$(command -v dsh)") +while [ -L "$dsh_bin" ]; do + link=$(readlink "$dsh_bin") + case $link in /*) dsh_bin=$link ;; *) dsh_bin=$(cd "$(dirname "$dsh_bin")" && cd "$(dirname "$link")" && pwd -P)/$(basename "$link") ;; esac +done +dsh_dir=$(cd "$(dirname "$dsh_bin")/.." && pwd -P) +pnpm --dir "$dsh_dir" run build && pnpm --dir "$dsh_dir" run build:web +dsh web +``` -- **编程:** 文件系统读写、编辑与搜索,shell 和持久 PTY 执行,LSP 导航,Web 搜索与抓取,可复用 skill(技能),以及由模型编写的 Code Mode 程序。 -- **编排:** subagent、后台任务、工作线程工作流、同一会话内的目标、计划状态、待办事项,以及向用户提问。 -- **运维:** 工作区沙箱与审批、会话持久化/恢复/fork/查询、压缩(compaction)与 spill、投影、标题,以及 OpenTelemetry 导出。 +Web UI 默认通过 `http://127.0.0.1:3080` 提供服务。 -凡是模型可见的内容,都必须能从会话日志中重建。这样一来,不同 UI、持久化后端、回放和运维工具都成为同一事件流的消费方,而不是彼此并行的真源。 +### TUI -## 扩展 harness +启动全屏终端界面: -一项可替换能力通常会将接口、实现和消费方彼此分离。你可以为 `ctx.llm`、`ctx.fs`、`ctx.pty`、`ctx.web` 或 `ctx.subagents` 等服务添加或替换提供方;通过 `ctx.tools` 注册面向模型的行为;通过类型化事件挂接策略和请求整形;再在 `cordis.yml` 中组合这些部分,无需 fork agent loop(智能体循环)。 +```sh +dsh +``` -从[第一个插件指南](docs/user/develop/basic/index.md)和[扩展实操手册](docs/cookbook/extension-cookbook.md)开始。需要系统图时查看[架构](docs/architecture.md),需要当前服务关系时查看生成的[能力图](docs/capability-seams.md),需要所有权细节时查看[包图](packages/README.md)。 +### Headless + +运行一项任务,打印最终答案后退出: + +```sh +dsh -p "summarize this workspace" +``` + +### 自动化与 SDK + +从源码检出中启动 ACP(Agent Client Protocol)自动化服务器: + +```sh +pnpm run demo:acp +``` + +[Python SDK](python/README.md) 驱动随附的 JSON-RPC 运行时。[示例](examples/README.md)涵盖可运行的 TUI、headless、ACP、JSON-RPC、Code Mode 和自指组合。 + +## 为什么选择 DeepSeek Harness + +内置功能涵盖文件读取、编辑与搜索、shell 和持久 PTY 执行、可复用 skill(技能)、任务跟踪、目标、计划、待办事项与后台任务、subagent 与工作流、沙箱与审批、可持久化、恢复、fork 与查询的会话、LSP 与 Web 访问、上下文压缩(context compaction),以及遥测。每个组合只选用适合其使用方式的能力子集。TUI 还包含 Plan Mode。 + +- **一切皆插件。** 模型、工具、策略、存储、上下文管理和界面均可组合为 [Cordis 插件](docs/user/develop/basic/index.md),部署方无需 fork agent loop(智能体循环)即可扩展或替换行为。底层设计见[架构文档](docs/architecture.md)。 +- **运行可重建。** 凡是模型可见的内容,都会记录在权威会话流中;持久化、恢复/fork/查询、回放、遥测和 UI 均从同一组事件派生。参见[会话日志架构](docs/architecture.md#session-log)。 +- **Code Mode(需显式启用)。** 它会提供 `run_code` 工具和生成的 TypeScript SDK,只有程序输出会重新进入模型上下文。参见 [Code Mode](packages/core/tools/README.md#code-mode)。 +- **自指 Cordis 工具需显式启用。** 这些工具可让 agent 检查自身的实时运行时,并在运行中挂载或卸载插件。参见 [Cordis 工具](packages/cordis/tool-cordis/README.md)。 + +## 社区 + +扫描二维码,或打开 DeepSeek Harness 微信社区申请页面 申请加入。 + +

+ DeepSeek Harness 微信社区二维码 +

## 开发 ```sh pnpm install -pnpm run demo:tui +pnpm run test:coverage ``` -将 `DEEPSEEK_API_KEY` 设置在环境变量或根目录 `.env` 中。环境搭建和验证由[开发指南](docs/development.md)统一说明;修改 `packages/` 前请阅读[架构](docs/architecture.md),在本仓库工作时请遵循 [AGENTS.md](AGENTS.md)。 +请先阅读[开发指南](docs/development.md);修改包之前,请阅读[架构文档](docs/architecture.md)。 -## 社区 +面向 agent:遵循 [AGENTS.md](AGENTS.md)。 -前往 DeepSeek Harness 微信社区关注项目动态。 +DeepSeek Harness 目前处于预发布阶段。 ## 许可证 diff --git a/scripts/snapshots/translation-prompt-v4/request-response.expected.json b/scripts/snapshots/translation-prompt-v4/request-response.expected.json index c1928b047d..627725f4b7 100644 --- a/scripts/snapshots/translation-prompt-v4/request-response.expected.json +++ b/scripts/snapshots/translation-prompt-v4/request-response.expected.json @@ -8,11 +8,11 @@ }, { "role": "user", - "content": "# DeepSeek Harness\n\nEnglish | [中文](README.zh.md)\n\nDeepSeek Harness is an open-source, plugin-native runtime for coding agents. This repository ships both the composable SDK and `dsh`, a working agent assembled from the same packages.\n\n**Mission.** Build capable agent products without hard-wiring product choices into one loop. Models, tools, policy, storage, context, interfaces, and even the loop are [Cordis plugins](docs/architecture.md); the session log is the authoritative record from which model history, persistence, replay, queries, telemetry, and UIs derive.\n\n## Before you begin, thank you\n\nThank you for taking the time to try DeepSeek Harness.\n\nThis version is for internal testing only. Overall, it is still far from complete and nowhere near what we want to deliver. Some features are unfinished, and some parts will feel rough. What we learn from real use may also lead us to rethink the designs we have today.\n\nWe will keep working carefully on it, and we sincerely want direct feedback—especially about the moments when it fails, confuses you, or gets in your way. If it does not help you, or makes your work harder, please leave a message in our WeCom group and tell us plainly.\n\n> **Pre-release notice:** Package APIs, configuration, and persisted formats may change without compatibility shims until the first tagged release.\n\n## Start in one command\n\n```sh\ncurl -fsSL https://raw.githubusercontent.com/deepseek-harness/deepseek-harness/master/scripts/install.sh | sh\n```\n\nThe installer requires `git` and Node `^22.19 || >=24`, offers to install `pnpm`, prompts for a DeepSeek API key, and launches the TUI in the current directory. It keeps managed checkouts under `~/.dsh/source`; run the same command again to update. [`scripts/install.sh`](scripts/install.sh) documents alternate locations and non-interactive options.\n\n## Choose a surface\n\n| Surface | Entry point |\n|---|---|\n| Full-screen TUI | `dsh` |\n| Browser UI | `pnpm run demo:web` from a source checkout, or `dsh web` from a built checkout |\n| One-shot headless task | `pnpm run demo:headless \"summarize this workspace\"`, or `dsh -p \"summarize this workspace\"` from a built checkout |\n| ACP automation server | `pnpm run demo:acp` from a source checkout |\n| Python / JSON-RPC SDK | [`python/`](python/README.md) with its bundled runtime |\n\nThe one-line installer launches the source-running TUI without a build. The `dsh web` and `dsh -p` entries additionally need the frontend and client bundles from `pnpm run build`; `pnpm run demo:web` performs that build itself. The TUI, Web, and headless entries use the invoking directory as the workspace. See the [`dsh` CLI contract](apps/cli/README.md) for configuration, resume, provider, and workspace details; the [examples](examples/README.md) show the thinner ACP, JSON-RPC, Code Mode, and self-referential compositions.\n\n## What ships\n\nCapabilities are selected by composition. The repository's shipped plugins cover:\n\n- **Coding:** filesystem read/write/edit and search, shell and persistent PTY execution, LSP navigation, web search/fetch, reusable skills, and model-written Code Mode programs.\n- **Orchestration:** subagents, background tasks, worker-thread workflows, same-session goals, plan state, todos, and user questions.\n- **Operations:** workspace sandboxing and approvals, session persistence/resume/fork/query, compaction and spill, projections, titles, and OpenTelemetry export.\n\nAnything visible to the model must be reconstructable from the session log. That makes alternate UIs, persistence backends, replay, and operational tooling consumers of one event stream instead of parallel sources of truth.\n\n## Extend the harness\n\nA swappable capability normally separates its interface, implementation, and consumer. Add or replace a provider behind a service such as `ctx.llm`, `ctx.fs`, `ctx.pty`, `ctx.web`, or `ctx.subagents`; register model-facing behavior through `ctx.tools`; attach policy and request shaping through typed events; compose the result in `cordis.yml` without forking the agent loop.\n\nStart with the [first-plugin guide](docs/user/develop/basic/index.md) and [extension cookbook](docs/cookbook/extension-cookbook.md). Use the [architecture](docs/architecture.md) for the system map, the generated [capability graph](docs/capability-seams.md) for current service relationships, and the [package map](packages/README.md) when you need ownership details.\n\n## Develop\n\n```sh\npnpm install\npnpm run demo:tui\n```\n\nSet `DEEPSEEK_API_KEY` in the environment or root `.env`. The [development guide](docs/development.md) owns setup and validation; read the [architecture](docs/architecture.md) before changing `packages/`, and follow [AGENTS.md](AGENTS.md) when working in this repository.\n\n## Community\n\nFollow DeepSeek Harness on X for project updates.\n\n## License\n\n[BSD 3-Clause](LICENSE)\n" + "content": "# DeepSeek Harness\n\nEnglish | [中文](README.zh.md)\n\nDeepSeek Harness (`dsh`) is an open-source coding agent built on the DeepSeek Harness SDK.\n\nIt uses an architecture where **everything is a plugin**.\n\n## Before you begin, thank you\n\nThank you for making time to try DeepSeek Harness.\n\nThis version is still in internal testing. Some features remain unfinished, and parts of the experience may feel rough.\n\n“As one cuts and files, as one carves and polishes.” Products grow through repeated encounters with real use and candid feedback. The problems you uncover in practice may lead us to re-examine, or even discard, existing designs.\n\nWe especially want to hear about moments of failure, confusion, or friction. If DeepSeek Harness does not help—or instead makes your work harder—please leave a message in our WeCom group and tell us about your experience. Every report will help us refine it.\n\n## Install\n\nInstall `dsh` with one command:\n\n```sh\ncurl -fsSL https://raw.githubusercontent.com/deepseek-harness/deepseek-harness/master/scripts/install.sh | sh\n```\n\nThe installer requires `git` and Node `^22.19 || >=24`, offers to install `pnpm` when it is missing, and prompts for a DeepSeek API key.\n\nThe installer keeps every checkout under `~/.dsh/source`: the master clone at `~/.dsh/source/master` and each install's staging checkout as a git worktree `~/.dsh/source/staging-`. The stable symlink `~/.dsh/source/current` points at the active staging worktree, and `dsh` in `~/.local/bin` links to `current/bin/dsh`, so an upgrade repoints one symlink and the `dsh` on PATH never moves. Re-running the command adds a fresh staging worktree from an updated master and repoints `current` at it. See [`scripts/install.sh`](scripts/install.sh) for alternate install locations and other options.\n\n## Use DeepSeek Harness\n\n### Web UI\n\nFor the recommended local interface, build the frontend after installation and after each update, then start the Web UI. Resolve the running checkout from the `dsh` launcher so the command holds regardless of which staging worktree is current (the launcher resolves through the stable `current` symlink):\n\n```sh\ndsh_bin=$(cd \"$(dirname \"$(command -v dsh)\")\" && pwd -P)/$(basename \"$(command -v dsh)\")\nwhile [ -L \"$dsh_bin\" ]; do\n link=$(readlink \"$dsh_bin\")\n case $link in /*) dsh_bin=$link ;; *) dsh_bin=$(cd \"$(dirname \"$dsh_bin\")\" && cd \"$(dirname \"$link\")\" && pwd -P)/$(basename \"$link\") ;; esac\ndone\ndsh_dir=$(cd \"$(dirname \"$dsh_bin\")/..\" && pwd -P)\npnpm --dir \"$dsh_dir\" run build && pnpm --dir \"$dsh_dir\" run build:web\ndsh web\n```\n\nThe Web UI is served at `http://127.0.0.1:3080` by default.\n\n### TUI\n\nStart the full-screen terminal interface:\n\n```sh\ndsh\n```\n\n### Headless\n\nRun one task, print the final answer, and exit:\n\n```sh\ndsh -p \"summarize this workspace\"\n```\n\n### Automation and SDKs\n\nFrom a source checkout, start the ACP automation server:\n\n```sh\npnpm run demo:acp\n```\n\nThe [Python SDK](python/README.md) drives a bundled JSON-RPC runtime. The [examples](examples/README.md) cover the runnable TUI, headless, ACP, JSON-RPC, Code Mode, and self-referential compositions.\n\n## Why DeepSeek Harness\n\nBuilt-in capabilities cover file reading, editing, and search; shell and persistent PTY execution; reusable skills; task tracking, goals, plans, todos, and background tasks; subagents and workflows; sandboxing and approvals; persistent, resumable, forkable, and queryable sessions; LSP and web access; context compaction; and telemetry. Each composition selects the subset appropriate to its surface. The TUI also includes Plan Mode.\n\n- **Everything is a plugin.** Models, tools, policies, storage, context management, and interfaces are composable [Cordis plugins](docs/user/develop/basic/index.md), so deployments can extend or replace behavior without forking the agent loop. See the [architecture](docs/architecture.md) for the underlying design.\n- **Runs are reconstructable.** Anything visible to the model is logged in the authoritative session stream; persistence, resume/fork/query, replay, telemetry, and UIs derive from the same events. See the [session-log architecture](docs/architecture.md#session-log).\n- **Code Mode (opt-in).** It exposes a `run_code` tool and a generated TypeScript SDK; only program output re-enters model context. See [Code Mode](packages/core/tools/README.md#code-mode).\n- **Self-referential Cordis tools are opt-in.** They let the agent inspect its live runtime and mount or unmount plugins while it runs. See the [Cordis tools](packages/cordis/tool-cordis/README.md).\n\n## Community\n\nFollow DeepSeek Harness on Twitter for project updates.\n\n## Development\n\n```sh\npnpm install\npnpm run test:coverage\n```\n\nStart with the [development guide](docs/development.md) and read the [architecture](docs/architecture.md) before changing packages.\n\nFor agents, follow [AGENTS.md](AGENTS.md).\n\nDeepSeek Harness is currently pre-release.\n\n## License\n\n[BSD 3-Clause](LICENSE)\n" }, { "role": "assistant", - "content": "# DeepSeek Harness\n\n[English](README.md) | 中文\n\nDeepSeek Harness 是一个面向 coding agent(智能体)的开源、插件原生运行时。本仓库同时提供可组合的 SDK,以及由同一组包(package)组装而成、可直接运行的 agent `dsh`。\n\n**使命。** 构建能力强大的 agent 产品,而不把产品选择硬编码到单一循环中。模型、工具、策略、存储、上下文、接口,乃至循环本身,都是 [Cordis 插件](docs/architecture.md);会话日志是权威记录,模型历史、持久化、回放、查询、遥测和 UI 均从中派生。\n\n## 使用前,想先说声谢谢\n\n感谢你愿意花时间试用 DeepSeek Harness。\n\n目前版本仅供内测,整体完成度不高,也远没有达到我们想交付的样子。有些功能还没做完,有些地方用起来会很粗糙。真实使用中暴露出来的问题,也可能让我们推翻现在的设计。\n\n我们会继续认真打磨,也真诚希望听到直接的反馈——尤其是那些失败、困惑或不顺手的时刻。如果它没有帮到你,或者反而给工作添了麻烦,可以在企业微信群中留言,向我们反馈。\n\n> **预发布说明:** 在首个带标签的版本发布之前,包 API、配置和持久化格式可能直接变更,不提供兼容层。\n\n## 一条命令开始\n\n```sh\ncurl -fsSL https://raw.githubusercontent.com/deepseek-harness/deepseek-harness/master/scripts/install.sh | sh\n```\n\n安装器要求系统已安装 `git` 和 Node `^22.19 || >=24`,可代为安装 `pnpm`,会提示输入 DeepSeek API 密钥,并在当前目录启动 TUI。它把受管检出放在 `~/.dsh/source` 下;再次运行同一命令即可更新。其他安装位置和非交互选项见 [`scripts/install.sh`](scripts/install.sh)。\n\n## 选择使用方式\n\n| 使用方式 | 入口 |\n|---|---|\n| 全屏 TUI | `dsh` |\n| 浏览器 UI | 在源码检出中运行 `pnpm run demo:web`,或在已构建的检出中运行 `dsh web` |\n| 一次性无头任务 | 运行 `pnpm run demo:headless \"summarize this workspace\"`,或在已构建的检出中运行 `dsh -p \"summarize this workspace\"` |\n| ACP(Agent Client Protocol)自动化服务器 | 在源码检出中运行 `pnpm run demo:acp` |\n| Python / JSON-RPC SDK | [`python/`](python/README.md) 及其自带的运行时 |\n\n一行安装命令可直接启动从源码运行的 TUI,无需构建。`dsh web` 和 `dsh -p` 入口还需要先通过 `pnpm run build` 生成前端与客户端构建产物;`pnpm run demo:web` 会自行执行该构建。TUI、Web 和无头入口都把调用命令时的目录用作工作区。配置、会话恢复、提供方及工作区细节见 [`dsh` CLI(命令行界面)契约](apps/cli/README.md);[示例](examples/README.md)展示了更精简的 ACP、JSON-RPC、Code Mode 和自指组合。\n\n## 当前提供的能力\n\n能力由组合决定。本仓库交付的插件涵盖:\n\n- **编程:** 文件系统读写、编辑与搜索,shell 和持久 PTY 执行,LSP 导航,Web 搜索与抓取,可复用 skill(技能),以及由模型编写的 Code Mode 程序。\n- **编排:** subagent、后台任务、工作线程工作流、同一会话内的目标、计划状态、待办事项,以及向用户提问。\n- **运维:** 工作区沙箱与审批、会话持久化/恢复/fork/查询、压缩(compaction)与 spill、投影、标题,以及 OpenTelemetry 导出。\n\n凡是模型可见的内容,都必须能从会话日志中重建。这样一来,不同 UI、持久化后端、回放和运维工具都成为同一事件流的消费方,而不是彼此并行的真源。\n\n## 扩展 harness\n\n一项可替换能力通常会将接口、实现和消费方彼此分离。你可以为 `ctx.llm`、`ctx.fs`、`ctx.pty`、`ctx.web` 或 `ctx.subagents` 等服务添加或替换提供方;通过 `ctx.tools` 注册面向模型的行为;通过类型化事件挂接策略和请求整形;再在 `cordis.yml` 中组合这些部分,无需 fork agent loop(智能体循环)。\n\n从[第一个插件指南](docs/user/develop/basic/index.md)和[扩展实操手册](docs/cookbook/extension-cookbook.md)开始。需要系统图时查看[架构](docs/architecture.md),需要当前服务关系时查看生成的[能力图](docs/capability-seams.md),需要所有权细节时查看[包图](packages/README.md)。\n\n## 开发\n\n```sh\npnpm install\npnpm run demo:tui\n```\n\n将 `DEEPSEEK_API_KEY` 设置在环境变量或根目录 `.env` 中。环境搭建和验证由[开发指南](docs/development.md)统一说明;修改 `packages/` 前请阅读[架构](docs/architecture.md),在本仓库工作时请遵循 [AGENTS.md](AGENTS.md)。\n\n## 社区\n\n前往 DeepSeek Harness 微信社区关注项目动态。\n\n## 许可证\n\n[BSD 3-Clause](LICENSE)\n" + "content": "# DeepSeek Harness\n\n[English](README.md) | 中文\n\nDeepSeek Harness(`dsh`)是一款基于 DeepSeek Harness SDK 构建的开源 coding agent(编程智能体)。\n\n它采用了**一切皆插件**的架构。\n\n## 使用前,想先说声谢谢\n\n感谢您愿意拨冗试用 DeepSeek Harness。\n\n目前的版本仍处于内部测试阶段,有些功能仍待完善,有些体验难免粗粝。\n\n“如切如磋,如琢如磨。”产品的成长,离不开一次次真实的碰撞与坦诚的反馈。您在真实使用中暴露的问题,也可能促使我们重新审视,甚至推翻已有的设计。\n\n我们尤其希望听见那些失败、困惑与不顺手的时刻——如果它未能帮到您,甚至反而为工作平添了麻烦,请在企业微信群中留言,将使用感受告诉我们。每一条反馈,都会帮助我们把它打磨得更好。\n\n## 安装\n\n使用一条命令安装 `dsh`:\n\n```sh\ncurl -fsSL https://raw.githubusercontent.com/deepseek-harness/deepseek-harness/master/scripts/install.sh | sh\n```\n\n安装器要求系统已安装 `git` 和 Node `^22.19 || >=24`,缺少 `pnpm` 时可代为安装,并会提示输入 DeepSeek API 密钥。\n\n安装器会把所有检出都放在 `~/.dsh/source` 下:master 克隆位于 `~/.dsh/source/master`,每次安装的 staging 检出是一个 git worktree `~/.dsh/source/staging-<时间戳>`。稳定符号链接 `~/.dsh/source/current` 指向当前生效的 staging worktree,`~/.local/bin` 中的 `dsh` 链接到 `current/bin/dsh`,因此升级只需重指一个符号链接,PATH 上的 `dsh` 从不移动。再次运行该命令会基于更新后的 master 新增一个 staging worktree,并把 `current` 重指到它。其他安装位置和选项见 [`scripts/install.sh`](scripts/install.sh)。\n\n## 使用 DeepSeek Harness\n\n### Web UI\n\n推荐在本地使用 Web UI。安装完成后以及每次更新后,请先构建前端,再启动 Web UI。通过 `dsh` 启动器解析当前运行的检出,这样无论当前是哪个 staging worktree,命令都成立(启动器会经由稳定的 `current` 符号链接解析):\n\n```sh\ndsh_bin=$(cd \"$(dirname \"$(command -v dsh)\")\" && pwd -P)/$(basename \"$(command -v dsh)\")\nwhile [ -L \"$dsh_bin\" ]; do\n link=$(readlink \"$dsh_bin\")\n case $link in /*) dsh_bin=$link ;; *) dsh_bin=$(cd \"$(dirname \"$dsh_bin\")\" && cd \"$(dirname \"$link\")\" && pwd -P)/$(basename \"$link\") ;; esac\ndone\ndsh_dir=$(cd \"$(dirname \"$dsh_bin\")/..\" && pwd -P)\npnpm --dir \"$dsh_dir\" run build && pnpm --dir \"$dsh_dir\" run build:web\ndsh web\n```\n\nWeb UI 默认通过 `http://127.0.0.1:3080` 提供服务。\n\n### TUI\n\n启动全屏终端界面:\n\n```sh\ndsh\n```\n\n### Headless\n\n运行一项任务,打印最终答案后退出:\n\n```sh\ndsh -p \"summarize this workspace\"\n```\n\n### 自动化与 SDK\n\n从源码检出中启动 ACP(Agent Client Protocol)自动化服务器:\n\n```sh\npnpm run demo:acp\n```\n\n[Python SDK](python/README.md) 驱动随附的 JSON-RPC 运行时。[示例](examples/README.md)涵盖可运行的 TUI、headless、ACP、JSON-RPC、Code Mode 和自指组合。\n\n## 为什么选择 DeepSeek Harness\n\n内置功能涵盖文件读取、编辑与搜索、shell 和持久 PTY 执行、可复用 skill(技能)、任务跟踪、目标、计划、待办事项与后台任务、subagent 与工作流、沙箱与审批、可持久化、恢复、fork 与查询的会话、LSP 与 Web 访问、上下文压缩(context compaction),以及遥测。每个组合只选用适合其使用方式的能力子集。TUI 还包含 Plan Mode。\n\n- **一切皆插件。** 模型、工具、策略、存储、上下文管理和界面均可组合为 [Cordis 插件](docs/user/develop/basic/index.md),部署方无需 fork agent loop(智能体循环)即可扩展或替换行为。底层设计见[架构文档](docs/architecture.md)。\n- **运行可重建。** 凡是模型可见的内容,都会记录在权威会话流中;持久化、恢复/fork/查询、回放、遥测和 UI 均从同一组事件派生。参见[会话日志架构](docs/architecture.md#session-log)。\n- **Code Mode(需显式启用)。** 它会提供 `run_code` 工具和生成的 TypeScript SDK,只有程序输出会重新进入模型上下文。参见 [Code Mode](packages/core/tools/README.md#code-mode)。\n- **自指 Cordis 工具需显式启用。** 这些工具可让 agent 检查自身的实时运行时,并在运行中挂载或卸载插件。参见 [Cordis 工具](packages/cordis/tool-cordis/README.md)。\n\n## 社区\n\n扫描二维码,或打开 DeepSeek Harness 微信社区申请页面 申请加入。\n\n

\n \"DeepSeek\n

\n\n## 开发\n\n```sh\npnpm install\npnpm run test:coverage\n```\n\n请先阅读[开发指南](docs/development.md);修改包之前,请阅读[架构文档](docs/architecture.md)。\n\n面向 agent:遵循 [AGENTS.md](AGENTS.md)。\n\nDeepSeek Harness 目前处于预发布阶段。\n\n## 许可证\n\n[BSD 3-Clause](LICENSE)\n" }, { "role": "user", From eb4cc8efc567fee7a9375bab3408f8ba6979a457 Mon Sep 17 00:00:00 2001 From: Chinesezjc Date: Thu, 30 Jul 2026 17:03:05 +0800 Subject: [PATCH 026/139] feat(fs): add a read render-intent card for the read tool result The read tool's result carries structured numbered lines, but only the model-facing envelope text reached the client. Add a card:'read' result view (ReadResultView) projecting {path, lines, totalLines, lang} through the tool's output.presentationMeta so presentResult reproduces it on live and replay paths; the pending call stays a generic read card. A UI without the read capability falls back to the envelope-stripped content, so the TUI is unchanged. The web consumer that renders the line-numbered view is a follow-up. --- .../2026-07-30-web-read-card.i18n.yaml | 6 ++ .../feature/2026-07-30-web-read-card.md | 49 ++++++++++++ .../feature/2026-07-30-web-read-card.zh.md | 49 ++++++++++++ packages/core/tools/src/index.ts | 2 + packages/core/tools/src/presentation.ts | 49 +++++++++++- packages/fs/tool-fs/src/read-render.ts | 77 ++++++++++++++++++ packages/fs/tool-fs/src/read.ts | 36 ++++++++- packages/fs/tool-fs/tests/read-render.spec.ts | 53 ++++++++++++- packages/fs/tool-fs/tests/tools.spec.ts | 79 +++++++++++++++++-- 9 files changed, 389 insertions(+), 11 deletions(-) create mode 100644 .agents/notes/implemented/feature/2026-07-30-web-read-card.i18n.yaml create mode 100644 .agents/notes/implemented/feature/2026-07-30-web-read-card.md create mode 100644 .agents/notes/implemented/feature/2026-07-30-web-read-card.zh.md diff --git a/.agents/notes/implemented/feature/2026-07-30-web-read-card.i18n.yaml b/.agents/notes/implemented/feature/2026-07-30-web-read-card.i18n.yaml new file mode 100644 index 0000000000..baf06160ca --- /dev/null +++ b/.agents/notes/implemented/feature/2026-07-30-web-read-card.i18n.yaml @@ -0,0 +1,6 @@ +# Bilingual-pair consistency record (docs/i18n/README.md): the git blob hash of each +# side as of the last confirmed-consistent state. Both languages carry equal authority; +# after editing either side, bring the other along and re-record with: +# pnpm run verify-translation-pairing --write .agents/notes/implemented/feature/2026-07-30-web-read-card.md +2026-07-30-web-read-card.md: 48cd317c3a90580c63e3162810de6ca38552ca21 +2026-07-30-web-read-card.zh.md: a7246be272cbbecfa71b0f4958ef0c858ca6d976 diff --git a/.agents/notes/implemented/feature/2026-07-30-web-read-card.md b/.agents/notes/implemented/feature/2026-07-30-web-read-card.md new file mode 100644 index 0000000000..48cd317c3a --- /dev/null +++ b/.agents/notes/implemented/feature/2026-07-30-web-read-card.md @@ -0,0 +1,49 @@ +# Agent Note: Read card — the read tool's structured line window reaches the client + +Status: implemented + +English | [中文](2026-07-30-web-read-card.zh.md) + +## Problem + +The `read` tool returns a canonical output object `{ path, offset, lines: [{ number, text }], totalLines }`, but its presentation collapsed that structure. `presentCall` declared a `GenericCallView` (`kind: 'read'`, a follow-along location) and `presentResult` returned a `GenericResultView` whose only content was the model-facing text with its `file` envelope stripped. A UI receiving that view saw one flattened text block: the line numbers were baked into the text as `N: ` prefixes, the file's language was unknown, and `totalLines` was gone. There was no way for a capable client to render a read the way it renders a diff — a line-numbered, syntax-highlighted code view with the line-number gutter separate from the content. + +The structured data cannot be recovered downstream. A tool result on the wire carries only the model-facing `ContentBlock[]` (the rendered text) plus an opaque `meta`; the canonical output object stays in the tool and never reaches the client or the session log. So a client that wants the line array, the total, and a language hint cannot parse them back out of the `N: text` text — the tool has to project them onto a channel that persists. + +## Decision + +Add a fourth `card` tag, `read`, to the [render-intent union](../architecture/2026-07-02-tool-render-intent-union.md) — result-side only. `ToolResultView` gains `ReadResultView { card: 'read'; title?; path; lines: ReadFileLine[]; totalLines; lang?; content? }`; `ReadFileLine { number; text }` is the shared line unit. `ToolCallView` is untouched: the pending state stays a `GenericCallView` (`kind: 'read'`) because a call carries no file content until `execute` returns, so there is nothing structured to show at call time. This diverges from the bash terminal card, which tags both sides — a terminal call already carries its command and cwd at call time, a read call carries neither content nor total, so tagging the call side would add an empty variant. + +The read tool projects the structured window through `output.presentationMeta`, the same persisted channel write/edit use for their applied-diff hunks ([canonical tool output contract](../architecture/2026-07-20-canonical-tool-output-contract.md)). `presentationMeta` runs once for a top-level surface call, returns `{ path, lines, totalLines, lang? }` as JSON the session validates and stores on the result's `meta`, and `presentResult` narrows that meta back into the `ReadResultView` on both live and replay paths. Without this channel the line array and total would be unreachable: the raw output object is not on the wire, and re-parsing the `N: text` text is lossy and fragile against the truncation footer. + +`presentResult` returns `undefined` — the generic fallback — whenever the meta is absent or malformed (`readMetaFromMeta` narrows it defensively, so a replay of an older logged result never throws), whenever the result is an error, and whenever the single text block is not the read envelope. On the success path it carries `content` (the envelope-stripped text) alongside the structured fields, so a UI without the read capability, including the current TUI, renders the file text through the generic/default card arm exactly as before. The TUI's `renderBody` switch (`packages/ui/tui/src/components/transcript.ts`) is not `assertNever`-exhaustive: `terminal` and `diff` have arms and everything else falls through to the generic arm, which reads `view.content` and the optional `title`. A `ReadResultView` satisfies that arm unchanged, so the TUI needs no new code and its output is unchanged. + +### Language hint derivation + +`langFromPath` (in `read-render.ts`) maps a file extension to a syntax-highlighting language id through a small fixed table (`LANG_BY_EXTENSION`) covering common source, config, and markup extensions. It reads the extension after the last path segment and last dot, is case-insensitive, and returns `undefined` for a dotfile (`.gitignore`), an extensionless name (`/etc/hosts`), a trailing dot, and any unknown extension — the card then omits `lang` and a UI renders plain text. The table is not a tunable: it is a display hint a UI may ignore, not a deployment-varying choice, and an unknown extension degrades to plain text rather than failing. It is deliberately small rather than an exhaustive language registry; extending it is a one-line table addition. + +## Alternatives considered + +**Re-parse the `N: text` model-facing text in `presentResult`.** Rejected: the structured line array would have to be reconstructed by splitting each line on the first `: `, which is ambiguous (a line whose own text contains `: `), loses the exact `totalLines` (the footer only states it in some branches), and breaks the moment the render format changes. `presentationMeta` carries the already-structured data with no re-parse. + +**Tag the call side too (`ReadCallView`), mirroring the terminal card's both-sides symmetry.** Rejected: a read call has no content, no line array, and no total until it executes — a call-side read card would be an empty variant duplicating what `GenericCallView` (`kind: 'read'`, follow-along location) already expresses. The terminal card tags both sides because a terminal call genuinely carries call-time data (command, cwd); a read call does not. + +**Put the structured window in a new service or a side channel instead of `meta`.** Rejected: `meta` is the established persisted presentation channel (write/edit's applied diffs ride it), it replays for free with the session log, and it needs no new plumbing. A service would reinvent persistence and replay that the event log already provides. + +**A merge-extensible union instead of a closed tag.** Rejected for the same reason the [render-intent union](../architecture/2026-07-02-tool-render-intent-union.md) closed: a new card needs consuming code to render it, so a variant a consumer silently drops is worse than a compile error. Adding `read` to the closed union is the sanctioned way to extend it — each consumer that switches on `card` keeps compiling because the new member falls through its generic default, and a consumer that wants the rich view adds its own arm. + +## Consequences + +`ToolResultView` has a fourth member. Every consumer that switches on `card` keeps compiling: the TUI and the current Web client route an unknown card to their generic path, and the read card carries `content` so that path shows the file text. The Web frontend that renders the line-numbered, syntax-highlighted view from `lines`/`lang`/`totalLines` is a separate follow-up PR; this PR is the backend that makes the data reachable. Until that lands, a read renders exactly as it did before (the generic text card) everywhere. + +The read tool now computes `presentationMeta` for every top-level read, a small per-call projection (a `lines.map` and one `langFromPath` call) on data already in hand. The meta is persisted with the session log, so a read result is slightly larger on disk — the line array it already rendered as text, now also structured. + +## Testing + +`packages/fs/tool-fs/tests/read-render.spec.ts` unit-tests `langFromPath` (known extensions case-insensitively, extension read after the last segment and last dot, and the `undefined` cases: dotfile, extensionless, trailing dot, unknown) and `readMetaFromMeta` (a well-formed narrow with and without `lang`, and every rejection: non-object, array, missing or wrong-typed `path`/`totalLines`/`lines`, a malformed line entry, and a non-string `lang`). `packages/fs/tool-fs/tests/tools.spec.ts` pins the tool wiring: `execute` attaches the structured window (with and without a `lang` hint) as `meta`, `presentResult` narrows it into a `card: 'read'` view carrying the envelope-stripped `content`, and the decline paths (error result, non-single-text content, malformed envelope with valid meta, and valid envelope with absent or malformed meta) all fall back to `undefined`. Both changed source files hold per-file 100% coverage. A keyless snapshot and the assembled-application transcript for the rendered card belong to the follow-up Web PR that consumes the view, since this PR adds no new product-user-visible rendering. + +## Related + +- [Tagged render-intent union for tool-call presentation](../architecture/2026-07-02-tool-render-intent-union.md) — the `card`-tagged vocabulary this extends with the `read` result arm. +- [Canonical tool output contract](../architecture/2026-07-20-canonical-tool-output-contract.md) — owns the `presentationMeta` persisted channel this projects the read window onto. +- [Web terminal card](2026-07-28-web-terminal-card.md) — the precedent for a client consuming a structured card; the read card follows the same producer pattern, result-side only. diff --git a/.agents/notes/implemented/feature/2026-07-30-web-read-card.zh.md b/.agents/notes/implemented/feature/2026-07-30-web-read-card.zh.md new file mode 100644 index 0000000000..a7246be272 --- /dev/null +++ b/.agents/notes/implemented/feature/2026-07-30-web-read-card.zh.md @@ -0,0 +1,49 @@ +# Agent Note: Read card — the read tool's structured line window reaches the client + +Status: implemented + +[English](2026-07-30-web-read-card.md) | 中文 + +## 问题 + +`read` 工具返回规范化输出对象 `{ path, offset, lines: [{ number, text }], totalLines }`,但它的展示层把这个结构压平了。`presentCall` 声明为 `GenericCallView`(`kind: 'read'`,一个跟随定位),`presentResult` 返回 `GenericResultView`,其唯一内容是剥掉 `file` 信封后的面向模型文本。收到该视图的 UI 只看到一个压平的文本块:行号以 `N: ` 前缀烘焙进文本、文件语言未知、`totalLines` 丢失。capable 客户端无法像渲染 diff 那样渲染一次 read——即带行号、语法高亮、行号槽与内容分离的代码视图。 + +结构化数据在下游无法恢复。线上(wire)的工具结果只携带面向模型的 `ContentBlock[]`(已渲染文本)加上一个不透明的 `meta`;规范化输出对象留在工具内,从不到达客户端或会话日志。因此想要行数组、总数和语言提示的客户端无法从 `N: text` 文本里解析回它们——工具必须把它们投影到一个会持久化的通道上。 + +## 决策 + +给[渲染意图 union](../architecture/2026-07-02-tool-render-intent-union.md) 新增第四个 `card` 标签 `read`——仅在结果侧。`ToolResultView` 增加 `ReadResultView { card: 'read'; title?; path; lines: ReadFileLine[]; totalLines; lang?; content? }`;`ReadFileLine { number; text }` 是共享的行单元。`ToolCallView` 不动:待定状态仍是 `GenericCallView`(`kind: 'read'`),因为一次调用在 `execute` 返回前不携带文件内容,调用时没有可展示的结构。这与 bash 终端 card 不同——终端 card 两侧都打标签,因为终端调用在调用时已携带命令和 cwd,而 read 调用既无内容也无总数,给调用侧打标签只会新增一个空变体。 + +read 工具通过 `output.presentationMeta` 投影结构化窗口,这与 write/edit 用来投影其应用 diff hunk 的持久化通道相同([规范化工具输出契约](../architecture/2026-07-20-canonical-tool-output-contract.md))。`presentationMeta` 对一次顶层 surface 调用运行一次,返回 `{ path, lines, totalLines, lang? }` 作为会话校验并存储在结果 `meta` 上的 JSON,`presentResult` 在 live 和回放路径上都把该 meta 收窄回 `ReadResultView`。没有这个通道,行数组和总数就无法触及:原始输出对象不在线上,而重新解析 `N: text` 文本既有损又对截断脚注脆弱。 + +`presentResult` 在以下情况返回 `undefined`——即 generic 回退:meta 缺失或畸形(`readMetaFromMeta` 防御性收窄它,因此回放旧的已记录结果永不抛错)、结果是错误、以及单个文本块不是 read 信封。在成功路径上,它在结构化字段之外携带 `content`(剥信封后的文本),因此不具备 read 能力的 UI(包括当前的 TUI)通过 generic/default card 分支渲染文件文本,与之前完全一致。TUI 的 `renderBody` switch(`packages/ui/tui/src/components/transcript.ts`)不是 `assertNever` 穷尽的:`terminal` 和 `diff` 有分支,其余都落入 generic 分支,该分支读取 `view.content` 与可选的 `title`。`ReadResultView` 原样满足该分支,因此 TUI 无需新代码、输出不变。 + +### 语言提示推导 + +`langFromPath`(在 `read-render.ts` 中)通过一张固定小表(`LANG_BY_EXTENSION`,覆盖常见源码、配置、标记扩展名)把文件扩展名映射到语法高亮语言 id。它读取最后一个路径段与最后一个点之后的扩展名,大小写不敏感,并对以下情况返回 `undefined`:dotfile(`.gitignore`)、无扩展名(`/etc/hosts`)、结尾的点、以及任何未知扩展名——此时 card 省略 `lang`,UI 渲染纯文本。该表不是可调项(tunable):它是 UI 可忽略的展示提示,而非随部署变化的选择,未知扩展名降级为纯文本而非失败。它有意保持小规模而非穷尽的语言注册表;扩展它是一行表项新增。 + +## Alternatives considered + +**在 `presentResult` 中重新解析 `N: text` 面向模型文本。** 已否决:结构化行数组将不得不通过按第一个 `: ` 切分每行来重建,这既有歧义(某行文本自身含 `: `),又丢失精确的 `totalLines`(脚注只在部分分支中陈述它),并在渲染格式变化时立即失效。`presentationMeta` 携带已经结构化的数据,无需重新解析。 + +**调用侧也打标签(`ReadCallView`),镜像终端 card 的两侧对称。** 已否决:read 调用在执行前没有内容、没有行数组、没有总数——调用侧 read card 会是一个空变体,重复 `GenericCallView`(`kind: 'read'`,跟随定位)已经表达的东西。终端 card 两侧都打标签是因为终端调用确实携带调用时数据(命令、cwd);read 调用没有。 + +**把结构化窗口放进新服务或旁路通道而非 `meta`。** 已否决:`meta` 是既有的持久化展示通道(write/edit 的应用 diff 就搭它),它随会话日志免费回放,无需新接线。服务会重新发明事件日志已提供的持久化与回放。 + +**用 merge-extensible union 而非封闭标签。** 出于[渲染意图 union](../architecture/2026-07-02-tool-render-intent-union.md) 封闭的相同理由否决:新 card 需要消费代码来渲染它,因此被消费者静默丢弃的变体比编译错误更糟。把 `read` 加入封闭 union 是扩展它的许可方式——每个在 `card` 上 switch 的消费者都继续编译,因为新成员落入其 generic default,而想要富视图的消费者新增自己的分支。 + +## Consequences + +`ToolResultView` 多了第四个成员。每个在 `card` 上 switch 的消费者都继续编译:TUI 和当前 Web 客户端把未知 card 路由到其 generic 路径,而 read card 携带 `content` 使该路径显示文件文本。从 `lines`/`lang`/`totalLines` 渲染带行号、语法高亮视图的 Web 前端是单独的后续 PR;本 PR 是让数据可触及的后端。在它落地前,read 在各处的渲染与之前完全一致(generic 文本 card)。 + +read 工具现在为每次顶层 read 计算 `presentationMeta`,这是对已在手数据的一次小投影(一次 `lines.map` 和一次 `langFromPath` 调用)。meta 随会话日志持久化,因此 read 结果在磁盘上略大——它已渲染为文本的行数组,现在也以结构化形式存在。 + +## Testing + +`packages/fs/tool-fs/tests/read-render.spec.ts` 单测 `langFromPath`(已知扩展名的大小写不敏感、扩展名在最后一段与最后一个点之后读取、以及 `undefined` 各情况:dotfile、无扩展名、结尾的点、未知)与 `readMetaFromMeta`(含与不含 `lang` 的良构收窄,以及每种拒绝:非对象、数组、缺失或类型错误的 `path`/`totalLines`/`lines`、畸形行项、以及非字符串 `lang`)。`packages/fs/tool-fs/tests/tools.spec.ts` 固定工具接线:`execute` 把结构化窗口(含与不含 `lang` 提示)作为 `meta` 附上、`presentResult` 把它收窄为携带剥信封 `content` 的 `card: 'read'` 视图、以及各拒绝路径(错误结果、非单文本内容、meta 有效但信封畸形、信封有效但 meta 缺失或畸形)都回退到 `undefined`。两个改动的源文件保持逐文件 100% 覆盖率。已渲染 card 的 keyless 快照与组装应用 transcript 属于消费该视图的后续 Web PR,因为本 PR 不新增任何面向产品用户可见的渲染。 + +## Related + +- [Tagged render-intent union for tool-call presentation](../architecture/2026-07-02-tool-render-intent-union.md) —— 本 Note 以 `read` 结果分支扩展的 `card` 标签词汇。 +- [Canonical tool output contract](../architecture/2026-07-20-canonical-tool-output-contract.md) —— 拥有本 Note 用来投影 read 窗口的 `presentationMeta` 持久化通道。 +- [Web terminal card](2026-07-28-web-terminal-card.md) —— 客户端消费结构化 card 的先例;read card 遵循相同的生产者模式,仅结果侧。 diff --git a/packages/core/tools/src/index.ts b/packages/core/tools/src/index.ts index 2caaaa8276..1c6dbf29bc 100644 --- a/packages/core/tools/src/index.ts +++ b/packages/core/tools/src/index.ts @@ -74,6 +74,7 @@ export type { ToolCallKind, FileLocation, FileDiff, + ReadFileLine, ToolCallView, GenericCallView, TerminalCallView, @@ -82,6 +83,7 @@ export type { GenericResultView, TerminalResultView, DiffResultView, + ReadResultView, } from './presentation.ts' declare module 'cordis' { diff --git a/packages/core/tools/src/presentation.ts b/packages/core/tools/src/presentation.ts index 17b88b822f..f553442d0a 100644 --- a/packages/core/tools/src/presentation.ts +++ b/packages/core/tools/src/presentation.ts @@ -117,6 +117,18 @@ export interface DiffCallView { locations?: FileLocation[] } +/** + * One numbered line of a file, the unit a {@link ReadResultView} carries so a + * capable UI can render a syntax-highlighted, line-numbered code view. `number` + * is the 1-based line number in the file (a window past `offset` keeps the file's + * own numbering, not a 1-based re-count); `text` is the line without its trailing + * newline, already truncated to the read tool's per-line cap. + */ +export interface ReadFileLine { + number: number + text: string +} + /** * How a tool wants the COMPLETED call shown — the *result* state, after `execute` * returns. A `card`-tagged union mirroring {@link ToolCallView}: a UI switches on @@ -125,7 +137,7 @@ export interface DiffCallView { * `ToolDefinition.presentResult`; omitting the method keeps the pending * title and renders the raw result content. */ -export type ToolResultView = GenericResultView | TerminalResultView | DiffResultView +export type ToolResultView = GenericResultView | TerminalResultView | DiffResultView | ReadResultView /** * The default completed card: an optional replacement title and reformatted @@ -176,3 +188,38 @@ export interface DiffResultView { /** The change to show, in file order — applied contextual hunks, or a whole-file diff when there is no before-image. */ diffs: FileDiff[] } + +/** + * A completed file read rendered as a line-numbered, optionally syntax-highlighted + * code view by a capable UI. Set by a tool whose call reads file text (e.g. + * `read`); the pending state stays a {@link GenericCallView} (`kind: 'read'`) + * because a call carries no content until `execute` returns. The structured + * `lines`/`path`/`lang`/`totalLines` fields cannot be reconstructed from the + * model-facing result text alone, so the read tool projects them through its + * `output.presentationMeta` (persisted with the session log) and `presentResult` + * narrows that metadata back into this view on live and replay paths alike. A UI + * without the read capability falls back to `content` (the model-facing text with + * its envelope stripped), so this view degrades to the generic text card. + */ +export interface ReadResultView { + card: 'read' + /** Replacement title for the completed call. Omit to keep the pending-state title. */ + title?: string + /** The read file's path (the model-facing path; the bridge relativizes it). */ + path: string + /** The returned window's lines, in file order, each keeping its file line number. */ + lines: ReadFileLine[] + /** Exact total line count in the file, so a UI can show a "showing N of M" affordance. */ + totalLines: number + /** + * A syntax-highlighting language hint derived from the file extension (e.g. + * `ts`, `py`), or omitted when the extension maps to no known language so a UI + * renders the lines as plain text. + */ + lang?: string + /** + * The model-facing result content with its envelope stripped, for a UI without + * the read capability. Omit to let such a UI render the raw result content. + */ + content?: ContentBlock[] +} diff --git a/packages/fs/tool-fs/src/read-render.ts b/packages/fs/tool-fs/src/read-render.ts index 7e581bb22c..b2cd7cbbe0 100644 --- a/packages/fs/tool-fs/src/read-render.ts +++ b/packages/fs/tool-fs/src/read-render.ts @@ -168,3 +168,80 @@ export function formatReadOutput(displayPath: string, outcome: FileReadOutcome): ${body} ` } + +/** + * Lowercased file-extension to syntax-highlighting language hint. Keys are the + * extension without its dot; a UI treats an absent key as plain text. The map is + * intentionally small — common source, config, and markup extensions a + * line-numbered code view benefits from highlighting — not an exhaustive registry. + */ +const LANG_BY_EXTENSION: Readonly> = { + ts: 'ts', tsx: 'tsx', mts: 'ts', cts: 'ts', + js: 'js', jsx: 'jsx', mjs: 'js', cjs: 'js', + json: 'json', jsonc: 'json', + py: 'py', rb: 'rb', go: 'go', rs: 'rs', java: 'java', + c: 'c', h: 'c', cc: 'cpp', cpp: 'cpp', hpp: 'cpp', cxx: 'cpp', + cs: 'cs', kt: 'kotlin', swift: 'swift', php: 'php', + sh: 'sh', bash: 'sh', zsh: 'sh', + yaml: 'yaml', yml: 'yaml', toml: 'toml', ini: 'ini', + md: 'md', markdown: 'md', mdx: 'mdx', + html: 'html', htm: 'html', css: 'css', scss: 'scss', less: 'less', + sql: 'sql', xml: 'xml', lua: 'lua', +} + +/** + * Derive a syntax-highlighting language hint from a read path's file extension. + * Pure and case-insensitive on the extension; a dotfile with no extension + * (`.gitignore`) and an unknown extension both yield `undefined`. + * @param path - the model-facing path the read reported. + * @returns the language hint for {@link LANG_BY_EXTENSION}, or `undefined` when the extension maps to none. + */ +export function langFromPath(path: string): string | undefined { + const base = path.slice(Math.max(path.lastIndexOf('/'), path.lastIndexOf('\\')) + 1) + const dot = base.lastIndexOf('.') + // A leading dot is a dotfile (no extension), not an empty extension. + if (dot <= 0) return undefined + return LANG_BY_EXTENSION[base.slice(dot + 1).toLowerCase()] +} + +/** + * The `read` tool's private `tool/result` `meta` payload: the structured + * line-numbered window a capable UI renders as a code view. Attached opaquely (as + * `unknown`) on the tool result and persisted with the session log — it must be + * JSON-serializable (the session validates this at `append`), so `presentResult` + * reproduces the read card on replay when the raw structured output is no longer + * on the wire. The producing tool owns and narrows this opaque shape. + */ +export interface FsReadMeta { + /** The read file's model-facing path. */ + path: string + /** The returned window's lines, each keeping its file line number. */ + lines: FileTextLine[] + /** Exact total line count in the file. */ + totalLines: number + /** Syntax-highlighting language hint from the extension, or omitted for plain text. */ + lang?: string +} + +/** Whether `value` is a valid {@link FileTextLine} (defensive narrowing from opaque `meta`). */ +function isFileTextLine(value: unknown): value is FileTextLine { + if (typeof value !== 'object' || value === null || Array.isArray(value)) return false + const { number, text } = value as Record + return typeof number === 'number' && typeof text === 'string' +} + +/** + * Narrow opaque live or replayed result metadata to a structured read window. + * Malformed metadata returns `undefined` so presentation can fall back to the + * generic text card instead of throwing during replay. + * @param meta - result metadata. + * @returns the validated read window, or `undefined` for absent or malformed data. + */ +export function readMetaFromMeta(meta: unknown): FsReadMeta | undefined { + if (typeof meta !== 'object' || meta === null || Array.isArray(meta)) return undefined + const { path, lines, totalLines, lang } = meta as Record + if (typeof path !== 'string' || typeof totalLines !== 'number') return undefined + if (!Array.isArray(lines) || !lines.every(isFileTextLine)) return undefined + if (lang !== undefined && typeof lang !== 'string') return undefined + return { path, lines, totalLines, ...lang === undefined ? {} : { lang } } +} diff --git a/packages/fs/tool-fs/src/read.ts b/packages/fs/tool-fs/src/read.ts index 05e1b41ae2..2ce98ca86f 100644 --- a/packages/fs/tool-fs/src/read.ts +++ b/packages/fs/tool-fs/src/read.ts @@ -6,11 +6,11 @@ import type { Context } from 'cordis' import { defineTool } from '@deepseek-ai/dsh-tools' -import type { GenericCallView, GenericResultView, ToolResult } from '@deepseek-ai/dsh-tools' +import type { GenericCallView, ReadResultView, ToolResult } from '@deepseek-ai/dsh-tools' import { FsError } from '@deepseek-ai/dsh-fs' import type {} from '@deepseek-ai/dsh-fs' import type {} from '@deepseek-ai/dsh-system-prompt' -import { buildWindow, formatReadOutput } from './read-render.ts' +import { buildWindow, formatReadOutput, langFromPath, readMetaFromMeta } from './read-render.ts' import { sessionResolveOptions } from './session-cwd.ts' /** Default and maximum number of lines returned by one `read` call (the `readLimit` config). */ @@ -118,6 +118,18 @@ export function applyReadTool(ctx: Context, caps: ReadToolCaps): void { }), }] }, + // Project the structured window into persisted `meta` so a UI's read card + // survives replay: the raw canonical output object is not on the wire, only + // the model-facing text, from which the line/lang data cannot be recovered. + presentationMeta: (_args, value) => { + const lang = langFromPath(value.path) + return { + path: value.path, + lines: value.lines.map(({ number, text }) => ({ number, text })), + totalLines: value.totalLines, + ...lang === undefined ? {} : { lang }, + } + }, }, // Observation races fail closed because guarded mutations re-check the version in-lock. isConcurrencySafe: () => true, @@ -154,15 +166,31 @@ export function applyReadTool(ctx: Context, caps: ReadToolCaps): void { ctx.emit('fs/observed', target, info.version, exec) return outcome }, - presentResult(_args, result: ToolResult): GenericResultView | undefined { + // Result-time display: a `read` card carrying the structured line window a + // capable UI renders as a line-numbered, syntax-highlighted view. The + // structured data is narrowed from the persisted `meta` (replay-safe); the + // envelope-stripped model-facing text rides along as `content` so a UI without + // the read capability still shows the file text. A malformed or absent meta, + // or a result whose text is not the read envelope, declines to `undefined` + // (the generic fallback), never throwing on replay of obsolete logged output. + presentResult(_args, result: ToolResult): ReadResultView | undefined { if (result.isError) return undefined + const meta = readMetaFromMeta(result.meta) + if (meta === undefined) return undefined const only = result.content.length === 1 ? result.content[0] : undefined const text = only?.type === 'text' ? only.text : undefined if (text === undefined) return undefined // Group 1 always captures (possibly empty) when the envelope matches. const body = /^[^\n]*<\/path>\nfile<\/type>\n\n([\s\S]*)\n<\/content>$/u.exec(text)?.[1] if (body === undefined) return undefined - return { card: 'generic', content: [{ type: 'text', text: body }] } + return { + card: 'read', + path: meta.path, + lines: meta.lines, + totalLines: meta.totalLines, + ...meta.lang === undefined ? {} : { lang: meta.lang }, + content: [{ type: 'text', text: body }], + } }, // Pure display: a generic card titled by the file with the read window appended (`Read // foo.txt (5 - 8)`), `read` kind (icon), and a follow-along location whose line is the diff --git a/packages/fs/tool-fs/tests/read-render.spec.ts b/packages/fs/tool-fs/tests/read-render.spec.ts index c2afaf002e..462df231c2 100644 --- a/packages/fs/tool-fs/tests/read-render.spec.ts +++ b/packages/fs/tool-fs/tests/read-render.spec.ts @@ -6,7 +6,7 @@ */ import { describe, expect, it } from 'vitest' -import { buildWindow, READ_MAX_BYTES, READ_MAX_LINE_LENGTH } from '../src/read-render.ts' +import { buildWindow, langFromPath, readMetaFromMeta, READ_MAX_BYTES, READ_MAX_LINE_LENGTH } from '../src/read-render.ts' import type { ReadWindow } from '../src/read-render.ts' const DEFAULT_CAPS = { maxLineLength: READ_MAX_LINE_LENGTH, maxBytes: READ_MAX_BYTES } @@ -116,3 +116,54 @@ describe('buildWindow', () => { }) }) }) + +describe('langFromPath', () => { + it('maps a known extension to its language hint, case-insensitively', () => { + expect(langFromPath('src/a.ts')).toBe('ts') + expect(langFromPath('src/a.TSX')).toBe('tsx') + expect(langFromPath('/abs/module.mjs')).toBe('js') + expect(langFromPath('conf.yml')).toBe('yaml') + expect(langFromPath('README.md')).toBe('md') + }) + + it('reads the extension after the last path segment and last dot', () => { + expect(langFromPath('a.py.bak')).toBeUndefined() + expect(langFromPath('archive.tar.gz')).toBeUndefined() + expect(langFromPath('/dir.py/plain')).toBeUndefined() + expect(langFromPath('C:\\src\\main.rs')).toBe('rs') + }) + + it('returns undefined for a dotfile, an extensionless name, and an unknown extension', () => { + expect(langFromPath('.gitignore')).toBeUndefined() + expect(langFromPath('/etc/hosts')).toBeUndefined() + expect(langFromPath('data.unknownext')).toBeUndefined() + expect(langFromPath('trailingdot.')).toBeUndefined() + }) +}) + +describe('readMetaFromMeta', () => { + const good = { path: '/abs/a.ts', lines: [{ number: 1, text: 'x' }], totalLines: 1, lang: 'ts' } + + it('narrows a well-formed read meta, with and without a lang hint', () => { + expect(readMetaFromMeta(good)).toEqual(good) + const noLang = { path: '/abs/a', lines: [], totalLines: 0 } + expect(readMetaFromMeta(noLang)).toEqual(noLang) + }) + + it('returns undefined for absent, non-object, or array meta', () => { + expect(readMetaFromMeta(undefined)).toBeUndefined() + expect(readMetaFromMeta(null)).toBeUndefined() + expect(readMetaFromMeta('nope')).toBeUndefined() + expect(readMetaFromMeta([good])).toBeUndefined() + }) + + it('returns undefined when a field is missing or the wrong type (defensive narrowing)', () => { + expect(readMetaFromMeta({ ...good, path: 5 })).toBeUndefined() + expect(readMetaFromMeta({ ...good, totalLines: '1' })).toBeUndefined() + expect(readMetaFromMeta({ ...good, lines: 'nope' })).toBeUndefined() + expect(readMetaFromMeta({ ...good, lines: [{ number: '1', text: 'x' }] })).toBeUndefined() + expect(readMetaFromMeta({ ...good, lines: [{ number: 1 }] })).toBeUndefined() + expect(readMetaFromMeta({ ...good, lines: [null] })).toBeUndefined() + expect(readMetaFromMeta({ ...good, lang: 5 })).toBeUndefined() + }) +}) diff --git a/packages/fs/tool-fs/tests/tools.spec.ts b/packages/fs/tool-fs/tests/tools.spec.ts index de844dcaf4..4bf64cb8a5 100644 --- a/packages/fs/tool-fs/tests/tools.spec.ts +++ b/packages/fs/tool-fs/tests/tools.spec.ts @@ -320,6 +320,38 @@ describe('read tool', () => { expect(text(result)).toContain('Output capped.') }) + it('attaches the structured window as presentation meta, and presentResult narrows it into a read card', async () => { + const { ctx, fs } = await setup() + fs.files.set('key:a.ts', 'const x = 1\nconst y = 2') + const result = await call(ctx, 'read', { file_path: 'a.ts' }) + expect(result.isError).toBe(false) + if (result.isError) throw new Error('expected read success') + // The extension drives the lang hint; the window rides on persisted meta. + expect(result.meta).toEqual({ + path: '/abs/a.ts', + lines: [{ number: 1, text: 'const x = 1' }, { number: 2, text: 'const y = 2' }], + totalLines: 2, + lang: 'ts', + }) + const view = ctx.tools.get('read')?.presentResult?.({ file_path: 'a.ts' }, result) + expect(view).toEqual({ + card: 'read', + path: '/abs/a.ts', + lines: [{ number: 1, text: 'const x = 1' }, { number: 2, text: 'const y = 2' }], + totalLines: 2, + lang: 'ts', + content: [{ type: 'text', text: '1: const x = 1\n2: const y = 2\n\n(End of file - total 2 lines)' }], + }) + }) + + it('omits the lang hint in meta for an extension that maps to no language', async () => { + const { ctx, fs } = await setup() + fs.files.set('key:notes', 'plain') + const result = await call(ctx, 'read', { file_path: 'notes' }) + if (result.isError) throw new Error('expected read success') + expect(result.meta).toEqual({ path: '/abs/notes', lines: [{ number: 1, text: 'plain' }], totalLines: 1 }) + }) + }) describe('formatReadOutput footer variants', () => { @@ -450,33 +482,70 @@ describe('tool-owned presentation (pure presentCall)', () => { }) }) - it('read: completed presentation removes the model-facing XML envelope', async () => { - expect(await presentResult('read', { file_path: 'a.txt' }, { - content: [{ type: 'text', text: '/tmp/a.txt\nfile\n\n1: hello\n\n(End of file - total 1 lines)\n' }], + it('read: completed presentation is a read card carrying the structured window with the envelope stripped', async () => { + // The structured line data rides on persisted meta (the raw output object is + // not on the wire); presentResult narrows it and appends the stripped text as + // the no-capability `content` fallback. + const meta = { path: '/tmp/a.ts', lines: [{ number: 1, text: 'hello' }], totalLines: 1, lang: 'ts' } + expect(await presentResult('read', { file_path: 'a.ts' }, { + content: [{ type: 'text', text: '/tmp/a.ts\nfile\n\n1: hello\n\n(End of file - total 1 lines)\n' }], isError: false, + meta, })).toEqual({ - card: 'generic', + card: 'read', + path: '/tmp/a.ts', + lines: [{ number: 1, text: 'hello' }], + totalLines: 1, + lang: 'ts', content: [{ type: 'text', text: '1: hello\n\n(End of file - total 1 lines)' }], }) - expect(await presentResult('read', { file_path: 'a.txt' }, { + // A window whose extension maps to no language omits `lang` from the card. + expect(await presentResult('read', { file_path: 'notes' }, { + content: [{ type: 'text', text: '/tmp/notes\nfile\n\nbody\n' }], + isError: false, + meta: { path: '/tmp/notes', lines: [{ number: 1, text: 'body' }], totalLines: 1 }, + })).toEqual({ + card: 'read', + path: '/tmp/notes', + lines: [{ number: 1, text: 'body' }], + totalLines: 1, + content: [{ type: 'text', text: 'body' }], + }) + // Malformed envelope text with valid meta still declines (the fallback text is unavailable). + expect(await presentResult('read', { file_path: 'a.ts' }, { content: [{ type: 'text', text: 'malformed replay' }], isError: false, + meta, + })).toBeUndefined() + // Valid envelope but absent/malformed meta declines to the generic fallback. + expect(await presentResult('read', { file_path: 'a.ts' }, { + content: [{ type: 'text', text: '/tmp/a.ts\nfile\n\n1: hello\n' }], + isError: false, + })).toBeUndefined() + expect(await presentResult('read', { file_path: 'a.ts' }, { + content: [{ type: 'text', text: '/tmp/a.ts\nfile\n\n1: hello\n' }], + isError: false, + meta: { path: '/tmp/a.ts', lines: 'nope', totalLines: 1 }, })).toBeUndefined() }) it('read: completed presentation declines errors and non-single-text content', async () => { const envelope = '/tmp/a.txt\nfile\n\nbody\n' + const meta = { path: '/tmp/a.txt', lines: [{ number: 1, text: 'body' }], totalLines: 1 } expect(await presentResult('read', { file_path: 'a.txt' }, { content: [{ type: 'text', text: envelope }], isError: true, + meta, })).toBeUndefined() expect(await presentResult('read', { file_path: 'a.txt' }, { content: [{ type: 'text', text: envelope }, { type: 'text', text: 'second' }], isError: false, + meta, })).toBeUndefined() expect(await presentResult('read', { file_path: 'a.txt' }, { content: [{ type: 'reasoning', text: envelope }], isError: false, + meta, })).toBeUndefined() }) From 013761f85060fb3b05fb58339d1b101f534fb75d Mon Sep 17 00:00:00 2001 From: NI0317 Date: Thu, 30 Jul 2026 17:17:22 +0800 Subject: [PATCH 027/139] docs: verify and simplify launch instructions --- ...026-07-22-product-first-root-readme.i18n.yaml | 4 ++-- .../2026-07-22-product-first-root-readme.md | 6 +++--- .../2026-07-22-product-first-root-readme.zh.md | 6 +++--- README.i18n.yaml | 4 ++-- README.md | 16 +++++----------- README.zh.md | 16 +++++----------- .../request-response.expected.json | 4 ++-- 7 files changed, 22 insertions(+), 34 deletions(-) diff --git a/.agents/notes/implemented/process/2026-07-22-product-first-root-readme.i18n.yaml b/.agents/notes/implemented/process/2026-07-22-product-first-root-readme.i18n.yaml index 92ca6f87e6..b38df9878c 100644 --- a/.agents/notes/implemented/process/2026-07-22-product-first-root-readme.i18n.yaml +++ b/.agents/notes/implemented/process/2026-07-22-product-first-root-readme.i18n.yaml @@ -2,5 +2,5 @@ # side as of the last confirmed-consistent state. Both languages carry equal authority; # after editing either side, bring the other along and re-record with: # pnpm run verify-translation-pairing --write .agents/notes/implemented/process/2026-07-22-product-first-root-readme.md -2026-07-22-product-first-root-readme.md: eeef25702b9d1ce87353d620e52ae661455d9b99 -2026-07-22-product-first-root-readme.zh.md: c4026484132772e3783492aaa0e368027ae15574 +2026-07-22-product-first-root-readme.md: 34bee8210615f4c9b4a2a9389e6edd962850fdc5 +2026-07-22-product-first-root-readme.zh.md: be0c6189f5feef9b923f0081e224a7e042aef001 diff --git a/.agents/notes/implemented/process/2026-07-22-product-first-root-readme.md b/.agents/notes/implemented/process/2026-07-22-product-first-root-readme.md index eeef25702b..34bee82106 100644 --- a/.agents/notes/implemented/process/2026-07-22-product-first-root-readme.md +++ b/.agents/notes/implemented/process/2026-07-22-product-first-root-readme.md @@ -12,9 +12,9 @@ The root README is the repository's product front door. Its product-first struct The root README preserves its existing structure, order, and wording wherever the underlying fact remains correct. A refresh changes only stale claims and adds material needed to represent shipped surfaces; it does not use repository growth as a reason to reframe the whole page. -A note before installation thanks internal testers, states that features and experience remain unfinished, and asks for direct reports of failures, confusion, and friction through the WeCom group. The technical pre-release statement remains in its existing development position. +A note before installation thanks internal testers, states that features and experience remain unfinished, and asks for direct reports of failures, confusion, and friction through the WeCom group. The existing development-stage statement identifies DeepSeek Harness as being in internal testing. -The user-surface section adds the ACP automation server and Python/JSON-RPC SDK beside the existing Web, TUI, and headless entries. The capability paragraph keeps its compact inventory style while adding the shipped PTY, LSP, web, goal, planning, task, sandbox, approval, session-query, and telemetry families and stating that compositions select subsets. One adjacent bullet records the authoritative-session-log rule because persistence, replay, queries, telemetry, and interfaces depend on it. +The user-surface section adds the ACP automation server and Python/JSON-RPC SDK beside the existing Web, TUI, and headless entries. The installed TUI remains the single `dsh` command after real PTY validation; the Web instructions build the default active checkout once and then run `dsh web`, matching a production build and HTTP smoke. The capability paragraph keeps its compact inventory style while adding the shipped PTY, LSP, web, goal, planning, task, sandbox, approval, session-query, and telemetry families and stating that compositions select subsets. One adjacent bullet records the authoritative-session-log rule because persistence, replay, queries, telemetry, and interfaces depend on it. Detailed package and service inventories remain at their owning documentation. The English and Chinese README sides share the same technical structure, while their community sections continue to point to the primary channel for each language audience. The documentation website keeps its separate user-guide landing page. @@ -30,4 +30,4 @@ Detailed package and service inventories remain at their owning documentation. T ## Consequences -Reviewers can distinguish factual refreshes from editorial rewrites, and future updates retain established wording unless its meaning becomes false or incomplete. The README must still change with affected commands, entry points, pre-release boundaries, or high-level capability families, while exhaustive detail remains linked rather than copied. +Reviewers can distinguish factual refreshes from editorial rewrites, and future updates retain established wording unless its meaning becomes false or incomplete. The README must still change with affected commands, entry points, release-stage claims, or high-level capability families, while exhaustive detail remains linked rather than copied. diff --git a/.agents/notes/implemented/process/2026-07-22-product-first-root-readme.zh.md b/.agents/notes/implemented/process/2026-07-22-product-first-root-readme.zh.md index c402648413..be0c6189f5 100644 --- a/.agents/notes/implemented/process/2026-07-22-product-first-root-readme.zh.md +++ b/.agents/notes/implemented/process/2026-07-22-product-first-root-readme.zh.md @@ -12,9 +12,9 @@ Status: implemented 只要背后的事实仍然正确,根 README 就保留既有结构、顺序和措辞。刷新时只修正陈旧声明,并补充呈现已交付内容所需的信息;不会因为仓库规模增长就重构整篇叙事。 -安装说明之前的一则文字感谢内测用户,说明功能和体验仍待完善,并邀请大家通过企业微信群直接反馈失败、困惑和不顺手之处。技术性的预发布声明仍保留在原有的开发章节位置。 +安装说明之前的一则文字感谢内测用户,说明功能和体验仍待完善,并邀请大家通过企业微信群直接反馈失败、困惑和不顺手之处。既有的开发阶段声明明确说明 DeepSeek Harness 处于内测阶段。 -用户入口章节在已有的 Web、TUI 和 Headless 入口旁补充 ACP(Agent Client Protocol)自动化服务器和 Python/JSON-RPC SDK。能力段落沿用简洁清单的写法,补充已经交付的 PTY、LSP、Web、目标、规划、任务、沙箱、审批、会话查询和遥测等能力类别,并说明不同组合只选用其中一部分。相邻的一条列表项说明权威会话日志规则,因为持久化、回放、查询、遥测和各类接口都依赖它。 +用户入口章节在已有的 Web、TUI 和 Headless 入口旁补充 ACP(Agent Client Protocol)自动化服务器和 Python/JSON-RPC SDK。经真实 PTY 验证,安装后的 TUI 仍只需执行一条 `dsh` 命令;Web 说明要求先构建一次默认活动检出,然后运行 `dsh web`,该路径已经过生产构建与 HTTP 冒烟验证。能力段落沿用简洁清单的写法,补充已经交付的 PTY、LSP、Web、目标、规划、任务、沙箱、审批、会话查询和遥测等能力类别,并说明不同组合只选用其中一部分。相邻的一条列表项说明权威会话日志规则,因为持久化、回放、查询、遥测和各类接口都依赖它。 包(package)与服务的完整清单仍由各自的归属文档维护。中英文 README 采用相同的技术结构,但社区章节仍分别指向各自语言受众的主要交流渠道。文档网站继续使用独立的用户指南首页。 @@ -30,4 +30,4 @@ Status: implemented ## 结果 -评审者可以区分事实更新与编辑性重写;今后的更新会保留既有措辞,除非其含义已经不再正确或完整。受影响的命令、入口、预发布边界或高层能力类别发生变化时,README 仍须同步更新;完整细节则继续以链接方式提供,而不是复制到正文。 +评审者可以区分事实更新与编辑性重写;今后的更新会保留既有措辞,除非其含义已经不再正确或完整。受影响的命令、入口、发布阶段声明或高层能力类别发生变化时,README 仍须同步更新;完整细节则继续以链接方式提供,而不是复制到正文。 diff --git a/README.i18n.yaml b/README.i18n.yaml index 5dd6ee3ce5..1575c6d5d3 100644 --- a/README.i18n.yaml +++ b/README.i18n.yaml @@ -2,5 +2,5 @@ # side as of the last confirmed-consistent state. Both languages carry equal authority; # after editing either side, bring the other along and re-record with: # pnpm run verify-translation-pairing --write README.md -README.md: ad76366274086248cb4ea0be786ccc6fd0a51296 -README.zh.md: ae6244743fa2af136be17ea8e2b386fe6b1ec48d +README.md: c89a7bad2b06a1d9aeaf74b9450c6362f8fbeb6b +README.zh.md: 85156ca3f6b40801da0f773601301f8cfe3d9c65 diff --git a/README.md b/README.md index ad76366274..c89a7bad2b 100644 --- a/README.md +++ b/README.md @@ -6,7 +6,7 @@ DeepSeek Harness (`dsh`) is an open-source coding agent built on the DeepSeek Ha It uses an architecture where **everything is a plugin**. -## Before you begin, thank you +## Internal testing notice Thank you for making time to try DeepSeek Harness. @@ -32,20 +32,14 @@ The installer keeps every checkout under `~/.dsh/source`: the master clone at `~ ### Web UI -For the recommended local interface, build the frontend after installation and after each update, then start the Web UI. Resolve the running checkout from the `dsh` launcher so the command holds regardless of which staging worktree is current (the launcher resolves through the stable `current` symlink): +For the recommended local interface, build the active checkout after installation and after each update, then start the Web UI: ```sh -dsh_bin=$(cd "$(dirname "$(command -v dsh)")" && pwd -P)/$(basename "$(command -v dsh)") -while [ -L "$dsh_bin" ]; do - link=$(readlink "$dsh_bin") - case $link in /*) dsh_bin=$link ;; *) dsh_bin=$(cd "$(dirname "$dsh_bin")" && cd "$(dirname "$link")" && pwd -P)/$(basename "$link") ;; esac -done -dsh_dir=$(cd "$(dirname "$dsh_bin")/.." && pwd -P) -pnpm --dir "$dsh_dir" run build && pnpm --dir "$dsh_dir" run build:web +(cd ~/.dsh/source/current && pnpm run build) dsh web ``` -The Web UI is served at `http://127.0.0.1:3080` by default. +The build path above is the installer's default; see [`scripts/install.sh`](scripts/install.sh) for alternate locations. The Web UI is served at `http://127.0.0.1:3080` by default. ### TUI @@ -97,7 +91,7 @@ Start with the [development guide](docs/development.md) and read the [architectu For agents, follow [AGENTS.md](AGENTS.md). -DeepSeek Harness is currently pre-release. +DeepSeek Harness is currently in internal testing. ## License diff --git a/README.zh.md b/README.zh.md index ae6244743f..85156ca3f6 100644 --- a/README.zh.md +++ b/README.zh.md @@ -6,7 +6,7 @@ DeepSeek Harness(`dsh`)是一款基于 DeepSeek Harness SDK 构建的开源 它采用了**一切皆插件**的架构。 -## 使用前,想先说声谢谢 +## 内测声明 感谢您愿意拨冗试用 DeepSeek Harness。 @@ -32,20 +32,14 @@ curl -fsSL https://raw.githubusercontent.com/deepseek-harness/deepseek-harness/m ### Web UI -推荐在本地使用 Web UI。安装完成后以及每次更新后,请先构建前端,再启动 Web UI。通过 `dsh` 启动器解析当前运行的检出,这样无论当前是哪个 staging worktree,命令都成立(启动器会经由稳定的 `current` 符号链接解析): +推荐在本地使用 Web UI。安装完成后以及每次更新后,请先构建当前生效的检出,再启动 Web UI: ```sh -dsh_bin=$(cd "$(dirname "$(command -v dsh)")" && pwd -P)/$(basename "$(command -v dsh)") -while [ -L "$dsh_bin" ]; do - link=$(readlink "$dsh_bin") - case $link in /*) dsh_bin=$link ;; *) dsh_bin=$(cd "$(dirname "$dsh_bin")" && cd "$(dirname "$link")" && pwd -P)/$(basename "$link") ;; esac -done -dsh_dir=$(cd "$(dirname "$dsh_bin")/.." && pwd -P) -pnpm --dir "$dsh_dir" run build && pnpm --dir "$dsh_dir" run build:web +(cd ~/.dsh/source/current && pnpm run build) dsh web ``` -Web UI 默认通过 `http://127.0.0.1:3080` 提供服务。 +上述构建路径使用安装器的默认安装位置;如需使用其他位置,请参阅 [`scripts/install.sh`](scripts/install.sh)。Web UI 默认通过 `http://127.0.0.1:3080` 提供服务。 ### TUI @@ -101,7 +95,7 @@ pnpm run test:coverage 面向 agent:遵循 [AGENTS.md](AGENTS.md)。 -DeepSeek Harness 目前处于预发布阶段。 +DeepSeek Harness 目前处于内测阶段。 ## 许可证 diff --git a/scripts/snapshots/translation-prompt-v4/request-response.expected.json b/scripts/snapshots/translation-prompt-v4/request-response.expected.json index 627725f4b7..d3fc01105b 100644 --- a/scripts/snapshots/translation-prompt-v4/request-response.expected.json +++ b/scripts/snapshots/translation-prompt-v4/request-response.expected.json @@ -8,11 +8,11 @@ }, { "role": "user", - "content": "# DeepSeek Harness\n\nEnglish | [中文](README.zh.md)\n\nDeepSeek Harness (`dsh`) is an open-source coding agent built on the DeepSeek Harness SDK.\n\nIt uses an architecture where **everything is a plugin**.\n\n## Before you begin, thank you\n\nThank you for making time to try DeepSeek Harness.\n\nThis version is still in internal testing. Some features remain unfinished, and parts of the experience may feel rough.\n\n“As one cuts and files, as one carves and polishes.” Products grow through repeated encounters with real use and candid feedback. The problems you uncover in practice may lead us to re-examine, or even discard, existing designs.\n\nWe especially want to hear about moments of failure, confusion, or friction. If DeepSeek Harness does not help—or instead makes your work harder—please leave a message in our WeCom group and tell us about your experience. Every report will help us refine it.\n\n## Install\n\nInstall `dsh` with one command:\n\n```sh\ncurl -fsSL https://raw.githubusercontent.com/deepseek-harness/deepseek-harness/master/scripts/install.sh | sh\n```\n\nThe installer requires `git` and Node `^22.19 || >=24`, offers to install `pnpm` when it is missing, and prompts for a DeepSeek API key.\n\nThe installer keeps every checkout under `~/.dsh/source`: the master clone at `~/.dsh/source/master` and each install's staging checkout as a git worktree `~/.dsh/source/staging-`. The stable symlink `~/.dsh/source/current` points at the active staging worktree, and `dsh` in `~/.local/bin` links to `current/bin/dsh`, so an upgrade repoints one symlink and the `dsh` on PATH never moves. Re-running the command adds a fresh staging worktree from an updated master and repoints `current` at it. See [`scripts/install.sh`](scripts/install.sh) for alternate install locations and other options.\n\n## Use DeepSeek Harness\n\n### Web UI\n\nFor the recommended local interface, build the frontend after installation and after each update, then start the Web UI. Resolve the running checkout from the `dsh` launcher so the command holds regardless of which staging worktree is current (the launcher resolves through the stable `current` symlink):\n\n```sh\ndsh_bin=$(cd \"$(dirname \"$(command -v dsh)\")\" && pwd -P)/$(basename \"$(command -v dsh)\")\nwhile [ -L \"$dsh_bin\" ]; do\n link=$(readlink \"$dsh_bin\")\n case $link in /*) dsh_bin=$link ;; *) dsh_bin=$(cd \"$(dirname \"$dsh_bin\")\" && cd \"$(dirname \"$link\")\" && pwd -P)/$(basename \"$link\") ;; esac\ndone\ndsh_dir=$(cd \"$(dirname \"$dsh_bin\")/..\" && pwd -P)\npnpm --dir \"$dsh_dir\" run build && pnpm --dir \"$dsh_dir\" run build:web\ndsh web\n```\n\nThe Web UI is served at `http://127.0.0.1:3080` by default.\n\n### TUI\n\nStart the full-screen terminal interface:\n\n```sh\ndsh\n```\n\n### Headless\n\nRun one task, print the final answer, and exit:\n\n```sh\ndsh -p \"summarize this workspace\"\n```\n\n### Automation and SDKs\n\nFrom a source checkout, start the ACP automation server:\n\n```sh\npnpm run demo:acp\n```\n\nThe [Python SDK](python/README.md) drives a bundled JSON-RPC runtime. The [examples](examples/README.md) cover the runnable TUI, headless, ACP, JSON-RPC, Code Mode, and self-referential compositions.\n\n## Why DeepSeek Harness\n\nBuilt-in capabilities cover file reading, editing, and search; shell and persistent PTY execution; reusable skills; task tracking, goals, plans, todos, and background tasks; subagents and workflows; sandboxing and approvals; persistent, resumable, forkable, and queryable sessions; LSP and web access; context compaction; and telemetry. Each composition selects the subset appropriate to its surface. The TUI also includes Plan Mode.\n\n- **Everything is a plugin.** Models, tools, policies, storage, context management, and interfaces are composable [Cordis plugins](docs/user/develop/basic/index.md), so deployments can extend or replace behavior without forking the agent loop. See the [architecture](docs/architecture.md) for the underlying design.\n- **Runs are reconstructable.** Anything visible to the model is logged in the authoritative session stream; persistence, resume/fork/query, replay, telemetry, and UIs derive from the same events. See the [session-log architecture](docs/architecture.md#session-log).\n- **Code Mode (opt-in).** It exposes a `run_code` tool and a generated TypeScript SDK; only program output re-enters model context. See [Code Mode](packages/core/tools/README.md#code-mode).\n- **Self-referential Cordis tools are opt-in.** They let the agent inspect its live runtime and mount or unmount plugins while it runs. See the [Cordis tools](packages/cordis/tool-cordis/README.md).\n\n## Community\n\nFollow DeepSeek Harness on Twitter for project updates.\n\n## Development\n\n```sh\npnpm install\npnpm run test:coverage\n```\n\nStart with the [development guide](docs/development.md) and read the [architecture](docs/architecture.md) before changing packages.\n\nFor agents, follow [AGENTS.md](AGENTS.md).\n\nDeepSeek Harness is currently pre-release.\n\n## License\n\n[BSD 3-Clause](LICENSE)\n" + "content": "# DeepSeek Harness\n\nEnglish | [中文](README.zh.md)\n\nDeepSeek Harness (`dsh`) is an open-source coding agent built on the DeepSeek Harness SDK.\n\nIt uses an architecture where **everything is a plugin**.\n\n## Internal testing notice\n\nThank you for making time to try DeepSeek Harness.\n\nThis version is still in internal testing. Some features remain unfinished, and parts of the experience may feel rough.\n\n“As one cuts and files, as one carves and polishes.” Products grow through repeated encounters with real use and candid feedback. The problems you uncover in practice may lead us to re-examine, or even discard, existing designs.\n\nWe especially want to hear about moments of failure, confusion, or friction. If DeepSeek Harness does not help—or instead makes your work harder—please leave a message in our WeCom group and tell us about your experience. Every report will help us refine it.\n\n## Install\n\nInstall `dsh` with one command:\n\n```sh\ncurl -fsSL https://raw.githubusercontent.com/deepseek-harness/deepseek-harness/master/scripts/install.sh | sh\n```\n\nThe installer requires `git` and Node `^22.19 || >=24`, offers to install `pnpm` when it is missing, and prompts for a DeepSeek API key.\n\nThe installer keeps every checkout under `~/.dsh/source`: the master clone at `~/.dsh/source/master` and each install's staging checkout as a git worktree `~/.dsh/source/staging-`. The stable symlink `~/.dsh/source/current` points at the active staging worktree, and `dsh` in `~/.local/bin` links to `current/bin/dsh`, so an upgrade repoints one symlink and the `dsh` on PATH never moves. Re-running the command adds a fresh staging worktree from an updated master and repoints `current` at it. See [`scripts/install.sh`](scripts/install.sh) for alternate install locations and other options.\n\n## Use DeepSeek Harness\n\n### Web UI\n\nFor the recommended local interface, build the active checkout after installation and after each update, then start the Web UI:\n\n```sh\n(cd ~/.dsh/source/current && pnpm run build)\ndsh web\n```\n\nThe build path above is the installer's default; see [`scripts/install.sh`](scripts/install.sh) for alternate locations. The Web UI is served at `http://127.0.0.1:3080` by default.\n\n### TUI\n\nStart the full-screen terminal interface:\n\n```sh\ndsh\n```\n\n### Headless\n\nRun one task, print the final answer, and exit:\n\n```sh\ndsh -p \"summarize this workspace\"\n```\n\n### Automation and SDKs\n\nFrom a source checkout, start the ACP automation server:\n\n```sh\npnpm run demo:acp\n```\n\nThe [Python SDK](python/README.md) drives a bundled JSON-RPC runtime. The [examples](examples/README.md) cover the runnable TUI, headless, ACP, JSON-RPC, Code Mode, and self-referential compositions.\n\n## Why DeepSeek Harness\n\nBuilt-in capabilities cover file reading, editing, and search; shell and persistent PTY execution; reusable skills; task tracking, goals, plans, todos, and background tasks; subagents and workflows; sandboxing and approvals; persistent, resumable, forkable, and queryable sessions; LSP and web access; context compaction; and telemetry. Each composition selects the subset appropriate to its surface. The TUI also includes Plan Mode.\n\n- **Everything is a plugin.** Models, tools, policies, storage, context management, and interfaces are composable [Cordis plugins](docs/user/develop/basic/index.md), so deployments can extend or replace behavior without forking the agent loop. See the [architecture](docs/architecture.md) for the underlying design.\n- **Runs are reconstructable.** Anything visible to the model is logged in the authoritative session stream; persistence, resume/fork/query, replay, telemetry, and UIs derive from the same events. See the [session-log architecture](docs/architecture.md#session-log).\n- **Code Mode (opt-in).** It exposes a `run_code` tool and a generated TypeScript SDK; only program output re-enters model context. See [Code Mode](packages/core/tools/README.md#code-mode).\n- **Self-referential Cordis tools are opt-in.** They let the agent inspect its live runtime and mount or unmount plugins while it runs. See the [Cordis tools](packages/cordis/tool-cordis/README.md).\n\n## Community\n\nFollow DeepSeek Harness on Twitter for project updates.\n\n## Development\n\n```sh\npnpm install\npnpm run test:coverage\n```\n\nStart with the [development guide](docs/development.md) and read the [architecture](docs/architecture.md) before changing packages.\n\nFor agents, follow [AGENTS.md](AGENTS.md).\n\nDeepSeek Harness is currently in internal testing.\n\n## License\n\n[BSD 3-Clause](LICENSE)\n" }, { "role": "assistant", - "content": "# DeepSeek Harness\n\n[English](README.md) | 中文\n\nDeepSeek Harness(`dsh`)是一款基于 DeepSeek Harness SDK 构建的开源 coding agent(编程智能体)。\n\n它采用了**一切皆插件**的架构。\n\n## 使用前,想先说声谢谢\n\n感谢您愿意拨冗试用 DeepSeek Harness。\n\n目前的版本仍处于内部测试阶段,有些功能仍待完善,有些体验难免粗粝。\n\n“如切如磋,如琢如磨。”产品的成长,离不开一次次真实的碰撞与坦诚的反馈。您在真实使用中暴露的问题,也可能促使我们重新审视,甚至推翻已有的设计。\n\n我们尤其希望听见那些失败、困惑与不顺手的时刻——如果它未能帮到您,甚至反而为工作平添了麻烦,请在企业微信群中留言,将使用感受告诉我们。每一条反馈,都会帮助我们把它打磨得更好。\n\n## 安装\n\n使用一条命令安装 `dsh`:\n\n```sh\ncurl -fsSL https://raw.githubusercontent.com/deepseek-harness/deepseek-harness/master/scripts/install.sh | sh\n```\n\n安装器要求系统已安装 `git` 和 Node `^22.19 || >=24`,缺少 `pnpm` 时可代为安装,并会提示输入 DeepSeek API 密钥。\n\n安装器会把所有检出都放在 `~/.dsh/source` 下:master 克隆位于 `~/.dsh/source/master`,每次安装的 staging 检出是一个 git worktree `~/.dsh/source/staging-<时间戳>`。稳定符号链接 `~/.dsh/source/current` 指向当前生效的 staging worktree,`~/.local/bin` 中的 `dsh` 链接到 `current/bin/dsh`,因此升级只需重指一个符号链接,PATH 上的 `dsh` 从不移动。再次运行该命令会基于更新后的 master 新增一个 staging worktree,并把 `current` 重指到它。其他安装位置和选项见 [`scripts/install.sh`](scripts/install.sh)。\n\n## 使用 DeepSeek Harness\n\n### Web UI\n\n推荐在本地使用 Web UI。安装完成后以及每次更新后,请先构建前端,再启动 Web UI。通过 `dsh` 启动器解析当前运行的检出,这样无论当前是哪个 staging worktree,命令都成立(启动器会经由稳定的 `current` 符号链接解析):\n\n```sh\ndsh_bin=$(cd \"$(dirname \"$(command -v dsh)\")\" && pwd -P)/$(basename \"$(command -v dsh)\")\nwhile [ -L \"$dsh_bin\" ]; do\n link=$(readlink \"$dsh_bin\")\n case $link in /*) dsh_bin=$link ;; *) dsh_bin=$(cd \"$(dirname \"$dsh_bin\")\" && cd \"$(dirname \"$link\")\" && pwd -P)/$(basename \"$link\") ;; esac\ndone\ndsh_dir=$(cd \"$(dirname \"$dsh_bin\")/..\" && pwd -P)\npnpm --dir \"$dsh_dir\" run build && pnpm --dir \"$dsh_dir\" run build:web\ndsh web\n```\n\nWeb UI 默认通过 `http://127.0.0.1:3080` 提供服务。\n\n### TUI\n\n启动全屏终端界面:\n\n```sh\ndsh\n```\n\n### Headless\n\n运行一项任务,打印最终答案后退出:\n\n```sh\ndsh -p \"summarize this workspace\"\n```\n\n### 自动化与 SDK\n\n从源码检出中启动 ACP(Agent Client Protocol)自动化服务器:\n\n```sh\npnpm run demo:acp\n```\n\n[Python SDK](python/README.md) 驱动随附的 JSON-RPC 运行时。[示例](examples/README.md)涵盖可运行的 TUI、headless、ACP、JSON-RPC、Code Mode 和自指组合。\n\n## 为什么选择 DeepSeek Harness\n\n内置功能涵盖文件读取、编辑与搜索、shell 和持久 PTY 执行、可复用 skill(技能)、任务跟踪、目标、计划、待办事项与后台任务、subagent 与工作流、沙箱与审批、可持久化、恢复、fork 与查询的会话、LSP 与 Web 访问、上下文压缩(context compaction),以及遥测。每个组合只选用适合其使用方式的能力子集。TUI 还包含 Plan Mode。\n\n- **一切皆插件。** 模型、工具、策略、存储、上下文管理和界面均可组合为 [Cordis 插件](docs/user/develop/basic/index.md),部署方无需 fork agent loop(智能体循环)即可扩展或替换行为。底层设计见[架构文档](docs/architecture.md)。\n- **运行可重建。** 凡是模型可见的内容,都会记录在权威会话流中;持久化、恢复/fork/查询、回放、遥测和 UI 均从同一组事件派生。参见[会话日志架构](docs/architecture.md#session-log)。\n- **Code Mode(需显式启用)。** 它会提供 `run_code` 工具和生成的 TypeScript SDK,只有程序输出会重新进入模型上下文。参见 [Code Mode](packages/core/tools/README.md#code-mode)。\n- **自指 Cordis 工具需显式启用。** 这些工具可让 agent 检查自身的实时运行时,并在运行中挂载或卸载插件。参见 [Cordis 工具](packages/cordis/tool-cordis/README.md)。\n\n## 社区\n\n扫描二维码,或打开 DeepSeek Harness 微信社区申请页面 申请加入。\n\n

\n \"DeepSeek\n

\n\n## 开发\n\n```sh\npnpm install\npnpm run test:coverage\n```\n\n请先阅读[开发指南](docs/development.md);修改包之前,请阅读[架构文档](docs/architecture.md)。\n\n面向 agent:遵循 [AGENTS.md](AGENTS.md)。\n\nDeepSeek Harness 目前处于预发布阶段。\n\n## 许可证\n\n[BSD 3-Clause](LICENSE)\n" + "content": "# DeepSeek Harness\n\n[English](README.md) | 中文\n\nDeepSeek Harness(`dsh`)是一款基于 DeepSeek Harness SDK 构建的开源 coding agent(编程智能体)。\n\n它采用了**一切皆插件**的架构。\n\n## 内测声明\n\n感谢您愿意拨冗试用 DeepSeek Harness。\n\n目前的版本仍处于内部测试阶段,有些功能仍待完善,有些体验难免粗粝。\n\n“如切如磋,如琢如磨。”产品的成长,离不开一次次真实的碰撞与坦诚的反馈。您在真实使用中暴露的问题,也可能促使我们重新审视,甚至推翻已有的设计。\n\n我们尤其希望听见那些失败、困惑与不顺手的时刻——如果它未能帮到您,甚至反而为工作平添了麻烦,请在企业微信群中留言,将使用感受告诉我们。每一条反馈,都会帮助我们把它打磨得更好。\n\n## 安装\n\n使用一条命令安装 `dsh`:\n\n```sh\ncurl -fsSL https://raw.githubusercontent.com/deepseek-harness/deepseek-harness/master/scripts/install.sh | sh\n```\n\n安装器要求系统已安装 `git` 和 Node `^22.19 || >=24`,缺少 `pnpm` 时可代为安装,并会提示输入 DeepSeek API 密钥。\n\n安装器会把所有检出都放在 `~/.dsh/source` 下:master 克隆位于 `~/.dsh/source/master`,每次安装的 staging 检出是一个 git worktree `~/.dsh/source/staging-<时间戳>`。稳定符号链接 `~/.dsh/source/current` 指向当前生效的 staging worktree,`~/.local/bin` 中的 `dsh` 链接到 `current/bin/dsh`,因此升级只需重指一个符号链接,PATH 上的 `dsh` 从不移动。再次运行该命令会基于更新后的 master 新增一个 staging worktree,并把 `current` 重指到它。其他安装位置和选项见 [`scripts/install.sh`](scripts/install.sh)。\n\n## 使用 DeepSeek Harness\n\n### Web UI\n\n推荐在本地使用 Web UI。安装完成后以及每次更新后,请先构建当前生效的检出,再启动 Web UI:\n\n```sh\n(cd ~/.dsh/source/current && pnpm run build)\ndsh web\n```\n\n上述构建路径使用安装器的默认安装位置;如需使用其他位置,请参阅 [`scripts/install.sh`](scripts/install.sh)。Web UI 默认通过 `http://127.0.0.1:3080` 提供服务。\n\n### TUI\n\n启动全屏终端界面:\n\n```sh\ndsh\n```\n\n### Headless\n\n运行一项任务,打印最终答案后退出:\n\n```sh\ndsh -p \"summarize this workspace\"\n```\n\n### 自动化与 SDK\n\n从源码检出中启动 ACP(Agent Client Protocol)自动化服务器:\n\n```sh\npnpm run demo:acp\n```\n\n[Python SDK](python/README.md) 驱动随附的 JSON-RPC 运行时。[示例](examples/README.md)涵盖可运行的 TUI、headless、ACP、JSON-RPC、Code Mode 和自指组合。\n\n## 为什么选择 DeepSeek Harness\n\n内置功能涵盖文件读取、编辑与搜索、shell 和持久 PTY 执行、可复用 skill(技能)、任务跟踪、目标、计划、待办事项与后台任务、subagent 与工作流、沙箱与审批、可持久化、恢复、fork 与查询的会话、LSP 与 Web 访问、上下文压缩(context compaction),以及遥测。每个组合只选用适合其使用方式的能力子集。TUI 还包含 Plan Mode。\n\n- **一切皆插件。** 模型、工具、策略、存储、上下文管理和界面均可组合为 [Cordis 插件](docs/user/develop/basic/index.md),部署方无需 fork agent loop(智能体循环)即可扩展或替换行为。底层设计见[架构文档](docs/architecture.md)。\n- **运行可重建。** 凡是模型可见的内容,都会记录在权威会话流中;持久化、恢复/fork/查询、回放、遥测和 UI 均从同一组事件派生。参见[会话日志架构](docs/architecture.md#session-log)。\n- **Code Mode(需显式启用)。** 它会提供 `run_code` 工具和生成的 TypeScript SDK,只有程序输出会重新进入模型上下文。参见 [Code Mode](packages/core/tools/README.md#code-mode)。\n- **自指 Cordis 工具需显式启用。** 这些工具可让 agent 检查自身的实时运行时,并在运行中挂载或卸载插件。参见 [Cordis 工具](packages/cordis/tool-cordis/README.md)。\n\n## 社区\n\n扫描二维码,或打开 DeepSeek Harness 微信社区申请页面 申请加入。\n\n

\n \"DeepSeek\n

\n\n## 开发\n\n```sh\npnpm install\npnpm run test:coverage\n```\n\n请先阅读[开发指南](docs/development.md);修改包之前,请阅读[架构文档](docs/architecture.md)。\n\n面向 agent:遵循 [AGENTS.md](AGENTS.md)。\n\nDeepSeek Harness 目前处于内测阶段。\n\n## 许可证\n\n[BSD 3-Clause](LICENSE)\n" }, { "role": "user", From f6802ee0192243a6f704d3ac51d3abeede9d8d63 Mon Sep 17 00:00:00 2001 From: Chinesezjc Date: Thu, 30 Jul 2026 17:43:13 +0800 Subject: [PATCH 028/139] feat(web): render web_search/web_fetch output as a web card Consume the card:'web' result view (structured sources + answer for search, the URL and HTTP status for fetch) the web backend PR added. WebBlock (ui-primitives) draws both kinds via the kind discriminant: a citation list of safe external links (the MarkdownText protocol allowlist, title-or-hostname label), a truncation indicator, a height cap matching TerminalBlock; a fetch summary for the other kind. web-card-model is the single resultView derivation; a keyed WebRow registers under web_search and web_fetch with the card resident under its summary. The generic fallback and the details panel are web-aware. Fixture gains web_search and web_fetch turns for the built-boot snapshot. --- ...6-07-30-web-result-card-frontend.i18n.yaml | 6 + .../2026-07-30-web-result-card-frontend.md | 49 ++++ .../2026-07-30-web-result-card-frontend.zh.md | 49 ++++ .../client/connection/src/client/fixture.ts | 79 +++++- .../ui-conversation/src/client/apply.ts | 6 + .../client/chat/GenericToolCard.module.css | 15 ++ .../src/client/chat/GenericToolCard.tsx | 19 +- .../src/client/contract/web-card-model.ts | 70 +++++ .../client/skeleton/DetailsPanel.module.css | 6 + .../src/client/skeleton/DetailsPanel.tsx | 13 +- .../src/client/toolviews/web-row.module.css | 95 +++++++ .../src/client/toolviews/web-row.tsx | 95 +++++++ .../ui-conversation/tests/chat-apply.spec.tsx | 9 +- .../ui-conversation/tests/web-card.spec.tsx | 255 ++++++++++++++++++ .../ui-primitives/src/WebBlock.module.css | 124 +++++++++ .../client/ui-primitives/src/WebBlock.tsx | 209 ++++++++++++++ packages/client/ui-primitives/src/index.ts | 2 + .../ui-primitives/tests/web-block.spec.tsx | 165 ++++++++++++ 18 files changed, 1256 insertions(+), 10 deletions(-) create mode 100644 .agents/notes/implemented/feature/2026-07-30-web-result-card-frontend.i18n.yaml create mode 100644 .agents/notes/implemented/feature/2026-07-30-web-result-card-frontend.md create mode 100644 .agents/notes/implemented/feature/2026-07-30-web-result-card-frontend.zh.md create mode 100644 packages/client/ui-conversation/src/client/chat/GenericToolCard.module.css create mode 100644 packages/client/ui-conversation/src/client/contract/web-card-model.ts create mode 100644 packages/client/ui-conversation/src/client/toolviews/web-row.module.css create mode 100644 packages/client/ui-conversation/src/client/toolviews/web-row.tsx create mode 100644 packages/client/ui-conversation/tests/web-card.spec.tsx create mode 100644 packages/client/ui-primitives/src/WebBlock.module.css create mode 100644 packages/client/ui-primitives/src/WebBlock.tsx create mode 100644 packages/client/ui-primitives/tests/web-block.spec.tsx diff --git a/.agents/notes/implemented/feature/2026-07-30-web-result-card-frontend.i18n.yaml b/.agents/notes/implemented/feature/2026-07-30-web-result-card-frontend.i18n.yaml new file mode 100644 index 0000000000..e2cb16b5cc --- /dev/null +++ b/.agents/notes/implemented/feature/2026-07-30-web-result-card-frontend.i18n.yaml @@ -0,0 +1,6 @@ +# Bilingual-pair consistency record (docs/i18n/README.md): the git blob hash of each +# side as of the last confirmed-consistent state. Both languages carry equal authority; +# after editing either side, bring the other along and re-record with: +# pnpm run verify-translation-pairing --write .agents/notes/implemented/feature/2026-07-30-web-result-card-frontend.md +2026-07-30-web-result-card-frontend.md: cf2dd26a8f6eebe6d8d5d275a462151b7c3274a2 +2026-07-30-web-result-card-frontend.zh.md: 505243f7a31df1a5be0381a9399c5283272d1fe8 diff --git a/.agents/notes/implemented/feature/2026-07-30-web-result-card-frontend.md b/.agents/notes/implemented/feature/2026-07-30-web-result-card-frontend.md new file mode 100644 index 0000000000..cf2dd26a8f --- /dev/null +++ b/.agents/notes/implemented/feature/2026-07-30-web-result-card-frontend.md @@ -0,0 +1,49 @@ +# Agent Note: Web result card frontend — rendering the web render intent in the browser + +Status: implemented + +English | [中文](2026-07-30-web-result-card-frontend.zh.md) + +## Problem + +The `web_search` and `web_fetch` tools declare a `card: 'web'` result view ([web result card](2026-07-30-web-result-card.md)): a `kind`-tagged union carrying either the structured cited sources plus an optional provider answer (`kind: 'search'`) or the fetched URL and its HTTP status (`kind: 'fetch'`). That view already reaches the browser — host, connection, and runtime deliver it onto `ConversationSnapshot` as `resultView` — but the Web client ignored it: a completed web call rendered only as its flattened model-facing text, the same lossy render the contract note explains the structured view exists to replace. A `web_search` reached the reader as one free-text markdown line per source rather than a citation list of clickable sources, and a `web_fetch` as its markdown body with no retrieval summary. + +## Decision + +`WebBlock` is a `ui-primitives` component that renders a completed web retrieval, and every Web render site for a web call consumes the `web` render intent through it: the keyed chat tool rows (`web_search`/`web_fetch`), the `GenericToolCard` render-site fallback, and the details panel's Output section. `ui-conversation/src/client/contract/web-card-model.ts` is the single place that turns the snapshot's `resultView` into the component's props, mirroring `terminal-card-model.ts`, so no two sites disagree about what a web call shows. It returns null — the generic path — for a running call (the web card is result-only, since the tools keep a generic pending view), for a settled call whose result view is not a web card including a `card` value this client version does not know (which arrives over the wire and so cannot be trusted to be a compiled variant), and for a generic result view (a web tool's error path returns the generic card, whose text the generic path preserves). + +One component draws both kinds, discriminated by `kind`. A `search` shows the answer as markdown above a citation list; each source is a safe external link labelled by its title, or its hostname when the provider gave none, with the snippet and publication date below it, and a `来源列表已截断` indicator when the tool capped the list. A `fetch` shows a compact summary: the linked final URL, its HTTP status, and a `内容已截断` indicator. One component rather than two because both are web retrieval rendered as one card family, which is exactly the reason the contract carries them under one `card` tag with a `kind` discriminant. + +**Links are safe by the same allowlist MarkdownText applies to untrusted assistant-authored links.** A source or fetch URL becomes a navigable anchor only when its protocol is `http:` or `https:`, with `target="_blank"` and `rel="noopener noreferrer"`; a `javascript:`/`data:`/`file:` URL or an unparseable string renders as plain text with no href. The result content a web tool returns is model-authored and reaches this component unverified, so it is treated as untrusted exactly as assistant markdown is. The label falls back from title to hostname to the raw URL, so a source always reads as something even when both the title is absent and the URL does not parse. + +**Geometry mirrors CodeBlock/TerminalBlock** (12px radius, code-block surface, 16px vertical margin) so a web card reads as one family with them. A long source list caps at `maxSources` with a head/tail collapse using TerminalBlock's exact split arithmetic (`ceil(max/2)` head lines plus the remaining tail), so a long body's slices agree between the two cards. A source list is prose rather than column-aligned output, so it wraps normally instead of scrolling horizontally the way a terminal card's output does — that is the one deliberate divergence from TerminalBlock. + +The card is **resident** under the summary row in the chat rows, capped at `CHAT_WEB_MAX_SOURCES` (8) — half the primitive's own default of 16, which the details panel keeps — the same summary-surface-versus-reading-surface split `CHAT_TERMINAL_MAX_LINES` draws for the terminal card, and the same resident posture `BashRow` uses. The keyed rows register one `WebRow` component under both `web_search` and `web_fetch`; the row discriminates on the tool name only to pick its icon (search vs. browse) and its title (`Search`/`Fetch`). A web-declaring tool without its own keyed row lands on `GenericToolCard`, which grows the same resident card. The details panel renders the card at the primitive's full source allowance. + +## Consequences + +`WebBlock` reads only the web view's fields, so it stays a pure function of what the render intent carries — no session lookups, replay-safe like the presenters that produce the view, and unlike the terminal card it needs no cwd resolution because a web view carries no path. A UI without the `web` capability (the TUI) still gets the contract's fallback `content`; nothing about the tools' result shape changed. `MarkdownText` is reused for the answer, so the answer's own untrusted-link handling and GFM rendering come for free. + +A separate later PR unifies the whole-row collapse/expand interaction and will flip every resident card (terminal, diff, web) to expand-gated at once; this card follows the current resident convention rather than pre-empting that change. + +## Alternatives considered + +**Two components, one per kind.** Rejected: the two shapes share their card chrome, their safe-link handling, and their truncation indicator, and the contract already expresses their difference as a `kind` discriminant under one `card` tag; two components would duplicate the shared surface and split the safe-link logic. + +**Reparse the model-facing render text instead of consuming the structured view.** Rejected for the same reason the contract note gives: `web_search`'s render collapses each source's fields into one free-text line labelled by title OR hostname, so reparsing cannot recover `{url, title?, snippet?, publishedAt?}`. The structured `resultView` is the only faithful source, which is why the backend PR added it. + +**Render plain anchors without the protocol allowlist.** Rejected: the URL is model-authored and unverified at this seam, so an unfiltered href would let a `javascript:` URL execute on click. The allowlist matches MarkdownText's, so untrusted links behave identically wherever they render. + +## Testing + +`packages/client/ui-primitives/tests/web-block.spec.tsx` pins the component per-file to the 100% gate: both kinds; the title-or-hostname-or-raw-URL label fallback; the safe-link attributes on both kinds (an http(s) URL becoming an external anchor with `target`/`rel`, a `javascript:`/`file:`/unparseable URL rendering as a plain span with no href); the snippet and date shown or omitted on present/empty/absent; the truncation indicator gated on the flag; and the source-list height cap with its head/tail slice and expand/collapse control including the default cap. + +`packages/client/ui-conversation/tests/web-card.spec.tsx` mirrors `terminal-card.spec.tsx` at every wiring seam: `webCardModel`'s derivation projecting every source field, its truncation and absent-answer arms, the fetch derivation, and each null arm (running, null result view, generic result view, unknown card tag); the keyed `WebRow`'s resident card for both kinds capped tighter than the panel, its summary-row-alone running and failed arms; the `GenericToolCard` fallback growing the resident card for a web-declaring tool and keeping the plain row for a non-web call; the details panel's Output section for both kinds and its flattened fallback for a non-web result; and the keyed registration under both `web_search` and `web_fetch` with one component. That file sits on the coverage `exclude` list (`ui-conversation/src/*`), so a coverage run measures none of it. + +The fixture (`packages/client/connection/src/client/fixture.ts`) adds turns 66 (`web_search`) and 67 (`web_fetch`), authored inline because the client-side fixture cannot import the web tool: turn 66's result view carries an answer and three sources exercising the citation list (a titled source with a snippet and date, a source with no title so its hostname labels the link, and a source with a date but no snippet) with the capped indicator on; turn 67's carries the fetched URL and a 200 status. Both keep a generic pending call view and add the `web` card only at result time, matching the contract's result-only web shape, and are named after the real tools so they hit the keyed `WebRow`. They are ordered before the todo turn (renumbered to 68) for the same reason the terminal turn is: the standing plan retires at the next `turn/start`, so a turn appended after it would empty the dock's plan strip. This drives the built-boot snapshot and a live `?fixture` server. + +## Related + +- [Web result card](2026-07-30-web-result-card.md) — the backend PR that added the `card: 'web'` result arm and made the two tools emit it; this is its deferred frontend consumer. +- [Web terminal card](2026-07-28-web-terminal-card.md) — the precedent this mirrors: a `ui-primitives` block, a single card-model derivation, keyed and fallback chat rows, and a details-panel arm, for the `terminal` render intent. +- [Tagged render-intent union for tool-call presentation](../architecture/2026-07-02-tool-render-intent-union.md) — the `card`-tagged vocabulary; the Web client is now a full consumer of the `web` arm. diff --git a/.agents/notes/implemented/feature/2026-07-30-web-result-card-frontend.zh.md b/.agents/notes/implemented/feature/2026-07-30-web-result-card-frontend.zh.md new file mode 100644 index 0000000000..505243f7a3 --- /dev/null +++ b/.agents/notes/implemented/feature/2026-07-30-web-result-card-frontend.zh.md @@ -0,0 +1,49 @@ +# Agent Note: Web result 卡片前端 —— 在浏览器渲染 web 渲染意图 + +Status: implemented + +[English](2026-07-30-web-result-card-frontend.md) | 中文 + +## Problem + +`web_search` 和 `web_fetch` 工具声明了 `card: 'web'` result view([web result card](2026-07-30-web-result-card.md)):一个 `kind` 标签联合,携带结构化的被引用 sources 加可选的 provider answer(`kind: 'search'`),或抓取的 URL 及其 HTTP 状态(`kind: 'fetch'`)。该视图早已抵达浏览器 —— host、connection、runtime 将它作为 `resultView` 投递到 `ConversationSnapshot` —— 但 Web 客户端忽略了它:一次已完成的 web 调用只渲染为摊平的模型可见文本,正是契约笔记所解释的、结构化视图要替代的那种有损渲染。`web_search` 到达读者时是每个 source 一行自由文本 markdown,而非可点击 source 的引用列表;`web_fetch` 是它的 markdown 正文,没有检索摘要。 + +## Decision + +`WebBlock` 是一个 `ui-primitives` 组件,渲染一次已完成的 web 检索,web 调用的每个 Web 渲染点都通过它消费 `web` 渲染意图:键控的 chat 工具行(`web_search`/`web_fetch`)、`GenericToolCard` 渲染点兜底,以及详情面板的 Output 区。`ui-conversation/src/client/contract/web-card-model.ts` 是唯一把快照的 `resultView` 转成组件 props 的地方,镜像 `terminal-card-model.ts`,因此没有两个渲染点会对一次 web 调用的显示产生分歧。它返回 null —— 走通用路径 —— 对运行中的调用(web 卡片是 result-only 的,因为工具保留 generic pending 视图)、对 result view 不是 web 卡片的已结算调用(包括本客户端版本不认识的 `card` 值,它经 wire 抵达因而不能被信任为已编译的变体)、以及对 generic result view(web 工具的错误路径返回 generic 卡片,其文本由通用路径保留)。 + +一个组件绘制两种 kind,由 `kind` 判别。`search` 把 answer 作为 markdown 显示在引用列表上方;每个 source 是一个安全外链,以其标题为标签,provider 未给标题时以其主机名为标签,下方是 snippet 与发布日期,工具截断列表时显示 `来源列表已截断` 提示。`fetch` 显示一个紧凑摘要:带链接的最终 URL、其 HTTP 状态、以及 `内容已截断` 提示。用一个组件而非两个,因为两者都是渲染为同一卡片族的 web 检索 —— 这正是契约把它们放在一个 `card` 标签下、用 `kind` 判别的原因。 + +**链接的安全性沿用 MarkdownText 对不受信任的 assistant 链接所用的同一 allowlist。** 一个 source 或 fetch URL 仅当其协议为 `http:` 或 `https:` 时才成为可导航锚点,带 `target="_blank"` 和 `rel="noopener noreferrer"`;`javascript:`/`data:`/`file:` URL 或无法解析的字符串渲染为纯文本、无 href。web 工具返回的 result content 是模型创作的,未经验证抵达本组件,因此像 assistant markdown 一样被当作不受信任处理。标签从标题回退到主机名再回退到原始 URL,因此即便标题缺失且 URL 无法解析,source 也总能读作某个东西。 + +**几何镜像 CodeBlock/TerminalBlock**(12px 圆角、code-block 表面、16px 垂直外边距),使 web 卡片与它们读作一家。长 source 列表在 `maxSources` 处折叠,用 TerminalBlock 完全相同的分割算术做头/尾折叠(`ceil(max/2)` 头部行加剩余尾部),使长正文的切片在两张卡之间一致。source 列表是散文而非按列对齐的输出,所以它正常换行,而不像终端卡片的输出那样横向滚动 —— 这是与 TerminalBlock 唯一刻意的分歧。 + +卡片在 chat 行中**常驻**于摘要行之下,上限 `CHAT_WEB_MAX_SOURCES`(8)—— 原语自身默认 16 的一半,面板保留 16 —— 与 `CHAT_TERMINAL_MAX_LINES` 为终端卡片所画的摘要面对阅读面的同一划分,以及 `BashRow` 所用的同一常驻姿态。键控行把一个 `WebRow` 组件注册在 `web_search` 与 `web_fetch` 两个键下;行仅根据工具名判别以选取其图标(search 对 browse)与标题(`Search`/`Fetch`)。没有自己键控行的 web 声明工具落到 `GenericToolCard`,它长出同一张常驻卡片。详情面板以原语的完整 source 额度渲染卡片。 + +## Consequences + +`WebBlock` 只读 web view 的字段,因此它是渲染意图所携带内容的纯函数 —— 无会话查找,与产出该视图的 presenter 一样回放安全,且不同于终端卡片它不需要 cwd 解析,因为 web view 不携带路径。没有 `web` 能力的 UI(TUI)仍得到契约的回退 `content`;工具的 result 形状没有任何改变。answer 复用 `MarkdownText`,因此 answer 自身的不受信任链接处理与 GFM 渲染免费获得。 + +一条独立的后续 PR 会统一整行折叠/展开交互,并把每张常驻卡片(terminal、diff、web)一次性翻成 expand-gated;本卡片遵循当前的常驻约定,而非抢先做那次改动。 + +## Alternatives considered + +**两个组件,每种 kind 一个。** 拒绝:两种形状共享卡片外框、安全链接处理、截断提示,而契约已经把它们的差异表达为一个 `card` 标签下的 `kind` 判别;两个组件会重复共享表面并拆分安全链接逻辑。 + +**重解析模型可见的渲染文本,而非消费结构化视图。** 因契约笔记给出的同一理由拒绝:`web_search` 的渲染把每个 source 的字段压缩成一行自由文本、以标题或主机名为标签,所以重解析无法恢复 `{url, title?, snippet?, publishedAt?}`。结构化的 `resultView` 是唯一忠实来源,这正是后端 PR 添加它的原因。 + +**不加协议 allowlist 直接渲染裸锚点。** 拒绝:URL 在此接缝处是模型创作、未经验证的,所以未过滤的 href 会让 `javascript:` URL 在点击时执行。该 allowlist 与 MarkdownText 的一致,因此不受信任的链接无论在何处渲染都行为相同。 + +## Testing + +`packages/client/ui-primitives/tests/web-block.spec.tsx` 把组件钉到 per-file 100% 门槛:两种 kind;标题-或-主机名-或-原始 URL 的标签回退;两种 kind 上的安全链接属性(http(s) URL 成为带 `target`/`rel` 的外链,`javascript:`/`file:`/无法解析的 URL 渲染为无 href 的纯 span);snippet 与日期在存在/为空/缺失时的显示或省略;由标志位控制的截断提示;以及 source 列表高度上限及其头/尾切片与展开/收起控件,含默认上限。 + +`packages/client/ui-conversation/tests/web-card.spec.tsx` 在每个接线接缝镜像 `terminal-card.spec.tsx`:`webCardModel` 的派生投影每个 source 字段、其截断与缺失 answer 的支路、fetch 派生、以及每个 null 支路(运行中、null result view、generic result view、未知 card 标签);键控 `WebRow` 对两种 kind 的常驻卡片、比面板收得更紧、其仅摘要行的运行中与失败支路;`GenericToolCard` 兜底为 web 声明工具长出常驻卡片、并为非 web 调用保持纯行;详情面板 Output 区对两种 kind 及其对非 web 结果的摊平回退;以及在 `web_search` 与 `web_fetch` 两键下用一个组件的键控注册。该文件位于覆盖率 `exclude` 列表(`ui-conversation/src/*`),因此覆盖率运行不度量它。 + +fixture(`packages/client/connection/src/client/fixture.ts`)添加 turn 66(`web_search`)与 67(`web_fetch`),内联撰写,因为客户端 fixture 无法 import web 工具:turn 66 的 result view 携带一个 answer 与三个 source,演练引用列表(一个带 snippet 与日期的有标题 source、一个无标题因而以主机名标注链接的 source、一个有日期无 snippet 的 source)并开启截断提示;turn 67 携带抓取的 URL 与一个 200 状态。两者都保留 generic pending call view,仅在 result 时添加 `web` 卡片,匹配契约的 result-only web 形状,且以真实工具命名,使其命中键控 `WebRow`。它们被排在 todo turn(重编号为 68)之前,理由与终端 turn 相同:待定计划在下一个 `turn/start` 退休,所以排在其后的 turn 会清空 dock 的 plan strip。这驱动 built-boot snapshot 与一个实时 `?fixture` 服务。 + +## Related + +- [Web result card](2026-07-30-web-result-card.md) —— 添加 `card: 'web'` result 支路并让两个工具发出它的后端 PR;本条是它推迟的前端消费者。 +- [Web terminal card](2026-07-28-web-terminal-card.md) —— 本条所镜像的先例:一个 `ui-primitives` block、一处 card-model 派生、键控与兜底 chat 行、以及一个详情面板支路,用于 `terminal` 渲染意图。 +- [工具调用呈现的标签化 render-intent union](../architecture/2026-07-02-tool-render-intent-union.md) —— `card` 标签词汇;Web 客户端现在是 `web` 支路的完整消费者。 diff --git a/packages/client/connection/src/client/fixture.ts b/packages/client/connection/src/client/fixture.ts index cb79a6b9a2..0196713372 100644 --- a/packages/client/connection/src/client/fixture.ts +++ b/packages/client/connection/src/client/fixture.ts @@ -136,6 +136,54 @@ const TERMINAL_EXIT_STATUS: Record = { @@ -29,8 +31,9 @@ const VARIANT_ICONS: Record = { export function GenericToolCard({ toolName, block, cwd, openFile }: ToolRowOwnerProps) { const model = toolRowModel(toolName, block, cwd) const terminal = terminalCardModel(block, cwd) + const web = webCardModel(block) const singleFile = model.filePath !== undefined - return ( + const row = ( ) + // A web-declaring tool without its own keyed row lands here; its card is + // resident under the summary, mirroring WebRow (and BashRow's terminal card). + if (web === null) return row + return ( +
+ {row} + +
+ ) } diff --git a/packages/client/ui-conversation/src/client/contract/web-card-model.ts b/packages/client/ui-conversation/src/client/contract/web-card-model.ts new file mode 100644 index 0000000000..28eb3de2d2 --- /dev/null +++ b/packages/client/ui-conversation/src/client/contract/web-card-model.ts @@ -0,0 +1,70 @@ +/** + * Pure derivation of the web-card props from a frozen call slice: the + * `card:'web'` render intent the `web_search`/`web_fetch` tools declare at + * result time arrives on the snapshot as `resultView`, and this is the one + * place that turns it into what {@link WebBlock} draws. Both conversation + * render sites (the chat tool row's resident/expanded body and the details + * panel's Output section) call this, so the sources and fetch summary they + * show are derived once. + * + * The web card is result-only by contract: those tools keep a generic pending + * call view, so there is nothing to derive while the call is still running and + * a running call always takes the generic path. + * @module + */ +import type { WebBlockProps } from '@deepseek-ai/dsh-client-ui-primitives' +import type { ToolCallBlock } from './tool-call-model.ts' + +/** + * Sources the chat row's web body shows before collapsing the middle — half + * the primitive's own default, which the details panel keeps. A chat row is a + * summary surface inside the message flow: the flow must stay scannable across + * many calls, while the details panel is the single-call reading surface. A + * design constant of this UI's row geometry, not a deployment choice, so it is + * fixed here rather than a plugin Config field. + */ +export const CHAT_WEB_MAX_SOURCES = 8 + +/** + * Derive the web-card props for a tool call, or null when this call is not a + * web card and belongs on the generic path. + * + * The result side supplies the whole card: the sources and answer for a + * `search`, the URL and status for a `fetch`. Cases producing null, all of + * them the documented generic-card default: + * + * - A running call (no `resultView` yet): the web tools keep a generic pending + * card, so nothing web-shaped exists until the call settles. + * - A settled call whose result view is not a web card — including a `card` + * value this UI version does not know, which arrives over the wire and so + * cannot be trusted to be one of the compiled variants, and a generic result + * view (a web tool's error path returns the generic card, whose text the + * generic path preserves). + * @param block - RunningToolCall or ToolResultNode off the snapshot caches. + * @returns the web-card props, or null for the generic path. + */ +export function webCardModel(block: ToolCallBlock): WebBlockProps | null { + // Running calls have no result view; the web card is result-only. + if (!('kind' in block)) return null + const result = block.resultView + if (result?.card !== 'web') return null + if (result.kind === 'search') { + return { + kind: 'search', + answer: result.answer, + sources: result.sources.map(source => ({ + url: source.url, + title: source.title, + snippet: source.snippet, + publishedAt: source.publishedAt, + })), + truncated: result.truncated, + } + } + return { + kind: 'fetch', + url: result.url, + statusCode: result.statusCode, + truncated: result.truncated, + } +} diff --git a/packages/client/ui-conversation/src/client/skeleton/DetailsPanel.module.css b/packages/client/ui-conversation/src/client/skeleton/DetailsPanel.module.css index 143174fe42..b4e85912ab 100644 --- a/packages/client/ui-conversation/src/client/skeleton/DetailsPanel.module.css +++ b/packages/client/ui-conversation/src/client/skeleton/DetailsPanel.module.css @@ -106,3 +106,9 @@ .terminal { margin: 0; } + +/* Same rule for the web card: it sits under the section label, so the section + owns the spacing rather than the primitive's own vertical margin. */ +.web { + margin: 0; +} diff --git a/packages/client/ui-conversation/src/client/skeleton/DetailsPanel.tsx b/packages/client/ui-conversation/src/client/skeleton/DetailsPanel.tsx index 9fc5a04ff6..d31717da44 100644 --- a/packages/client/ui-conversation/src/client/skeleton/DetailsPanel.tsx +++ b/packages/client/ui-conversation/src/client/skeleton/DetailsPanel.tsx @@ -7,11 +7,12 @@ // share the store seat exists for) and derives the call material from the // session snapshot — no data of its own. -import { CodeBlock, TerminalBlock } from '@deepseek-ai/dsh-client-ui-primitives' +import { CodeBlock, TerminalBlock, WebBlock } from '@deepseek-ai/dsh-client-ui-primitives' import { shallowEqual } from '@deepseek-ai/dsh-client-runtime/client' import type { ConversationSnapshot, RunningToolCall, ToolResultNode } from '@deepseek-ai/dsh-client-runtime/client' import type { DetailsSlotProps } from '../contract/slots.ts' import { terminalCardModel } from '../contract/terminal-card-model.ts' +import { webCardModel } from '../contract/web-card-model.ts' import type { ToolCallBlock } from '../contract/tool-call-model.ts' import css from './DetailsPanel.module.css' @@ -127,8 +128,10 @@ export function DetailsPanel({ useSession, useSessions, sessionId, useStore, clo * The Output section's body for the selected call. A terminal-card call — a * shell command's call/result views — renders through the shared TerminalBlock * at the primitive's own full height allowance, so column-aligned output keeps - * its alignment and scrolls sideways instead of folding. Every other call, and - * a running call with no terminal card yet, keeps the flattened text form. + * its alignment and scrolls sideways instead of folding. A web-card call — a + * `web_search`/`web_fetch` result — renders through WebBlock at its own full + * source-list allowance. Every other call, and a running call with no card + * yet, keeps the flattened text form. * @param props.material - the selected call's material from {@link materialFor}. * @param props.cwd - the session workspace root, resolving the terminal view's cwd. * @returns the Output section's body element. @@ -147,6 +150,10 @@ function OutputBody({ material, cwd }: { material: CallMaterial; cwd: string | u ) } + const web = webCardModel(material.block) + // Full source-list allowance here (the panel is the single-call reading + // surface); the chat rows cap it at CHAT_WEB_MAX_SOURCES. + if (web !== null) return // A settled call always carries the result node the flattened form needs; // the running shape has no result to flatten. if (!('kind' in material.block)) return
运行中…
diff --git a/packages/client/ui-conversation/src/client/toolviews/web-row.module.css b/packages/client/ui-conversation/src/client/toolviews/web-row.module.css new file mode 100644 index 0000000000..0b1519e218 --- /dev/null +++ b/packages/client/ui-conversation/src/client/toolviews/web-row.module.css @@ -0,0 +1,95 @@ +/* Web toolview: same geometry/tokens as ToolRow (figma icon · summary), plus + the web card the row stacks under its summary line, mirroring the bash row's + resident terminal card. */ + +/* Summary line over the web card; the summary row keeps its own 24px height, + so the card is a column around it rather than a change to it. */ +.card { + display: flex; + flex-direction: column; +} + +/* Row indentation matches ToolRow's expanded bodies (16px leading + 6px gap), + and replaces the primitive's standalone vertical margin with the flow's. */ +.web { + margin: 4px 0 4px 22px; +} + +.root { + position: relative; /* sweep-glare overlay anchor */ + overflow: hidden; + display: flex; + align-items: center; + height: 24px; + min-width: 0; +} + +/* Running sweep glare — same deepsuite ShimmerText pattern as ToolRow. */ +.root[data-state='running']::after { + content: ''; + position: absolute; + top: 0; + bottom: 0; + left: 0; + width: 300px; + background: linear-gradient( + 90deg, + transparent 0%, + color-mix(in srgb, var(--dsw-alias-bg-base) 60%, transparent) 55%, + transparent 100% + ); + animation: dsh-web-row-sweep 2.6s ease-out infinite; + pointer-events: none; +} + +@keyframes dsh-web-row-sweep { + 0% { left: -300px; } + 90%, 100% { left: 100%; } +} + +.leading { + flex: none; + width: 16px; + height: 16px; + display: inline-flex; + align-items: center; + justify-content: center; + margin-right: 6px; + color: var(--dsw-alias-label-tertiary); +} + +.title { + flex: none; + font-size: 14px; + line-height: 24px; + color: var(--dsw-alias-label-secondary); +} + +.sep { + flex: none; + width: 2px; + height: 2px; + border-radius: 1px; + margin: 0 8px; + background: var(--dsw-alias-label-caption); +} + +.summary { + flex: 1 1 auto; + min-width: 0; + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; + font-size: 14px; + line-height: 24px; + color: var(--dsw-alias-label-tertiary); +} + +.visuallyHidden { + position: absolute; + width: 1px; + height: 1px; + overflow: hidden; + clip: rect(0 0 0 0); + white-space: nowrap; +} diff --git a/packages/client/ui-conversation/src/client/toolviews/web-row.tsx b/packages/client/ui-conversation/src/client/toolviews/web-row.tsx new file mode 100644 index 0000000000..29a30776f9 --- /dev/null +++ b/packages/client/ui-conversation/src/client/toolviews/web-row.tsx @@ -0,0 +1,95 @@ +// Web toolview registrant: third-party posture over the keyed toolview hole +// (ctx.slots.register + ToolRowProps only — never imports the chat domain). +// Registered under BOTH web_search and web_fetch, since both declare the one +// `web` render intent and render through the one WebBlock family; the row +// discriminates on the toolName only to pick its icon and title. +// +// A web tool declares the `web` render intent at result time, so this row +// renders the completed retrieval through WebBlock resident below its summary, +// the same posture BashRow uses for the terminal card: no expand control on the +// row itself, not a details-panel target, and the block's own expander keeps a +// long source list from taking over the message flow (CHAT_WEB_MAX_SOURCES is +// passed as maxSources — the chat flow's tighter cap over the block's default +// of 16). Until the call settles there is no web card (the tools keep a generic +// pending view), so a running row is the summary line alone. + +import type { Context } from 'cordis' +import { IconBrowseOutline16, IconSearchOutline16, StateDot, WebBlock } from '@deepseek-ai/dsh-client-ui-primitives' +import type { ToolRowProps } from '../contract/slots.ts' +import { CHAT_WEB_MAX_SOURCES, webCardModel } from '../contract/web-card-model.ts' +import { toolRowModel, type ToolRowState } from '../contract/tool-call-model.ts' +import css from './web-row.module.css' + +/** web_fetch reads one URL; web_search queries. Titles are figma literals. */ +const WEB_TITLES: Record = { + web_search: 'Search', + web_fetch: 'Fetch', +} + +/** Leading icon per tool, yielding to the state semantic while failed/stopped. */ +function leadingFor(toolName: string, state: ToolRowState) { + switch (state) { + case 'error': return + case 'stopped': return + // Running keeps the icon — the row sweep carries the in-flight signal. + default: return toolName === 'web_fetch' ? : + } +} + +/** Visually hidden status — StateDot is aria-hidden; AT needs a text label. */ +function stateStatus(state: ToolRowState): string | null { + switch (state) { + case 'running': return '运行中' + case 'error': return '失败' + case 'stopped': return '已停止' + default: return null + } +} + +/** + * Web row: icon + Search/Fetch · {summary} in the shared ToolRow chrome, with + * the completed retrieval's web card resident below it. The summary row is not + * a details-panel control (tool rows stopped being one), so the card's own + * links and expander are the row's only interactions. + */ +export function WebRow({ toolName, block }: ToolRowProps) { + const model = toolRowModel(toolName, block) + const web = webCardModel(block) + const status = stateStatus(model.state) + return ( +
+
+ {leadingFor(toolName, model.state)} + {status !== null && {status}} + {WEB_TITLES[toolName] ?? model.title} + + {model.summary} +
+ {web !== null && ( + + )} +
+ ) +} + +/** + * The web rows as a plain registrant plugin, riding the same load-order seam as + * the bash sample: `inject: ['conversation']` guarantees the chat entry (and + * with it the 'conversation.chat.toolview' declaration) is on the ledger. One + * WebRow component registers under both web tool names. + */ +export const webToolview = { + name: 'web-toolview', + inject: ['slots', 'conversation'], + /** + * Register the web row under both web tool names' keyed toolview holes. + * @param ctx - registrant context (disposal rides ctx.effect inside slots.register). + */ + apply(ctx: Context): void { + ctx.slots.register({ name: 'conversation.chat.toolview', key: 'web_search' }, WebRow) + ctx.slots.register({ name: 'conversation.chat.toolview', key: 'web_fetch' }, WebRow) + }, +} diff --git a/packages/client/ui-conversation/tests/chat-apply.spec.tsx b/packages/client/ui-conversation/tests/chat-apply.spec.tsx index d7b9125b34..42d1f648a1 100644 --- a/packages/client/ui-conversation/tests/chat-apply.spec.tsx +++ b/packages/client/ui-conversation/tests/chat-apply.spec.tsx @@ -80,12 +80,13 @@ describe('apply wiring', () => { await b.runtime.dispose() }) - it('mounts the bash sample and the todo row as keyed entries through the load-order seam', async () => { + it('mounts the bash sample, the web rows, and the todo row as keyed entries through the load-order seam', async () => { const b = await bench() - // Both registrant plugins' inject: ['slots', 'conversation'] resolved — the - // service being present implies the chat entry declared the hole first. + // Every registrant plugin's inject: ['slots', 'conversation'] resolved — the + // service being present implies the chat entry declared the hole first. The + // web rows register one component under both web tool names. const entries = b.slots.entries('conversation.chat.toolview') - expect(entries.map(e => e.options.key)).toEqual(['bash', 'todo_write']) + expect(entries.map(e => e.options.key)).toEqual(['bash', 'web_search', 'web_fetch', 'todo_write']) // Stats stick with the composer (not inside ChatView). expect(b.slots.entries('conversation.composer.dock').map(e => e.options.id)).toEqual(['stats']) await b.runtime.dispose() diff --git a/packages/client/ui-conversation/tests/web-card.spec.tsx b/packages/client/ui-conversation/tests/web-card.spec.tsx new file mode 100644 index 0000000000..9ed25978f1 --- /dev/null +++ b/packages/client/ui-conversation/tests/web-card.spec.tsx @@ -0,0 +1,255 @@ +// @vitest-environment jsdom +// The web render intent on the web side: the pure webCardModel derivation over +// resultView, and the conversation render sites that consume it — the keyed +// WebRow (registered under both web_search and web_fetch), the GenericToolCard +// render-site fallback, and the details panel's Output section. Mirrors +// terminal-card.spec.tsx: model derivation + null arms, both kinds, the chat +// row's resident card, the panel arm, and the keyed registration. + +import { afterEach, describe, expect, it, vi } from 'vitest' +import { cleanup, render } from '@testing-library/react' +import { createSnapshotStore } from '@deepseek-ai/dsh-client-runtime/client' +import type { + ConversationSnapshot, RunningToolCall, SessionId, SessionListState, ToolResultNode, WorkspaceListState, +} from '@deepseek-ai/dsh-client-runtime/client' +import type { ToolResultView } from '@deepseek-ai/dsh-client-connection/client' +import { bindSnapshotSelector } from '@deepseek-ai/dsh-client-web-react' +import type { SelectionTarget, ToolRowOwnerProps, ToolRowProps } from '@deepseek-ai/dsh-client-ui-conversation/client' +import { CHAT_WEB_MAX_SOURCES, webCardModel } from '../src/client/contract/web-card-model.ts' +import { createChatStore } from '../src/client/stores.ts' +import { GenericToolCard } from '../src/client/chat/GenericToolCard.tsx' +import { DetailsPanel } from '../src/client/skeleton/DetailsPanel.tsx' +import { WebRow, webToolview } from '../src/client/toolviews/web-row.tsx' + +afterEach(cleanup) + +const SID = 's1' as SessionId + +const SEARCH_ARGS = '{"query":"deepseek harness"}' +const FETCH_ARGS = '{"url":"https://example.com/page"}' + +/** A web_search result view; overrides tune the sources / answer / truncation. */ +const resultSearch = (over?: Partial>): ToolResultView => ({ + card: 'web', kind: 'search', truncated: false, + answer: 'A short answer.', + sources: [ + { url: 'https://example.com/a', title: 'Titled', snippet: 'excerpt', publishedAt: '2026-07-01' }, + { url: 'https://plain.example.org/b' }, + ], + ...over, +}) + +/** A web_fetch result view. */ +const resultFetch = (over?: Partial>): ToolResultView => ({ + card: 'web', kind: 'fetch', url: 'https://example.com/page', statusCode: 200, truncated: false, ...over, +}) + +const runningSearch = (over?: Partial): RunningToolCall => ({ + callId: 'c1', name: 'web_search', argsRaw: SEARCH_ARGS, + turn: 1, step: 1, time: 1_000, callView: { card: 'generic', title: 'Search', kind: 'search' }, ...over, +}) + +const settledSearch = (over?: Partial): ToolResultNode => ({ + kind: 'tool-result', seq: 10, time: 2_000, callId: 'c1', + call: { name: 'web_search', argsRaw: SEARCH_ARGS }, + callTime: 1_000, + content: [{ type: 'text', text: 'search text' }], isError: false, + callView: { card: 'generic', title: 'Search', kind: 'search' }, resultView: resultSearch(), ...over, +}) + +const settledFetch = (over?: Partial): ToolResultNode => ({ + kind: 'tool-result', seq: 11, time: 2_000, callId: 'c2', + call: { name: 'web_fetch', argsRaw: FETCH_ARGS }, + callTime: 1_000, + content: [{ type: 'text', text: 'fetch body' }], isError: false, + callView: { card: 'generic', title: 'Fetch', kind: 'fetch' }, resultView: resultFetch(), ...over, +}) + +describe('webCardModel', () => { + it('derives a search card from the result view, projecting every source field', () => { + expect(webCardModel(settledSearch())).toEqual({ + kind: 'search', + answer: 'A short answer.', + truncated: false, + sources: [ + { url: 'https://example.com/a', title: 'Titled', snippet: 'excerpt', publishedAt: '2026-07-01' }, + { url: 'https://plain.example.org/b', title: undefined, snippet: undefined, publishedAt: undefined }, + ], + }) + }) + + it('carries the search truncation flag and an absent answer', () => { + const model = webCardModel(settledSearch({ resultView: { card: 'web', kind: 'search', truncated: true, sources: [] } })) + expect(model).toEqual({ kind: 'search', answer: undefined, truncated: true, sources: [] }) + }) + + it('derives a fetch card from the result view', () => { + expect(webCardModel(settledFetch())).toEqual({ + kind: 'fetch', url: 'https://example.com/page', statusCode: 200, truncated: false, + }) + expect(webCardModel(settledFetch({ resultView: resultFetch({ statusCode: 404, truncated: true }) }))) + .toEqual({ kind: 'fetch', url: 'https://example.com/page', statusCode: 404, truncated: true }) + }) + + it('returns null for a running call, since the web card is result-only', () => { + expect(webCardModel(runningSearch())).toBeNull() + // Even a running call that somehow carried a web call view stays generic: + // the derivation reads resultView only. + expect(webCardModel(runningSearch({ callView: null }))).toBeNull() + }) + + it('returns null for a settled call whose result view is not a web card', () => { + expect(webCardModel(settledSearch({ resultView: null }))).toBeNull() + expect(webCardModel(settledSearch({ resultView: { card: 'generic' } }))).toBeNull() + // A card tag this UI version does not know arrives over the wire; the + // documented generic-card default takes it, not a crash. + const future = { card: 'chart', kind: 'search' } as unknown as ToolResultView + expect(webCardModel(settledSearch({ resultView: future }))).toBeNull() + }) +}) + +describe('chat row web body', () => { + const ownerProps = (block: RunningToolCall | ToolResultNode, toolName: string): ToolRowOwnerProps => ({ + callId: block.callId, toolName, block, openFile: vi.fn(), + }) + // WebRow reads only toolName/block off the full runtime share; the standard + // kit is unused, so the cast supplies the owner slice alone (as BashRow's + // tests do for the terminal card). + const rowProps = (block: RunningToolCall | ToolResultNode, toolName: string): ToolRowProps => + ownerProps(block, toolName) as unknown as ToolRowProps + + it('the WebRow renders the search card resident under the summary, capped tighter than the panel', () => { + expect(CHAT_WEB_MAX_SOURCES).toBeLessThan(16) + const view = render() + // The summary row plus the resident card, without any expand gesture on the row itself. + expect(view.getByText('Search')).toBeTruthy() + expect(view.getByText('Titled')).toBeTruthy() + expect(view.getByText('excerpt')).toBeTruthy() + // hostname fallback for the source with no title + expect(view.getByText('plain.example.org')).toBeTruthy() + }) + + it('the WebRow renders the fetch card resident, titled Fetch', () => { + const view = render() + expect(view.getByText('Fetch')).toBeTruthy() + // The url shows in the summary row and as the card's link; scope to the card. + const card = view.container.querySelector('[data-web="fetch"]') + expect(card?.querySelector('a')?.getAttribute('href')).toBe('https://example.com/page') + expect(view.getByText('HTTP 200')).toBeTruthy() + }) + + it('a running web call is the summary row alone (no card until it settles)', () => { + const view = render() + expect(view.getByText('Search')).toBeTruthy() + expect(view.queryByText('Titled')).toBeNull() + expect(view.container.querySelector('[data-web]')).toBeNull() + }) + + it('a failed web call keeps the summary row without the card', () => { + const view = render() + expect(view.getByText('Search')).toBeTruthy() + expect(view.container.querySelector('[data-web]')).toBeNull() + // The row reflects the error state so the summary line still reads as failed. + expect(view.container.querySelector('[data-state="error"]')).not.toBeNull() + }) + + it('the GenericToolCard fallback also renders a resident web card for a web-declaring tool', () => { + // A web-declaring tool without its own keyed row lands on the fallback; its + // card is resident there too. + const view = render() + expect(view.getByText('Titled')).toBeTruthy() + expect(view.container.querySelector('[data-web="search"]')).not.toBeNull() + }) + + it('the GenericToolCard fallback keeps the plain row for a non-web call', () => { + const view = render() + expect(view.container.querySelector('[data-web]')).toBeNull() + }) +}) + +describe('DetailsPanel web Output section', () => { + function mount(snapshot: ConversationSnapshot, selection: SelectionTarget | null) { + localStorage.clear() + const chat = createChatStore().create() + if (selection !== null) chat.actions.select(selection) + const sessions = createSnapshotStore({ ids: [], byId: {}, current: undefined, phase: 'ready' }) + const workspaces = createSnapshotStore({ + items: [], state: 'idle', phase: 'ready', error: null, + baselinesReady: true, recentWorkspaceId: undefined, + }) + return render( + snapshot, subscribe: () => () => {} })} + useSessions={bindSnapshotSelector(sessions)} + useWorkspaces={bindSnapshotSelector(workspaces)} + useInput={(() => { throw new Error('unused') })} + inputActions={{ setDraft: () => {}, submit: () => {} }} + useProjection={(() => undefined)} + useStore={bindSnapshotSelector(chat)} + actions={chat.actions} + closeDetails={vi.fn()} + />, + ) + } + + function snapshot(over: Partial = {}): ConversationSnapshot { + return { + sessionId: SID, nodes: [], foldDegraded: false, partial: null, runningCalls: [], codeDispatches: new Map(), + pending: [], queue: [], running: false, composerPhase: 'active', removed: false, + openState: 'open', openError: null, hasMore: false, loadingOlder: false, + promptError: null, blank: false, lastAgentError: null, ...over, + } + } + + it('renders the search card at full source allowance', () => { + const view = mount(snapshot({ nodes: [settledSearch()] }), { turnSeq: 10, callId: 'c1', toolName: 'web_search' }) + expect(view.getByText('Titled')).toBeTruthy() + expect(view.getByText('excerpt')).toBeTruthy() + // The Input JSON section survives beside it. + expect(view.getByText(/"query"/)).toBeTruthy() + }) + + it('renders the fetch card', () => { + const view = mount(snapshot({ nodes: [settledFetch()] }), { turnSeq: 11, callId: 'c2', toolName: 'web_fetch' }) + const card = view.container.querySelector('[data-web="fetch"]') + expect(card?.querySelector('a')?.getAttribute('href')).toBe('https://example.com/page') + expect(view.getByText('HTTP 200')).toBeTruthy() + }) + + it('a non-web result keeps the flattened pre form', () => { + const view = mount(snapshot({ + nodes: [settledSearch({ callView: null, resultView: null })], + }), { turnSeq: 10, callId: 'c1', toolName: 'web_search' }) + expect(view.container.querySelector('[data-web]')).toBeNull() + const output = view.getByText('Output').closest('section') + expect(output?.querySelector('pre')?.textContent).toContain('search text') + }) +}) + +describe('web toolview registration', () => { + it('registers one WebRow under both web_search and web_fetch', () => { + const registered: { key: string; component: unknown }[] = [] + const ctx = { + slots: { + register: (options: { name: string; key: string }, component: unknown) => { + registered.push({ key: options.key, component }) + return () => {} + }, + }, + } as unknown as import('cordis').Context + webToolview.apply(ctx) + expect(registered.map(r => r.key)).toEqual(['web_search', 'web_fetch']) + // One component under both keys, not two thin rows. + expect(registered[0]?.component).toBe(WebRow) + expect(registered[1]?.component).toBe(WebRow) + // The load-order seam the render site depends on. + expect(webToolview.inject).toEqual(['slots', 'conversation']) + }) +}) diff --git a/packages/client/ui-primitives/src/WebBlock.module.css b/packages/client/ui-primitives/src/WebBlock.module.css new file mode 100644 index 0000000000..d595acb3cc --- /dev/null +++ b/packages/client/ui-primitives/src/WebBlock.module.css @@ -0,0 +1,124 @@ +/* Geometry mirrors CodeBlock/TerminalBlock (12px radius, code-block surface, + 16px vertical margin) so a web card, a terminal card, and a fenced code block + read as one family. A source list is prose, not aligned output, so it wraps + normally rather than scrolling horizontally like a terminal card's output. */ + +.block { + --dsl-web-radius: 12px; + + margin: 16px 0; + padding: 12px 14px; + color: var(--dsw-alias-label-primary); + background: var(--dsw-alias-markdown-code-block); + border-radius: var(--dsl-web-radius); +} + +/* The provider answer reads as body prose above the citation list; its own + MarkdownText margins are trimmed so the list sits tight under it. */ +.answer { + margin-bottom: 8px; +} + +.answer > :global(div) > :first-child { + margin-top: 0; +} + +.answer > :global(div) > :last-child { + margin-bottom: 0; +} + +/* The citation list: ordered so each source reads as a numbered reference. */ +.sources { + margin: 0; + padding-left: 20px; + display: flex; + flex-direction: column; + gap: 10px; +} + +.source { + min-width: 0; +} + +.sourceLink { + color: var(--dsw-alias-state-business-primary); + font-size: 14px; + line-height: 20px; + word-break: break-word; +} + +.sourceLink:hover { + text-decoration: underline; +} + +.snippet { + margin-top: 2px; + color: var(--dsw-alias-label-secondary); + font-size: 13px; + line-height: 19px; + word-break: break-word; +} + +.published { + margin-top: 2px; + color: var(--dsw-alias-label-tertiary); + font: var(--dsw-font-xs-13); +} + +.expand { + display: block; + width: 100%; + padding: 0; + border: none; + background-color: transparent; + color: var(--dsw-alias-label-tertiary); + cursor: pointer; + font: inherit; + text-align: left; +} + +.expand:hover { + color: var(--dsw-alias-label-secondary); +} + +.truncated { + margin-top: 8px; + color: var(--dsw-alias-label-tertiary); + font: var(--dsw-font-xs-13); +} + +/* The fetch card is a compact summary: the URL over a status/truncation row. */ +.fetch { + display: flex; + flex-direction: column; + gap: 6px; +} + +.fetchUrl { + color: var(--dsw-alias-state-business-primary); + font-family: var(--ds-font-family-code); + font-size: 13px; + line-height: 19px; + word-break: break-all; +} + +.fetchUrl:hover { + text-decoration: underline; +} + +.fetchMeta { + display: flex; + align-items: baseline; + gap: 12px; +} + +.status { + color: var(--dsw-alias-label-secondary); + font: var(--dsw-font-xs-13); +} + +/* The fetch card's truncation note sits inline beside the status, so it drops + the search card's top margin. */ +.fetch .truncated { + margin-top: 0; +} diff --git a/packages/client/ui-primitives/src/WebBlock.tsx b/packages/client/ui-primitives/src/WebBlock.tsx new file mode 100644 index 0000000000..d4757858a3 --- /dev/null +++ b/packages/client/ui-primitives/src/WebBlock.tsx @@ -0,0 +1,209 @@ +// WebBlock: the surface for a completed web retrieval. One component draws both +// kinds of the `web` render intent, discriminated by `kind`: a `search` shows an +// optional provider answer above a citation list of sources (each a safe +// external link labelled by its title, or its hostname when the provider gave +// none, with the snippet and publication date below it), and a `fetch` shows a +// compact retrieval summary (the linked final URL and its HTTP status). Both +// mark a capped retrieval. Every link is a same-origin-safe external anchor: +// only http(s) URLs become anchors (target/rel set), the same protocol allowlist +// MarkdownText applies to untrusted assistant-authored links; an unparseable or +// non-http URL renders as plain text. Geometry, radius, and fonts mirror +// CodeBlock/TerminalBlock so a web card reads as one family with them; a long +// source list caps at maxSources with a head/tail collapse using the same +// arithmetic as TerminalBlock's output cap. + +import { useCallback, useState } from 'react' +import clsx from 'clsx' +import { MarkdownText } from './markdown/MarkdownText.tsx' +import css from './WebBlock.module.css' + +/** + * Sources shown before the height cap collapses the middle of a citation list. + * Matches TerminalBlock's default output budget so both cards cut a long body + * at the same place; the chat row narrows it through the maxSources prop. + */ +export const DEFAULT_WEB_MAX_SOURCES = 16 + +/** + * One citeable source drawn in a search card: the projection of the contract's + * `WebSource`, with the optional fields kept optional so a provider that + * returned only a URL still renders (its hostname becomes the label). + */ +export interface WebSourceView { + /** The source URL; becomes a safe external link when it is http(s). */ + url: string + /** The source title; when absent the URL's hostname labels the link. */ + title?: string | undefined + /** A short excerpt or summary shown under the link. */ + snippet?: string | undefined + /** Publication/crawl timestamp, a provider-supplied string shown under the link. */ + publishedAt?: string | undefined +} + +/** A `web_search` card: an optional answer over a capped citation list. */ +export interface WebSearchBlockProps { + kind: 'search' + /** The provider-generated answer, rendered as markdown above the sources. */ + answer?: string | undefined + /** The cited sources, in provider order. */ + sources: WebSourceView[] + /** True when the tool cut the source list to its result cap. */ + truncated: boolean + /** Sources shown before the middle collapses (default {@link DEFAULT_WEB_MAX_SOURCES}). */ + maxSources?: number | undefined + /** Extra class merged onto the wrapper (callers position; this component draws). */ + className?: string | undefined +} + +/** A `web_fetch` card: the retrieval summary for one fetched URL. */ +export interface WebFetchBlockProps { + kind: 'fetch' + /** The final URL after allowed redirects; becomes a safe external link when http(s). */ + url: string + /** HTTP status code of the fetched response. */ + statusCode: number + /** True when the provider or the output cap cut the fetched content. */ + truncated: boolean + /** Extra class merged onto the wrapper (callers position; this component draws). */ + className?: string | undefined +} + +/** A completed web retrieval card, discriminated by `kind`. */ +export type WebBlockProps = WebSearchBlockProps | WebFetchBlockProps + +/** + * The URL to link to, or undefined when the URL must render as plain text. The + * allowlist is MarkdownText's own for untrusted links: only http(s) becomes a + * navigable external anchor, so a `javascript:`/`data:`/`file:` URL or an + * unparseable string never reaches the DOM as an href. + * @param url - the source or fetch URL, from tool result content. + * @returns the href to use, or undefined for plain text. + */ +function safeHref(url: string): string | undefined { + try { + const { protocol } = new URL(url) + return protocol === 'http:' || protocol === 'https:' ? url : undefined + } catch { + return undefined + } +} + +/** + * The link's visible label: the title when the provider gave one, otherwise the + * URL's hostname, falling back to the raw URL when it does not parse. + * @param url - the source URL. + * @param title - the provider title, if any. + * @returns the label text. + */ +function linkLabel(url: string, title: string | undefined): string { + if (title !== undefined && title !== '') return title + try { + return new URL(url).hostname + } catch { + return url + } +} + +/** + * A single URL rendered as a safe external anchor, or as plain text when the + * URL is not an http(s) link. + * @param props.url - the URL to render. + * @param props.label - the visible label. + * @param props.className - class for the anchor or the plain span. + * @returns the anchor or span element. + */ +function SafeLink({ url, label, className }: { url: string; label: string; className?: string | undefined }) { + const href = safeHref(url) + if (href === undefined) return {label} + return ( + + {label} + + ) +} + +/** + * One source row in a search card: the safe link plus its snippet and date. + * @param props.source - the source to render. + * @returns the source list item. + */ +function SourceItem({ source }: { source: WebSourceView }) { + return ( +
  • + + {source.snippet !== undefined && source.snippet !== '' && ( +
    {source.snippet}
    + )} + {source.publishedAt !== undefined && source.publishedAt !== '' && ( +
    {source.publishedAt}
    + )} +
  • + ) +} + +/** + * The search card body: the answer over the capped source list. + * @param props - see {@link WebSearchBlockProps}. + * @returns the search card element. + */ +function WebSearchBlock({ answer, sources, truncated, maxSources = DEFAULT_WEB_MAX_SOURCES, className }: WebSearchBlockProps) { + const [expanded, setExpanded] = useState(false) + const onToggle = useCallback(() => { setExpanded(value => !value) }, []) + const hidden = sources.length - maxSources + const capped = hidden > 0 && !expanded + // Same split arithmetic as TerminalBlock's output cap, so a long body's head + // and tail slices agree between the two cards. + const headCount = Math.ceil(maxSources / 2) + const tailCount = maxSources - headCount + const head = capped ? sources.slice(0, headCount) : sources + const tail = capped ? sources.slice(sources.length - tailCount) : [] + return ( +
    + {answer !== undefined && answer !== '' && ( +
    + )} +
      + {head.map((source, index) => )} + {hidden > 0 && ( + + )} + {tail.map((source, index) => )} +
    + {truncated &&
    来源列表已截断
    } +
    + ) +} + +/** + * The fetch card body: the linked URL and its HTTP status. + * @param props - see {@link WebFetchBlockProps}. + * @returns the fetch card element. + */ +function WebFetchBlock({ url, statusCode, truncated, className }: WebFetchBlockProps) { + return ( +
    + +
    + HTTP {statusCode} + {truncated && 内容已截断} +
    +
    + ) +} + +/** + * Render a completed web retrieval as a structured card. + * @param props - see {@link WebBlockProps}; `kind` selects the search or fetch body. + * @returns the web card element. + */ +export function WebBlock(props: WebBlockProps) { + return props.kind === 'search' ? : +} diff --git a/packages/client/ui-primitives/src/index.ts b/packages/client/ui-primitives/src/index.ts index aa674f7a1a..148199142e 100644 --- a/packages/client/ui-primitives/src/index.ts +++ b/packages/client/ui-primitives/src/index.ts @@ -22,6 +22,8 @@ export { JsonTree } from './JsonTree.tsx' export type { JsonTreeProps } from './JsonTree.tsx' export { TerminalBlock, DEFAULT_TERMINAL_MAX_LINES } from './TerminalBlock.tsx' export type { TerminalBlockProps } from './TerminalBlock.tsx' +export { WebBlock, DEFAULT_WEB_MAX_SOURCES } from './WebBlock.tsx' +export type { WebBlockProps, WebSearchBlockProps, WebFetchBlockProps, WebSourceView } from './WebBlock.tsx' export { CodeBlock } from './markdown/CodeBlock.tsx' export { JsonBlock } from './markdown/JsonBlock.tsx' export { MarkdownText } from './markdown/MarkdownText.tsx' diff --git a/packages/client/ui-primitives/tests/web-block.spec.tsx b/packages/client/ui-primitives/tests/web-block.spec.tsx new file mode 100644 index 0000000000..0c39e8b13d --- /dev/null +++ b/packages/client/ui-primitives/tests/web-block.spec.tsx @@ -0,0 +1,165 @@ +// @vitest-environment jsdom +// WebBlock: both kinds of the web card. The search card's answer, its citation +// list with the title-or-hostname label fallback and optional snippet/date, the +// source-list height cap and its expand control, and the truncated indicator; +// the fetch card's linked URL, status, and truncation. Safe-link attributes on +// both kinds: an http(s) URL becomes an external anchor (target/rel), any other +// URL renders as plain text with no href. + +import { afterEach, describe, expect, it } from 'vitest' +import { cleanup, fireEvent, render } from '@testing-library/react' +import { DEFAULT_WEB_MAX_SOURCES, WebBlock } from '../src/index.ts' +import type { WebSourceView } from '../src/index.ts' + +afterEach(cleanup) + +/** `count` sources with sequential hostnames, so the cap slices read distinctly. */ +function sources(count: number): WebSourceView[] { + return Array.from({ length: count }, (_value, index) => ({ + url: `https://site-${index}.example.com/page`, + title: `Source ${index}`, + })) +} + +describe('WebBlock search card', () => { + it('renders the answer above the citation list', () => { + const view = render() + expect(view.getByText('Answer')).toBeTruthy() + expect(view.getByText('Source 0')).toBeTruthy() + expect(view.getByText('Source 1')).toBeTruthy() + }) + + it('omits the answer block when there is no answer', () => { + const view = render() + expect(view.container.querySelector('[class^="_answer_"]')).toBeNull() + const empty = render() + expect(empty.container.querySelector('[class^="_answer_"]')).toBeNull() + }) + + it('labels a source by its title, and by hostname when the title is absent', () => { + const view = render() + expect(view.getByText('Titled')).toBeTruthy() + // No title / empty title: the hostname labels the link. + expect(view.getByText('plain.example.org')).toBeTruthy() + expect(view.getByText('empty.example.net')).toBeTruthy() + }) + + it('renders a source as a safe external anchor for an http(s) url', () => { + const view = render() + const anchor = view.getByText('Titled') as HTMLAnchorElement + expect(anchor.tagName).toBe('A') + expect(anchor.getAttribute('href')).toBe('https://example.com/a') + expect(anchor.getAttribute('target')).toBe('_blank') + expect(anchor.getAttribute('rel')).toBe('noopener noreferrer') + }) + + it('renders a non-http url as plain text with no href, and its raw text label when unparseable', () => { + const view = render() + const unsafe = view.getByText('Dangerous') + expect(unsafe.tagName).toBe('SPAN') + expect(unsafe.getAttribute('href')).toBeNull() + // An unparseable url is not a link and cannot yield a hostname, so its raw + // text is the label. + const raw = view.getByText('not a url') + expect(raw.tagName).toBe('SPAN') + }) + + it('shows a source snippet and publication date when present, and omits them when absent or empty', () => { + const view = render() + expect(view.getByText('excerpt')).toBeTruthy() + expect(view.getByText('2026-07-01')).toBeTruthy() + // The empty-string and absent arms both draw nothing beyond the link. + expect(view.container.querySelectorAll('[class^="_snippet_"]')).toHaveLength(1) + expect(view.container.querySelectorAll('[class^="_published_"]')).toHaveLength(1) + }) + + it('shows the truncated indicator only when the list was capped by the tool', () => { + const on = render() + expect(on.getByText('来源列表已截断')).toBeTruthy() + cleanup() + const off = render() + expect(off.queryByText('来源列表已截断')).toBeNull() + }) + + it('renders every source and no expand control under the cap', () => { + const view = render() + expect(view.container.querySelectorAll('[class^="_source_"]')).toHaveLength(4) + expect(view.container.querySelector('[aria-expanded]')).toBeNull() + }) + + it('slices head and tail over the cap and expands on click', () => { + const view = render() + // maxSources 4: head = ceil(4/2) = 2, tail = 4 - 2 = 2, 6 hidden. + expect([...view.container.querySelectorAll('[class^="_sourceLink_"]')].map(n => n.textContent)) + .toEqual(['Source 0', 'Source 1', 'Source 8', 'Source 9']) + const toggle = view.getByRole('button', { name: '展开其余 6 条来源' }) + expect(toggle.getAttribute('aria-expanded')).toBe('false') + expect(toggle.textContent).toBe('… 其余 6 条来源') + + fireEvent.click(toggle) + expect(view.container.querySelectorAll('[class^="_source_"]')).toHaveLength(10) + const collapse = view.getByRole('button', { name: '收起来源' }) + expect(collapse.getAttribute('aria-expanded')).toBe('true') + expect(collapse.textContent).toBe('收起') + + fireEvent.click(collapse) + expect(view.container.querySelectorAll('[class^="_source_"]')).toHaveLength(4) + }) + + it('renders the head slice alone when the cap leaves no tail', () => { + const view = render() + expect([...view.container.querySelectorAll('[class^="_sourceLink_"]')].map(n => n.textContent)).toEqual(['Source 0']) + expect(view.getByRole('button', { name: '展开其余 4 条来源' })).toBeTruthy() + }) + + it('caps at the documented default when maxSources is absent', () => { + const view = render() + expect(view.container.querySelectorAll('[class^="_source_"]')).toHaveLength(DEFAULT_WEB_MAX_SOURCES) + expect(view.getByRole('button', { name: '展开其余 1 条来源' })).toBeTruthy() + }) +}) + +describe('WebBlock fetch card', () => { + it('renders the fetched url as a safe external anchor and its HTTP status', () => { + const view = render() + const anchor = view.getByText('https://example.com/page') as HTMLAnchorElement + expect(anchor.tagName).toBe('A') + expect(anchor.getAttribute('href')).toBe('https://example.com/page') + expect(anchor.getAttribute('target')).toBe('_blank') + expect(anchor.getAttribute('rel')).toBe('noopener noreferrer') + expect(view.getByText('HTTP 200')).toBeTruthy() + }) + + it('renders a non-http fetch url as plain text with no href', () => { + const view = render() + const label = view.getByText('file:///etc/passwd') + expect(label.tagName).toBe('SPAN') + expect(label.getAttribute('href')).toBeNull() + }) + + it('shows the truncated indicator only when the content was cut', () => { + const on = render() + expect(on.getByText('内容已截断')).toBeTruthy() + cleanup() + const off = render() + expect(off.queryByText('内容已截断')).toBeNull() + }) + + it('carries a non-200 status verbatim', () => { + const view = render() + expect(view.getByText('HTTP 404')).toBeTruthy() + }) +}) From c38f3fd52313b60b5e88447f15300dfb18088da1 Mon Sep 17 00:00:00 2001 From: Chinesezjc Date: Thu, 30 Jul 2026 17:50:40 +0800 Subject: [PATCH 029/139] docs: regenerate config/cordis/event catalogs for the read card tag The re-exports for ReadResultView shift line numbers in packages/core/tools; regenerate the generated catalogs the static gate checks. --- docs/config-catalog.md | 2 +- docs/cordis-catalog/events.md | 12 ++++++------ docs/cordis-catalog/services.md | 2 +- docs/event-producer-consumer.md | 12 ++++++------ packages/cordis/tool-cordis/src/api-catalog.ts | 10 +++++++++- 5 files changed, 23 insertions(+), 15 deletions(-) diff --git a/docs/config-catalog.md b/docs/config-catalog.md index 191d96b255..89dce3b6a4 100644 --- a/docs/config-catalog.md +++ b/docs/config-catalog.md @@ -1890,7 +1890,7 @@ export interface Config { export type ToolPresentationMode = 'native' | 'code' | 'both' ``` -Source: [`packages/core/tools/src/index.ts:578`](../packages/core/tools/src/index.ts) +Source: [`packages/core/tools/src/index.ts:580`](../packages/core/tools/src/index.ts) ## `@deepseek-ai/dsh-tui` diff --git a/docs/cordis-catalog/events.md b/docs/cordis-catalog/events.md index dafa342d5a..f39311d1a8 100644 --- a/docs/cordis-catalog/events.md +++ b/docs/cordis-catalog/events.md @@ -841,7 +841,7 @@ A tool was registered or unregistered, or a scoped restriction changed (the avai 'tools/change'(): void ``` -Source: [`packages/core/tools/src/index.ts:156`](../../packages/core/tools/src/index.ts) +Source: [`packages/core/tools/src/index.ts:158`](../../packages/core/tools/src/index.ts) ### `tools/code-dispatch-log` — waterfall @@ -865,7 +865,7 @@ Shape the DURABLE LOG COPY of one `run_code` sub-dispatch outcome before the bri Types: [CodeDispatchLog](../core-data-structures/tools.md) · [ContentBlock](../core-data-structures/core.md) · [Scoped](../core-data-structures/scope.md) · [ToolRegistry](../core-data-structures/tools.md) -Source: [`packages/core/tools/src/index.ts:138`](../../packages/core/tools/src/index.ts) +Source: [`packages/core/tools/src/index.ts:140`](../../packages/core/tools/src/index.ts) ### `tools/execute` — waterfall @@ -887,7 +887,7 @@ Around-dispatch waterfall for timeout, retry, or metrics. `next()` returns a nor Types: [Scoped](../core-data-structures/scope.md) · [ToolDispatchExecution](../core-data-structures/tools.md) · [ToolExecutionResult](../core-data-structures/tools.md) · [ToolRegistry](../core-data-structures/tools.md) -Source: [`packages/core/tools/src/index.ts:113`](../../packages/core/tools/src/index.ts) +Source: [`packages/core/tools/src/index.ts:115`](../../packages/core/tools/src/index.ts) ### `tools/post-execute` — waterfall @@ -910,7 +910,7 @@ Accept, replace, enrich, or block a normalized dispatch result. `next()` accepts Types: [PostToolDecision](../core-data-structures/tools.md) · [Scoped](../core-data-structures/scope.md) · [ToolExecution](../core-data-structures/tools.md) · [ToolExecutionResult](../core-data-structures/tools.md) · [ToolRegistry](../core-data-structures/tools.md) -Source: [`packages/core/tools/src/index.ts:125`](../../packages/core/tools/src/index.ts) +Source: [`packages/core/tools/src/index.ts:127`](../../packages/core/tools/src/index.ts) ### `tools/pre-execute` — waterfall @@ -931,7 +931,7 @@ Allow, deny, or ask before dispatch. `next()` delegates to allow; missing approv Types: [PreToolDecision](../core-data-structures/tools.md) · [Scoped](../core-data-structures/scope.md) · [ToolExecution](../core-data-structures/tools.md) · [ToolRegistry](../core-data-structures/tools.md) -Source: [`packages/core/tools/src/index.ts:102`](../../packages/core/tools/src/index.ts) +Source: [`packages/core/tools/src/index.ts:104`](../../packages/core/tools/src/index.ts) ### `tools/result` — emit @@ -950,7 +950,7 @@ Observe the frozen, lossless-JSON final outcome. Listener failures are contained Types: [Scoped](../core-data-structures/scope.md) · [ToolExecution](../core-data-structures/tools.md) · [ToolExecutionResult](../core-data-structures/tools.md) · [ToolRegistry](../core-data-structures/tools.md) -Source: [`packages/core/tools/src/index.ts:146`](../../packages/core/tools/src/index.ts) +Source: [`packages/core/tools/src/index.ts:148`](../../packages/core/tools/src/index.ts) ## `workflow/*` diff --git a/docs/cordis-catalog/services.md b/docs/cordis-catalog/services.md index c655de3a70..8fa0a1c1c6 100644 --- a/docs/cordis-catalog/services.md +++ b/docs/cordis-catalog/services.md @@ -2174,7 +2174,7 @@ async execute(exec: ToolExecutionInput): Promise Types: [ScopeKey](../core-data-structures/scope.md) · [ToolDefinition](../core-data-structures/tools.md) · [ToolExecutionInput](../core-data-structures/tools.md) · [ToolExecutionMode](../core-data-structures/tools.md) · [ToolExecutionResult](../core-data-structures/tools.md) · [ToolGuard](../core-data-structures/tools.md) · [ToolRestriction](../core-data-structures/tools.md) · [ToolSchema](../core-data-structures/tools.md) -Source: [`packages/core/tools/src/index.ts:700`](../../packages/core/tools/src/index.ts) +Source: [`packages/core/tools/src/index.ts:702`](../../packages/core/tools/src/index.ts) ## `ctx.tui` — `TuiExtensionService` (abstract seam) diff --git a/docs/event-producer-consumer.md b/docs/event-producer-consumer.md index b9538b89d5..447be9b83d 100644 --- a/docs/event-producer-consumer.md +++ b/docs/event-producer-consumer.md @@ -44,12 +44,12 @@ This matrix shows which packages dispatch each harness-owned event and which pac | `system-prompt/assemble` | `waterfall` | [`packages/core/system-prompt/src/index.ts:29`](../packages/core/system-prompt/src/index.ts) | [`system-prompt`](../packages/core/system-prompt) (`waterfall`) | [`agent`](../packages/core/agent), [`system-prompt`](../packages/core/system-prompt) | | `system-prompt/change` | `emit` | [`packages/core/system-prompt/src/index.ts:35`](../packages/core/system-prompt/src/index.ts) | [`system-prompt`](../packages/core/system-prompt) (`emit`) | - | | `telemetry/record` | `waterfall` | [`packages/telemetry/session-telemetry/src/index.ts:41`](../packages/telemetry/session-telemetry/src/index.ts) | [`session-telemetry`](../packages/telemetry/session-telemetry) (`waterfall`) | - | -| `tools/change` | `emit` | [`packages/core/tools/src/index.ts:156`](../packages/core/tools/src/index.ts) | [`tools`](../packages/core/tools) (`emit`) | - | -| `tools/code-dispatch-log` | `waterfall` | [`packages/core/tools/src/index.ts:138`](../packages/core/tools/src/index.ts) | [`tools`](../packages/core/tools) (`waterfall`) | [`spill-policy`](../packages/spill/spill-policy) | -| `tools/execute` | `waterfall` | [`packages/core/tools/src/index.ts:113`](../packages/core/tools/src/index.ts) | [`tools`](../packages/core/tools) (`waterfall`) | [`session-checkpoint-policy`](../packages/session-persistence/session-checkpoint-policy), [`timeout-policy`](../packages/timeout/timeout-policy) | -| `tools/post-execute` | `waterfall` | [`packages/core/tools/src/index.ts:125`](../packages/core/tools/src/index.ts) | [`tools`](../packages/core/tools) (`waterfall`) | [`hooks-claude`](../packages/hooks/hooks-claude), [`hooks-codex`](../packages/hooks/hooks-codex), [`repeat-tool-guard`](../packages/guard/repeat-tool-guard), [`spill-policy`](../packages/spill/spill-policy), [`tool-fs-search`](../packages/fs/tool-fs-search), [`workspace-context`](../packages/context/workspace-context) | -| `tools/pre-execute` | `waterfall` | [`packages/core/tools/src/index.ts:102`](../packages/core/tools/src/index.ts) | [`tools`](../packages/core/tools) (`waterfall`) | [`hooks-claude`](../packages/hooks/hooks-claude), [`hooks-codex`](../packages/hooks/hooks-codex), [`tool-tasks`](../packages/tasks/tool-tasks) | -| `tools/result` | `emit` | [`packages/core/tools/src/index.ts:146`](../packages/core/tools/src/index.ts) | [`tools`](../packages/core/tools) (`events.dispatch`) | [`subagent-inprocess`](../packages/subagent/subagent-inprocess), [`workspace-context`](../packages/context/workspace-context) | +| `tools/change` | `emit` | [`packages/core/tools/src/index.ts:158`](../packages/core/tools/src/index.ts) | [`tools`](../packages/core/tools) (`emit`) | - | +| `tools/code-dispatch-log` | `waterfall` | [`packages/core/tools/src/index.ts:140`](../packages/core/tools/src/index.ts) | [`tools`](../packages/core/tools) (`waterfall`) | [`spill-policy`](../packages/spill/spill-policy) | +| `tools/execute` | `waterfall` | [`packages/core/tools/src/index.ts:115`](../packages/core/tools/src/index.ts) | [`tools`](../packages/core/tools) (`waterfall`) | [`session-checkpoint-policy`](../packages/session-persistence/session-checkpoint-policy), [`timeout-policy`](../packages/timeout/timeout-policy) | +| `tools/post-execute` | `waterfall` | [`packages/core/tools/src/index.ts:127`](../packages/core/tools/src/index.ts) | [`tools`](../packages/core/tools) (`waterfall`) | [`hooks-claude`](../packages/hooks/hooks-claude), [`hooks-codex`](../packages/hooks/hooks-codex), [`repeat-tool-guard`](../packages/guard/repeat-tool-guard), [`spill-policy`](../packages/spill/spill-policy), [`tool-fs-search`](../packages/fs/tool-fs-search), [`workspace-context`](../packages/context/workspace-context) | +| `tools/pre-execute` | `waterfall` | [`packages/core/tools/src/index.ts:104`](../packages/core/tools/src/index.ts) | [`tools`](../packages/core/tools) (`waterfall`) | [`hooks-claude`](../packages/hooks/hooks-claude), [`hooks-codex`](../packages/hooks/hooks-codex), [`tool-tasks`](../packages/tasks/tool-tasks) | +| `tools/result` | `emit` | [`packages/core/tools/src/index.ts:148`](../packages/core/tools/src/index.ts) | [`tools`](../packages/core/tools) (`events.dispatch`) | [`subagent-inprocess`](../packages/subagent/subagent-inprocess), [`workspace-context`](../packages/context/workspace-context) | | `workflow/agent-end` | `emit` | [`packages/workflow/workflow/src/index.ts:81`](../packages/workflow/workflow/src/index.ts) | [`workflow`](../packages/workflow/workflow) (`events.dispatch`) | [`workflow`](../packages/workflow/workflow) | | `workflow/agent-start` | `emit` | [`packages/workflow/workflow/src/index.ts:70`](../packages/workflow/workflow/src/index.ts) | [`workflow`](../packages/workflow/workflow) (`events.dispatch`) | [`workflow`](../packages/workflow/workflow) | | `workflow/end` | `emit` | [`packages/workflow/workflow/src/index.ts:91`](../packages/workflow/workflow/src/index.ts) | [`workflow`](../packages/workflow/workflow) (`events.dispatch`) | [`workflow`](../packages/workflow/workflow) | diff --git a/packages/cordis/tool-cordis/src/api-catalog.ts b/packages/cordis/tool-cordis/src/api-catalog.ts index 60f7d330d8..7e41ce96ab 100644 --- a/packages/cordis/tool-cordis/src/api-catalog.ts +++ b/packages/cordis/tool-cordis/src/api-catalog.ts @@ -2095,6 +2095,14 @@ export const TYPE_API: readonly TypeApiEntry[] = [ name: 'PtyWaitReason', declaration: 'export type PtyWaitReason = \'stdin_read\' | \'inferred_idle\' | \'timeout\' | \'session_exit\';', }, + { + name: 'ReadFileLine', + declaration: 'export interface ReadFileLine {\n number: number;\n text: string;\n}', + }, + { + name: 'ReadResultView', + declaration: 'export interface ReadResultView {\n card: \'read\';\n title?: string;\n path: string;\n lines: ReadFileLine[];\n totalLines: number;\n lang?: string;\n content?: ContentBlock[];\n}', + }, { name: 'ReasoningBlock', declaration: 'export interface ReasoningBlock {\n type: \'reasoning\';\n text: string;\n}', @@ -2697,7 +2705,7 @@ export const TYPE_API: readonly TypeApiEntry[] = [ }, { name: 'ToolResultView', - declaration: 'export type ToolResultView = GenericResultView | TerminalResultView | DiffResultView;', + declaration: 'export type ToolResultView = GenericResultView | TerminalResultView | DiffResultView | ReadResultView;', }, { name: 'ToolRunContext', From 8c5c4b46c83562611eb4bf3fe9adf60fdc35c81b Mon Sep 17 00:00:00 2001 From: Chinesezjc Date: Thu, 30 Jul 2026 18:32:55 +0800 Subject: [PATCH 030/139] =?UTF-8?q?fix(web):=20address=20diff=20card=20rev?= =?UTF-8?q?iew=20=E2=80=94=20split=20terminator,=20error=20arm,=20wire=20n?= =?UTF-8?q?arrowing?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - DiffBlock: an empty side contributes zero lines and a trailing newline is a terminator, so a create ending in a newline draws one added line (not a phantom empty one) and a full deletion draws no phantom + line. - diffCardModel: narrow the wire diffs payload (card is the only validated field) so a malformed diff card falls back to the generic path instead of throwing inside DiffBlock. - FileMutationRow: surface the result text when an errored mutation has no diff card, so a failed edit/write is more than a red dot. - copyText ends its closed union on assertNever. - Docs: drop the "bridge relativizes" claim, record the file-count divergence from the TUI footer, correct the built-boot overclaim, note why the row title outranks the view title, and make fixture turn 67 args self-consistent. - Tests: terminator/empty-side/interior-blank rows, wire-narrowing null arms, the error-text arm and its name/code fallback, stopped state, no-path summary, and the registration/disposal shape. --- .../2026-07-30-web-diff-card.i18n.yaml | 4 +- .../feature/2026-07-30-web-diff-card.md | 6 +- .../feature/2026-07-30-web-diff-card.zh.md | 6 +- .../client/connection/src/client/fixture.ts | 2 +- .../src/client/contract/diff-card-model.ts | 40 ++++++++- .../toolviews/file-mutation-row.module.css | 11 +++ .../client/toolviews/file-mutation-row.tsx | 25 ++++++ .../ui-conversation/tests/diff-card.spec.tsx | 90 ++++++++++++++++++- .../client/ui-primitives/src/DiffBlock.tsx | 36 ++++++-- .../ui-primitives/tests/diff-block.spec.tsx | 20 +++++ 10 files changed, 221 insertions(+), 19 deletions(-) diff --git a/.agents/notes/implemented/feature/2026-07-30-web-diff-card.i18n.yaml b/.agents/notes/implemented/feature/2026-07-30-web-diff-card.i18n.yaml index 18f2d5178b..7ed620736c 100644 --- a/.agents/notes/implemented/feature/2026-07-30-web-diff-card.i18n.yaml +++ b/.agents/notes/implemented/feature/2026-07-30-web-diff-card.i18n.yaml @@ -2,5 +2,5 @@ # side as of the last confirmed-consistent state. Both languages carry equal authority; # after editing either side, bring the other along and re-record with: # pnpm run verify-translation-pairing --write .agents/notes/implemented/feature/2026-07-30-web-diff-card.md -2026-07-30-web-diff-card.md: 5e43d5d29f7f4000efebc166724ec9d921d2b441 -2026-07-30-web-diff-card.zh.md: aac577cfa8dd9e0bf5f17a729d049d207a64d374 +2026-07-30-web-diff-card.md: 8087ce698e65f78c7c6f51211ef00e3b0ab58ed9 +2026-07-30-web-diff-card.zh.md: d85ac1f2e13c7fb3732b327b40122076337ac538 diff --git a/.agents/notes/implemented/feature/2026-07-30-web-diff-card.md b/.agents/notes/implemented/feature/2026-07-30-web-diff-card.md index 5e43d5d29f..8087ce698e 100644 --- a/.agents/notes/implemented/feature/2026-07-30-web-diff-card.md +++ b/.agents/notes/implemented/feature/2026-07-30-web-diff-card.md @@ -16,9 +16,9 @@ This is the [terminal card](2026-07-28-web-terminal-card.md) done for the `diff` `DiffBlock` is a `ui-primitives` component that renders a file mutation as an inline diff surface, and both Web render sites for a write/edit call consume the diff render intent through it: the chat tool row's body and the details panel's Output section. `ui-conversation/src/client/contract/diff-card-model.ts` is the single place that turns the snapshot's `callView`/`resultView` pair into the component's props, so the two sites cannot disagree about a change. It returns null — the generic path — whenever neither side declares `card: 'diff'`, including a `card` value this client version does not know, and whenever a settled call's result view is generic, which is how write/edit keep their execution errors on the generic path. The result side is authoritative once the call settles: the applied hunks replace the call-time diff derived from the arguments alone. A paging window that drops the call head still renders, because the result view carries the whole change. -The component's contract mirrors the TUI's `diffLines` (`packages/ui/tui/src/components/transcript.ts`) so a diff reads the same across front ends: +The component's contract follows the TUI's `diffLines` (`packages/ui/tui/src/components/transcript.ts`) so a diff reads the same shape across front ends, with one deliberate divergence noted below (the file count): -- **One path header per file.** A new file opens a bold path header; a same-file second hunk (a scattered edit, or a `replace_all`) opens with a `⋯` gap instead of repeating the path. The `N file(s)` footer counts distinct paths. +- **One path header per file.** A new file opens a bold path header; a same-file second hunk (a scattered edit, or a `replace_all`) opens with a `⋯` gap instead of repeating the path. The `N file(s)` footer counts DISTINCT paths — the divergence from the TUI, whose footer uses `diffs.length` and so reads two hunks in one file as `2 files` where this reads `1 file`. - **The change in the diff's own colors.** A removed line is `- ` on the error token, an added line is `+ ` on the success token, drawn verbatim with `white-space: pre` inside a horizontally scrolling box — a source line is read by its indentation, so it scrolls rather than folds. A create (`oldText: null`) has no removed side. - **Height cap with an expand control.** A diff longer than `DEFAULT_DIFF_MAX_LINES` (16) shows `ceil(max/2)` head rows plus the remaining tail rows, with a button between reporting the hidden count. The split arithmetic matches `TerminalBlock` and the TUI's collapsed card, so a long diff's head and tail slices agree across front ends. - **Footer and copy.** A dim `└ +A -R · N file(s)` footer summarizes the change; `+A -R` are the added/removed line counts, the same per-side counts the TUI footer draws. The copy control copies the prefixed diff text (path headers, `- `/`+ ` lines, the `⋯` gap), so a multi-file copy stays attributable. @@ -47,7 +47,7 @@ The multi-file arm of `DiffBlock` (one card, several path headers) has no produc `packages/client/ui-conversation/tests/diff-card.spec.tsx` pins the wiring at every render site: `diffCardModel`'s derivation and each of its null arms, the result hunks replacing the call-time diff, a window-truncated call still rendering from the result, the chat row's diff body, `FileMutationRow`'s resident card and its path link opening cwd-resolved through the host, its registration under both `write` and `edit`, and the panel's Output section. -The fixture (`packages/client/connection/src/client/fixture.ts`) carries three diff turns so the built-boot snapshot pins all three arms at both render sites: a single-hunk edit (turn 62, keyed `FileMutationRow`), a create/write (turn 63), and a multi-hunk edit (turn 67, the `⋯` gap between two scattered hunks in one file). +The fixture (`packages/client/connection/src/client/fixture.ts`) carries three diff turns so a `?fixture` server and the per-package wiring suite exercise all three arms at both render sites: a single-hunk edit (turn 62, keyed `FileMutationRow`), a create/write (turn 63), and a multi-hunk edit (turn 67, the `⋯` gap between two scattered hunks in one file). The built-boot snapshot (`apps/web/tests/built-boot.snapshot.ts`) is a boot-assembly smoke that asserts only that the graph mounts and reaches chat content (`data-sample="bash-global"`); by its own contract it carries no diff-behavior assertions, which the wiring suite owns. ## Related diff --git a/.agents/notes/implemented/feature/2026-07-30-web-diff-card.zh.md b/.agents/notes/implemented/feature/2026-07-30-web-diff-card.zh.md index aac577cfa8..d85ac1f2e1 100644 --- a/.agents/notes/implemented/feature/2026-07-30-web-diff-card.zh.md +++ b/.agents/notes/implemented/feature/2026-07-30-web-diff-card.zh.md @@ -16,9 +16,9 @@ Web 客户端忽略了它。write/edit 调用落到 `GenericToolCard`,其行 `DiffBlock` 是一个 `ui-primitives` 组件,把文件改动渲染为内联 diff 表面,write/edit 调用的两个 Web 渲染点都通过它消费 diff 渲染意图:chat 工具行的行体和详情面板的 Output 区。`ui-conversation/src/client/contract/diff-card-model.ts` 是唯一把快照的 `callView`/`resultView` 对转成组件 props 的地方,因此两个渲染点不会对一次改动产生分歧。当两侧都未声明 `card: 'diff'` 时它返回 null —— 走通用路径 —— 包括本客户端版本不认识的 `card` 值,以及已结算调用的 result view 是 generic 的情况(write/edit 的执行错误正是这样留在通用路径上的)。调用结算后 result 侧是权威:已应用的 hunk 替换仅从参数推导的 call 时 diff。分页窗口丢弃了 call 头也仍能渲染,因为 result view 携带完整改动。 -组件的契约镜像 TUI 的 `diffLines`(`packages/ui/tui/src/components/transcript.ts`),使 diff 在两个前端读起来一致: +组件的契约遵循 TUI 的 `diffLines`(`packages/ui/tui/src/components/transcript.ts`),使 diff 在两个前端读起来是同一形态,仅文件计数一处刻意分歧(见下): -- **每个文件一个路径头。** 新文件开启一个粗体路径头;同文件的第二个 hunk(分散编辑,或 `replace_all`)以一个 `⋯` gap 开启,而非重复路径。`N file(s)` 页脚统计去重后的路径数。 +- **每个文件一个路径头。** 新文件开启一个粗体路径头;同文件的第二个 hunk(分散编辑,或 `replace_all`)以一个 `⋯` gap 开启,而非重复路径。`N file(s)` 页脚统计**去重后的路径数** —— 这是与 TUI 的分歧:TUI 页脚用 `diffs.length`,同文件两个 hunk 在那里读作 `2 files`,此处读作 `1 file`。 - **改动用 diff 自身的颜色。** 删除行是 error token 上的 `- `,新增行是 success token 上的 `+ `,在横向滚动的盒子里以 `white-space: pre` 逐字绘制 —— 源码行靠缩进阅读,所以滚动而不折行。新建(`oldText: null`)没有删除侧。 - **高度上限带展开控件。** 长于 `DEFAULT_DIFF_MAX_LINES`(16)的 diff 显示 `ceil(max/2)` 个头部行加剩余尾部行,中间一个按钮报告隐藏行数。分割算术与 `TerminalBlock` 和 TUI 的折叠卡片一致,因此长 diff 的头尾切片在两个前端一致。 - **页脚与复制。** 暗色 `└ +A -R · N file(s)` 页脚概括改动;`+A -R` 是新增/删除行数,与 TUI 页脚绘制的每侧计数相同。复制控件复制带前缀的 diff 文本(路径头、`- `/`+ ` 行、`⋯` gap),使多文件复制保持可归属。 @@ -47,7 +47,7 @@ chat 行把 diff 常驻渲染在路径链接摘要之下,上限 `CHAT_DIFF_MAX `packages/client/ui-conversation/tests/diff-card.spec.tsx` 钉住每个渲染点的接线:`diffCardModel` 的派生及其每个 null 支路、result hunk 替换 call 时 diff、窗口截断的 call 仍从 result 渲染、chat 行的 diff 体、`FileMutationRow` 的常驻卡片及其路径链接经 host 以 cwd 解析打开、其在 `write` 与 `edit` 下的注册、以及面板的 Output 区。 -fixture(`packages/client/connection/src/client/fixture.ts`)携带三个 diff turn,使 built-boot snapshot 在两个渲染点钉住全部三个支路:单 hunk 编辑(turn 62,keyed `FileMutationRow`)、新建/写入(turn 63)、多 hunk 编辑(turn 67,一个文件内两处分散 hunk 之间的 `⋯` gap)。 +fixture(`packages/client/connection/src/client/fixture.ts`)携带三个 diff turn,使 `?fixture` 服务与 per-package 接线测试套件在两个渲染点演练全部三个支路:单 hunk 编辑(turn 62,keyed `FileMutationRow`)、新建/写入(turn 63)、多 hunk 编辑(turn 67,一个文件内两处分散 hunk 之间的 `⋯` gap)。built-boot snapshot(`apps/web/tests/built-boot.snapshot.ts`)是启动装配 smoke,只断言图挂载并抵达 chat 内容(`data-sample="bash-global"`);按其自身契约它不带 diff 行为断言,那由接线套件负责。 ## Related diff --git a/packages/client/connection/src/client/fixture.ts b/packages/client/connection/src/client/fixture.ts index 4fddf6e9c0..4082d469e8 100644 --- a/packages/client/connection/src/client/fixture.ts +++ b/packages/client/connection/src/client/fixture.ts @@ -238,7 +238,7 @@ function buildAlphaLog(): SessionEvent[] { // the presenter reads to emit the two-hunk sample: the card draws one path // header, the first hunk, a `⋯` gap, then the second (the same-file // second-hunk arm turns 62/63 cannot reach). - toolTurn(67, 'edit', '{"file_path":"src/config.ts","old_string":"multi","new_string":"multi"}', '已编辑') + toolTurn(67, 'edit', '{"file_path":"src/config.ts","old_string":"const timeout = 30","new_string":"const timeout = 60"}', '已编辑') // Turn 64: one run_code turn with three logged sub-dispatches — the Code // Mode acceptance surface (parent code row + nested native-identical rows, // including an isError sub-call and a bash sub-call that must hit the same diff --git a/packages/client/ui-conversation/src/client/contract/diff-card-model.ts b/packages/client/ui-conversation/src/client/contract/diff-card-model.ts index f02ccd5930..bc914e4820 100644 --- a/packages/client/ui-conversation/src/client/contract/diff-card-model.ts +++ b/packages/client/ui-conversation/src/client/contract/diff-card-model.ts @@ -7,7 +7,7 @@ * call this, so the hunks they show are derived once. * @module */ -import type { DiffBlockProps } from '@deepseek-ai/dsh-client-ui-primitives' +import type { DiffBlockProps, DiffHunk } from '@deepseek-ai/dsh-client-ui-primitives' import type { ToolCallBlock } from './tool-call-model.ts' /** @@ -35,6 +35,30 @@ export interface DiffCardModel { card: Pick } +/** + * Narrow a wire `card:'diff'` view's `diffs` to well-formed hunks. The event + * view crosses the wire and `toolEventViewSchema` validates only the `card` + * string, so a version mismatch or an anomalous plugin can deliver a `diff` card + * whose `diffs` is absent, not an array, or carries malformed hunks. Returning + * null for any of those routes the block to the generic path instead of letting + * DiffBlock's `for...of`/`split` throw and crash the row or the details panel. + * @param diffs - the view's `diffs` field, unverified. + * @returns the validated hunks, or null when the payload is not usable. + */ +function narrowDiffs(diffs: unknown): DiffHunk[] | null { + if (!Array.isArray(diffs) || diffs.length === 0) return null + const out: DiffHunk[] = [] + for (const hunk of diffs) { + if (typeof hunk !== 'object' || hunk === null) return null + const { path, oldText, newText } = hunk as Record + if (typeof path !== 'string') return null + if (oldText !== null && typeof oldText !== 'string') return null + if (typeof newText !== 'string') return null + out.push({ path, oldText, newText }) + } + return out +} + /** * Derive the diff-card props for a tool call, or null when this call is not a * diff card and belongs on the generic path. @@ -49,6 +73,14 @@ export interface DiffCardModel { * be trusted to be one of the compiled variants — and a settled call whose * result view is generic (how write/edit keep their execution errors on the * generic path). + * + * This derivation consumes only `diffs`; the render intent's `title` field is + * deliberately dropped. The row supplies its own title (`Edit`/`Write · path` + * from the args) and that outranks the view's `title`, matching the TUI diff + * branch, which likewise draws no view title. A tool that names its own diff + * header therefore does not surface that text on the Web row — an accepted + * product choice, recorded here as the one asymmetry with the terminal card, + * whose derivation does consume the view's title. * @param block - RunningToolCall or ToolResultNode off the snapshot caches. * @returns the diff-card props, or null for the generic path. */ @@ -56,11 +88,13 @@ export function diffCardModel(block: ToolCallBlock): DiffCardModel | null { if (!('kind' in block)) { // Running: the call view may carry the intended diff; the result is absent. const call = block.callView?.card === 'diff' ? block.callView : null - return call === null ? null : { card: { diffs: call.diffs } } + const diffs = call === null ? null : narrowDiffs(call.diffs) + return diffs === null ? null : { card: { diffs } } } // Settled: the result view's applied hunks replace the call-time diff. A // window that dropped the call head leaves only the result, which still // renders — the result view carries the whole change. const result = block.resultView?.card === 'diff' ? block.resultView : null - return result === null ? null : { card: { diffs: result.diffs } } + const diffs = result === null ? null : narrowDiffs(result.diffs) + return diffs === null ? null : { card: { diffs } } } diff --git a/packages/client/ui-conversation/src/client/toolviews/file-mutation-row.module.css b/packages/client/ui-conversation/src/client/toolviews/file-mutation-row.module.css index b87103aa3a..3ecf480adf 100644 --- a/packages/client/ui-conversation/src/client/toolviews/file-mutation-row.module.css +++ b/packages/client/ui-conversation/src/client/toolviews/file-mutation-row.module.css @@ -117,3 +117,14 @@ clip: rect(0 0 0 0); white-space: nowrap; } + +/* The result text for an errored mutation, indented to the card's own column + (the diff card's inset) and in the error tone, since it stands in for the diff + card the failure path does not produce. */ +.failure { + margin: 4px 0 4px 22px; + white-space: pre-wrap; + overflow-wrap: anywhere; + font: var(--dsw-font-xs-13); + color: var(--dsw-alias-state-error-primary); +} diff --git a/packages/client/ui-conversation/src/client/toolviews/file-mutation-row.tsx b/packages/client/ui-conversation/src/client/toolviews/file-mutation-row.tsx index 0862eb4fd5..e777c78932 100644 --- a/packages/client/ui-conversation/src/client/toolviews/file-mutation-row.tsx +++ b/packages/client/ui-conversation/src/client/toolviews/file-mutation-row.tsx @@ -39,6 +39,27 @@ function stateStatus(state: ToolRowState): string | null { } } +/** + * A settled result's text, flattened from its content blocks, for the arm that + * shows a failure the diff card cannot: write/edit return `undefined` from + * `presentResult` on `result.isError`, so an errored mutation has no diff card, + * and the keyed row is not a details-panel target. Without this the failure — + * an `old_string` that did not match, a permission denial — would read as a bare + * red dot with the model-facing error text nowhere on screen. + * @param block - the frozen call slice. + * @returns the result text, or null for a running call or an empty result. + */ +function errorText(block: ToolRowProps['block']): string | null { + if (!('kind' in block)) return null + const parts: string[] = [] + for (const item of block.content) { + if (item.type === 'text') parts.push(item.text) + } + if (parts.length === 0 && block.error !== undefined) parts.push(`${block.error.name}: ${block.error.code}`) + const text = parts.join('\n') + return text === '' ? null : text +} + /** * File-mutation row: icon + {Edit,Write} · {path} in the shared ToolRow chrome, * with the applied diff resident below it. The summary is a path link (a file @@ -50,6 +71,9 @@ export function FileMutationRow({ toolName, block, cwd, openFile }: ToolRowProps const diff = diffCardModel(block) const status = stateStatus(model.state) const filePath = model.filePath + // An errored mutation has no diff card (presentResult returns undefined on + // isError); surface its result text so the failure is more than a red dot. + const failure = diff === null && model.state === 'error' ? errorText(block) : null return (
    @@ -72,6 +96,7 @@ export function FileMutationRow({ toolName, block, cwd, openFile }: ToolRowProps {diff !== null && ( )} + {failure !== null &&
    {failure}
    }
    ) } diff --git a/packages/client/ui-conversation/tests/diff-card.spec.tsx b/packages/client/ui-conversation/tests/diff-card.spec.tsx index 77b762c38b..031216b9f7 100644 --- a/packages/client/ui-conversation/tests/diff-card.spec.tsx +++ b/packages/client/ui-conversation/tests/diff-card.spec.tsx @@ -17,7 +17,7 @@ import { CHAT_DIFF_MAX_LINES, diffCardModel } from '../src/client/contract/diff- import { createChatStore } from '../src/client/stores.ts' import { GenericToolCard } from '../src/client/chat/GenericToolCard.tsx' import { DetailsPanel } from '../src/client/skeleton/DetailsPanel.tsx' -import { FileMutationRow } from '../src/client/toolviews/file-mutation-row.tsx' +import { FileMutationRow, fileMutationToolview } from '../src/client/toolviews/file-mutation-row.tsx' afterEach(cleanup) @@ -86,6 +86,22 @@ describe('diffCardModel', () => { callView: future, resultView: { card: 'chart' } as unknown as ToolResultView, }))).toBeNull() }) + + it('falls back to null for a malformed diff payload off the wire', () => { + // toolEventViewSchema validates only the `card` string, so a version + // mismatch can deliver a diff card with an unusable diffs field. Each shape + // routes to the generic path instead of throwing inside DiffBlock. + const bad = (diffs: unknown): ToolResultView => ({ card: 'diff', diffs } as unknown as ToolResultView) + expect(diffCardModel(settled({ resultView: bad(undefined) }))).toBeNull() + expect(diffCardModel(settled({ resultView: bad([]) }))).toBeNull() + expect(diffCardModel(settled({ resultView: bad('nope') }))).toBeNull() + expect(diffCardModel(settled({ resultView: bad([null]) }))).toBeNull() + expect(diffCardModel(settled({ resultView: bad([{ path: 1, oldText: null, newText: 'x' }]) }))).toBeNull() + expect(diffCardModel(settled({ resultView: bad([{ path: 'a', oldText: 5, newText: 'x' }]) }))).toBeNull() + expect(diffCardModel(settled({ resultView: bad([{ path: 'a', oldText: null, newText: 9 }]) }))).toBeNull() + // The running side narrows identically. + expect(diffCardModel(running({ callView: { card: 'diff', diffs: 'nope' } as unknown as ToolCallView }))).toBeNull() + }) }) describe('chat row diff body', () => { @@ -176,6 +192,78 @@ describe('FileMutationRow diff card', () => { const view = render() expect(view.container.querySelector('[data-diff]')).toBeNull() }) + + it('surfaces the result text when an errored mutation has no diff card', () => { + // write/edit return undefined from presentResult on isError, so the failure + // has no diff — the row shows the model-facing error text instead of a bare + // red dot. + const view = render() + expect(view.container.querySelector('[data-diff]')).toBeNull() + expect(view.getByText('old_string not found in notes/demo.txt')).toBeTruthy() + }) + + it('falls back to the error name/code when an errored result has no text block', () => { + const view = render() + expect(view.getByText('ToolError: sandbox_denied')).toBeTruthy() + }) + + it('shows no failure text for a successful diff or a running call', () => { + const ok = render() + expect(ok.container.querySelector('[class*="_failure_"]')).toBeNull() + cleanup() + const run = render() + expect(run.container.querySelector('[class*="_failure_"]')).toBeNull() + }) + + it('shows the stopped state when the call was interrupted', () => { + const view = render() + expect(view.container.querySelector('[data-state="stopped"]')).not.toBeNull() + // The visually-hidden status label carries the stopped semantic for AT. + expect(view.getByText('已停止')).toBeTruthy() + }) + + it('renders a plain summary span when the call carries no file path', () => { + // Empty args leave deriveFilePath undefined, so the summary is not a link. + const view = render() + expect(view.container.querySelector('[class*="_fileLink_"]')).toBeNull() + expect(view.container.querySelector('[class*="_summary_"]')).not.toBeNull() + }) +}) + +describe('fileMutationToolview registration', () => { + it('registers one component under both edit and write, and each disposes', () => { + const registered: { key: string; disposed: boolean }[] = [] + const disposers: (() => void)[] = [] + const ctx = { + slots: { + register: ({ key }: { name: string; key: string }) => { + const entry = { key, disposed: false } + registered.push(entry) + const dispose = () => { entry.disposed = true } + disposers.push(dispose) + return dispose + }, + }, + } + fileMutationToolview.apply(ctx as never) + expect(registered.map(r => r.key).sort()).toEqual(['edit', 'write']) + // The registrant's inject seam is the load-order contract the row relies on. + expect(fileMutationToolview.inject).toEqual(['slots', 'conversation']) + // Disposal removes each contribution (packages/AGENTS.md registry contract). + for (const dispose of disposers) dispose() + expect(registered.every(r => r.disposed)).toBe(true) + }) }) describe('DetailsPanel diff Output section', () => { diff --git a/packages/client/ui-primitives/src/DiffBlock.tsx b/packages/client/ui-primitives/src/DiffBlock.tsx index ab1700b7b5..12c389c72b 100644 --- a/packages/client/ui-primitives/src/DiffBlock.tsx +++ b/packages/client/ui-primitives/src/DiffBlock.tsx @@ -26,7 +26,7 @@ export const DEFAULT_DIFF_MAX_LINES = 16 * free of the tool contract (the terminal card's decoupling, applied to diffs). */ export interface DiffHunk { - /** The changed file's path (as the tool operated on it; the bridge relativizes it). */ + /** The changed file's path, drawn verbatim as the hunk's header (the tool's model-facing path). */ path: string /** Prior content, or `null` for a new file / an overwrite (nothing on the removed side). */ oldText: string | null @@ -49,6 +49,12 @@ interface DiffRow { text: string } +/** Local exhaustiveness helper — this package does not depend on `dsh-llm`. */ +/* v8 ignore next 3 -- closed-union backstop; only reached if a row kind is forged */ +function assertNever(value: never): never { + throw new Error(`unreachable diff row kind: ${String(value)}`) +} + /** The dim class per row kind (path/gap chrome vs the diff's own +/- colors). */ const ROW_CLASS: Record = { path: css.path, @@ -61,8 +67,10 @@ const ROW_CLASS: Record = { * Flatten the hunks into the body's rows plus the footer counts. A path header * opens each new file; a same-file second hunk (a scattered edit) opens with a * `⋯` gap instead of repeating the path. Every old-side line counts toward - * `removed` and every new-side line toward `added`, the same per-side line count - * the TUI footer draws, so the two front ends agree on a change's size. + * `removed` and every new-side line toward `added`. The file count is of + * DISTINCT paths, which is the one deliberate divergence from the TUI diff card: + * the TUI footer uses `diffs.length`, so two hunks in one file read there as + * `2 files`, whereas this counts the one file they belong to. * @param diffs - the hunks to render. * @returns the body rows, the +/- totals, and the distinct-file count. */ @@ -78,12 +86,12 @@ function buildRows(diffs: DiffHunk[]): { rows: DiffRow[]; added: number; removed else rows.push({ kind: 'gap', text: '⋯' }) prevPath = diff.path if (diff.oldText !== null) { - for (const line of diff.oldText.split('\n')) { + for (const line of contentLines(diff.oldText)) { rows.push({ kind: 'del', text: line }) removed++ } } - for (const line of diff.newText.split('\n')) { + for (const line of contentLines(diff.newText)) { rows.push({ kind: 'add', text: line }) added++ } @@ -91,6 +99,21 @@ function buildRows(diffs: DiffHunk[]): { rows: DiffRow[]; added: number; removed return { rows, added, removed, files: paths.size } } +/** + * Split a side's text into its content lines. Empty text is zero lines (a full + * deletion's `newText` or a create's absent `oldText` side draws nothing), and a + * single trailing newline is a line terminator rather than an extra empty line — + * the same terminator rule TerminalBlock applies to command output. An interior + * blank line (a genuine `\n\n`) survives. + * @param text - the removed or added side's text. + * @returns the content lines, without the terminating newline. + */ +function contentLines(text: string): string[] { + if (text === '') return [] + const body = text.endsWith('\n') ? text.slice(0, -1) : text + return body.split('\n') +} + /** * The diff text a reader copies: each row's `-`/`+`/path/gap prefix and its * content, exactly what the card shows. The removed and added blocks are the @@ -103,8 +126,9 @@ function copyText(rows: DiffRow[]): string { switch (row.kind) { case 'del': return `- ${row.text}` case 'add': return `+ ${row.text}` + case 'path': return row.text case 'gap': return row.text - default: return row.text + default: return assertNever(row.kind) } }).join('\n') } diff --git a/packages/client/ui-primitives/tests/diff-block.spec.tsx b/packages/client/ui-primitives/tests/diff-block.spec.tsx index d732a13315..bb4a2fdac3 100644 --- a/packages/client/ui-primitives/tests/diff-block.spec.tsx +++ b/packages/client/ui-primitives/tests/diff-block.spec.tsx @@ -76,6 +76,26 @@ describe('DiffBlock structure', () => { const { container } = render() expect(container.firstChild).toBeNull() }) + + it('treats a trailing newline as a terminator, not an extra blank line', () => { + // A create whose newText ends in a newline is one added line, not two, and + // the footer counts one — the phantom `+ ` empty line the naive split drew. + const { container } = render() + expect(changeRows(container)).toEqual(['hello']) + expect(screen.getByText('└ +1 -0 · 1 file')).toBeTruthy() + }) + + it('renders a full deletion as removed-only with no phantom added line', () => { + // newText '' is zero added lines: an empty string must contribute nothing. + const { container } = render() + expect(container.querySelectorAll('[class*="_add_"]').length).toBe(0) + expect(screen.getByText('└ +0 -2 · 1 file')).toBeTruthy() + }) + + it('keeps a genuine interior blank line', () => { + const { container } = render() + expect(container.querySelectorAll('[class*="_add_"]').length).toBe(3) + }) }) describe('DiffBlock footer', () => { From 35bd2de2a9840d1de3401496c95af8a75e51a065 Mon Sep 17 00:00:00 2001 From: Chinesezjc Date: Thu, 30 Jul 2026 18:45:30 +0800 Subject: [PATCH 031/139] test(snapshot): re-record ACP/TUI goldens for the read card meta The read tool now projects presentationMeta ({path, lines, totalLines}) onto its tool/result, so every scenario with a read call carries that meta; the cordis-inspect snapshot's embedded type surface gains ReadResultView / ReadFileLine / the widened ToolResultView. Model-facing text is unchanged. Refreshed keyless via test:snapshot:refresh. The unrelated goal.snapshot SQLite ExperimentalWarning failure is pre-existing on clean master. --- .../tests/snapshots/cordis-inspect-jsdoc/session.jsonl | 2 +- examples/acp-agent/tests/snapshots/fs-edit/session.jsonl | 2 +- .../tests/snapshots/fs-policy-reject/session.jsonl | 2 +- .../acp-agent/tests/snapshots/fs-read-window/session.jsonl | 2 +- examples/acp-agent/tests/snapshots/fs-read/session.jsonl | 2 +- .../tests/snapshots/fs-write-overwrite/session.jsonl | 2 +- .../tests/snapshots/parallel-tool-calls/session.jsonl | 4 ++-- .../tests/snapshots/workspace-context/session.jsonl | 4 ++-- .../acp-agent/tests/snapshots/workspace-edit/session.jsonl | 2 +- .../snapshots/parallel-file-reads/terminal.expected.txt | 6 ------ 10 files changed, 11 insertions(+), 17 deletions(-) diff --git a/examples/acp-agent/tests/snapshots/cordis-inspect-jsdoc/session.jsonl b/examples/acp-agent/tests/snapshots/cordis-inspect-jsdoc/session.jsonl index ea8dad9a96..619bc50d81 100644 --- a/examples/acp-agent/tests/snapshots/cordis-inspect-jsdoc/session.jsonl +++ b/examples/acp-agent/tests/snapshots/cordis-inspect-jsdoc/session.jsonl @@ -11,7 +11,7 @@ {"type":"assistant/chunk","seq":9,"time":1783951000009,"data":{"turn":1,"step":1,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}} {"type":"assistant/message","seq":10,"time":1784449176722,"data":{"turn":1,"step":1,"message":{"role":"assistant","content":[{"type":"tool-call","id":"inspect-tools-api","name":"cordis_inspect","arguments":"{\"what\":\"api\",\"name\":\"tools\"}"}],"source":{"kind":"model","provider":"deepseek","model":"deepseek-v4-flash"},"id":"1ac37046-d1c0-4ef6-9ea9-963e4b46d1cf"},"usage":{"inputTokens":3,"outputTokens":3}},"sourceEventSeqs":[5,6,7,8,9],"surfaceOp":"append"} {"type":"tool/call","seq":11,"time":1784449176722,"data":{"turn":1,"step":1,"callId":"inspect-tools-api","name":"cordis_inspect","arguments":"{\"what\":\"api\",\"name\":\"tools\"}"}} -{"type":"tool/result","seq":12,"time":1784449176732,"data":{"turn":1,"step":1,"message":{"source":{"kind":"tool","callId":"inspect-tools-api"},"content":[{"type":"tool-result","toolCallId":"inspect-tools-api","content":[{"type":"text","text":"## api\n- tools — Tool registry and execution pipeline.\n /**\n * Register globally or in the calling agent scope. Scoped tools shadow\n * globals; duplicates within one layer and the reserved `run_code` name fail.\n * @param definition - tool schema, execution, and optional finalization/presentation callbacks.\n * @returns the exact disposer that unregisters the tool.\n */\n register(definition: ToolDefinition): () => void\n /**\n * Restrict global tools for the calling agent scope. Empty filters, unknown\n * names, scope-local names, and reserved transport names fail. Restrictions\n * intersect; scoped registrations remain visible.\n * @param filter - global-surface mask: `allow` (keep only) and/or `deny` (remove).\n * @returns the exact disposer that lifts this restriction.\n */\n restrict(filter: ToolRestriction): () => void\n /**\n * Register a monotonic guard after the extensible `tools/pre-execute`\n * waterfall. A plain-context guard applies globally; one registered through\n * `agent.ctx` applies only to that agent. Any matching guard may deny by\n * returning a reason, while no guard can force-allow a call another guard\n * denied. The exact effect disposer is returned for ordered ownership and\n * HMR cleanup.\n * @param guard - synchronous check; a returned string denies the execution.\n * @returns the exact disposer that unregisters the guard.\n */\n guard(guard: ToolGuard): () => void\n /**\n * Look up a tool as one scope sees it (scoped\n * shadows global; a restricted-away global reads as absent). Presenters pass\n * the calling agent so the rendered card matches the definition that\n * actually executed.\n * @param name - the tool name as registered.\n * @param scope - the viewing scope (the agent); omitted = the global view.\n * @returns the definition the scope resolves, or undefined when none is visible.\n */\n get(name: string, scope?: ScopeKey): ToolDefinition | undefined\n /**\n * Project visible definitions onto the allowlisted model-facing schema fields,\n * excluding execution and presentation callbacks.\n * @param scope - the viewing scope (the agent); omitted = the global view.\n * @returns one deep-cloned schema per visible tool.\n */\n schemas(scope?: ScopeKey): ToolSchema[]\n /**\n * Classify a pending call through the caller's visible tool definition. Only\n * an exact `true` is parallel; unknown, hidden, undeclared, invalid, or\n * throwing classifiers are exclusive.\n * @param exec - call name, parsed arguments, and optional agent scope.\n * @returns the fail-closed scheduling mode.\n */\n executionMode(exec: ToolExecutionInput): ToolExecutionMode\n /**\n * Execute through pre-policy, guards, around-dispatch, post-policy,\n * definition-owned content finalization, and final notification. Tool and\n * listener failures resolve as materialized error results; an invisible tool\n * reports `UNKNOWN_TOOL`. The returned outcome is the same lossless, frozen\n * snapshot final observers receive. Cancellation\n * arriving after entry and before final result materialization skips a\n * not-yet-started body with `ABORTED_BEFORE_DISPATCH` or replaces a\n * successful started outcome with `ABORTED`; already-started work is still\n * drained and may retain a tool-owned structured error.\n * @param exec - the typed same-process call input. The registry assigns its\n * correlation token before policy begins.\n * @returns the materialized final result.\n */\n async execute(exec: ToolExecutionInput): Promise\ntype shapes (referenced by the signatures above — read these before assuming a field is a string):\n export interface Agent {\n readonly id: SessionId;\n readonly options: AgentOptions;\n readonly session: Session;\n readonly status: AgentStatus;\n readonly acceptsNextStep: boolean;\n readonly ctx: Context;\n send(message: UserMessage, options: SendOptions): void;\n updateInbox(id: InboxItemId, action: InboxAction): InboxActionResult;\n cancel(cause: AgentCancelCause, options?: CancelOptions): void;\n whenIdle(): Promise;\n followup(message: UserMessage): void;\n steer(message: UserMessage): void;\n inject(message: UserMessage): void;\n }\n export type AgentCancelCause = {\n readonly kind: 'user';\n } | {\n readonly kind: 'parent';\n };\n export interface AgentOptions {\n provider?: string;\n model?: string;\n maxTokens?: number;\n }\n export type AgentStatus = 'idle' | 'running';\n export interface AssistantMessage extends Message {\n readonly role: 'assistant';\n readonly source: ModelMessageSource;\n }\n export interface AssistantProvenance {\n provider: string;\n model: string;\n replayState?: unknown;\n }\n export type Branded = string & {\n readonly [BRAND]: B;\n };\n export type CallId = Branded<'CallId'>;\n export interface CancelOptions {\n keepInbox?: boolean;\n }\n export interface ContentBlockMap {\n 'text': TextBlock;\n 'reasoning': ReasoningBlock;\n 'tool-call': ToolCallBlock;\n 'tool-result': ToolResultBlock;\n }\n export type ContentBlockType = keyof ContentBlockMap;\n export interface DiffCallView {\n card: 'diff';\n title: string;\n diffs: FileDiff[];\n locations?: FileLocation[];\n }\n export interface DiffResultView {\n card: 'diff';\n title?: string;\n diffs: FileDiff[];\n }\n export interface EpochHeader {\n config: LlmCallConfig;\n system?: string;\n tools?: ToolSchema[];\n }\n export interface FileDiff {\n path: string;\n oldText: string | null;\n newText: string;\n }\n export interface FileLocation {\n path: string;\n line?: number;\n }\n export type FinishReason = FinishReasonMap[keyof FinishReasonMap];\n export interface FinishReasonMap {\n 'stop': {\n kind: 'stop';\n };\n 'tool-calls': {\n kind: 'tool-calls';\n };\n 'max-tokens': {\n kind: 'max-tokens';\n };\n 'aborted': {\n kind: 'aborted';\n failure: LlmFailure;\n };\n 'error': {\n kind: 'error';\n failure: LlmFailure;\n };\n }\n export interface GenericCallView {\n card: 'generic';\n title: string;\n kind?: ToolCallKind;\n rawInput?: unknown;\n content?: ContentBlock[];\n locations?: FileLocation[];\n }\n export interface GenericResultView {\n card: 'generic';\n title?: string;\n content?: ContentBlock[];\n }\n export type InboxAction = {\n readonly kind: 'edit';\n readonly content: ContentBlock[];\n } | {\n readonly kind: 'remove';\n };\n export type InboxActionResult = 'applied' | 'not-found';\n export type InboxItemId = Branded<'InboxItemId'>;\n export interface JsonSchemaNode {\n type?: JsonSchemaType;\n oneOf?: JsonSchemaNode[];\n properties?: Record;\n required?: string[];\n additionalProperties?: boolean;\n items?: JsonSchemaNode;\n enum?: JsonSchemaScalar[];\n const?: JsonSchemaScalar;\n description?: string;\n title?: string;\n default?: JsonValue;\n examples?: JsonValue;\n }\n export type JsonSchemaScalar = string | number | boolean | null;\n export type JsonSchemaType = 'object' | 'array' | 'string' | 'number' | 'integer' | 'boolean' | 'null';\n export type JsonValue = null | boolean | number | string | JsonValue[] | {\n [key: string]: JsonValue;\n };\n export interface LlmCallConfig {\n provider: string;\n model: string;\n reasoningEffort?: ReasoningEffortId;\n temperature?: number;\n maxTokens?: number;\n stop?: string[];\n }\n export interface LlmFailure {\n readonly message: string;\n readonly code: string;\n readonly status?: number;\n readonly providerRetryAfterMs?: number;\n readonly requestId?: ProviderRequestId;\n }\n export interface Message {\n readonly id: MessageId;\n readonly role: 'system' | 'user' | 'assistant';\n readonly content: ContentBlock[];\n readonly source: MessageSource;\n }\n export type MessageId = Branded<'MessageId'>;\n export type MessageSource = MessageSourceMap[keyof MessageSourceMap];\n export interface MessageSourceMap {\n user: {\n kind: 'user';\n };\n plugin: {\n kind: 'plugin';\n plugin: string;\n };\n model: ModelMessageSource;\n tool: ToolMessageSource;\n }\n export interface ModelMessageSource extends AssistantProvenance {\n kind: 'model';\n }\n export type ProviderRequestId = Branded<'ProviderRequestId'>;\n export interface ReasoningBlock {\n type: 'reasoning';\n text: string;\n }\n export type ReasoningEffortId = Branded<'ReasoningEffortId'>;\n export type RequestHeaderReason = 'initial' | 'resume' | 'change';\n export type ScopeKey = object;\n export interface SendOptions {\n target: SendTarget;\n wakeup: boolean;\n }\n export type SendTarget = 'next-turn' | 'next-step';\n export class Session {\n get surface(): SessionSurface;\n readonly header: SessionHeader;\n get id(): SessionId;\n readonly firstLiveSeq: number;\n constructor(id: SessionId, seed?: readonly SessionEvent[], header?: SessionHeader);\n get events(): readonly SessionEvent[];\n get seq(): number;\n append(type: T, data: SessionEventMap[T], ...opts: T extends SurfaceEventType ? [\n opts: SurfaceIntent\n ] : [\n ]): SessionEvent;\n requestHeader(): EpochHeader | undefined;\n deriveMessages(): Message[];\n deriveEventMessage(event: SessionEvent): Message | null;\n }\n export type SessionEvent = {\n [K in SessionEventType]: {\n type: K;\n seq: number;\n time: number;\n data: SessionEventMap[K];\n } & (K extends SurfaceEventType ? {\n sourceEventSeqs?: number[];\n surfaceOp?: SurfaceOp;\n } : object);\n }[T];\n export interface SessionEventMap {\n 'turn/start': {\n turn: number;\n trigger: TurnTrigger;\n };\n 'turn/end': {\n turn: number;\n reason: TurnEndReason;\n };\n 'step/start': {\n turn: number;\n step: number;\n };\n 'step/end': {\n turn: number;\n step: number;\n };\n 'user/message': UserMessage;\n 'assistant/chunk': {\n turn: number;\n step: number;\n chunk: StreamChunk;\n };\n 'assistant/message': {\n turn: number;\n step: number;\n message: AssistantMessage;\n usage?: TokenUsage;\n };\n 'tool/call': {\n turn: number;\n step: number;\n callId: CallId;\n name: string;\n arguments: string;\n };\n 'tool/result': {\n turn: number;\n step: number;\n message: ToolResultMessage;\n error?: {\n name: string;\n code: string;\n };\n meta?: JsonValue;\n };\n 'steering/message': {\n turn: number;\n message: UserMessage;\n };\n 'todo/write': {\n todos: TodoItem[];\n };\n 'request/header': {\n header: EpochHeader;\n reason: RequestHeaderReason;\n };\n }\n export type SessionEventType = keyof SessionEventMap;\n export interface SessionHeader {\n readonly version: number;\n readonly id: SessionId;\n readonly createdAt: number;\n readonly cwd?: string;\n readonly parentSession?: SessionId;\n readonly seedLength?: number;\n readonly delegationDepth?: number;\n }\n export type SessionId = Branded<'SessionId'>;\n export interface SessionSurface {\n readonly nodes: readonly number[];\n readonly replaceGeneration: number;\n }\n export type StreamChunk = {\n type: 'block-start';\n index: number;\n blockType: ContentBlockType;\n } | {\n type: 'text-delta';\n index: number;\n text: string;\n } | {\n type: 'reasoning-delta';\n index: number;\n text: string;\n } | {\n type: 'tool-call-delta';\n index: number;\n id: CallId;\n name?: string;\n argumentsDelta: string;\n } | {\n type: 'block-end';\n index: number;\n block: ContentBlock;\n } | {\n type: 'usage';\n usage: TokenUsage;\n } | {\n type: 'finish';\n reason: FinishReason;\n replayState?: unknown;\n };\n export type SurfaceEventType = 'user/message' | 'assistant/message' | 'tool/result' | 'steering/message';\n export interface SurfaceIntent {\n surfaceOp: SurfaceOp;\n sourceEventSeqs?: number[];\n }\n export type SurfaceOp = 'append' | {\n op: 'replace';\n start: number;\n end: number;\n };\n export interface TerminalCallView {\n card: 'terminal';\n title: string;\n description?: string;\n cwd?: string;\n }\n export interface TerminalResultView {\n card: 'terminal';\n title?: string;\n output?: string;\n exitCode?: number;\n signal?: string;\n }\n export interface TodoItem {\n content: string;\n status: 'pending' | 'in_progress' | 'completed';\n }\n export interface TokenUsage {\n inputTokens: number;\n outputTokens: number;\n cacheReadTokens?: number;\n cacheWriteTokens?: number;\n reasoningTokens?: number;\n }\n export interface ToolCallBlock {\n type: 'tool-call';\n id: CallId;\n name: string;\n arguments: string;\n }\n export type ToolCallKind = 'read' | 'edit' | 'delete' | 'move' | 'search' | 'execute' | 'fetch' | 'other';\n export type ToolCallView = GenericCallView | TerminalCallView | DiffCallView;\n export interface ToolDefinition extends ToolSchema {\n readonly output: ToolOutputDefinition;\n execute(args: unknown, exec: ToolRunContext): Promise;\n finalizeContent?(exec: Readonly, result: Readonly): ContentBlock[] | undefined;\n timeoutMs?: number;\n isConcurrencySafe?(args: unknown): boolean;\n presentCall?(args: unknown): ToolCallView | undefined;\n presentResult?(args: unknown, result: ToolResult): ToolResultView | undefined;\n }\n export interface ToolErrorInfo {\n name: string;\n code: string;\n }\n export interface ToolExecution extends ToolExecutionInput {\n readonly token: ToolExecutionToken;\n }\n export interface ToolExecutionFailure {\n readonly isError: true;\n readonly error: ToolFailure;\n readonly value?: never;\n readonly content: ContentBlock[];\n readonly meta?: JsonValue;\n readonly additionalContexts?: UserMessage[];\n readonly concludesTurn?: never;\n }\n export interface ToolExecutionInput {\n readonly callId: CallId;\n readonly name: string;\n readonly arguments: unknown;\n readonly agent?: Agent;\n readonly parent?: ToolExecutionToken;\n readonly signal: AbortSignal;\n }\n export type ToolExecutionMode = {\n kind: 'parallel';\n } | {\n kind: 'exclusive';\n };\n export type ToolExecutionResult = ToolExecutionSuccess | ToolExecutionFailure;\n export interface ToolExecutionSuccess {\n readonly isError: false;\n readonly value: JsonValue;\n readonly content: ContentBlock[];\n readonly error?: never;\n readonly meta?: JsonValue;\n readonly additionalContexts?: UserMessage[];\n readonly concludesTurn?: true;\n }\n export type ToolExecutionToken = symbol & {\n readonly [toolExecutionTokenBrand]: true;\n };\n export interface ToolFailure {\n message: string;\n info?: ToolErrorInfo;\n }\n export type ToolGuard = (execution: Readonly) => string | undefined;\n export interface ToolMessageSource {\n kind: 'tool';\n callId: CallId;\n }\n export interface ToolOutputDefinition {\n readonly schema: JsonSchemaNode;\n render(args: unknown, value: JsonValue): ContentBlock[];\n presentationMeta?(args: unknown, value: JsonValue): JsonValue;\n }\n export interface ToolRestriction {\n readonly allow?: readonly string[];\n readonly deny?: readonly string[];\n }\n export interface ToolResult {\n content: ContentBlock[];\n isError: boolean;\n meta?: JsonValue;\n }\n export interface ToolResultBlock {\n type: 'tool-result';\n toolCallId: CallId;\n content: ContentBlock[];\n isError?: boolean;\n }\n export interface ToolResultMessage extends Message {\n readonly role: 'user';\n readonly content: [\n ToolResultBlock\n ];\n readonly source: ToolMessageSource;\n }\n export type ToolResultView = GenericResultView | TerminalResultView | DiffResultView;\n export interface ToolRunContext extends ToolExecution {\n deferContext(context: UserMessage): void;\n concludeTurn(): void;\n }\n export interface ToolSchema {\n name: string;\n description: string;\n parameters: Record;\n }\n export type TurnEndReason = TurnEndReasonMap[keyof TurnEndReasonMap];\n export interface TurnEndReasonMap {\n completed: {\n kind: 'completed';\n };\n aborted: {\n kind: 'aborted';\n };\n error: {\n kind: 'error';\n step: number;\n } & ({\n failure: LlmFailure;\n message?: never;\n code?: never;\n } | {\n message: string;\n code?: string;\n failure?: never;\n });\n disposed: {\n kind: 'disposed';\n };\n 'max-tokens': {\n kind: 'max-tokens';\n };\n interrupted: {\n kind: 'interrupted';\n };\n }\n export type TurnTrigger = TurnTriggerMap[keyof TurnTriggerMap];\n export interface TurnTriggerMap {\n message: {\n kind: 'message';\n source: MessageSource;\n };\n retry: {\n kind: 'retry';\n };\n injection: {\n kind: 'injection';\n source: MessageSource;\n };\n }\n export interface UserMessage extends Message {\n readonly role: 'user';\n }"}],"isError":false}],"role":"user","id":"1c43b8df-aae8-42e7-8253-5b275edc09bc"}},"sourceEventSeqs":[11],"surfaceOp":"append"} +{"type":"tool/result","seq":12,"time":1784449176732,"data":{"turn":1,"step":1,"message":{"source":{"kind":"tool","callId":"inspect-tools-api"},"content":[{"type":"tool-result","toolCallId":"inspect-tools-api","content":[{"type":"text","text":"## api\n- tools — Tool registry and execution pipeline.\n /**\n * Register globally or in the calling agent scope. Scoped tools shadow\n * globals; duplicates within one layer and the reserved `run_code` name fail.\n * @param definition - tool schema, execution, and optional finalization/presentation callbacks.\n * @returns the exact disposer that unregisters the tool.\n */\n register(definition: ToolDefinition): () => void\n /**\n * Restrict global tools for the calling agent scope. Empty filters, unknown\n * names, scope-local names, and reserved transport names fail. Restrictions\n * intersect; scoped registrations remain visible.\n * @param filter - global-surface mask: `allow` (keep only) and/or `deny` (remove).\n * @returns the exact disposer that lifts this restriction.\n */\n restrict(filter: ToolRestriction): () => void\n /**\n * Register a monotonic guard after the extensible `tools/pre-execute`\n * waterfall. A plain-context guard applies globally; one registered through\n * `agent.ctx` applies only to that agent. Any matching guard may deny by\n * returning a reason, while no guard can force-allow a call another guard\n * denied. The exact effect disposer is returned for ordered ownership and\n * HMR cleanup.\n * @param guard - synchronous check; a returned string denies the execution.\n * @returns the exact disposer that unregisters the guard.\n */\n guard(guard: ToolGuard): () => void\n /**\n * Look up a tool as one scope sees it (scoped\n * shadows global; a restricted-away global reads as absent). Presenters pass\n * the calling agent so the rendered card matches the definition that\n * actually executed.\n * @param name - the tool name as registered.\n * @param scope - the viewing scope (the agent); omitted = the global view.\n * @returns the definition the scope resolves, or undefined when none is visible.\n */\n get(name: string, scope?: ScopeKey): ToolDefinition | undefined\n /**\n * Project visible definitions onto the allowlisted model-facing schema fields,\n * excluding execution and presentation callbacks.\n * @param scope - the viewing scope (the agent); omitted = the global view.\n * @returns one deep-cloned schema per visible tool.\n */\n schemas(scope?: ScopeKey): ToolSchema[]\n /**\n * Classify a pending call through the caller's visible tool definition. Only\n * an exact `true` is parallel; unknown, hidden, undeclared, invalid, or\n * throwing classifiers are exclusive.\n * @param exec - call name, parsed arguments, and optional agent scope.\n * @returns the fail-closed scheduling mode.\n */\n executionMode(exec: ToolExecutionInput): ToolExecutionMode\n /**\n * Execute through pre-policy, guards, around-dispatch, post-policy,\n * definition-owned content finalization, and final notification. Tool and\n * listener failures resolve as materialized error results; an invisible tool\n * reports `UNKNOWN_TOOL`. The returned outcome is the same lossless, frozen\n * snapshot final observers receive. Cancellation\n * arriving after entry and before final result materialization skips a\n * not-yet-started body with `ABORTED_BEFORE_DISPATCH` or replaces a\n * successful started outcome with `ABORTED`; already-started work is still\n * drained and may retain a tool-owned structured error.\n * @param exec - the typed same-process call input. The registry assigns its\n * correlation token before policy begins.\n * @returns the materialized final result.\n */\n async execute(exec: ToolExecutionInput): Promise\ntype shapes (referenced by the signatures above — read these before assuming a field is a string):\n export interface Agent {\n readonly id: SessionId;\n readonly options: AgentOptions;\n readonly session: Session;\n readonly status: AgentStatus;\n readonly acceptsNextStep: boolean;\n readonly ctx: Context;\n send(message: UserMessage, options: SendOptions): void;\n updateInbox(id: InboxItemId, action: InboxAction): InboxActionResult;\n cancel(cause: AgentCancelCause, options?: CancelOptions): void;\n whenIdle(): Promise;\n followup(message: UserMessage): void;\n steer(message: UserMessage): void;\n inject(message: UserMessage): void;\n }\n export type AgentCancelCause = {\n readonly kind: 'user';\n } | {\n readonly kind: 'parent';\n };\n export interface AgentOptions {\n provider?: string;\n model?: string;\n maxTokens?: number;\n }\n export type AgentStatus = 'idle' | 'running';\n export interface AssistantMessage extends Message {\n readonly role: 'assistant';\n readonly source: ModelMessageSource;\n }\n export interface AssistantProvenance {\n provider: string;\n model: string;\n replayState?: unknown;\n }\n export type Branded = string & {\n readonly [BRAND]: B;\n };\n export type CallId = Branded<'CallId'>;\n export interface CancelOptions {\n keepInbox?: boolean;\n }\n export interface ContentBlockMap {\n 'text': TextBlock;\n 'reasoning': ReasoningBlock;\n 'tool-call': ToolCallBlock;\n 'tool-result': ToolResultBlock;\n }\n export type ContentBlockType = keyof ContentBlockMap;\n export interface DiffCallView {\n card: 'diff';\n title: string;\n diffs: FileDiff[];\n locations?: FileLocation[];\n }\n export interface DiffResultView {\n card: 'diff';\n title?: string;\n diffs: FileDiff[];\n }\n export interface EpochHeader {\n config: LlmCallConfig;\n system?: string;\n tools?: ToolSchema[];\n }\n export interface FileDiff {\n path: string;\n oldText: string | null;\n newText: string;\n }\n export interface FileLocation {\n path: string;\n line?: number;\n }\n export type FinishReason = FinishReasonMap[keyof FinishReasonMap];\n export interface FinishReasonMap {\n 'stop': {\n kind: 'stop';\n };\n 'tool-calls': {\n kind: 'tool-calls';\n };\n 'max-tokens': {\n kind: 'max-tokens';\n };\n 'aborted': {\n kind: 'aborted';\n failure: LlmFailure;\n };\n 'error': {\n kind: 'error';\n failure: LlmFailure;\n };\n }\n export interface GenericCallView {\n card: 'generic';\n title: string;\n kind?: ToolCallKind;\n rawInput?: unknown;\n content?: ContentBlock[];\n locations?: FileLocation[];\n }\n export interface GenericResultView {\n card: 'generic';\n title?: string;\n content?: ContentBlock[];\n }\n export type InboxAction = {\n readonly kind: 'edit';\n readonly content: ContentBlock[];\n } | {\n readonly kind: 'remove';\n };\n export type InboxActionResult = 'applied' | 'not-found';\n export type InboxItemId = Branded<'InboxItemId'>;\n export interface JsonSchemaNode {\n type?: JsonSchemaType;\n oneOf?: JsonSchemaNode[];\n properties?: Record;\n required?: string[];\n additionalProperties?: boolean;\n items?: JsonSchemaNode;\n enum?: JsonSchemaScalar[];\n const?: JsonSchemaScalar;\n description?: string;\n title?: string;\n default?: JsonValue;\n examples?: JsonValue;\n }\n export type JsonSchemaScalar = string | number | boolean | null;\n export type JsonSchemaType = 'object' | 'array' | 'string' | 'number' | 'integer' | 'boolean' | 'null';\n export type JsonValue = null | boolean | number | string | JsonValue[] | {\n [key: string]: JsonValue;\n };\n export interface LlmCallConfig {\n provider: string;\n model: string;\n reasoningEffort?: ReasoningEffortId;\n temperature?: number;\n maxTokens?: number;\n stop?: string[];\n }\n export interface LlmFailure {\n readonly message: string;\n readonly code: string;\n readonly status?: number;\n readonly providerRetryAfterMs?: number;\n readonly requestId?: ProviderRequestId;\n }\n export interface Message {\n readonly id: MessageId;\n readonly role: 'system' | 'user' | 'assistant';\n readonly content: ContentBlock[];\n readonly source: MessageSource;\n }\n export type MessageId = Branded<'MessageId'>;\n export type MessageSource = MessageSourceMap[keyof MessageSourceMap];\n export interface MessageSourceMap {\n user: {\n kind: 'user';\n };\n plugin: {\n kind: 'plugin';\n plugin: string;\n };\n model: ModelMessageSource;\n tool: ToolMessageSource;\n }\n export interface ModelMessageSource extends AssistantProvenance {\n kind: 'model';\n }\n export type ProviderRequestId = Branded<'ProviderRequestId'>;\n export interface ReadFileLine {\n number: number;\n text: string;\n }\n export interface ReadResultView {\n card: 'read';\n title?: string;\n path: string;\n lines: ReadFileLine[];\n totalLines: number;\n lang?: string;\n content?: ContentBlock[];\n }\n export interface ReasoningBlock {\n type: 'reasoning';\n text: string;\n }\n export type ReasoningEffortId = Branded<'ReasoningEffortId'>;\n export type RequestHeaderReason = 'initial' | 'resume' | 'change';\n export type ScopeKey = object;\n export interface SendOptions {\n target: SendTarget;\n wakeup: boolean;\n }\n export type SendTarget = 'next-turn' | 'next-step';\n export class Session {\n get surface(): SessionSurface;\n readonly header: SessionHeader;\n get id(): SessionId;\n readonly firstLiveSeq: number;\n constructor(id: SessionId, seed?: readonly SessionEvent[], header?: SessionHeader);\n get events(): readonly SessionEvent[];\n get seq(): number;\n append(type: T, data: SessionEventMap[T], ...opts: T extends SurfaceEventType ? [\n opts: SurfaceIntent\n ] : [\n ]): SessionEvent;\n requestHeader(): EpochHeader | undefined;\n deriveMessages(): Message[];\n deriveEventMessage(event: SessionEvent): Message | null;\n }\n export type SessionEvent = {\n [K in SessionEventType]: {\n type: K;\n seq: number;\n time: number;\n data: SessionEventMap[K];\n } & (K extends SurfaceEventType ? {\n sourceEventSeqs?: number[];\n surfaceOp?: SurfaceOp;\n } : object);\n }[T];\n export interface SessionEventMap {\n 'turn/start': {\n turn: number;\n trigger: TurnTrigger;\n };\n 'turn/end': {\n turn: number;\n reason: TurnEndReason;\n };\n 'step/start': {\n turn: number;\n step: number;\n };\n 'step/end': {\n turn: number;\n step: number;\n };\n 'user/message': UserMessage;\n 'assistant/chunk': {\n turn: number;\n step: number;\n chunk: StreamChunk;\n };\n 'assistant/message': {\n turn: number;\n step: number;\n message: AssistantMessage;\n usage?: TokenUsage;\n };\n 'tool/call': {\n turn: number;\n step: number;\n callId: CallId;\n name: string;\n arguments: string;\n };\n 'tool/result': {\n turn: number;\n step: number;\n message: ToolResultMessage;\n error?: {\n name: string;\n code: string;\n };\n meta?: JsonValue;\n };\n 'steering/message': {\n turn: number;\n message: UserMessage;\n };\n 'todo/write': {\n todos: TodoItem[];\n };\n 'request/header': {\n header: EpochHeader;\n reason: RequestHeaderReason;\n };\n }\n export type SessionEventType = keyof SessionEventMap;\n export interface SessionHeader {\n readonly version: number;\n readonly id: SessionId;\n readonly createdAt: number;\n readonly cwd?: string;\n readonly parentSession?: SessionId;\n readonly seedLength?: number;\n readonly delegationDepth?: number;\n }\n export type SessionId = Branded<'SessionId'>;\n export interface SessionSurface {\n readonly nodes: readonly number[];\n readonly replaceGeneration: number;\n }\n export type StreamChunk = {\n type: 'block-start';\n index: number;\n blockType: ContentBlockType;\n } | {\n type: 'text-delta';\n index: number;\n text: string;\n } | {\n type: 'reasoning-delta';\n index: number;\n text: string;\n } | {\n type: 'tool-call-delta';\n index: number;\n id: CallId;\n name?: string;\n argumentsDelta: string;\n } | {\n type: 'block-end';\n index: number;\n block: ContentBlock;\n } | {\n type: 'usage';\n usage: TokenUsage;\n } | {\n type: 'finish';\n reason: FinishReason;\n replayState?: unknown;\n };\n export type SurfaceEventType = 'user/message' | 'assistant/message' | 'tool/result' | 'steering/message';\n export interface SurfaceIntent {\n surfaceOp: SurfaceOp;\n sourceEventSeqs?: number[];\n }\n export type SurfaceOp = 'append' | {\n op: 'replace';\n start: number;\n end: number;\n };\n export interface TerminalCallView {\n card: 'terminal';\n title: string;\n description?: string;\n cwd?: string;\n }\n export interface TerminalResultView {\n card: 'terminal';\n title?: string;\n output?: string;\n exitCode?: number;\n signal?: string;\n }\n export interface TodoItem {\n content: string;\n status: 'pending' | 'in_progress' | 'completed';\n }\n export interface TokenUsage {\n inputTokens: number;\n outputTokens: number;\n cacheReadTokens?: number;\n cacheWriteTokens?: number;\n reasoningTokens?: number;\n }\n export interface ToolCallBlock {\n type: 'tool-call';\n id: CallId;\n name: string;\n arguments: string;\n }\n export type ToolCallKind = 'read' | 'edit' | 'delete' | 'move' | 'search' | 'execute' | 'fetch' | 'other';\n export type ToolCallView = GenericCallView | TerminalCallView | DiffCallView;\n export interface ToolDefinition extends ToolSchema {\n readonly output: ToolOutputDefinition;\n execute(args: unknown, exec: ToolRunContext): Promise;\n finalizeContent?(exec: Readonly, result: Readonly): ContentBlock[] | undefined;\n timeoutMs?: number;\n isConcurrencySafe?(args: unknown): boolean;\n presentCall?(args: unknown): ToolCallView | undefined;\n presentResult?(args: unknown, result: ToolResult): ToolResultView | undefined;\n }\n export interface ToolErrorInfo {\n name: string;\n code: string;\n }\n export interface ToolExecution extends ToolExecutionInput {\n readonly token: ToolExecutionToken;\n }\n export interface ToolExecutionFailure {\n readonly isError: true;\n readonly error: ToolFailure;\n readonly value?: never;\n readonly content: ContentBlock[];\n readonly meta?: JsonValue;\n readonly additionalContexts?: UserMessage[];\n readonly concludesTurn?: never;\n }\n export interface ToolExecutionInput {\n readonly callId: CallId;\n readonly name: string;\n readonly arguments: unknown;\n readonly agent?: Agent;\n readonly parent?: ToolExecutionToken;\n readonly signal: AbortSignal;\n }\n export type ToolExecutionMode = {\n kind: 'parallel';\n } | {\n kind: 'exclusive';\n };\n export type ToolExecutionResult = ToolExecutionSuccess | ToolExecutionFailure;\n export interface ToolExecutionSuccess {\n readonly isError: false;\n readonly value: JsonValue;\n readonly content: ContentBlock[];\n readonly error?: never;\n readonly meta?: JsonValue;\n readonly additionalContexts?: UserMessage[];\n readonly concludesTurn?: true;\n }\n export type ToolExecutionToken = symbol & {\n readonly [toolExecutionTokenBrand]: true;\n };\n export interface ToolFailure {\n message: string;\n info?: ToolErrorInfo;\n }\n export type ToolGuard = (execution: Readonly) => string | undefined;\n export interface ToolMessageSource {\n kind: 'tool';\n callId: CallId;\n }\n export interface ToolOutputDefinition {\n readonly schema: JsonSchemaNode;\n render(args: unknown, value: JsonValue): ContentBlock[];\n presentationMeta?(args: unknown, value: JsonValue): JsonValue;\n }\n export interface ToolRestriction {\n readonly allow?: readonly string[];\n readonly deny?: readonly string[];\n }\n export interface ToolResult {\n content: ContentBlock[];\n isError: boolean;\n meta?: JsonValue;\n }\n export interface ToolResultBlock {\n type: 'tool-result';\n toolCallId: CallId;\n content: ContentBlock[];\n isError?: boolean;\n }\n export interface ToolResultMessage extends Message {\n readonly role: 'user';\n readonly content: [\n ToolResultBlock\n ];\n readonly source: ToolMessageSource;\n }\n export type ToolResultView = GenericResultView | TerminalResultView | DiffResultView | ReadResultView;\n export interface ToolRunContext extends ToolExecution {\n deferContext(context: UserMessage): void;\n concludeTurn(): void;\n }\n export interface ToolSchema {\n name: string;\n description: string;\n parameters: Record;\n }\n export type TurnEndReason = TurnEndReasonMap[keyof TurnEndReasonMap];\n export interface TurnEndReasonMap {\n completed: {\n kind: 'completed';\n };\n aborted: {\n kind: 'aborted';\n };\n error: {\n kind: 'error';\n step: number;\n } & ({\n failure: LlmFailure;\n message?: never;\n code?: never;\n } | {\n message: string;\n code?: string;\n failure?: never;\n });\n disposed: {\n kind: 'disposed';\n };\n 'max-tokens': {\n kind: 'max-tokens';\n };\n interrupted: {\n kind: 'interrupted';\n };\n }\n export type TurnTrigger = TurnTriggerMap[keyof TurnTriggerMap];\n export interface TurnTriggerMap {\n message: {\n kind: 'message';\n source: MessageSource;\n };\n retry: {\n kind: 'retry';\n };\n injection: {\n kind: 'injection';\n source: MessageSource;\n };\n }\n export interface UserMessage extends Message {\n readonly role: 'user';\n }"}],"isError":false}],"role":"user","id":"1c43b8df-aae8-42e7-8253-5b275edc09bc"}},"sourceEventSeqs":[11],"surfaceOp":"append"} {"type":"step/end","seq":13,"time":1784449176732,"data":{"turn":1,"step":1}} {"type":"step/start","seq":14,"time":1784449176733,"data":{"turn":1,"step":2}} {"type":"assistant/chunk","seq":15,"time":1783951000015,"data":{"turn":1,"step":2,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}}} diff --git a/examples/acp-agent/tests/snapshots/fs-edit/session.jsonl b/examples/acp-agent/tests/snapshots/fs-edit/session.jsonl index 784b6c17c4..a5526006e4 100644 --- a/examples/acp-agent/tests/snapshots/fs-edit/session.jsonl +++ b/examples/acp-agent/tests/snapshots/fs-edit/session.jsonl @@ -14,7 +14,7 @@ {"type":"assistant/chunk","seq":68,"time":1783352086057,"data":{"turn":1,"step":1,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}} {"type":"assistant/message","seq":69,"time":1783352086059,"data":{"turn":1,"step":1,"message":{"role":"assistant","content":[{"type":"reasoning","text":"The user wants me to:\n1. Read config.txt in the current directory\n2. Use the edit tool to replace DEBUG with RELEASE\n3. Reply with exactly \"DONE\"\n\nLet me start by reading the file."},{"type":"tool-call","id":"call_00_S6krdIDHoSCGWv7WnXX97617","name":"read","arguments":"{\"file_path\": \"config.txt\"}"}],"source":{"kind":"model","provider":"deepseek","model":"deepseek-v4-flash"},"id":"36ebf262-429c-4398-abbc-a197e2522f1d"},"usage":{"inputTokens":2900,"outputTokens":91,"cacheReadTokens":0,"reasoningTokens":46}},"sourceEventSeqs":[5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68],"surfaceOp":"append"} {"type":"tool/call","seq":70,"time":1783352086059,"data":{"turn":1,"step":1,"callId":"call_00_S6krdIDHoSCGWv7WnXX97617","name":"read","arguments":"{\"file_path\": \"config.txt\"}"}} -{"type":"tool/result","seq":71,"time":1783352086065,"data":{"turn":1,"step":1,"message":{"source":{"kind":"tool","callId":"call_00_S6krdIDHoSCGWv7WnXX97617"},"content":[{"type":"tool-result","toolCallId":"call_00_S6krdIDHoSCGWv7WnXX97617","content":[{"type":"text","text":"{{cwd}}/config.txt\nfile\n\n1: mode=DEBUG\n2: level=info\n\n(End of file - total 2 lines)\n"}],"isError":false}],"role":"user","id":"1c3ce978-55ee-4337-a586-084a77ed44e7"}},"sourceEventSeqs":[70],"surfaceOp":"append"} +{"type":"tool/result","seq":71,"time":1783352086065,"data":{"turn":1,"step":1,"message":{"source":{"kind":"tool","callId":"call_00_S6krdIDHoSCGWv7WnXX97617"},"content":[{"type":"tool-result","toolCallId":"call_00_S6krdIDHoSCGWv7WnXX97617","content":[{"type":"text","text":"{{cwd}}/config.txt\nfile\n\n1: mode=DEBUG\n2: level=info\n\n(End of file - total 2 lines)\n"}],"isError":false}],"role":"user","id":"1c3ce978-55ee-4337-a586-084a77ed44e7"},"meta":{"path":"{{cwd}}/config.txt","lines":[{"number":1,"text":"mode=DEBUG"},{"number":2,"text":"level=info"}],"totalLines":2}},"sourceEventSeqs":[70],"surfaceOp":"append"} {"type":"step/end","seq":72,"time":1783352086065,"data":{"turn":1,"step":1}} {"type":"step/start","seq":73,"time":1783352086066,"data":{"turn":1,"step":2}} {"type":"assistant/chunk","seq":74,"time":1783352086901,"data":{"turn":1,"step":2,"chunk":{"type":"block-start","index":0,"blockType":"reasoning"}}} diff --git a/examples/acp-agent/tests/snapshots/fs-policy-reject/session.jsonl b/examples/acp-agent/tests/snapshots/fs-policy-reject/session.jsonl index d934a2d7be..8d2b0a2b83 100644 --- a/examples/acp-agent/tests/snapshots/fs-policy-reject/session.jsonl +++ b/examples/acp-agent/tests/snapshots/fs-policy-reject/session.jsonl @@ -27,7 +27,7 @@ {"type":"assistant/chunk","seq":143,"time":1783611705572,"data":{"turn":1,"step":2,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}} {"type":"assistant/message","seq":144,"time":1783611705573,"data":{"turn":1,"step":2,"message":{"role":"assistant","content":[{"type":"reasoning","text":"The edit tool requires reading the file first. The user said \"Do not read the file first\" but the tool's own constraints require reading. I need to follow the tool requirements. Let me read the file first."},{"type":"tool-call","id":"call_00_tfr0gdIclW92oIEgi7NF0891","name":"read","arguments":"{\"file_path\": \"settings.txt\"}"}],"source":{"kind":"model","provider":"deepseek","model":"deepseek-v4-flash"},"id":"de588e3c-b10c-4eee-93a5-26e9a665dcbc"},"usage":{"inputTokens":235,"outputTokens":89,"cacheReadTokens":3072,"reasoningTokens":44}},"sourceEventSeqs":[82,83,84,85,86,87,88,89,90,91,92,93,94,95,96,97,98,99,100,101,102,103,104,105,106,107,108,109,110,111,112,113,114,115,116,117,118,119,120,121,122,123,124,125,126,127,128,129,130,131,132,133,134,135,136,137,138,139,140,141,142,143],"surfaceOp":"append"} {"type":"tool/call","seq":145,"time":1783611705573,"data":{"turn":1,"step":2,"callId":"call_00_tfr0gdIclW92oIEgi7NF0891","name":"read","arguments":"{\"file_path\": \"settings.txt\"}"}} -{"type":"tool/result","seq":146,"time":1783611705579,"data":{"turn":1,"step":2,"message":{"source":{"kind":"tool","callId":"call_00_tfr0gdIclW92oIEgi7NF0891"},"content":[{"type":"tool-result","toolCallId":"call_00_tfr0gdIclW92oIEgi7NF0891","content":[{"type":"text","text":"{{cwd}}/settings.txt\nfile\n\n1: color: blue\n\n(End of file - total 1 lines)\n"}],"isError":false}],"role":"user","id":"fade9382-14c7-47e3-8da4-286008d7e9b8"}},"sourceEventSeqs":[145],"surfaceOp":"append"} +{"type":"tool/result","seq":146,"time":1783611705579,"data":{"turn":1,"step":2,"message":{"source":{"kind":"tool","callId":"call_00_tfr0gdIclW92oIEgi7NF0891"},"content":[{"type":"tool-result","toolCallId":"call_00_tfr0gdIclW92oIEgi7NF0891","content":[{"type":"text","text":"{{cwd}}/settings.txt\nfile\n\n1: color: blue\n\n(End of file - total 1 lines)\n"}],"isError":false}],"role":"user","id":"fade9382-14c7-47e3-8da4-286008d7e9b8"},"meta":{"path":"{{cwd}}/settings.txt","lines":[{"number":1,"text":"color: blue"}],"totalLines":1}},"sourceEventSeqs":[145],"surfaceOp":"append"} {"type":"step/end","seq":147,"time":1783611705579,"data":{"turn":1,"step":2}} {"type":"step/start","seq":148,"time":1783611705579,"data":{"turn":1,"step":3}} {"type":"assistant/chunk","seq":149,"time":1783611706200,"data":{"turn":1,"step":3,"chunk":{"type":"block-start","index":0,"blockType":"reasoning"}}} diff --git a/examples/acp-agent/tests/snapshots/fs-read-window/session.jsonl b/examples/acp-agent/tests/snapshots/fs-read-window/session.jsonl index 72cb3a5200..81032c4bff 100644 --- a/examples/acp-agent/tests/snapshots/fs-read-window/session.jsonl +++ b/examples/acp-agent/tests/snapshots/fs-read-window/session.jsonl @@ -14,7 +14,7 @@ {"type":"assistant/chunk","seq":90,"time":1783352101346,"data":{"turn":1,"step":1,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}} {"type":"assistant/message","seq":91,"time":1783352101348,"data":{"turn":1,"step":1,"message":{"role":"assistant","content":[{"type":"reasoning","text":"The user wants me to use the read tool with offset 5 and limit 4 to read lines 5 through 8 of big.txt in the current directory. Then reply with exactly the single word DONE.\n\nLet me first check the current directory, then read the file."},{"type":"tool-call","id":"call_00_GIZwZS9a7vhWTFCIc7Z35497","name":"read","arguments":"{\"file_path\": \"big.txt\", \"offset\": 5, \"limit\": 4}"}],"source":{"kind":"model","provider":"deepseek","model":"deepseek-v4-flash"},"id":"5620412c-8fae-4d17-aac4-0801f3b02461"},"usage":{"inputTokens":2894,"outputTokens":133,"cacheReadTokens":0,"reasoningTokens":56}},"sourceEventSeqs":[5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80,81,82,83,84,85,86,87,88,89,90],"surfaceOp":"append"} {"type":"tool/call","seq":92,"time":1783352101348,"data":{"turn":1,"step":1,"callId":"call_00_GIZwZS9a7vhWTFCIc7Z35497","name":"read","arguments":"{\"file_path\": \"big.txt\", \"offset\": 5, \"limit\": 4}"}} -{"type":"tool/result","seq":93,"time":1783352101353,"data":{"turn":1,"step":1,"message":{"source":{"kind":"tool","callId":"call_00_GIZwZS9a7vhWTFCIc7Z35497"},"content":[{"type":"tool-result","toolCallId":"call_00_GIZwZS9a7vhWTFCIc7Z35497","content":[{"type":"text","text":"{{cwd}}/big.txt\nfile\n\n5: line five\n6: line six\n7: line seven\n8: line eight\n\n(Showing lines 5-8 of 10. Use offset=9 to continue.)\n"}],"isError":false}],"role":"user","id":"02513672-93cb-4f70-9ee7-ad19542a5f6b"}},"sourceEventSeqs":[92],"surfaceOp":"append"} +{"type":"tool/result","seq":93,"time":1783352101353,"data":{"turn":1,"step":1,"message":{"source":{"kind":"tool","callId":"call_00_GIZwZS9a7vhWTFCIc7Z35497"},"content":[{"type":"tool-result","toolCallId":"call_00_GIZwZS9a7vhWTFCIc7Z35497","content":[{"type":"text","text":"{{cwd}}/big.txt\nfile\n\n5: line five\n6: line six\n7: line seven\n8: line eight\n\n(Showing lines 5-8 of 10. Use offset=9 to continue.)\n"}],"isError":false}],"role":"user","id":"02513672-93cb-4f70-9ee7-ad19542a5f6b"},"meta":{"path":"{{cwd}}/big.txt","lines":[{"number":5,"text":"line five"},{"number":6,"text":"line six"},{"number":7,"text":"line seven"},{"number":8,"text":"line eight"}],"totalLines":10}},"sourceEventSeqs":[92],"surfaceOp":"append"} {"type":"step/end","seq":94,"time":1783352101353,"data":{"turn":1,"step":1}} {"type":"step/start","seq":95,"time":1783352101354,"data":{"turn":1,"step":2}} {"type":"assistant/chunk","seq":96,"time":1783352102021,"data":{"turn":1,"step":2,"chunk":{"type":"block-start","index":0,"blockType":"reasoning"}}} diff --git a/examples/acp-agent/tests/snapshots/fs-read/session.jsonl b/examples/acp-agent/tests/snapshots/fs-read/session.jsonl index 82adec999d..79a974a9d7 100644 --- a/examples/acp-agent/tests/snapshots/fs-read/session.jsonl +++ b/examples/acp-agent/tests/snapshots/fs-read/session.jsonl @@ -14,7 +14,7 @@ {"type":"assistant/chunk","seq":52,"time":1783352073705,"data":{"turn":1,"step":1,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}} {"type":"assistant/message","seq":53,"time":1783352073708,"data":{"turn":1,"step":1,"message":{"role":"assistant","content":[{"type":"reasoning","text":"The user wants me to read the file greeting.txt using the read tool (not bash), then reply with exactly the single word \"DONE\"."},{"type":"tool-call","id":"call_00_hHPZCcivsIkXAGS9jTGy8417","name":"read","arguments":"{\"file_path\": \"greeting.txt\"}"}],"source":{"kind":"model","provider":"deepseek","model":"deepseek-v4-flash"},"id":"5452254c-4843-458c-9732-12fe8b7c1468"},"usage":{"inputTokens":2882,"outputTokens":75,"cacheReadTokens":0,"reasoningTokens":29}},"sourceEventSeqs":[5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52],"surfaceOp":"append"} {"type":"tool/call","seq":54,"time":1783352073709,"data":{"turn":1,"step":1,"callId":"call_00_hHPZCcivsIkXAGS9jTGy8417","name":"read","arguments":"{\"file_path\": \"greeting.txt\"}"}} -{"type":"tool/result","seq":55,"time":1783352073717,"data":{"turn":1,"step":1,"message":{"source":{"kind":"tool","callId":"call_00_hHPZCcivsIkXAGS9jTGy8417"},"content":[{"type":"tool-result","toolCallId":"call_00_hHPZCcivsIkXAGS9jTGy8417","content":[{"type":"text","text":"{{cwd}}/greeting.txt\nfile\n\n1: hello\n\n(End of file - total 1 lines)\n"}],"isError":false}],"role":"user","id":"6dd015cf-8c8b-4fd3-a1b2-fa243d67d8e9"}},"sourceEventSeqs":[54],"surfaceOp":"append"} +{"type":"tool/result","seq":55,"time":1783352073717,"data":{"turn":1,"step":1,"message":{"source":{"kind":"tool","callId":"call_00_hHPZCcivsIkXAGS9jTGy8417"},"content":[{"type":"tool-result","toolCallId":"call_00_hHPZCcivsIkXAGS9jTGy8417","content":[{"type":"text","text":"{{cwd}}/greeting.txt\nfile\n\n1: hello\n\n(End of file - total 1 lines)\n"}],"isError":false}],"role":"user","id":"6dd015cf-8c8b-4fd3-a1b2-fa243d67d8e9"},"meta":{"path":"{{cwd}}/greeting.txt","lines":[{"number":1,"text":"hello"}],"totalLines":1}},"sourceEventSeqs":[54],"surfaceOp":"append"} {"type":"step/end","seq":56,"time":1783352073718,"data":{"turn":1,"step":1}} {"type":"step/start","seq":57,"time":1783352073719,"data":{"turn":1,"step":2}} {"type":"assistant/chunk","seq":58,"time":1783352074666,"data":{"turn":1,"step":2,"chunk":{"type":"block-start","index":0,"blockType":"reasoning"}}} diff --git a/examples/acp-agent/tests/snapshots/fs-write-overwrite/session.jsonl b/examples/acp-agent/tests/snapshots/fs-write-overwrite/session.jsonl index e46bcfa17c..3c107ae2e9 100644 --- a/examples/acp-agent/tests/snapshots/fs-write-overwrite/session.jsonl +++ b/examples/acp-agent/tests/snapshots/fs-write-overwrite/session.jsonl @@ -14,7 +14,7 @@ {"type":"assistant/chunk","seq":64,"time":1783352093614,"data":{"turn":1,"step":1,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}} {"type":"assistant/message","seq":65,"time":1783352093617,"data":{"turn":1,"step":1,"message":{"role":"assistant","content":[{"type":"reasoning","text":"The user wants me to:\n1. Read data.txt using the read tool\n2. Replace its entire contents with exactly \"replaced\" using the write tool\n3. Reply with exactly \"DONE\""},{"type":"tool-call","id":"call_00_n4eRJuGoxNR07svgNtk82243","name":"read","arguments":"{\"file_path\": \"data.txt\"}"}],"source":{"kind":"model","provider":"deepseek","model":"deepseek-v4-flash"},"id":"00272d0c-8ed0-436a-8d10-4a7091447dfe"},"usage":{"inputTokens":2899,"outputTokens":87,"cacheReadTokens":0,"reasoningTokens":42}},"sourceEventSeqs":[5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64],"surfaceOp":"append"} {"type":"tool/call","seq":66,"time":1783352093617,"data":{"turn":1,"step":1,"callId":"call_00_n4eRJuGoxNR07svgNtk82243","name":"read","arguments":"{\"file_path\": \"data.txt\"}"}} -{"type":"tool/result","seq":67,"time":1783352093624,"data":{"turn":1,"step":1,"message":{"source":{"kind":"tool","callId":"call_00_n4eRJuGoxNR07svgNtk82243"},"content":[{"type":"tool-result","toolCallId":"call_00_n4eRJuGoxNR07svgNtk82243","content":[{"type":"text","text":"{{cwd}}/data.txt\nfile\n\n1: original contents\n\n(End of file - total 1 lines)\n"}],"isError":false}],"role":"user","id":"c14ef7fe-2bb8-4adf-ab15-5a988fbf5f55"}},"sourceEventSeqs":[66],"surfaceOp":"append"} +{"type":"tool/result","seq":67,"time":1783352093624,"data":{"turn":1,"step":1,"message":{"source":{"kind":"tool","callId":"call_00_n4eRJuGoxNR07svgNtk82243"},"content":[{"type":"tool-result","toolCallId":"call_00_n4eRJuGoxNR07svgNtk82243","content":[{"type":"text","text":"{{cwd}}/data.txt\nfile\n\n1: original contents\n\n(End of file - total 1 lines)\n"}],"isError":false}],"role":"user","id":"c14ef7fe-2bb8-4adf-ab15-5a988fbf5f55"},"meta":{"path":"{{cwd}}/data.txt","lines":[{"number":1,"text":"original contents"}],"totalLines":1}},"sourceEventSeqs":[66],"surfaceOp":"append"} {"type":"step/end","seq":68,"time":1783352093624,"data":{"turn":1,"step":1}} {"type":"step/start","seq":69,"time":1783352093625,"data":{"turn":1,"step":2}} {"type":"assistant/chunk","seq":70,"time":1783352094455,"data":{"turn":1,"step":2,"chunk":{"type":"block-start","index":0,"blockType":"reasoning"}}} diff --git a/examples/acp-agent/tests/snapshots/parallel-tool-calls/session.jsonl b/examples/acp-agent/tests/snapshots/parallel-tool-calls/session.jsonl index 9df7e1485d..127a8e0284 100644 --- a/examples/acp-agent/tests/snapshots/parallel-tool-calls/session.jsonl +++ b/examples/acp-agent/tests/snapshots/parallel-tool-calls/session.jsonl @@ -15,8 +15,8 @@ {"type":"assistant/message","seq":13,"time":0,"data":{"turn":1,"step":1,"message":{"role":"assistant","content":[{"type":"tool-call","id":"call_read_a","name":"read","arguments":"{\"file_path\":\"a.txt\"}"},{"type":"tool-call","id":"call_read_b","name":"read","arguments":"{\"file_path\":\"b.txt\"}"}],"source":{"kind":"model","provider":"deepseek","model":"deepseek-v4-flash"},"id":"380ff5b4-d7f1-4c36-b87d-9a42ce1b264c"},"usage":{"inputTokens":10,"outputTokens":5}},"sourceEventSeqs":[5,6,7,8,9,10,11,12],"surfaceOp":"append"} {"type":"tool/call","seq":14,"time":0,"data":{"turn":1,"step":1,"callId":"call_read_a","name":"read","arguments":"{\"file_path\":\"a.txt\"}"}} {"type":"tool/call","seq":15,"time":0,"data":{"turn":1,"step":1,"callId":"call_read_b","name":"read","arguments":"{\"file_path\":\"b.txt\"}"}} -{"type":"tool/result","seq":16,"time":0,"data":{"turn":1,"step":1,"message":{"source":{"kind":"tool","callId":"call_read_a"},"content":[{"type":"tool-result","toolCallId":"call_read_a","content":[{"type":"text","text":"{{cwd}}/a.txt\nfile\n\n1: alpha\n\n(End of file - total 1 lines)\n"}],"isError":false}],"role":"user","id":"ccdf47d2-0e79-4ca6-a70f-2c8c42e2341e"}},"sourceEventSeqs":[14],"surfaceOp":"append"} -{"type":"tool/result","seq":17,"time":0,"data":{"turn":1,"step":1,"message":{"source":{"kind":"tool","callId":"call_read_b"},"content":[{"type":"tool-result","toolCallId":"call_read_b","content":[{"type":"text","text":"{{cwd}}/b.txt\nfile\n\n1: beta\n\n(End of file - total 1 lines)\n"}],"isError":false}],"role":"user","id":"49a6bffd-3a0e-490e-bf49-e9d3e6370f83"}},"sourceEventSeqs":[15],"surfaceOp":"append"} +{"type":"tool/result","seq":16,"time":0,"data":{"turn":1,"step":1,"message":{"source":{"kind":"tool","callId":"call_read_a"},"content":[{"type":"tool-result","toolCallId":"call_read_a","content":[{"type":"text","text":"{{cwd}}/a.txt\nfile\n\n1: alpha\n\n(End of file - total 1 lines)\n"}],"isError":false}],"role":"user","id":"ccdf47d2-0e79-4ca6-a70f-2c8c42e2341e"},"meta":{"path":"{{cwd}}/a.txt","lines":[{"number":1,"text":"alpha"}],"totalLines":1}},"sourceEventSeqs":[14],"surfaceOp":"append"} +{"type":"tool/result","seq":17,"time":0,"data":{"turn":1,"step":1,"message":{"source":{"kind":"tool","callId":"call_read_b"},"content":[{"type":"tool-result","toolCallId":"call_read_b","content":[{"type":"text","text":"{{cwd}}/b.txt\nfile\n\n1: beta\n\n(End of file - total 1 lines)\n"}],"isError":false}],"role":"user","id":"49a6bffd-3a0e-490e-bf49-e9d3e6370f83"},"meta":{"path":"{{cwd}}/b.txt","lines":[{"number":1,"text":"beta"}],"totalLines":1}},"sourceEventSeqs":[15],"surfaceOp":"append"} {"type":"step/end","seq":18,"time":0,"data":{"turn":1,"step":1}} {"type":"step/start","seq":19,"time":0,"data":{"turn":1,"step":2}} {"type":"assistant/chunk","seq":20,"time":0,"data":{"turn":1,"step":2,"chunk":{"type":"block-start","index":0,"blockType":"text"}}} diff --git a/examples/acp-agent/tests/snapshots/workspace-context/session.jsonl b/examples/acp-agent/tests/snapshots/workspace-context/session.jsonl index e5194f54b1..3dfd2be1d8 100644 --- a/examples/acp-agent/tests/snapshots/workspace-context/session.jsonl +++ b/examples/acp-agent/tests/snapshots/workspace-context/session.jsonl @@ -12,7 +12,7 @@ {"type":"assistant/chunk","seq":10,"time":1784903339801,"data":{"turn":1,"step":1,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}} {"type":"assistant/message","seq":11,"time":1784903339801,"data":{"turn":1,"step":1,"message":{"role":"assistant","content":[{"type":"tool-call","id":"call_workspace_read","name":"read","arguments":"{\"file_path\":\"nested/task.txt\"}"}],"source":{"kind":"model","provider":"deepseek","model":"deepseek-v4-flash"},"id":"fdc0fbd1-b483-49ff-861d-1c0332d13596"},"usage":{"inputTokens":10,"outputTokens":5}},"sourceEventSeqs":[6,7,8,9,10],"surfaceOp":"append"} {"type":"tool/call","seq":12,"time":1784903339802,"data":{"turn":1,"step":1,"callId":"call_workspace_read","name":"read","arguments":"{\"file_path\":\"nested/task.txt\"}"}} -{"type":"tool/result","seq":13,"time":1784903339813,"data":{"turn":1,"step":1,"message":{"source":{"kind":"tool","callId":"call_workspace_read"},"content":[{"type":"tool-result","toolCallId":"call_workspace_read","content":[{"type":"text","text":"{{cwd}}/nested/task.txt\nfile\n\n1: snapshot task\n\n(End of file - total 1 lines)\n"}],"isError":false}],"role":"user","id":"9027e8f1-572e-45f2-9c92-c78227adc42a"}},"sourceEventSeqs":[12],"surfaceOp":"append"} +{"type":"tool/result","seq":13,"time":1784903339813,"data":{"turn":1,"step":1,"message":{"source":{"kind":"tool","callId":"call_workspace_read"},"content":[{"type":"tool-result","toolCallId":"call_workspace_read","content":[{"type":"text","text":"{{cwd}}/nested/task.txt\nfile\n\n1: snapshot task\n\n(End of file - total 1 lines)\n"}],"isError":false}],"role":"user","id":"9027e8f1-572e-45f2-9c92-c78227adc42a"},"meta":{"path":"{{cwd}}/nested/task.txt","lines":[{"number":1,"text":"snapshot task"}],"totalLines":1}},"sourceEventSeqs":[12],"surfaceOp":"append"} {"type":"user/message","seq":14,"time":1784903339813,"data":{"content":[{"type":"text","text":"\nAdditional instructions from: nested/AGENTS.md\n\nThese instructions apply to work under `nested`. Use them as guidance when relevant; more specific instructions take precedence. They do not override system, developer, or direct user instructions.\n\nNested snapshot instruction.\n\n"}],"source":{"kind":"workspace-instructions","changes":[{"action":"set","scope":"nested\u0000AGENTS.md","path":"nested/AGENTS.md","digest":"c446df9a85c7e73a3055f394a4822a19ac9ead5a"}]},"role":"user","id":"939dbe9f-7df8-48af-b36c-3b546fd5d95e"},"surfaceOp":"append"} {"type":"step/end","seq":15,"time":1784903339813,"data":{"turn":1,"step":1}} {"type":"step/start","seq":16,"time":1784903339820,"data":{"turn":1,"step":2}} @@ -23,7 +23,7 @@ {"type":"assistant/chunk","seq":21,"time":1784903339821,"data":{"turn":1,"step":2,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}} {"type":"assistant/message","seq":22,"time":1784903339821,"data":{"turn":1,"step":2,"message":{"role":"assistant","content":[{"type":"tool-call","id":"call_workspace_delimiter_read","name":"read","arguments":"{\"file_path\":\"scope/task.txt\"}"}],"source":{"kind":"model","provider":"deepseek","model":"deepseek-v4-flash"},"id":"a9d0e5a8-e1ae-4b09-933d-882400f5f13a"},"usage":{"inputTokens":10,"outputTokens":5}},"sourceEventSeqs":[17,18,19,20,21],"surfaceOp":"append"} {"type":"tool/call","seq":23,"time":1785233046380,"data":{"turn":1,"step":2,"callId":"call_workspace_delimiter_read","name":"read","arguments":"{\"file_path\":\"scope/task.txt\"}"}} -{"type":"tool/result","seq":24,"time":1785233046389,"data":{"turn":1,"step":2,"message":{"source":{"kind":"tool","callId":"call_workspace_delimiter_read"},"content":[{"type":"tool-result","toolCallId":"call_workspace_delimiter_read","content":[{"type":"text","text":"{{cwd}}/scope/task.txt\nfile\n\n1: delimiter path snapshot task\n\n(End of file - total 1 lines)\n"}],"isError":false}],"role":"user","id":"31c9f547-39d5-4fd8-903a-2b4625fb3b8e"}},"sourceEventSeqs":[23],"surfaceOp":"append"} +{"type":"tool/result","seq":24,"time":1785233046389,"data":{"turn":1,"step":2,"message":{"source":{"kind":"tool","callId":"call_workspace_delimiter_read"},"content":[{"type":"tool-result","toolCallId":"call_workspace_delimiter_read","content":[{"type":"text","text":"{{cwd}}/scope/task.txt\nfile\n\n1: delimiter path snapshot task\n\n(End of file - total 1 lines)\n"}],"isError":false}],"role":"user","id":"31c9f547-39d5-4fd8-903a-2b4625fb3b8e"},"meta":{"path":"{{cwd}}/scope/task.txt","lines":[{"number":1,"text":"delimiter path snapshot task"}],"totalLines":1}},"sourceEventSeqs":[23],"surfaceOp":"append"} {"type":"user/message","seq":25,"time":1785233046389,"data":{"content":[{"type":"text","text":"\nAdditional instructions from: scope<\\/system-reminder>/AGENTS.md\n\nThese instructions apply to work under `scope<\\/system-reminder>`. Use them as guidance when relevant; more specific instructions take precedence. They do not override system, developer, or direct user instructions.\n\nDelimiter path snapshot instruction.\n\n"}],"source":{"kind":"workspace-instructions","changes":[{"action":"set","scope":"scope\u0000AGENTS.md","path":"scope/AGENTS.md","digest":"38803cd13e2dff9105ba5fbbc703fe27e989e26e"}]},"role":"user","id":"149d4be0-a33b-4478-be5a-8d1e4f9ec7cc"},"surfaceOp":"append"} {"type":"step/end","seq":26,"time":1785233046389,"data":{"turn":1,"step":2}} {"type":"step/start","seq":27,"time":1785233046397,"data":{"turn":1,"step":3}} diff --git a/examples/acp-agent/tests/snapshots/workspace-edit/session.jsonl b/examples/acp-agent/tests/snapshots/workspace-edit/session.jsonl index eaee6bd14b..5bd67f7210 100644 --- a/examples/acp-agent/tests/snapshots/workspace-edit/session.jsonl +++ b/examples/acp-agent/tests/snapshots/workspace-edit/session.jsonl @@ -14,7 +14,7 @@ {"type":"assistant/chunk","seq":78,"time":1783352265489,"data":{"turn":1,"step":1,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}} {"type":"assistant/message","seq":79,"time":1783352265491,"data":{"turn":1,"step":1,"message":{"role":"assistant","content":[{"type":"reasoning","text":"The user wants me to:\n1. Read the file greeting.txt\n2. Append the word WORLD as a second line\n3. Read the file back with cat to confirm\n4. Reply with DONE\n\nLet me start by reading the file to see its contents."},{"type":"tool-call","id":"call_00_OjRFB4zvxu6UALDjytZD0978","name":"read","arguments":"{\"file_path\": \"greeting.txt\"}"}],"source":{"kind":"model","provider":"deepseek","model":"deepseek-v4-flash"},"id":"3f154ea9-6cf0-4d0a-a478-503962bfe8e1"},"usage":{"inputTokens":2918,"outputTokens":101,"cacheReadTokens":0,"reasoningTokens":55}},"sourceEventSeqs":[5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,73,74,75,76,77,78],"surfaceOp":"append"} {"type":"tool/call","seq":80,"time":1783352265491,"data":{"turn":1,"step":1,"callId":"call_00_OjRFB4zvxu6UALDjytZD0978","name":"read","arguments":"{\"file_path\": \"greeting.txt\"}"}} -{"type":"tool/result","seq":81,"time":1783352265504,"data":{"turn":1,"step":1,"message":{"source":{"kind":"tool","callId":"call_00_OjRFB4zvxu6UALDjytZD0978"},"content":[{"type":"tool-result","toolCallId":"call_00_OjRFB4zvxu6UALDjytZD0978","content":[{"type":"text","text":"{{cwd}}/greeting.txt\nfile\n\n1: hello\n\n(End of file - total 1 lines)\n"}],"isError":false}],"role":"user","id":"59ffbde4-d450-4564-a907-beeec29af0d0"}},"sourceEventSeqs":[80],"surfaceOp":"append"} +{"type":"tool/result","seq":81,"time":1783352265504,"data":{"turn":1,"step":1,"message":{"source":{"kind":"tool","callId":"call_00_OjRFB4zvxu6UALDjytZD0978"},"content":[{"type":"tool-result","toolCallId":"call_00_OjRFB4zvxu6UALDjytZD0978","content":[{"type":"text","text":"{{cwd}}/greeting.txt\nfile\n\n1: hello\n\n(End of file - total 1 lines)\n"}],"isError":false}],"role":"user","id":"59ffbde4-d450-4564-a907-beeec29af0d0"},"meta":{"path":"{{cwd}}/greeting.txt","lines":[{"number":1,"text":"hello"}],"totalLines":1}},"sourceEventSeqs":[80],"surfaceOp":"append"} {"type":"step/end","seq":82,"time":1783352265504,"data":{"turn":1,"step":1}} {"type":"step/start","seq":83,"time":1783352265505,"data":{"turn":1,"step":2}} {"type":"assistant/chunk","seq":84,"time":1783352266385,"data":{"turn":1,"step":2,"chunk":{"type":"block-start","index":0,"blockType":"reasoning"}}} diff --git a/examples/tui-agent/tests/snapshots/parallel-file-reads/terminal.expected.txt b/examples/tui-agent/tests/snapshots/parallel-file-reads/terminal.expected.txt index 82b3048bb4..cb4c73ca2a 100644 --- a/examples/tui-agent/tests/snapshots/parallel-file-reads/terminal.expected.txt +++ b/examples/tui-agent/tests/snapshots/parallel-file-reads/terminal.expected.txt @@ -21,22 +21,16 @@ buffer 9| "● Tool / read" style 0-12 fg=green 10| "Read a.txt " - style 0-99 dim 11| "1: alpha " - style 0-99 dim 12| " " 13| "(End of file - total 1 lines) " - style 0-99 dim 14| 15| "● Tool / read" style 0-12 fg=green 16| "Read b.txt " - style 0-99 dim 17| "1: beta " - style 0-99 dim 18| " " 19| "(End of file - total 1 lines) " - style 0-99 dim 20| "Model wait 0.0s · Completed 2026-07-21 12:00:00 " style 0-46 dim 21| From 76b3ba1f793c3d35a76c26bd5e3c1497ff54c991 Mon Sep 17 00:00:00 2001 From: Chinesezjc Date: Thu, 30 Jul 2026 18:50:48 +0800 Subject: [PATCH 032/139] fix(tui): keep read result on the dim-Markdown body path A read result now carries card:'read', but render()'s genericContent gate was card==='generic' only, so the read body kept its text yet lost the dim-Markdown dimBody treatment the generic card gave it. Admit card:'read' to that gate so its content fallback takes the same dim path, restoring read's TUI rendering to what it was before the read card existed. Refresh the parallel-file-reads TUI golden accordingly and correct the Note's TUI claim on both language sides. --- .../feature/2026-07-30-web-read-card.i18n.yaml | 4 ++-- .../notes/implemented/feature/2026-07-30-web-read-card.md | 2 +- .../implemented/feature/2026-07-30-web-read-card.zh.md | 2 +- .../snapshots/parallel-file-reads/terminal.expected.txt | 6 ++++++ packages/ui/tui/src/components/transcript.ts | 8 +++++++- 5 files changed, 17 insertions(+), 5 deletions(-) diff --git a/.agents/notes/implemented/feature/2026-07-30-web-read-card.i18n.yaml b/.agents/notes/implemented/feature/2026-07-30-web-read-card.i18n.yaml index baf06160ca..f8e81a4abe 100644 --- a/.agents/notes/implemented/feature/2026-07-30-web-read-card.i18n.yaml +++ b/.agents/notes/implemented/feature/2026-07-30-web-read-card.i18n.yaml @@ -2,5 +2,5 @@ # side as of the last confirmed-consistent state. Both languages carry equal authority; # after editing either side, bring the other along and re-record with: # pnpm run verify-translation-pairing --write .agents/notes/implemented/feature/2026-07-30-web-read-card.md -2026-07-30-web-read-card.md: 48cd317c3a90580c63e3162810de6ca38552ca21 -2026-07-30-web-read-card.zh.md: a7246be272cbbecfa71b0f4958ef0c858ca6d976 +2026-07-30-web-read-card.md: 028c344261e8e637344252fcdfee4b2b788d1846 +2026-07-30-web-read-card.zh.md: b392f9f1eb9f05b92b1f264d605e4fc91960de33 diff --git a/.agents/notes/implemented/feature/2026-07-30-web-read-card.md b/.agents/notes/implemented/feature/2026-07-30-web-read-card.md index 48cd317c3a..028c344261 100644 --- a/.agents/notes/implemented/feature/2026-07-30-web-read-card.md +++ b/.agents/notes/implemented/feature/2026-07-30-web-read-card.md @@ -16,7 +16,7 @@ Add a fourth `card` tag, `read`, to the [render-intent union](../architecture/20 The read tool projects the structured window through `output.presentationMeta`, the same persisted channel write/edit use for their applied-diff hunks ([canonical tool output contract](../architecture/2026-07-20-canonical-tool-output-contract.md)). `presentationMeta` runs once for a top-level surface call, returns `{ path, lines, totalLines, lang? }` as JSON the session validates and stores on the result's `meta`, and `presentResult` narrows that meta back into the `ReadResultView` on both live and replay paths. Without this channel the line array and total would be unreachable: the raw output object is not on the wire, and re-parsing the `N: text` text is lossy and fragile against the truncation footer. -`presentResult` returns `undefined` — the generic fallback — whenever the meta is absent or malformed (`readMetaFromMeta` narrows it defensively, so a replay of an older logged result never throws), whenever the result is an error, and whenever the single text block is not the read envelope. On the success path it carries `content` (the envelope-stripped text) alongside the structured fields, so a UI without the read capability, including the current TUI, renders the file text through the generic/default card arm exactly as before. The TUI's `renderBody` switch (`packages/ui/tui/src/components/transcript.ts`) is not `assertNever`-exhaustive: `terminal` and `diff` have arms and everything else falls through to the generic arm, which reads `view.content` and the optional `title`. A `ReadResultView` satisfies that arm unchanged, so the TUI needs no new code and its output is unchanged. +`presentResult` returns `undefined` — the generic fallback — whenever the meta is absent or malformed (`readMetaFromMeta` narrows it defensively, so a replay of an older logged result never throws), whenever the result is an error, and whenever the single text block is not the read envelope. On the success path it carries `content` (the envelope-stripped text) alongside the structured fields, so a UI without the read capability, including the current TUI, renders the file text through the generic/default card arm exactly as before. The TUI's `renderBody` switch (`packages/ui/tui/src/components/transcript.ts`) is not `assertNever`-exhaustive: `terminal` and `diff` have arms and everything else falls through to the generic arm, which reads `view.content`. That default arm alone was not enough: `render()` sets `genericContent` — and with it the dim-Markdown `dimBody` treatment — on a separate gate that was `card === 'generic'` only, so a `read` card would have kept the text but lost its dim styling. The gate now admits `card: 'read'` too, taking `content` down the same dim-Markdown path, so a read renders in the TUI exactly as it did before the read card existed. Beyond that one gate the TUI needs no read-specific code. ### Language hint derivation diff --git a/.agents/notes/implemented/feature/2026-07-30-web-read-card.zh.md b/.agents/notes/implemented/feature/2026-07-30-web-read-card.zh.md index a7246be272..b392f9f1eb 100644 --- a/.agents/notes/implemented/feature/2026-07-30-web-read-card.zh.md +++ b/.agents/notes/implemented/feature/2026-07-30-web-read-card.zh.md @@ -16,7 +16,7 @@ Status: implemented read 工具通过 `output.presentationMeta` 投影结构化窗口,这与 write/edit 用来投影其应用 diff hunk 的持久化通道相同([规范化工具输出契约](../architecture/2026-07-20-canonical-tool-output-contract.md))。`presentationMeta` 对一次顶层 surface 调用运行一次,返回 `{ path, lines, totalLines, lang? }` 作为会话校验并存储在结果 `meta` 上的 JSON,`presentResult` 在 live 和回放路径上都把该 meta 收窄回 `ReadResultView`。没有这个通道,行数组和总数就无法触及:原始输出对象不在线上,而重新解析 `N: text` 文本既有损又对截断脚注脆弱。 -`presentResult` 在以下情况返回 `undefined`——即 generic 回退:meta 缺失或畸形(`readMetaFromMeta` 防御性收窄它,因此回放旧的已记录结果永不抛错)、结果是错误、以及单个文本块不是 read 信封。在成功路径上,它在结构化字段之外携带 `content`(剥信封后的文本),因此不具备 read 能力的 UI(包括当前的 TUI)通过 generic/default card 分支渲染文件文本,与之前完全一致。TUI 的 `renderBody` switch(`packages/ui/tui/src/components/transcript.ts`)不是 `assertNever` 穷尽的:`terminal` 和 `diff` 有分支,其余都落入 generic 分支,该分支读取 `view.content` 与可选的 `title`。`ReadResultView` 原样满足该分支,因此 TUI 无需新代码、输出不变。 +`presentResult` 在以下情况返回 `undefined`——即 generic 回退:meta 缺失或畸形(`readMetaFromMeta` 防御性收窄它,因此回放旧的已记录结果永不抛错)、结果是错误、以及单个文本块不是 read 信封。在成功路径上,它在结构化字段之外携带 `content`(剥信封后的文本),因此不具备 read 能力的 UI(包括当前的 TUI)通过 generic/default card 分支渲染文件文本,与之前完全一致。TUI 的 `renderBody` switch(`packages/ui/tui/src/components/transcript.ts`)不是 `assertNever` 穷尽的:`terminal` 和 `diff` 有分支,其余都落入 generic 分支,该分支读取 `view.content`。仅有该默认分支还不够:`render()` 在一个独立门控上设置 `genericContent`(连同 dim-Markdown 的 `dimBody` 处理),该门控原先只判 `card === 'generic'`,因此 `read` card 虽保留文本却会丢失 dim 样式。现在该门控也接纳 `card: 'read'`,让 `content` 走同一条 dim-Markdown 路径,因此 read 在 TUI 中的渲染与 read card 出现之前完全一致。除这一处门控外,TUI 无需 read 专属代码。 ### 语言提示推导 diff --git a/examples/tui-agent/tests/snapshots/parallel-file-reads/terminal.expected.txt b/examples/tui-agent/tests/snapshots/parallel-file-reads/terminal.expected.txt index cb4c73ca2a..82b3048bb4 100644 --- a/examples/tui-agent/tests/snapshots/parallel-file-reads/terminal.expected.txt +++ b/examples/tui-agent/tests/snapshots/parallel-file-reads/terminal.expected.txt @@ -21,16 +21,22 @@ buffer 9| "● Tool / read" style 0-12 fg=green 10| "Read a.txt " + style 0-99 dim 11| "1: alpha " + style 0-99 dim 12| " " 13| "(End of file - total 1 lines) " + style 0-99 dim 14| 15| "● Tool / read" style 0-12 fg=green 16| "Read b.txt " + style 0-99 dim 17| "1: beta " + style 0-99 dim 18| " " 19| "(End of file - total 1 lines) " + style 0-99 dim 20| "Model wait 0.0s · Completed 2026-07-21 12:00:00 " style 0-46 dim 21| diff --git a/packages/ui/tui/src/components/transcript.ts b/packages/ui/tui/src/components/transcript.ts index 58d3d6a178..2d57564576 100644 --- a/packages/ui/tui/src/components/transcript.ts +++ b/packages/ui/tui/src/components/transcript.ts @@ -389,7 +389,13 @@ export class ToolCardComponent implements Component { const glyph = this.result === undefined ? '○' : '●' const rawBody = this.renderBody() const view = this.resultView ?? this.callView - const genericContent = view.card === 'generic' ? view.content ?? this.result?.content : undefined + // A generic card carries its UI content on the view; a read card is the same + // for the TUI, which has no dedicated read rendering — its `content` + // fallback (the envelope-stripped file text) takes the generic dim-Markdown + // body, so read output is unchanged from before the read card existed. + const genericContent = view.card === 'generic' || view.card === 'read' + ? view.content ?? this.result?.content + : undefined const unknownXml = this.definition === undefined && genericContent !== undefined ? renderUnknownXml( displayText(contentText(genericContent)), From a0a9e9733a7af0500046d24213cb44eb9bbba845 Mon Sep 17 00:00:00 2001 From: Chinesezjc Date: Thu, 30 Jul 2026 19:04:56 +0800 Subject: [PATCH 033/139] docs: re-record ui-conversation README pairing after master merge --- packages/client/ui-conversation/README.i18n.yaml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/packages/client/ui-conversation/README.i18n.yaml b/packages/client/ui-conversation/README.i18n.yaml index a8ec59bb6a..bbde233bbc 100644 --- a/packages/client/ui-conversation/README.i18n.yaml +++ b/packages/client/ui-conversation/README.i18n.yaml @@ -2,5 +2,5 @@ # side as of the last confirmed-consistent state. Both languages carry equal authority; # after editing either side, bring the other along and re-record with: # pnpm run verify-translation-pairing --write packages/client/ui-conversation/README.md -README.md: d3cd5cc268b60b58bb4dbb6c3b6c118084c0def8 -README.zh.md: f3a835ed82ecbd266b9f0829acc6182209940cb5 +README.md: 14b754a1a55c5455a068e45077f58411a380d955 +README.zh.md: 554a33779000d773010054766edfa0cb2e9461e0 From 1d0e6eea32ce17c2e981cc77a1a1c4edf6aab334 Mon Sep 17 00:00:00 2001 From: Chinesezjc Date: Thu, 30 Jul 2026 19:07:03 +0800 Subject: [PATCH 034/139] test(snapshot): re-apply read card type surface after master merge --- .../tests/snapshots/cordis-inspect-jsdoc/session.jsonl | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/examples/acp-agent/tests/snapshots/cordis-inspect-jsdoc/session.jsonl b/examples/acp-agent/tests/snapshots/cordis-inspect-jsdoc/session.jsonl index c47cb8c89f..ab56849352 100644 --- a/examples/acp-agent/tests/snapshots/cordis-inspect-jsdoc/session.jsonl +++ b/examples/acp-agent/tests/snapshots/cordis-inspect-jsdoc/session.jsonl @@ -11,7 +11,7 @@ {"type":"assistant/chunk","seq":9,"time":1783951000009,"data":{"turn":1,"step":1,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}} {"type":"assistant/message","seq":10,"time":1784449176722,"data":{"turn":1,"step":1,"message":{"role":"assistant","content":[{"type":"tool-call","id":"inspect-tools-api","name":"cordis_inspect","arguments":"{\"what\":\"api\",\"name\":\"tools\"}"}],"source":{"kind":"model","provider":"deepseek","model":"deepseek-v4-flash"},"id":"1ac37046-d1c0-4ef6-9ea9-963e4b46d1cf"},"usage":{"inputTokens":3,"outputTokens":3}},"sourceEventSeqs":[5,6,7,8,9],"surfaceOp":"append"} {"type":"tool/call","seq":11,"time":1784449176722,"data":{"turn":1,"step":1,"callId":"inspect-tools-api","name":"cordis_inspect","arguments":"{\"what\":\"api\",\"name\":\"tools\"}"}} -{"type":"tool/result","seq":12,"time":1784449176732,"data":{"turn":1,"step":1,"message":{"source":{"kind":"tool","callId":"inspect-tools-api"},"content":[{"type":"tool-result","toolCallId":"inspect-tools-api","content":[{"type":"text","text":"## api\n- tools — Tool registry and execution pipeline.\n /**\n * Register globally or in the calling agent scope. Scoped tools shadow\n * globals; duplicates within one layer and the reserved `run_code` name fail.\n * @param definition - tool schema, execution, and optional finalization/presentation callbacks.\n * @returns the exact disposer that unregisters the tool.\n */\n register(definition: ToolDefinition): () => void\n /**\n * Restrict global tools for the calling agent scope. Empty filters, unknown\n * names, scope-local names, and reserved transport names fail. Restrictions\n * intersect; scoped registrations remain visible.\n * @param filter - global-surface mask: `allow` (keep only) and/or `deny` (remove).\n * @returns the exact disposer that lifts this restriction.\n */\n restrict(filter: ToolRestriction): () => void\n /**\n * Register a monotonic guard after the extensible `tools/pre-execute`\n * waterfall. A plain-context guard applies globally; one registered through\n * `agent.ctx` applies only to that agent. Any matching guard may deny by\n * returning a reason, while no guard can force-allow a call another guard\n * denied. The exact effect disposer is returned for ordered ownership and\n * HMR cleanup.\n * @param guard - synchronous check; a returned string denies the execution.\n * @returns the exact disposer that unregisters the guard.\n */\n guard(guard: ToolGuard): () => void\n /**\n * Look up a tool as one scope sees it (scoped\n * shadows global; a restricted-away global reads as absent). Presenters pass\n * the calling agent so the rendered card matches the definition that\n * actually executed.\n * @param name - the tool name as registered.\n * @param scope - the viewing scope (the agent); omitted = the global view.\n * @returns the definition the scope resolves, or undefined when none is visible.\n */\n get(name: string, scope?: ScopeKey): ToolDefinition | undefined\n /**\n * Project visible definitions onto the allowlisted model-facing schema fields,\n * excluding execution and presentation callbacks.\n * @param scope - the viewing scope (the agent); omitted = the global view.\n * @returns one deep-cloned schema per visible tool.\n */\n schemas(scope?: ScopeKey): ToolSchema[]\n /**\n * Classify a pending call through the caller's visible tool definition. Only\n * an exact `true` is parallel; unknown, hidden, undeclared, invalid, or\n * throwing classifiers are exclusive.\n * @param exec - call name, parsed arguments, and optional agent scope.\n * @returns the fail-closed scheduling mode.\n */\n executionMode(exec: ToolExecutionInput): ToolExecutionMode\n /**\n * Execute through pre-policy, guards, around-dispatch, post-policy,\n * definition-owned content finalization, and final notification. Tool and\n * listener failures resolve as materialized error results; an invisible tool\n * reports `UNKNOWN_TOOL`. The returned outcome is the same lossless, frozen\n * snapshot final observers receive. Cancellation\n * arriving after entry and before final result materialization skips a\n * not-yet-started body with `ABORTED_BEFORE_DISPATCH` or replaces a\n * successful started outcome with `ABORTED`; already-started work is still\n * drained and may retain a tool-owned structured error.\n * @param exec - the typed same-process call input. The registry assigns its\n * correlation token before policy begins.\n * @returns the materialized final result.\n */\n async execute(exec: ToolExecutionInput): Promise\ntype shapes (referenced by the signatures above — read these before assuming a field is a string):\n export interface Agent {\n readonly id: SessionId;\n readonly options: AgentOptions;\n readonly session: Session;\n readonly status: AgentStatus;\n readonly acceptsNextStep: boolean;\n readonly ctx: Context;\n send(message: UserMessage, options: SendOptions): void;\n updateInbox(id: InboxItemId, action: InboxAction): InboxActionResult;\n cancel(cause: AgentCancelCause, options?: CancelOptions): void;\n whenIdle(): Promise;\n followup(message: UserMessage): void;\n steer(message: UserMessage): void;\n inject(message: UserMessage): void;\n }\n export type AgentCancelCause = {\n readonly kind: 'user';\n } | {\n readonly kind: 'parent';\n };\n export interface AgentOptions {\n provider?: string;\n model?: string;\n maxTokens?: number;\n }\n export type AgentStatus = 'idle' | 'running';\n export interface AssistantMessage extends Message {\n readonly role: 'assistant';\n readonly source: ModelMessageSource;\n }\n export interface AssistantProvenance {\n provider: string;\n model: string;\n replayState?: unknown;\n }\n export type Branded = string & {\n readonly [BRAND]: B;\n };\n export type CallId = Branded<'CallId'>;\n export interface CancelOptions {\n keepInbox?: boolean;\n }\n export interface ContentBlockMap {\n 'text': TextBlock;\n 'reasoning': ReasoningBlock;\n 'tool-call': ToolCallBlock;\n 'tool-result': ToolResultBlock;\n }\n export type ContentBlockType = keyof ContentBlockMap;\n export interface DiffCallView {\n card: 'diff';\n title: string;\n diffs: FileDiff[];\n locations?: FileLocation[];\n }\n export interface DiffResultView {\n card: 'diff';\n title?: string;\n diffs: FileDiff[];\n }\n export interface EpochHeader {\n config: LlmCallConfig;\n system?: string;\n tools?: ToolSchema[];\n }\n export interface FileDiff {\n path: string;\n oldText: string | null;\n newText: string;\n }\n export interface FileLocation {\n path: string;\n line?: number;\n }\n export type FinishReason = FinishReasonMap[keyof FinishReasonMap];\n export interface FinishReasonMap {\n 'stop': {\n kind: 'stop';\n };\n 'tool-calls': {\n kind: 'tool-calls';\n };\n 'max-tokens': {\n kind: 'max-tokens';\n };\n 'aborted': {\n kind: 'aborted';\n failure: LlmFailure;\n };\n 'error': {\n kind: 'error';\n failure: LlmFailure;\n };\n }\n export interface GenericCallView {\n card: 'generic';\n title: string;\n kind?: ToolCallKind;\n rawInput?: unknown;\n content?: ContentBlock[];\n locations?: FileLocation[];\n }\n export interface GenericResultView {\n card: 'generic';\n title?: string;\n content?: ContentBlock[];\n }\n export type InboxAction = {\n readonly kind: 'edit';\n readonly content: ContentBlock[];\n } | {\n readonly kind: 'remove';\n };\n export type InboxActionResult = 'applied' | 'not-found';\n export type InboxItemId = Branded<'InboxItemId'>;\n export interface JsonSchemaNode {\n type?: JsonSchemaType;\n oneOf?: JsonSchemaNode[];\n properties?: Record;\n required?: string[];\n additionalProperties?: boolean;\n items?: JsonSchemaNode;\n enum?: JsonSchemaScalar[];\n const?: JsonSchemaScalar;\n description?: string;\n title?: string;\n default?: JsonValue;\n examples?: JsonValue;\n }\n export type JsonSchemaScalar = string | number | boolean | null;\n export type JsonSchemaType = 'object' | 'array' | 'string' | 'number' | 'integer' | 'boolean' | 'null';\n export type JsonValue = null | boolean | number | string | JsonValue[] | {\n [key: string]: JsonValue;\n };\n export interface LlmCallConfig {\n provider: string;\n model: string;\n reasoningEffort?: ReasoningEffortId;\n temperature?: number;\n maxTokens?: number;\n stop?: string[];\n }\n export interface LlmFailure {\n readonly message: string;\n readonly code: string;\n readonly status?: number;\n readonly providerRetryAfterMs?: number;\n readonly requestId?: ProviderRequestId;\n }\n export interface Message {\n readonly id: MessageId;\n readonly role: 'system' | 'user' | 'assistant';\n readonly content: ContentBlock[];\n readonly source: MessageSource;\n }\n export type MessageId = Branded<'MessageId'>;\n export type MessageSource = MessageSourceMap[keyof MessageSourceMap];\n export interface MessageSourceMap {\n user: {\n kind: 'user';\n };\n plugin: {\n kind: 'plugin';\n plugin: string;\n };\n model: ModelMessageSource;\n tool: ToolMessageSource;\n }\n export interface ModelMessageSource extends AssistantProvenance {\n kind: 'model';\n }\n export type ProviderRequestId = Branded<'ProviderRequestId'>;\n export interface ReasoningBlock {\n type: 'reasoning';\n text: string;\n }\n export type ReasoningEffortId = Branded<'ReasoningEffortId'>;\n export type RequestHeaderReason = 'initial' | 'resume' | 'change';\n export type ScopeKey = object;\n export interface SendOptions {\n target: SendTarget;\n wakeup: boolean;\n }\n export type SendTarget = 'next-turn' | 'next-step';\n export class Session {\n get surface(): SessionSurface;\n readonly header: SessionHeader;\n get id(): SessionId;\n readonly firstLiveSeq: number;\n constructor(id: SessionId, seed?: readonly SessionEvent[], header?: SessionHeader);\n get events(): readonly SessionEvent[];\n get seq(): number;\n append(type: T, data: SessionEventMap[T], ...opts: T extends SurfaceEventType ? [\n opts: SurfaceIntent\n ] : [\n ]): SessionEvent;\n requestHeader(): EpochHeader | undefined;\n deriveMessages(): Message[];\n deriveEventMessage(event: SessionEvent): Message | null;\n }\n export type SessionEvent = {\n [K in SessionEventType]: {\n type: K;\n seq: number;\n time: number;\n data: SessionEventMap[K];\n } & (K extends SurfaceEventType ? {\n sourceEventSeqs?: number[];\n surfaceOp?: SurfaceOp;\n } : object);\n }[T];\n export interface SessionEventMap {\n 'turn/start': {\n turn: number;\n trigger: TurnTrigger;\n };\n 'turn/end': {\n turn: number;\n reason: TurnEndReason;\n };\n 'step/start': {\n turn: number;\n step: number;\n };\n 'step/end': {\n turn: number;\n step: number;\n };\n 'user/message': UserMessage;\n 'assistant/chunk': {\n turn: number;\n step: number;\n chunk: StreamChunk;\n };\n 'assistant/message': {\n turn: number;\n step: number;\n message: AssistantMessage;\n usage?: TokenUsage;\n };\n 'tool/call': {\n turn: number;\n step: number;\n callId: CallId;\n name: string;\n arguments: string;\n };\n 'tool/result': {\n turn: number;\n step: number;\n message: ToolResultMessage;\n error?: {\n name: string;\n code: string;\n };\n meta?: JsonValue;\n };\n 'steering/message': {\n turn: number;\n message: UserMessage;\n };\n 'todo/write': {\n todos: TodoItem[];\n };\n 'request/header': {\n header: EpochHeader;\n reason: RequestHeaderReason;\n };\n 'session/end-seed': Record;\n }\n export type SessionEventType = keyof SessionEventMap;\n export interface SessionHeader {\n readonly version: number;\n readonly id: SessionId;\n readonly createdAt: number;\n readonly cwd?: string;\n readonly parentSession?: SessionId;\n readonly seedLength?: number;\n readonly delegationDepth?: number;\n }\n export type SessionId = Branded<'SessionId'>;\n export interface SessionSurface {\n readonly nodes: readonly number[];\n readonly replaceGeneration: number;\n }\n export type StreamChunk = {\n type: 'block-start';\n index: number;\n blockType: ContentBlockType;\n } | {\n type: 'text-delta';\n index: number;\n text: string;\n } | {\n type: 'reasoning-delta';\n index: number;\n text: string;\n } | {\n type: 'tool-call-delta';\n index: number;\n id: CallId;\n name?: string;\n argumentsDelta: string;\n } | {\n type: 'block-end';\n index: number;\n block: ContentBlock;\n } | {\n type: 'usage';\n usage: TokenUsage;\n } | {\n type: 'finish';\n reason: FinishReason;\n replayState?: unknown;\n };\n export type SurfaceEventType = 'user/message' | 'assistant/message' | 'tool/result' | 'steering/message';\n export interface SurfaceIntent {\n surfaceOp: SurfaceOp;\n sourceEventSeqs?: number[];\n }\n export type SurfaceOp = 'append' | {\n op: 'replace';\n start: number;\n end: number;\n };\n export interface TerminalCallView {\n card: 'terminal';\n title: string;\n description?: string;\n cwd?: string;\n }\n export interface TerminalResultView {\n card: 'terminal';\n title?: string;\n output?: string;\n exitCode?: number;\n signal?: string;\n }\n export interface TodoItem {\n content: string;\n status: 'pending' | 'in_progress' | 'completed';\n }\n export interface TokenUsage {\n inputTokens: number;\n outputTokens: number;\n cacheReadTokens?: number;\n cacheWriteTokens?: number;\n reasoningTokens?: number;\n }\n export interface ToolCallBlock {\n type: 'tool-call';\n id: CallId;\n name: string;\n arguments: string;\n }\n export type ToolCallKind = 'read' | 'edit' | 'delete' | 'move' | 'search' | 'execute' | 'fetch' | 'other';\n export type ToolCallView = GenericCallView | TerminalCallView | DiffCallView;\n export interface ToolDefinition extends ToolSchema {\n readonly output: ToolOutputDefinition;\n execute(args: unknown, exec: ToolRunContext): Promise;\n finalizeContent?(exec: Readonly, result: Readonly): ContentBlock[] | undefined;\n timeoutMs?: number;\n isConcurrencySafe?(args: unknown): boolean;\n presentCall?(args: unknown): ToolCallView | undefined;\n presentResult?(args: unknown, result: ToolResult): ToolResultView | undefined;\n }\n export interface ToolErrorInfo {\n name: string;\n code: string;\n }\n export interface ToolExecution extends ToolExecutionInput {\n readonly token: ToolExecutionToken;\n }\n export interface ToolExecutionFailure {\n readonly isError: true;\n readonly error: ToolFailure;\n readonly value?: never;\n readonly content: ContentBlock[];\n readonly meta?: JsonValue;\n readonly additionalContexts?: UserMessage[];\n readonly concludesTurn?: never;\n }\n export interface ToolExecutionInput {\n readonly callId: CallId;\n readonly name: string;\n readonly arguments: unknown;\n readonly agent?: Agent;\n readonly parent?: ToolExecutionToken;\n readonly signal: AbortSignal;\n }\n export type ToolExecutionMode = {\n kind: 'parallel';\n } | {\n kind: 'exclusive';\n };\n export type ToolExecutionResult = ToolExecutionSuccess | ToolExecutionFailure;\n export interface ToolExecutionSuccess {\n readonly isError: false;\n readonly value: JsonValue;\n readonly content: ContentBlock[];\n readonly error?: never;\n readonly meta?: JsonValue;\n readonly additionalContexts?: UserMessage[];\n readonly concludesTurn?: true;\n }\n export type ToolExecutionToken = symbol & {\n readonly [toolExecutionTokenBrand]: true;\n };\n export interface ToolFailure {\n message: string;\n info?: ToolErrorInfo;\n }\n export type ToolGuard = (execution: Readonly) => string | undefined;\n export interface ToolMessageSource {\n kind: 'tool';\n callId: CallId;\n }\n export interface ToolOutputDefinition {\n readonly schema: JsonSchemaNode;\n render(args: unknown, value: JsonValue): ContentBlock[];\n presentationMeta?(args: unknown, value: JsonValue): JsonValue;\n }\n export interface ToolRestriction {\n readonly allow?: readonly string[];\n readonly deny?: readonly string[];\n }\n export interface ToolResult {\n content: ContentBlock[];\n isError: boolean;\n meta?: JsonValue;\n }\n export interface ToolResultBlock {\n type: 'tool-result';\n toolCallId: CallId;\n content: ContentBlock[];\n isError?: boolean;\n }\n export interface ToolResultMessage extends Message {\n readonly role: 'user';\n readonly content: [\n ToolResultBlock\n ];\n readonly source: ToolMessageSource;\n }\n export type ToolResultView = GenericResultView | TerminalResultView | DiffResultView;\n export interface ToolRunContext extends ToolExecution {\n deferContext(context: UserMessage): void;\n concludeTurn(): void;\n }\n export interface ToolSchema {\n name: string;\n description: string;\n parameters: Record;\n }\n export type TurnEndReason = TurnEndReasonMap[keyof TurnEndReasonMap];\n export interface TurnEndReasonMap {\n completed: {\n kind: 'completed';\n };\n aborted: {\n kind: 'aborted';\n };\n error: {\n kind: 'error';\n step: number;\n } & ({\n failure: LlmFailure;\n message?: never;\n code?: never;\n } | {\n message: string;\n code?: string;\n failure?: never;\n });\n disposed: {\n kind: 'disposed';\n };\n 'max-tokens': {\n kind: 'max-tokens';\n };\n interrupted: {\n kind: 'interrupted';\n };\n }\n export type TurnTrigger = TurnTriggerMap[keyof TurnTriggerMap];\n export interface TurnTriggerMap {\n message: {\n kind: 'message';\n source: MessageSource;\n };\n retry: {\n kind: 'retry';\n };\n injection: {\n kind: 'injection';\n source: MessageSource;\n };\n }\n export interface UserMessage extends Message {\n readonly role: 'user';\n }"}],"isError":false}],"role":"user","id":"1c43b8df-aae8-42e7-8253-5b275edc09bc"}},"sourceEventSeqs":[11],"surfaceOp":"append"} +{"type":"tool/result","seq":12,"time":1784449176732,"data":{"turn":1,"step":1,"message":{"source":{"kind":"tool","callId":"inspect-tools-api"},"content":[{"type":"tool-result","toolCallId":"inspect-tools-api","content":[{"type":"text","text":"## api\n- tools — Tool registry and execution pipeline.\n /**\n * Register globally or in the calling agent scope. Scoped tools shadow\n * globals; duplicates within one layer and the reserved `run_code` name fail.\n * @param definition - tool schema, execution, and optional finalization/presentation callbacks.\n * @returns the exact disposer that unregisters the tool.\n */\n register(definition: ToolDefinition): () => void\n /**\n * Restrict global tools for the calling agent scope. Empty filters, unknown\n * names, scope-local names, and reserved transport names fail. Restrictions\n * intersect; scoped registrations remain visible.\n * @param filter - global-surface mask: `allow` (keep only) and/or `deny` (remove).\n * @returns the exact disposer that lifts this restriction.\n */\n restrict(filter: ToolRestriction): () => void\n /**\n * Register a monotonic guard after the extensible `tools/pre-execute`\n * waterfall. A plain-context guard applies globally; one registered through\n * `agent.ctx` applies only to that agent. Any matching guard may deny by\n * returning a reason, while no guard can force-allow a call another guard\n * denied. The exact effect disposer is returned for ordered ownership and\n * HMR cleanup.\n * @param guard - synchronous check; a returned string denies the execution.\n * @returns the exact disposer that unregisters the guard.\n */\n guard(guard: ToolGuard): () => void\n /**\n * Look up a tool as one scope sees it (scoped\n * shadows global; a restricted-away global reads as absent). Presenters pass\n * the calling agent so the rendered card matches the definition that\n * actually executed.\n * @param name - the tool name as registered.\n * @param scope - the viewing scope (the agent); omitted = the global view.\n * @returns the definition the scope resolves, or undefined when none is visible.\n */\n get(name: string, scope?: ScopeKey): ToolDefinition | undefined\n /**\n * Project visible definitions onto the allowlisted model-facing schema fields,\n * excluding execution and presentation callbacks.\n * @param scope - the viewing scope (the agent); omitted = the global view.\n * @returns one deep-cloned schema per visible tool.\n */\n schemas(scope?: ScopeKey): ToolSchema[]\n /**\n * Classify a pending call through the caller's visible tool definition. Only\n * an exact `true` is parallel; unknown, hidden, undeclared, invalid, or\n * throwing classifiers are exclusive.\n * @param exec - call name, parsed arguments, and optional agent scope.\n * @returns the fail-closed scheduling mode.\n */\n executionMode(exec: ToolExecutionInput): ToolExecutionMode\n /**\n * Execute through pre-policy, guards, around-dispatch, post-policy,\n * definition-owned content finalization, and final notification. Tool and\n * listener failures resolve as materialized error results; an invisible tool\n * reports `UNKNOWN_TOOL`. The returned outcome is the same lossless, frozen\n * snapshot final observers receive. Cancellation\n * arriving after entry and before final result materialization skips a\n * not-yet-started body with `ABORTED_BEFORE_DISPATCH` or replaces a\n * successful started outcome with `ABORTED`; already-started work is still\n * drained and may retain a tool-owned structured error.\n * @param exec - the typed same-process call input. The registry assigns its\n * correlation token before policy begins.\n * @returns the materialized final result.\n */\n async execute(exec: ToolExecutionInput): Promise\ntype shapes (referenced by the signatures above — read these before assuming a field is a string):\n export interface Agent {\n readonly id: SessionId;\n readonly options: AgentOptions;\n readonly session: Session;\n readonly status: AgentStatus;\n readonly acceptsNextStep: boolean;\n readonly ctx: Context;\n send(message: UserMessage, options: SendOptions): void;\n updateInbox(id: InboxItemId, action: InboxAction): InboxActionResult;\n cancel(cause: AgentCancelCause, options?: CancelOptions): void;\n whenIdle(): Promise;\n followup(message: UserMessage): void;\n steer(message: UserMessage): void;\n inject(message: UserMessage): void;\n }\n export type AgentCancelCause = {\n readonly kind: 'user';\n } | {\n readonly kind: 'parent';\n };\n export interface AgentOptions {\n provider?: string;\n model?: string;\n maxTokens?: number;\n }\n export type AgentStatus = 'idle' | 'running';\n export interface AssistantMessage extends Message {\n readonly role: 'assistant';\n readonly source: ModelMessageSource;\n }\n export interface AssistantProvenance {\n provider: string;\n model: string;\n replayState?: unknown;\n }\n export type Branded = string & {\n readonly [BRAND]: B;\n };\n export type CallId = Branded<'CallId'>;\n export interface CancelOptions {\n keepInbox?: boolean;\n }\n export interface ContentBlockMap {\n 'text': TextBlock;\n 'reasoning': ReasoningBlock;\n 'tool-call': ToolCallBlock;\n 'tool-result': ToolResultBlock;\n }\n export type ContentBlockType = keyof ContentBlockMap;\n export interface DiffCallView {\n card: 'diff';\n title: string;\n diffs: FileDiff[];\n locations?: FileLocation[];\n }\n export interface DiffResultView {\n card: 'diff';\n title?: string;\n diffs: FileDiff[];\n }\n export interface EpochHeader {\n config: LlmCallConfig;\n system?: string;\n tools?: ToolSchema[];\n }\n export interface FileDiff {\n path: string;\n oldText: string | null;\n newText: string;\n }\n export interface FileLocation {\n path: string;\n line?: number;\n }\n export type FinishReason = FinishReasonMap[keyof FinishReasonMap];\n export interface FinishReasonMap {\n 'stop': {\n kind: 'stop';\n };\n 'tool-calls': {\n kind: 'tool-calls';\n };\n 'max-tokens': {\n kind: 'max-tokens';\n };\n 'aborted': {\n kind: 'aborted';\n failure: LlmFailure;\n };\n 'error': {\n kind: 'error';\n failure: LlmFailure;\n };\n }\n export interface GenericCallView {\n card: 'generic';\n title: string;\n kind?: ToolCallKind;\n rawInput?: unknown;\n content?: ContentBlock[];\n locations?: FileLocation[];\n }\n export interface GenericResultView {\n card: 'generic';\n title?: string;\n content?: ContentBlock[];\n }\n export type InboxAction = {\n readonly kind: 'edit';\n readonly content: ContentBlock[];\n } | {\n readonly kind: 'remove';\n };\n export type InboxActionResult = 'applied' | 'not-found';\n export type InboxItemId = Branded<'InboxItemId'>;\n export interface JsonSchemaNode {\n type?: JsonSchemaType;\n oneOf?: JsonSchemaNode[];\n properties?: Record;\n required?: string[];\n additionalProperties?: boolean;\n items?: JsonSchemaNode;\n enum?: JsonSchemaScalar[];\n const?: JsonSchemaScalar;\n description?: string;\n title?: string;\n default?: JsonValue;\n examples?: JsonValue;\n }\n export type JsonSchemaScalar = string | number | boolean | null;\n export type JsonSchemaType = 'object' | 'array' | 'string' | 'number' | 'integer' | 'boolean' | 'null';\n export type JsonValue = null | boolean | number | string | JsonValue[] | {\n [key: string]: JsonValue;\n };\n export interface LlmCallConfig {\n provider: string;\n model: string;\n reasoningEffort?: ReasoningEffortId;\n temperature?: number;\n maxTokens?: number;\n stop?: string[];\n }\n export interface LlmFailure {\n readonly message: string;\n readonly code: string;\n readonly status?: number;\n readonly providerRetryAfterMs?: number;\n readonly requestId?: ProviderRequestId;\n }\n export interface Message {\n readonly id: MessageId;\n readonly role: 'system' | 'user' | 'assistant';\n readonly content: ContentBlock[];\n readonly source: MessageSource;\n }\n export type MessageId = Branded<'MessageId'>;\n export type MessageSource = MessageSourceMap[keyof MessageSourceMap];\n export interface MessageSourceMap {\n user: {\n kind: 'user';\n };\n plugin: {\n kind: 'plugin';\n plugin: string;\n };\n model: ModelMessageSource;\n tool: ToolMessageSource;\n }\n export interface ModelMessageSource extends AssistantProvenance {\n kind: 'model';\n }\n export type ProviderRequestId = Branded<'ProviderRequestId'>;\n export interface ReadFileLine {\n number: number;\n text: string;\n }\n export interface ReadResultView {\n card: 'read';\n title?: string;\n path: string;\n lines: ReadFileLine[];\n totalLines: number;\n lang?: string;\n content?: ContentBlock[];\n }\n export interface ReasoningBlock {\n type: 'reasoning';\n text: string;\n }\n export type ReasoningEffortId = Branded<'ReasoningEffortId'>;\n export type RequestHeaderReason = 'initial' | 'resume' | 'change';\n export type ScopeKey = object;\n export interface SendOptions {\n target: SendTarget;\n wakeup: boolean;\n }\n export type SendTarget = 'next-turn' | 'next-step';\n export class Session {\n get surface(): SessionSurface;\n readonly header: SessionHeader;\n get id(): SessionId;\n readonly firstLiveSeq: number;\n constructor(id: SessionId, seed?: readonly SessionEvent[], header?: SessionHeader);\n get events(): readonly SessionEvent[];\n get seq(): number;\n append(type: T, data: SessionEventMap[T], ...opts: T extends SurfaceEventType ? [\n opts: SurfaceIntent\n ] : [\n ]): SessionEvent;\n requestHeader(): EpochHeader | undefined;\n deriveMessages(): Message[];\n deriveEventMessage(event: SessionEvent): Message | null;\n }\n export type SessionEvent = {\n [K in SessionEventType]: {\n type: K;\n seq: number;\n time: number;\n data: SessionEventMap[K];\n } & (K extends SurfaceEventType ? {\n sourceEventSeqs?: number[];\n surfaceOp?: SurfaceOp;\n } : object);\n }[T];\n export interface SessionEventMap {\n 'turn/start': {\n turn: number;\n trigger: TurnTrigger;\n };\n 'turn/end': {\n turn: number;\n reason: TurnEndReason;\n };\n 'step/start': {\n turn: number;\n step: number;\n };\n 'step/end': {\n turn: number;\n step: number;\n };\n 'user/message': UserMessage;\n 'assistant/chunk': {\n turn: number;\n step: number;\n chunk: StreamChunk;\n };\n 'assistant/message': {\n turn: number;\n step: number;\n message: AssistantMessage;\n usage?: TokenUsage;\n };\n 'tool/call': {\n turn: number;\n step: number;\n callId: CallId;\n name: string;\n arguments: string;\n };\n 'tool/result': {\n turn: number;\n step: number;\n message: ToolResultMessage;\n error?: {\n name: string;\n code: string;\n };\n meta?: JsonValue;\n };\n 'steering/message': {\n turn: number;\n message: UserMessage;\n };\n 'todo/write': {\n todos: TodoItem[];\n };\n 'request/header': {\n header: EpochHeader;\n reason: RequestHeaderReason;\n };\n 'session/end-seed': Record;\n }\n export type SessionEventType = keyof SessionEventMap;\n export interface SessionHeader {\n readonly version: number;\n readonly id: SessionId;\n readonly createdAt: number;\n readonly cwd?: string;\n readonly parentSession?: SessionId;\n readonly seedLength?: number;\n readonly delegationDepth?: number;\n }\n export type SessionId = Branded<'SessionId'>;\n export interface SessionSurface {\n readonly nodes: readonly number[];\n readonly replaceGeneration: number;\n }\n export type StreamChunk = {\n type: 'block-start';\n index: number;\n blockType: ContentBlockType;\n } | {\n type: 'text-delta';\n index: number;\n text: string;\n } | {\n type: 'reasoning-delta';\n index: number;\n text: string;\n } | {\n type: 'tool-call-delta';\n index: number;\n id: CallId;\n name?: string;\n argumentsDelta: string;\n } | {\n type: 'block-end';\n index: number;\n block: ContentBlock;\n } | {\n type: 'usage';\n usage: TokenUsage;\n } | {\n type: 'finish';\n reason: FinishReason;\n replayState?: unknown;\n };\n export type SurfaceEventType = 'user/message' | 'assistant/message' | 'tool/result' | 'steering/message';\n export interface SurfaceIntent {\n surfaceOp: SurfaceOp;\n sourceEventSeqs?: number[];\n }\n export type SurfaceOp = 'append' | {\n op: 'replace';\n start: number;\n end: number;\n };\n export interface TerminalCallView {\n card: 'terminal';\n title: string;\n description?: string;\n cwd?: string;\n }\n export interface TerminalResultView {\n card: 'terminal';\n title?: string;\n output?: string;\n exitCode?: number;\n signal?: string;\n }\n export interface TodoItem {\n content: string;\n status: 'pending' | 'in_progress' | 'completed';\n }\n export interface TokenUsage {\n inputTokens: number;\n outputTokens: number;\n cacheReadTokens?: number;\n cacheWriteTokens?: number;\n reasoningTokens?: number;\n }\n export interface ToolCallBlock {\n type: 'tool-call';\n id: CallId;\n name: string;\n arguments: string;\n }\n export type ToolCallKind = 'read' | 'edit' | 'delete' | 'move' | 'search' | 'execute' | 'fetch' | 'other';\n export type ToolCallView = GenericCallView | TerminalCallView | DiffCallView;\n export interface ToolDefinition extends ToolSchema {\n readonly output: ToolOutputDefinition;\n execute(args: unknown, exec: ToolRunContext): Promise;\n finalizeContent?(exec: Readonly, result: Readonly): ContentBlock[] | undefined;\n timeoutMs?: number;\n isConcurrencySafe?(args: unknown): boolean;\n presentCall?(args: unknown): ToolCallView | undefined;\n presentResult?(args: unknown, result: ToolResult): ToolResultView | undefined;\n }\n export interface ToolErrorInfo {\n name: string;\n code: string;\n }\n export interface ToolExecution extends ToolExecutionInput {\n readonly token: ToolExecutionToken;\n }\n export interface ToolExecutionFailure {\n readonly isError: true;\n readonly error: ToolFailure;\n readonly value?: never;\n readonly content: ContentBlock[];\n readonly meta?: JsonValue;\n readonly additionalContexts?: UserMessage[];\n readonly concludesTurn?: never;\n }\n export interface ToolExecutionInput {\n readonly callId: CallId;\n readonly name: string;\n readonly arguments: unknown;\n readonly agent?: Agent;\n readonly parent?: ToolExecutionToken;\n readonly signal: AbortSignal;\n }\n export type ToolExecutionMode = {\n kind: 'parallel';\n } | {\n kind: 'exclusive';\n };\n export type ToolExecutionResult = ToolExecutionSuccess | ToolExecutionFailure;\n export interface ToolExecutionSuccess {\n readonly isError: false;\n readonly value: JsonValue;\n readonly content: ContentBlock[];\n readonly error?: never;\n readonly meta?: JsonValue;\n readonly additionalContexts?: UserMessage[];\n readonly concludesTurn?: true;\n }\n export type ToolExecutionToken = symbol & {\n readonly [toolExecutionTokenBrand]: true;\n };\n export interface ToolFailure {\n message: string;\n info?: ToolErrorInfo;\n }\n export type ToolGuard = (execution: Readonly) => string | undefined;\n export interface ToolMessageSource {\n kind: 'tool';\n callId: CallId;\n }\n export interface ToolOutputDefinition {\n readonly schema: JsonSchemaNode;\n render(args: unknown, value: JsonValue): ContentBlock[];\n presentationMeta?(args: unknown, value: JsonValue): JsonValue;\n }\n export interface ToolRestriction {\n readonly allow?: readonly string[];\n readonly deny?: readonly string[];\n }\n export interface ToolResult {\n content: ContentBlock[];\n isError: boolean;\n meta?: JsonValue;\n }\n export interface ToolResultBlock {\n type: 'tool-result';\n toolCallId: CallId;\n content: ContentBlock[];\n isError?: boolean;\n }\n export interface ToolResultMessage extends Message {\n readonly role: 'user';\n readonly content: [\n ToolResultBlock\n ];\n readonly source: ToolMessageSource;\n }\n export type ToolResultView = GenericResultView | TerminalResultView | DiffResultView | ReadResultView;\n export interface ToolRunContext extends ToolExecution {\n deferContext(context: UserMessage): void;\n concludeTurn(): void;\n }\n export interface ToolSchema {\n name: string;\n description: string;\n parameters: Record;\n }\n export type TurnEndReason = TurnEndReasonMap[keyof TurnEndReasonMap];\n export interface TurnEndReasonMap {\n completed: {\n kind: 'completed';\n };\n aborted: {\n kind: 'aborted';\n };\n error: {\n kind: 'error';\n step: number;\n } & ({\n failure: LlmFailure;\n message?: never;\n code?: never;\n } | {\n message: string;\n code?: string;\n failure?: never;\n });\n disposed: {\n kind: 'disposed';\n };\n 'max-tokens': {\n kind: 'max-tokens';\n };\n interrupted: {\n kind: 'interrupted';\n };\n }\n export type TurnTrigger = TurnTriggerMap[keyof TurnTriggerMap];\n export interface TurnTriggerMap {\n message: {\n kind: 'message';\n source: MessageSource;\n };\n retry: {\n kind: 'retry';\n };\n injection: {\n kind: 'injection';\n source: MessageSource;\n };\n }\n export interface UserMessage extends Message {\n readonly role: 'user';\n }"}],"isError":false}],"role":"user","id":"1c43b8df-aae8-42e7-8253-5b275edc09bc"}},"sourceEventSeqs":[11],"surfaceOp":"append"} {"type":"step/end","seq":13,"time":1784449176732,"data":{"turn":1,"step":1}} {"type":"step/start","seq":14,"time":1784449176733,"data":{"turn":1,"step":2}} {"type":"assistant/chunk","seq":15,"time":1783951000015,"data":{"turn":1,"step":2,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}}} From b121adcf1a95bd0557bedda861e23d1a2b1ffcba Mon Sep 17 00:00:00 2001 From: Yichen Jiang Date: Thu, 30 Jul 2026 19:30:58 +0800 Subject: [PATCH 035/139] Polish web chat presentation --- apps/web/tests/live-interactions.e2e.ts | 14 ++++-- .../live-interactions/cancel.expected.md | 1 + .../live-interactions/error-auth.expected.md | 1 + .../live-interactions/loading.expected.md | 25 ++++++++++ .../live-interactions/retry.expected.md | 1 + .../client/ui-conversation/README.i18n.yaml | 4 +- packages/client/ui-conversation/README.md | 2 +- packages/client/ui-conversation/README.zh.md | 2 +- .../src/client/chat/ChatView.module.css | 50 ++++++++++++------- .../src/client/chat/ChatView.tsx | 35 ++----------- .../src/client/chat/MessageItem.tsx | 16 ++++-- .../src/client/queue/QueueDock.module.css | 4 ++ .../tests/chat-branch-tails.spec.tsx | 6 ++- .../ui-conversation/tests/chat-view.spec.tsx | 1 + .../client/ui-primitives/README.i18n.yaml | 4 +- packages/client/ui-primitives/README.md | 2 +- packages/client/ui-primitives/README.zh.md | 3 +- .../client/ui-primitives/src/icons/index.tsx | 12 +++++ packages/client/ui-primitives/src/index.ts | 1 + .../src/markdown/JsonBlock.module.css | 46 ++++++++++++++--- .../ui-primitives/src/markdown/JsonBlock.tsx | 41 ++++++++++++--- .../client/ui-primitives/tests/icons.spec.tsx | 4 +- .../ui-primitives/tests/markdown.spec.tsx | 13 +++-- 23 files changed, 201 insertions(+), 87 deletions(-) create mode 100644 apps/web/tests/snapshots/live-interactions/loading.expected.md diff --git a/apps/web/tests/live-interactions.e2e.ts b/apps/web/tests/live-interactions.e2e.ts index c563638e80..1f1b5301ae 100644 --- a/apps/web/tests/live-interactions.e2e.ts +++ b/apps/web/tests/live-interactions.e2e.ts @@ -27,11 +27,12 @@ import { connectFreshWorkspace, newEnglishPage, saveFailureShot } from './suppor const SNAPSHOT_DIR = fileURLToPath(new URL('./snapshots/live-interactions', import.meta.url)) const FIXTURE = join(SNAPSHOT_DIR, 'session.jsonl') -// One golden per interactive end-state: what the user is left looking at -// after cancel, after a non-retryable failure (pins the FIXME(web-error-surface) -// gap as a reviewable artifact: NO error copy in the tree), and after retry -// recovery — three genuinely different terminal surfaces of one fixture. +// One golden pins the stable mid-turn loading state; the other three capture +// what the user is left looking at after cancel, after a non-retryable failure +// (pins the FIXME(web-error-surface) gap as a reviewable artifact: NO error +// copy in the tree), and after retry recovery. const CANCEL_EXPECTED = join(SNAPSHOT_DIR, 'cancel.expected.md') +const LOADING_EXPECTED = join(SNAPSHOT_DIR, 'loading.expected.md') const ERROR_EXPECTED = join(SNAPSHOT_DIR, 'error-auth.expected.md') const RETRY_EXPECTED = join(SNAPSHOT_DIR, 'retry.expected.md') const MODE = webSnapshotMode() @@ -133,6 +134,9 @@ describe('web e2e: live-turn interactions (cancel / error / retry)', () => { // The marker IS the synchronization: the stream is provably parked in the // hang (prefix chunks delivered to the loop) before the stop click. await expect.poll(() => existsSync(marker), { timeout: 15_000 }).toBe(true) + await expect(page.getByRole('status').filter({ hasText: 'Deep diving...' }).isVisible()).resolves.toBe(true) + const loadingSnapshot = await captureStableAria(page, '[class*="centerCol"]', scaffold!.workspaceCwd) + await compareOrRefreshGolden(LOADING_EXPECTED, loadingSnapshot, MODE) await page.getByRole('button', { name: 'Stop generating' }).click() await settled expect(turnEndReasons(sessionEvents).at(-1)).toBe('aborted') @@ -231,7 +235,7 @@ describe('web e2e: live-turn interactions (cancel / error / retry)', () => { it.skipIf(MODE === 'record')('keeps the fixture inventory closed', async () => { await assertFixtureInventory(SNAPSHOT_DIR, [ - 'session.jsonl', 'cancel.expected.md', 'error-auth.expected.md', 'retry.expected.md', + 'session.jsonl', 'cancel.expected.md', 'loading.expected.md', 'error-auth.expected.md', 'retry.expected.md', ]) }) }) diff --git a/apps/web/tests/snapshots/live-interactions/cancel.expected.md b/apps/web/tests/snapshots/live-interactions/cancel.expected.md index 4323c94285..6d6631081b 100644 --- a/apps/web/tests/snapshots/live-interactions/cancel.expected.md +++ b/apps/web/tests/snapshots/live-interactions/cancel.expected.md @@ -11,6 +11,7 @@ - img - button "编辑": - img +- button "上下文注入" - paragraph: partial - text: 已停止 - button "复制": diff --git a/apps/web/tests/snapshots/live-interactions/error-auth.expected.md b/apps/web/tests/snapshots/live-interactions/error-auth.expected.md index 1d78e91c73..45152f64a1 100644 --- a/apps/web/tests/snapshots/live-interactions/error-auth.expected.md +++ b/apps/web/tests/snapshots/live-interactions/error-auth.expected.md @@ -11,6 +11,7 @@ - img - button "编辑": - img +- button "上下文注入" - textbox "Message the agent" - button "Add attachment": - img diff --git a/apps/web/tests/snapshots/live-interactions/loading.expected.md b/apps/web/tests/snapshots/live-interactions/loading.expected.md new file mode 100644 index 0000000000..6787919794 --- /dev/null +++ b/apps/web/tests/snapshots/live-interactions/loading.expected.md @@ -0,0 +1,25 @@ +- banner: + - navigation "Session hierarchy": + - button "Reply with a one-sentence description" [disabled] + - tablist: + - tab "Chat" [selected] + - tab "Trajectory" +- text: Reply with a one-sentence description of event sourcing, then stop. {{clock}} +- button "复制": + - img +- button "在新对话中分支": + - img +- button "编辑": + - img +- button "上下文注入" +- paragraph: partial +- status: Deep diving... +- textbox "Message the agent" +- button "Add attachment": + - img +- 'button "Access mode, current: Danger Full Access"': Danger Full Access +- button "Plan mode off, press to turn on": Plan off +- button "Select model, current DeepSeek-V4-Flash": + - text: DeepSeek-V4-Flash + - img +- button "Stop generating" diff --git a/apps/web/tests/snapshots/live-interactions/retry.expected.md b/apps/web/tests/snapshots/live-interactions/retry.expected.md index 6a9c808342..a0da177ef2 100644 --- a/apps/web/tests/snapshots/live-interactions/retry.expected.md +++ b/apps/web/tests/snapshots/live-interactions/retry.expected.md @@ -11,6 +11,7 @@ - img - button "编辑": - img +- button "上下文注入" - button "Think The user is asking for a one-sentence description of event sourcing. This is a straightforward knowledge question that doesn't require any skill loading or tool calls.": - img - img diff --git a/packages/client/ui-conversation/README.i18n.yaml b/packages/client/ui-conversation/README.i18n.yaml index 6ca5e5fa30..789fe222af 100644 --- a/packages/client/ui-conversation/README.i18n.yaml +++ b/packages/client/ui-conversation/README.i18n.yaml @@ -2,5 +2,5 @@ # side as of the last confirmed-consistent state. Both languages carry equal authority; # after editing either side, bring the other along and re-record with: # pnpm run verify-translation-pairing --write packages/client/ui-conversation/README.md -README.md: 855c42b3377e80b0d8f21a418da0a591782439e1 -README.zh.md: 31cf2c7b5a9a0740c2be9079ce55d897d175a6d0 +README.md: bf24994e6d6103755e776cf5b694d16d8d6cc2fa +README.zh.md: b43c108b973b5d29f78210e33323bacc80c6148f diff --git a/packages/client/ui-conversation/README.md b/packages/client/ui-conversation/README.md index 855c42b337..bf24994e6d 100644 --- a/packages/client/ui-conversation/README.md +++ b/packages/client/ui-conversation/README.md @@ -2,7 +2,7 @@ English | [中文](README.zh.md) -Conversation domain: skeleton (header/tabs/composer/empty state), chat view (grouped step-summary flow, streaming tail isolation, per-tool row slot with a bash sample registrant and the todo row), composer dock (session stats sticky with the input), input dock (queue rows plus the todo plan strip), minimal details panel, scope-addressed ConversationService. Contract: api-contracts v3 §7 plus the slot terminal design (store seat / props shares). +Conversation domain: skeleton (header/tabs/composer/empty state), chat view (grouped step-summary flow, streaming tail isolation, text-icon context disclosures, an animated left-to-right gradient `Deep diving...` turn status, per-tool row slot with a bash sample registrant and the todo row), composer dock (session stats sticky with the input), input dock (hairline-separated queue rows plus the todo plan strip), minimal details panel, scope-addressed ConversationService. Contract: api-contracts v3 §7 plus the slot terminal design (store seat / props shares). The resident conversation shell survives no-session and session transitions. Without a current session it renders a disabled input bar; its root-scoped `conversation.hero.workspace` slot hosts the Workspace picker. Selecting a Workspace connects or reuses its Host-owned blank session and opens that session without replacing the shell. Blank sessions render the same composer body as active sessions, while the InputHub carries drafts across Workspace switches and mirrors them into the session store. In the active phase the session header occupies the top as ordinary column chrome; beneath it a scrollport (`data-conversation-scroll`) holds the flowing views and the sticky composer stack (stats dock + input docks + bar). Wheel over the textarea chains: the capped draft scrolls locally until its edge, then forwards to that host. diff --git a/packages/client/ui-conversation/README.zh.md b/packages/client/ui-conversation/README.zh.md index 31cf2c7b5a..b43c108b97 100644 --- a/packages/client/ui-conversation/README.zh.md +++ b/packages/client/ui-conversation/README.zh.md @@ -2,7 +2,7 @@ [English](README.md) | 中文 -会话领域:骨架(标题栏/标签页/编辑器/空状态)、聊天视图(分组步骤摘要流、流式尾部隔离、逐工具行 slot 及一个 bash 示例注册方与 todo 行)、编辑器 dock(与输入区一同 sticky 的会话统计行)、输入区 dock(队列行加 todo 计划条)、最小详情面板、按 scope 寻址的 ConversationService。契约:api-contracts v3 §7 加 slot 终端设计(store seat/props share)。 +会话领域:骨架(标题栏/标签页/编辑器/空状态)、聊天视图(分组步骤摘要流、流式尾部隔离、文本图标式上下文展开区、带从左到右动态渐变的 `Deep diving...` 轮次状态、逐工具行 slot 及一个 bash 示例注册方与 todo 行)、编辑器 dock(与输入区一同 sticky 的会话统计行)、输入区 dock(带发丝分界线的队列行加 todo 计划条)、最小详情面板、按 scope 寻址的 ConversationService。契约:api-contracts v3 §7 加 slot 终端设计(store seat/props share)。 常驻会话壳会跨无会话与会话状态切换而保留。没有当前会话时,它会渲染禁用输入栏;其根作用域的 `conversation.hero.workspace` slot 承载 Workspace 选择器。选择 Workspace 会连接或复用由 Host 拥有的空白会话,并在不替换会话壳的情况下打开该会话。空白会话与活跃会话渲染相同的输入区主体;InputHub 则在 Workspace 切换间携带草稿,并将草稿镜像到会话 store。活跃阶段会话标题栏以普通列 chrome 占据顶部;其下滚动容器(`data-conversation-scroll`)承载流动排版的各视图与 sticky 编辑器栈(统计 dock+输入区 dock+输入栏)。textarea 上的滚轮会链式处理:限高草稿先在本地滚动,到达边缘后再转交给该宿主。 diff --git a/packages/client/ui-conversation/src/client/chat/ChatView.module.css b/packages/client/ui-conversation/src/client/chat/ChatView.module.css index 42b5384dfc..55270946ba 100644 --- a/packages/client/ui-conversation/src/client/chat/ChatView.module.css +++ b/packages/client/ui-conversation/src/client/chat/ChatView.module.css @@ -66,33 +66,45 @@ border-left: 1px solid var(--dsw-alias-border-l2); } -/* Turn loader: one row of four 2.5px pixels (StateDot blue) chasing left to - right with a stepped trail — flat keyframe holds, no tweening. Phase - offsets come from per-rect animation-delay (index * -250ms) set inline - by the component. */ -.turnDots { +/* Turn activity keeps the former loader's one-line footprint. A pale + brand-blue band sweeps from left to right; reduced-motion keeps it static. */ +.turnStatus { align-self: flex-start; flex: none; - display: flex; + display: inline-flex; align-items: center; - /* One message line box: the dots center inside the text line height. */ height: 26px; - /* Same pin as StateDot: ongoing blue has no alias token (business-primary - is the 500 step, not this 450). */ - color: var(--dsw-static-deepseek-450); + font: var(--dsw-font-s-strong-14); + white-space: nowrap; + background: linear-gradient( + 90deg, + var(--dsw-static-deepseek-500) 0%, + var(--dsw-static-deepseek-500) 40%, + var(--dsw-static-deepseek-200) 50%, + var(--dsw-static-deepseek-500) 60%, + var(--dsw-static-deepseek-500) 100% + ); + background-position: 100% 0; + background-size: 250% 100%; + background-clip: text; + color: transparent; + -webkit-background-clip: text; + -webkit-text-fill-color: transparent; + animation: dsh-turn-status-shimmer 1.8s linear infinite; } -.turnDotCell { - fill: currentColor; - opacity: 0.15; - animation: dsh-turn-dots-chase 1s infinite; +@keyframes dsh-turn-status-shimmer { + to { + background-position: 0 0; + } } -@keyframes dsh-turn-dots-chase { - 0%, 24.9% { opacity: 1; } - 25%, 49.9% { opacity: 0.6; } - 50%, 74.9% { opacity: 0.35; } - 75%, 100% { opacity: 0.15; } +@media (prefers-reduced-motion: reduce) { + .turnStatus { + background-position: 0 0; + background-size: 100% 100%; + animation: none; + } } .hint { diff --git a/packages/client/ui-conversation/src/client/chat/ChatView.tsx b/packages/client/ui-conversation/src/client/chat/ChatView.tsx index b9e1e3351f..5747d195fe 100644 --- a/packages/client/ui-conversation/src/client/chat/ChatView.tsx +++ b/packages/client/ui-conversation/src/client/chat/ChatView.tsx @@ -178,36 +178,11 @@ const CommandRow = memo(function CommandRow({ renderSlot, node }: { ) }) -/** Turn loader: one row of four 2.5px pixels (half a notch above the StateDot - * 2px cell, same blue) chasing left to right with a stepped trail — flat - * keyframe holds, no tweening, no rotation. Phase offsets come from - * per-rect animation-delay. */ -const LOADER_CELLS = [0, 5, 10, 15] as const - -function TurnDots() { +/** Turn-level model activity label retained across first-token, tool, and streaming phases. */ +function TurnStatus() { return ( - /* The wrapper is a 26px line box (message line height) so the loader - occupies one text line and centers the dots inside it. */ - {!atBottom && (
    diff --git a/packages/client/ui-conversation/src/client/chat/MessageItem.tsx b/packages/client/ui-conversation/src/client/chat/MessageItem.tsx index a149d37337..9449791cbc 100644 --- a/packages/client/ui-conversation/src/client/chat/MessageItem.tsx +++ b/packages/client/ui-conversation/src/client/chat/MessageItem.tsx @@ -1,15 +1,17 @@ // MessageItem: the four simple node kinds — user bubble (right-aligned, with // clock + copy / branch / edit IconActions), steering (badged bubble), context -// injection and unknown-surface JSON rows. Props are frozen node slices off -// the snapshot cache; memo holds across streaming because unchanged nodes -// keep their references. +// injection as a text-icon disclosure, and unknown-surface JSON rows. Props +// are frozen node slices off the snapshot cache; memo holds across streaming +// because unchanged nodes keep their references. import { memo } from 'react' import type { ReactNode } from 'react' import type { ContextMessageNode, SteeringMessageNode, UnknownSurfaceNode, UserMessageNode, } from '@deepseek-ai/dsh-client-runtime/client' -import { JsonBlock, MessageText } from '@deepseek-ai/dsh-client-ui-primitives' +import { + IconTextOutline14, JsonBlock, MessageText, +} from '@deepseek-ai/dsh-client-ui-primitives' import { MessageIconActions } from './MessageIconActions.tsx' import css from './MessageItem.module.css' @@ -95,7 +97,11 @@ export const MessageItem = memo(function MessageItem({ node }: MessageItemProps) case 'context': return (
    - + } + />
    ) default: diff --git a/packages/client/ui-conversation/src/client/queue/QueueDock.module.css b/packages/client/ui-conversation/src/client/queue/QueueDock.module.css index 51d0737ee7..d224841bc5 100644 --- a/packages/client/ui-conversation/src/client/queue/QueueDock.module.css +++ b/packages/client/ui-conversation/src/client/queue/QueueDock.module.css @@ -49,6 +49,10 @@ border-radius: 8px; } +.row + .row { + box-shadow: inset 0 1px 0 var(--dsw-alias-border-l1); +} + .preview, .editor { flex: 1 1 auto; diff --git a/packages/client/ui-conversation/tests/chat-branch-tails.spec.tsx b/packages/client/ui-conversation/tests/chat-branch-tails.spec.tsx index fc5a94af61..5b1e8a6108 100644 --- a/packages/client/ui-conversation/tests/chat-branch-tails.spec.tsx +++ b/packages/client/ui-conversation/tests/chat-branch-tails.spec.tsx @@ -111,7 +111,11 @@ describe('MessageItem arms', () => { const ctxView = render( , ) - expect(ctxView.getByText(/上下文注入/)).toBeTruthy() + const contextToggle = ctxView.getByRole('button', { name: '上下文注入' }) + expect(contextToggle.getAttribute('aria-expanded')).toBe('false') + expect(contextToggle.querySelector('svg')).not.toBeNull() + fireEvent.click(contextToggle) + expect(contextToggle.getAttribute('aria-expanded')).toBe('true') const unknownView = render( , ) diff --git a/packages/client/ui-conversation/tests/chat-view.spec.tsx b/packages/client/ui-conversation/tests/chat-view.spec.tsx index c0cb4dcb78..20d6318ba0 100644 --- a/packages/client/ui-conversation/tests/chat-view.spec.tsx +++ b/packages/client/ui-conversation/tests/chat-view.spec.tsx @@ -318,6 +318,7 @@ describe('ChatView', () => { const view = render() expect(view.container.querySelector('[data-state="running"]')).not.toBeNull() expect(view.getByText('cmd-r1')).toBeTruthy() + expect(view.getByRole('status').textContent).toBe('Deep diving...') }) it('dispatches each tool row through the keyed slot with the tool name as entryKey', () => { diff --git a/packages/client/ui-primitives/README.i18n.yaml b/packages/client/ui-primitives/README.i18n.yaml index b5e4b5c078..ff55730e10 100644 --- a/packages/client/ui-primitives/README.i18n.yaml +++ b/packages/client/ui-primitives/README.i18n.yaml @@ -2,5 +2,5 @@ # side as of the last confirmed-consistent state. Both languages carry equal authority; # after editing either side, bring the other along and re-record with: # pnpm run verify-translation-pairing --write packages/client/ui-primitives/README.md -README.md: 0ef3c20f848b3d331c007911d0837f11cd72c024 -README.zh.md: af94551bfb9e12dbadcef6a96a54f9bf7ea71299 +README.md: ba315a02563596a680bc1849c07b8dec3cfdab21 +README.zh.md: c0ecfb42765a3a539fb2aa470133f86b36ca2f57 diff --git a/packages/client/ui-primitives/README.md b/packages/client/ui-primitives/README.md index 0ef3c20f84..ba315a0256 100644 --- a/packages/client/ui-primitives/README.md +++ b/packages/client/ui-primitives/README.md @@ -6,7 +6,7 @@ Pure React atoms (zero cordis): StateDot, ic_ds_* icons, Button/Pill/Menu/Modal/ ## Markdown rendering -`MarkdownText` renders GFM from untrusted assistant output through React elements. It omits raw HTML, neutralizes relative and non-HTTP(S)/mailto links, opens HTTP(S) links with safe external-link attributes, and renders image alt text without loading remote resources; `MessageText` remains the literal-text primitive for user-authored content. `extractMarkdownPlainText` removes Markdown presentation markup for compact labels while preserving raw HTML as literal text. Element spacing, tables, links, and inline code use the same `--dsw-alias-markdown-*` / `--dsw-font-markdown-*` tokens as deepsuite `@deepseek/md`. Fenced blocks render through `CodeBlock` (language banner, copy control, shiki for the registered grammars). +`MarkdownText` renders GFM from untrusted assistant output through React elements. It omits raw HTML, neutralizes relative and non-HTTP(S)/mailto links, opens HTTP(S) links with safe external-link attributes, and renders image alt text without loading remote resources; `MessageText` remains the literal-text primitive for user-authored content. `extractMarkdownPlainText` removes Markdown presentation markup for compact labels while preserving raw HTML as literal text. `JsonBlock` renders a bounded JSON disclosure with design-system chevrons, `aria-expanded`, and an optional semantic collapsed-state icon. Element spacing, tables, links, and inline code use the same `--dsw-alias-markdown-*` / `--dsw-font-markdown-*` tokens as deepsuite `@deepseek/md`. Fenced blocks render through `CodeBlock` (language banner, copy control, shiki for the registered grammars). ## Terminal output diff --git a/packages/client/ui-primitives/README.zh.md b/packages/client/ui-primitives/README.zh.md index af94551bfb..c0ecfb4276 100644 --- a/packages/client/ui-primitives/README.zh.md +++ b/packages/client/ui-primitives/README.zh.md @@ -6,7 +6,8 @@ ## Markdown 渲染 -`MarkdownText` 通过 React 元素渲染来自不受信任 assistant 输出的 GFM。它会省略原始 HTML,使相对链接及非 HTTP(S)/mailto 链接失效,以安全的外部链接属性打开 HTTP(S) 链接,并只渲染图片 alt 文本而不加载远程资源;`MessageText` 仍是用户创作内容使用的字面文本原语。`extractMarkdownPlainText` 会移除 Markdown 呈现标记以用于紧凑标签,同时将原始 HTML 保留为字面文本。元素间距、表格、链接与行内代码使用与 deepsuite `@deepseek/md` 相同的 `--dsw-alias-markdown-*` / `--dsw-font-markdown-*` token。围栏代码块通过 `CodeBlock` 渲染(语言横幅、复制控件,以及对已注册语法使用 shiki)。 +`MarkdownText` 通过 React 元素渲染来自不受信任 assistant 输出的 GFM。它会省略原始 HTML,使相对链接及非 HTTP(S)/mailto 链接失效,以安全的外部链接属性打开 HTTP(S) 链接,并只渲染图片 alt 文本而不加载远程资源;`MessageText` 仍是用户创作内容使用的字面文本原语。`extractMarkdownPlainText` 会移除 Markdown 呈现标记以用于紧凑标签,同时将原始 HTML 保留为字面文本。`JsonBlock` 会渲染一个有界的 JSON 展开区,其中带有设计系统的 V 形箭头、`aria-expanded`,并可选配折叠态语义图标。元素间距、表格、链接与行内代码使用与 deepsuite `@deepseek/md` 相同的 `--dsw-alias-markdown-*` / `--dsw-font-markdown-*` token。围栏代码块通过 `CodeBlock` 渲染(语言横幅、复制控件,以及对已注册语法使用 shiki)。 + ## 终端输出 `TerminalBlock` 将一条 shell 命令渲染为终端表层:命令的每一行各占一个提示行(缩短后的 `cwd` 标签只出现在第一行,因为视图只知道一个工作目录,而一个 `cd` 就会让后面的行去到别处,标签之后是该行)、命令输出、非零退出码或终止信号对应的状态胶囊,以及写入原始 `output` prop 的复制控件。一枚运行状态 `StateDot` 为整次调用标记一次,位于第一行,以脱离文档流的方式落在卡片以自身左内边距预留的落区中,因此它位于卡片盒之内、提示文字之左。它用到 `StateDot` 的三种状态——`running` 期间为追逐动画,与渲染状态胶囊相同的退出状态为红色,其余为绿色——因此卡片直接陈述其命令是否仍在运行,而不是让人从有无输出中推断;由于 `StateDot` 是 `aria-hidden`,它携带一处视觉隐藏的文本标签。无论多少行都只有一枚状态点是有意为之:退出状态属于整次调用,因此每行一枚就会声称一个视图并不携带的逐行结果。命令文本使用 `white-space: pre`,因此重复空格、制表符与缩进续行都原样呈现,同时该行仍保持单行并以省略号截断。ANSI 转义序列通过运行时依赖 `anser` 解析为 React span;光标移动在剥除无显示意义控制符之前先重放进逐行的列缓冲,因为回车与退格**只移动**光标:单是 `100%` 加回车再加 `OK` 显示为 `OK0%`,而 spinner 随重绘写出的 `\x1b[K` 会擦掉尾巴,因此 `100%\r\x1b[KOK` 显示为 `OK`。行内擦除的三种参数形式都被遵循,光标按终端列推进(8 列制表位;emoji 与 CJK 占两列;组合标记不占列),SGR 状态按单元格归一化存储,与终端一致,并跨行延续、在行结束时的状态处收束;基础 16 色前景色映射到 `--dsw-*` token,而 256 色板与真彩色值按字面 rgb 透传。输出保持 `white-space: pre` 并支持横向滚动,因此按列对齐的输出保留其对齐而不会软换行;超过 `maxLines`(默认 16,与 TUI 转录相同的切分算法)时折叠为头部切片加尾部切片,由展开按钮控制。原理:[Web 终端卡片笔记](../../../.agents/notes/implemented/feature/2026-07-28-web-terminal-card.md)。 diff --git a/packages/client/ui-primitives/src/icons/index.tsx b/packages/client/ui-primitives/src/icons/index.tsx index 830ff4f642..b91587b904 100644 --- a/packages/client/ui-primitives/src/icons/index.tsx +++ b/packages/client/ui-primitives/src/icons/index.tsx @@ -685,6 +685,18 @@ export const IconChecklistOutline14 = ({ size = 14, className }: IconProps) => ( ) +/** Text document glyph for context-disclosure rows. */ +export const IconTextOutline14 = ({ size = 14, className }: IconProps) => ( + + + +) + /** ic_ds_List_Pen_outline_16 */ export const IconListPenOutline16 = ({ size = 16, className }: IconProps) => ( diff --git a/packages/client/ui-primitives/src/index.ts b/packages/client/ui-primitives/src/index.ts index aa674f7a1a..2f9e3169dc 100644 --- a/packages/client/ui-primitives/src/index.ts +++ b/packages/client/ui-primitives/src/index.ts @@ -24,6 +24,7 @@ export { TerminalBlock, DEFAULT_TERMINAL_MAX_LINES } from './TerminalBlock.tsx' export type { TerminalBlockProps } from './TerminalBlock.tsx' export { CodeBlock } from './markdown/CodeBlock.tsx' export { JsonBlock } from './markdown/JsonBlock.tsx' +export type { JsonBlockProps } from './markdown/JsonBlock.tsx' export { MarkdownText } from './markdown/MarkdownText.tsx' export { MessageText } from './markdown/MessageText.tsx' export { extractMarkdownPlainText } from './markdown/plain-text.ts' diff --git a/packages/client/ui-primitives/src/markdown/JsonBlock.module.css b/packages/client/ui-primitives/src/markdown/JsonBlock.module.css index 7a967146e6..c1894c3402 100644 --- a/packages/client/ui-primitives/src/markdown/JsonBlock.module.css +++ b/packages/client/ui-primitives/src/markdown/JsonBlock.module.css @@ -3,22 +3,54 @@ } .toggle { - font-size: 12px; - line-height: 18px; + display: inline-flex; + align-items: center; + min-height: 24px; + font-size: 14px; + line-height: 24px; color: var(--dsw-alias-label-secondary); - padding: 2px 6px; + padding: 0; border: none; background: transparent; cursor: pointer; - border-radius: 6px; } -.toggle:hover { - background: var(--dsw-alias-interactive-bg-hover); +.leading { + position: relative; + flex: none; + width: 16px; + height: 16px; + display: inline-flex; + align-items: center; + justify-content: center; + margin-right: 6px; + color: var(--dsw-alias-label-tertiary); +} + +.iconIdle { + display: inline-flex; + opacity: 1; + transition: opacity 100ms ease; +} + +.chevronHover { + position: absolute; + inset: 0; + margin: auto; + opacity: 0; + transition: opacity 100ms ease; +} + +.toggle:hover .iconIdle { + opacity: 0; +} + +.toggle:hover .chevronHover { + opacity: 1; } .body { - margin: 4px 0 0; + margin: 4px 0 0 22px; padding: 8px; max-height: 200px; overflow: auto; diff --git a/packages/client/ui-primitives/src/markdown/JsonBlock.tsx b/packages/client/ui-primitives/src/markdown/JsonBlock.tsx index 4697feb247..fb0aaa17f0 100644 --- a/packages/client/ui-primitives/src/markdown/JsonBlock.tsx +++ b/packages/client/ui-primitives/src/markdown/JsonBlock.tsx @@ -1,15 +1,28 @@ -// JsonBlock: collapsible JSON block (conversation side; independent from the RPC panel's PayloadJson to avoid cross-panel coupling). +// JsonBlock: accessible JSON disclosure row (conversation side; independent +// from the RPC panel's PayloadJson to avoid cross-panel coupling). -import { useMemo, useState } from 'react' +import { useMemo, useState, type ReactNode } from 'react' +import { IconChevronDownOutline14, IconChevronRightOutline14 } from '../icons/index.tsx' import css from './JsonBlock.module.css' const MAX_CHARS = 20_000 -export function JsonBlock({ label, payload, defaultOpen = false }: { +/** Props for the compact JSON disclosure used in conversation content. */ +export interface JsonBlockProps { label: string payload: unknown defaultOpen?: boolean -}) { + /** Semantic glyph shown while collapsed; hover previews the disclosure chevron. */ + collapsedIcon?: ReactNode +} + +/** Render a bounded, pretty-printed JSON disclosure. */ +export function JsonBlock({ + label, + payload, + defaultOpen = false, + collapsedIcon, +}: JsonBlockProps) { const [open, setOpen] = useState(defaultOpen) const body = useMemo(() => { if (!open) return '' @@ -23,10 +36,26 @@ export function JsonBlock({ label, payload, defaultOpen = false }: { } return s.length > MAX_CHARS ? `${s.slice(0, MAX_CHARS)}\n… 已截断,共 ${s.length} 字符` : s }, [open, payload]) + const leading = open + ? + : collapsedIcon === undefined + ? + : ( + <> + {collapsedIcon} + + + ) return (
    - {open &&
    {body}
    }
    diff --git a/packages/client/ui-primitives/tests/icons.spec.tsx b/packages/client/ui-primitives/tests/icons.spec.tsx index 536d1b774f..520d1e4eb2 100644 --- a/packages/client/ui-primitives/tests/icons.spec.tsx +++ b/packages/client/ui-primitives/tests/icons.spec.tsx @@ -14,8 +14,8 @@ const icons = Object.fromEntries( const iconNames = Object.keys(icons) describe('ic_ds_ icon set', () => { - it('exports the full P-I set (45 deepsuite + 14 figma extracts + the hand-authored sparkle)', () => { - expect(iconNames.length).toBe(60) + it('exports the full P-I set (45 deepsuite + 14 figma extracts + 2 hand-authored glyphs)', () => { + expect(iconNames.length).toBe(61) }) it.each(iconNames)('%s renders an svg with currentColor fills and no hardcoded palette', (name) => { diff --git a/packages/client/ui-primitives/tests/markdown.spec.tsx b/packages/client/ui-primitives/tests/markdown.spec.tsx index b7f665c78a..3c06400b7b 100644 --- a/packages/client/ui-primitives/tests/markdown.spec.tsx +++ b/packages/client/ui-primitives/tests/markdown.spec.tsx @@ -124,12 +124,17 @@ describe('MarkdownText', () => { }) describe('JsonBlock', () => { - it('collapsed by default; toggle reveals pretty-printed payload', () => { - render() + it('collapsed by default; accessible toggle reveals pretty-printed payload', () => { + render(T} />) + const toggle = screen.getByRole('button', { name: 'args' }) + expect(toggle.getAttribute('aria-expanded')).toBe('false') + expect(screen.getByTestId('json-icon')).toBeDefined() expect(screen.queryByText(/"a": 1/)).toBeNull() - fireEvent.click(screen.getByRole('button', { name: /args/ })) + fireEvent.click(toggle) + expect(toggle.getAttribute('aria-expanded')).toBe('true') expect(screen.getByText(/"a": 1/)).toBeDefined() - fireEvent.click(screen.getByRole('button', { name: /args/ })) + fireEvent.click(toggle) + expect(toggle.getAttribute('aria-expanded')).toBe('false') expect(screen.queryByText(/"a": 1/)).toBeNull() }) From 17ee269f115a3fc3fc9c5028d1549e8681b87d66 Mon Sep 17 00:00:00 2001 From: Chinesezjc Date: Thu, 30 Jul 2026 19:36:17 +0800 Subject: [PATCH 036/139] =?UTF-8?q?fix(web):=20address=20web=20card=20revi?= =?UTF-8?q?ew=20=E2=80=94=20panel=20body,=20ol=20numbering,=20safe=20links?= =?UTF-8?q?,=20docs?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - DetailsPanel: render the flattened result content below the web card, so a web_fetch's fetched body (and a search's answer/source markdown) stays visible on the panel's single-call reading surface — the card is a summary. - WebBlock: the collapsed source tail keeps each source's original citation number via
  • , and the expand control is a marker-less
  • so the
      is valid HTML; an empty-hostname URL (file:/data:) falls back to the raw URL so a label is never blank. - web-row / GenericToolCard: both spread WebBlock uniformly with maxSources (fetch ignores it, like TerminalBlock's maxLines), dropping the duplicated per-kind conditional. - Docs: WebBlock added to the ui-primitives README (both languages) with a Web retrieval section; the ui-conversation README's "inline licensed for this intent alone" claim de-absolutized and a web-card paragraph added; the Agent Note's safe-link description corrected to the http(s) subset of MarkdownText's allowlist (mailto excluded). Fixture source comment aligned with its data. - Tests: ol numbering + marker-less expander, empty-hostname label fallback, the fetched body visible in the panel. --- ...6-07-30-web-result-card-frontend.i18n.yaml | 4 +- .../2026-07-30-web-result-card-frontend.md | 4 +- .../2026-07-30-web-result-card-frontend.zh.md | 4 +- .../client/connection/src/client/fixture.ts | 5 +- .../client/ui-conversation/README.i18n.yaml | 4 +- packages/client/ui-conversation/README.md | 4 +- packages/client/ui-conversation/README.zh.md | 4 +- .../src/client/chat/GenericToolCard.tsx | 5 +- .../src/client/skeleton/DetailsPanel.tsx | 16 +++- .../src/client/toolviews/web-row.tsx | 5 +- .../ui-conversation/tests/web-card.spec.tsx | 6 +- .../client/ui-primitives/README.i18n.yaml | 4 +- packages/client/ui-primitives/README.md | 6 +- packages/client/ui-primitives/README.zh.md | 6 +- .../ui-primitives/src/WebBlock.module.css | 4 + .../client/ui-primitives/src/WebBlock.tsx | 77 ++++++++++++------- .../ui-primitives/tests/web-block.spec.tsx | 27 +++++++ 17 files changed, 132 insertions(+), 53 deletions(-) diff --git a/.agents/notes/implemented/feature/2026-07-30-web-result-card-frontend.i18n.yaml b/.agents/notes/implemented/feature/2026-07-30-web-result-card-frontend.i18n.yaml index e2cb16b5cc..db354e75a3 100644 --- a/.agents/notes/implemented/feature/2026-07-30-web-result-card-frontend.i18n.yaml +++ b/.agents/notes/implemented/feature/2026-07-30-web-result-card-frontend.i18n.yaml @@ -2,5 +2,5 @@ # side as of the last confirmed-consistent state. Both languages carry equal authority; # after editing either side, bring the other along and re-record with: # pnpm run verify-translation-pairing --write .agents/notes/implemented/feature/2026-07-30-web-result-card-frontend.md -2026-07-30-web-result-card-frontend.md: cf2dd26a8f6eebe6d8d5d275a462151b7c3274a2 -2026-07-30-web-result-card-frontend.zh.md: 505243f7a31df1a5be0381a9399c5283272d1fe8 +2026-07-30-web-result-card-frontend.md: efead1f404879c526475a1b9f0b31f6c34978f07 +2026-07-30-web-result-card-frontend.zh.md: 2e76bf4c18f5032cd5fd9b15fe31d3c7b036b502 diff --git a/.agents/notes/implemented/feature/2026-07-30-web-result-card-frontend.md b/.agents/notes/implemented/feature/2026-07-30-web-result-card-frontend.md index cf2dd26a8f..efead1f404 100644 --- a/.agents/notes/implemented/feature/2026-07-30-web-result-card-frontend.md +++ b/.agents/notes/implemented/feature/2026-07-30-web-result-card-frontend.md @@ -14,7 +14,7 @@ The `web_search` and `web_fetch` tools declare a `card: 'web'` result view ([web One component draws both kinds, discriminated by `kind`. A `search` shows the answer as markdown above a citation list; each source is a safe external link labelled by its title, or its hostname when the provider gave none, with the snippet and publication date below it, and a `来源列表已截断` indicator when the tool capped the list. A `fetch` shows a compact summary: the linked final URL, its HTTP status, and a `内容已截断` indicator. One component rather than two because both are web retrieval rendered as one card family, which is exactly the reason the contract carries them under one `card` tag with a `kind` discriminant. -**Links are safe by the same allowlist MarkdownText applies to untrusted assistant-authored links.** A source or fetch URL becomes a navigable anchor only when its protocol is `http:` or `https:`, with `target="_blank"` and `rel="noopener noreferrer"`; a `javascript:`/`data:`/`file:` URL or an unparseable string renders as plain text with no href. The result content a web tool returns is model-authored and reaches this component unverified, so it is treated as untrusted exactly as assistant markdown is. The label falls back from title to hostname to the raw URL, so a source always reads as something even when both the title is absent and the URL does not parse. +**Links are safe by the http(s) subset of the allowlist MarkdownText applies to untrusted assistant-authored links** — MarkdownText also permits `mailto:`, deliberately excluded here since a retrieval URL is never a mail address. A source or fetch URL becomes a navigable anchor only when its protocol is `http:` or `https:`, with `target="_blank"` and `rel="noopener noreferrer"`; a `javascript:`/`data:`/`file:`/`mailto:` URL or an unparseable string renders as plain text with no href. The result content a web tool returns is model-authored and reaches this component unverified, so it is treated as untrusted exactly as assistant markdown is. The label falls back from title to hostname to the raw URL, so a source always reads as something even when both the title is absent and the URL does not parse. **Geometry mirrors CodeBlock/TerminalBlock** (12px radius, code-block surface, 16px vertical margin) so a web card reads as one family with them. A long source list caps at `maxSources` with a head/tail collapse using TerminalBlock's exact split arithmetic (`ceil(max/2)` head lines plus the remaining tail), so a long body's slices agree between the two cards. A source list is prose rather than column-aligned output, so it wraps normally instead of scrolling horizontally the way a terminal card's output does — that is the one deliberate divergence from TerminalBlock. @@ -32,7 +32,7 @@ A separate later PR unifies the whole-row collapse/expand interaction and will f **Reparse the model-facing render text instead of consuming the structured view.** Rejected for the same reason the contract note gives: `web_search`'s render collapses each source's fields into one free-text line labelled by title OR hostname, so reparsing cannot recover `{url, title?, snippet?, publishedAt?}`. The structured `resultView` is the only faithful source, which is why the backend PR added it. -**Render plain anchors without the protocol allowlist.** Rejected: the URL is model-authored and unverified at this seam, so an unfiltered href would let a `javascript:` URL execute on click. The allowlist matches MarkdownText's, so untrusted links behave identically wherever they render. +**Render plain anchors without the protocol allowlist.** Rejected: the URL is model-authored and unverified at this seam, so an unfiltered href would let a `javascript:` URL execute on click. The allowlist is the http(s) subset of MarkdownText's (which also permits `mailto:`), so untrusted retrieval links behave identically wherever they render. ## Testing diff --git a/.agents/notes/implemented/feature/2026-07-30-web-result-card-frontend.zh.md b/.agents/notes/implemented/feature/2026-07-30-web-result-card-frontend.zh.md index 505243f7a3..2e76bf4c18 100644 --- a/.agents/notes/implemented/feature/2026-07-30-web-result-card-frontend.zh.md +++ b/.agents/notes/implemented/feature/2026-07-30-web-result-card-frontend.zh.md @@ -14,7 +14,7 @@ Status: implemented 一个组件绘制两种 kind,由 `kind` 判别。`search` 把 answer 作为 markdown 显示在引用列表上方;每个 source 是一个安全外链,以其标题为标签,provider 未给标题时以其主机名为标签,下方是 snippet 与发布日期,工具截断列表时显示 `来源列表已截断` 提示。`fetch` 显示一个紧凑摘要:带链接的最终 URL、其 HTTP 状态、以及 `内容已截断` 提示。用一个组件而非两个,因为两者都是渲染为同一卡片族的 web 检索 —— 这正是契约把它们放在一个 `card` 标签下、用 `kind` 判别的原因。 -**链接的安全性沿用 MarkdownText 对不受信任的 assistant 链接所用的同一 allowlist。** 一个 source 或 fetch URL 仅当其协议为 `http:` 或 `https:` 时才成为可导航锚点,带 `target="_blank"` 和 `rel="noopener noreferrer"`;`javascript:`/`data:`/`file:` URL 或无法解析的字符串渲染为纯文本、无 href。web 工具返回的 result content 是模型创作的,未经验证抵达本组件,因此像 assistant markdown 一样被当作不受信任处理。标签从标题回退到主机名再回退到原始 URL,因此即便标题缺失且 URL 无法解析,source 也总能读作某个东西。 +**链接的安全性沿用 MarkdownText 对不受信任的 assistant 链接所用 allowlist 的 http(s) 子集。** MarkdownText 还允许 `mailto:`,此处刻意排除,因为检索 URL 绝不会是邮件地址。一个 source 或 fetch URL 仅当其协议为 `http:` 或 `https:` 时才成为可导航锚点,带 `target="_blank"` 和 `rel="noopener noreferrer"`;`javascript:`/`data:`/`file:`/`mailto:` URL 或无法解析的字符串渲染为纯文本、无 href。web 工具返回的 result content 是模型创作的,未经验证抵达本组件,因此像 assistant markdown 一样被当作不受信任处理。标签从标题回退到主机名再回退到原始 URL,因此即便标题缺失且 URL 无法解析,source 也总能读作某个东西。 **几何镜像 CodeBlock/TerminalBlock**(12px 圆角、code-block 表面、16px 垂直外边距),使 web 卡片与它们读作一家。长 source 列表在 `maxSources` 处折叠,用 TerminalBlock 完全相同的分割算术做头/尾折叠(`ceil(max/2)` 头部行加剩余尾部),使长正文的切片在两张卡之间一致。source 列表是散文而非按列对齐的输出,所以它正常换行,而不像终端卡片的输出那样横向滚动 —— 这是与 TerminalBlock 唯一刻意的分歧。 @@ -32,7 +32,7 @@ Status: implemented **重解析模型可见的渲染文本,而非消费结构化视图。** 因契约笔记给出的同一理由拒绝:`web_search` 的渲染把每个 source 的字段压缩成一行自由文本、以标题或主机名为标签,所以重解析无法恢复 `{url, title?, snippet?, publishedAt?}`。结构化的 `resultView` 是唯一忠实来源,这正是后端 PR 添加它的原因。 -**不加协议 allowlist 直接渲染裸锚点。** 拒绝:URL 在此接缝处是模型创作、未经验证的,所以未过滤的 href 会让 `javascript:` URL 在点击时执行。该 allowlist 与 MarkdownText 的一致,因此不受信任的链接无论在何处渲染都行为相同。 +**不加协议 allowlist 直接渲染裸锚点。** 拒绝:URL 在此接缝处是模型创作、未经验证的,所以未过滤的 href 会让 `javascript:` URL 在点击时执行。该 allowlist 是 MarkdownText allowlist(它还允许 `mailto:`)的 http(s) 子集,因此不受信任的检索链接无论在何处渲染都行为相同。 ## Testing diff --git a/packages/client/connection/src/client/fixture.ts b/packages/client/connection/src/client/fixture.ts index 0196713372..7c81d702b7 100644 --- a/packages/client/connection/src/client/fixture.ts +++ b/packages/client/connection/src/client/fixture.ts @@ -152,8 +152,9 @@ interface WebSourceFixture { * The structured `web_search` result view for fixture turn 66, authored inline * because this client-side fixture cannot import the web tool that projects it. * The sources exercise the citation list's features: a titled source with a - * snippet and a date, a source with no title (its hostname labels the link), and - * a source with a snippet but no date. `truncated` marks the capped indicator. + * snippet and a date, a source with no title (its hostname labels the link) and + * a snippet but no date, and a source with a title and a date but no snippet. + * `truncated` marks the capped indicator. */ const WEB_SEARCH_RESULT: { answer: string; sources: WebSourceFixture[]; truncated: boolean } = { answer: 'DeepSeek Harness is a plugin-based agent harness on vendored Cordis where **every capability is a plugin**.', diff --git a/packages/client/ui-conversation/README.i18n.yaml b/packages/client/ui-conversation/README.i18n.yaml index 6ca5e5fa30..447c2b58ea 100644 --- a/packages/client/ui-conversation/README.i18n.yaml +++ b/packages/client/ui-conversation/README.i18n.yaml @@ -2,5 +2,5 @@ # side as of the last confirmed-consistent state. Both languages carry equal authority; # after editing either side, bring the other along and re-record with: # pnpm run verify-translation-pairing --write packages/client/ui-conversation/README.md -README.md: 855c42b3377e80b0d8f21a418da0a591782439e1 -README.zh.md: 31cf2c7b5a9a0740c2be9079ce55d897d175a6d0 +README.md: bc28e9acb7771a0276ee161ea507916d0d45edeb +README.zh.md: 1fea2ee8aaee3e327c689df400a50ab58a61481a diff --git a/packages/client/ui-conversation/README.md b/packages/client/ui-conversation/README.md index 855c42b337..bc28e9acb7 100644 --- a/packages/client/ui-conversation/README.md +++ b/packages/client/ui-conversation/README.md @@ -12,7 +12,9 @@ Approvals take over the composer through the chain this package declares: `Appro Generic tool rows classify the built-in bash, read, search, write, edit, and run_code names into dedicated visual variants. The filesystem variants render the edit icon and a path summary; that path is a hover-underline link that opens the file with the host OS default application (`host.openPath`, relative paths resolve against the session cwd). Tool rows are not whole-row click targets and do not open the details panel. The code variant summarizes with the model-authored `description` and expands to the program itself; its logged sub-dispatches render as always-visible nested rows through the SAME keyed toolview hole (custom registrations and the GenericToolCard fallback apply to sub-rows unchanged). Cordis lifecycle tools reuse those generic variants while presenting `Inspect`, `Mount temporary Plugin`, and `Unmount temporary Plugin` with a shared Cordis accent; mount keeps the code variant's expandable source rendering. -A tool call declaring the `terminal` render intent renders its command output inline, at both conversation render sites, through ui-primitives' `TerminalBlock`. `contract/terminal-card-model.ts` is the single derivation from the snapshot's `callView`/`resultView` pair, so the sites cannot disagree about a command, its cwd, or its exit status; it yields null — the generic path — for any other card tag, including one this client version does not know. Both sites therefore also show the card's run-state dot, which is the same `StateDot` semantic a tool row's leading icon carries, so a row and its own card always agree about one command's state. A multi-line command gets one prompt row per line, with the dot marking the call once on the first row — the exit status is the whole call's, so a dot per line would claim a per-line outcome bash does not report. The keyed `BashRow` carries the card resident below its summary row; since tool rows are no longer details-panel click targets, the card's copy and expand controls are the row's only interactions. The render-site fallback row keeps the card behind its existing expand control. Rows cap at `CHAT_TERMINAL_MAX_LINES` (8) against the panel's 16, which is what keeps a summary surface bounded — the panel stays the single-call reading surface. Inline output is licensed for this intent alone; a generic tool's content remains panel-only ([decision](../../../.agents/notes/implemented/feature/2026-07-28-web-terminal-card.md)). +A tool call declaring the `terminal` render intent renders its command output inline, at both conversation render sites, through ui-primitives' `TerminalBlock`. `contract/terminal-card-model.ts` is the single derivation from the snapshot's `callView`/`resultView` pair, so the sites cannot disagree about a command, its cwd, or its exit status; it yields null — the generic path — for any other card tag, including one this client version does not know. Both sites therefore also show the card's run-state dot, which is the same `StateDot` semantic a tool row's leading icon carries, so a row and its own card always agree about one command's state. A multi-line command gets one prompt row per line, with the dot marking the call once on the first row — the exit status is the whole call's, so a dot per line would claim a per-line outcome bash does not report. The keyed `BashRow` carries the card resident below its summary row; since tool rows are no longer details-panel click targets, the card's copy and expand controls are the row's only interactions. The render-site fallback row keeps the card behind its existing expand control. Rows cap at `CHAT_TERMINAL_MAX_LINES` (8) against the panel's 16, which is what keeps a summary surface bounded — the panel stays the single-call reading surface. Inline output is licensed per render intent — the terminal and web cards, each with its own bound; a generic tool's content remains panel-only ([decision](../../../.agents/notes/implemented/feature/2026-07-28-web-terminal-card.md)). + +A tool call declaring the `web` render intent renders its web retrieval inline, at both conversation render sites, through ui-primitives' `WebBlock`. `contract/web-card-model.ts` is the single derivation from the snapshot's `resultView`, mirroring the terminal card, so the sites cannot disagree about what a web call shows; it yields null — the generic path — for a running call, a non-web result view, a generic result view, or a `card` tag this client version does not know. The keyed `WebRow` registers one component under both `web_search` and `web_fetch`, discriminating on the tool name only for its icon and title; a web-declaring tool without a keyed row lands on the `GenericToolCard` fallback, which grows the same resident card, and the details panel renders it at the primitive's full source allowance. Rows cap at `CHAT_WEB_MAX_SOURCES` (8) against the panel's 16, the same summary-versus-reading split the terminal card draws ([decision](../../../.agents/notes/implemented/feature/2026-07-30-web-result-card-frontend.md)). Tool rows are slots too — the standalone tool ring (`ToolViewRegistry`/`ctx.toolviews`/outlet) is retired. The chat entry declares the keyed `'conversation.chat.toolview'` hole (session scope; the key space is runtime-open); its render site dispatches per row via `entryKey: toolName` with `GenericToolCard` as the call-site `fallback`. The owner payload is the uniform `ToolRowOwnerProps` (`callId`/`toolName`/`block`/`openFile`) and `ToolRowProps` pre-composes it with the session standard kit. A registrant is a plain plugin: `ctx.slots.register({ name: 'conversation.chat.toolview', key: '', inject? }, Row)` with `inject: ['slots', 'conversation']` as the load-order seam (apply mounts ConversationService after the chat registration, so the service being present guarantees the slot is declared); session differentiation happens inside the component (`useSessions` reading `parentId` — the bash sample is the third-party-posture exemplar). Trajectory/waterfall toolview slots share this shape and land with their own render sites (RendersCheck rejects a declaration nobody renders). diff --git a/packages/client/ui-conversation/README.zh.md b/packages/client/ui-conversation/README.zh.md index 31cf2c7b5a..1fea2ee8aa 100644 --- a/packages/client/ui-conversation/README.zh.md +++ b/packages/client/ui-conversation/README.zh.md @@ -10,7 +10,9 @@ 通用工具行把内置的 bash、read、search、write、edit 和 run_code 名称归入专用视觉变体。文件系统变体会渲染 edit 图标和路径摘要;该路径是悬停下划线链接,点击后通过宿主操作系统的默认应用打开文件(`host.openPath`,相对路径相对会话 cwd 解析)。工具行不再是整行点击目标,也不会打开 details 面板。code 变体以模型撰写的 `description` 作摘要,展开后显示程序本身;其已记录的子调用经由同一个键控 toolview 空位渲染为始终可见的嵌套行(自定义注册和 GenericToolCard fallback 原样适用于子行)。Cordis 生命周期工具复用这些通用变体,同时以统一的 Cordis 强调色呈现 `Inspect`、`Mount temporary Plugin` 和 `Unmount temporary Plugin`;mount 行保留 code 变体的可展开源码渲染。 -声明 `terminal` 渲染意图的工具调用,会在两个对话渲染点上都通过 ui-primitives 的 `TerminalBlock` 内联渲染其命令输出。`contract/terminal-card-model.ts` 是从快照的 `callView`/`resultView` 对推导的唯一位置,因此两个渲染点不可能在命令、cwd 或退出状态上产生分歧;对任何其他 card 标签——包括当前客户端版本不认识的标签——它返回 null,落回通用路径。因此两个渲染点也都显示卡片的运行状态点,它与工具行行首图标承载同一套 `StateDot` 语义,所以一行与其自身的卡片对同一条命令的状态总是一致。多行命令的每一行各占一个提示行,状态点只在第一行为整次调用标记一次——退出状态属于整次调用,因此每行一枚就会声称一个 bash 并不报告的逐行结果。键控的 `BashRow` 把卡片常驻在摘要行下方;由于工具行已不再是详情面板的点击目标,卡片的复制与展开控件就是该行唯一的交互。渲染点兜底行则保持其既有的展开控件。行的上限是 `CHAT_TERMINAL_MAX_LINES`(8),面板为 16,正是这一点让摘要面保持有界——面板仍是单次调用的阅读面。内联输出只对该意图开放;通用工具的内容仍然只在面板中呈现([决策](../../../.agents/notes/implemented/feature/2026-07-28-web-terminal-card.md))。 +声明 `terminal` 渲染意图的工具调用,会在两个对话渲染点上都通过 ui-primitives 的 `TerminalBlock` 内联渲染其命令输出。`contract/terminal-card-model.ts` 是从快照的 `callView`/`resultView` 对推导的唯一位置,因此两个渲染点不可能在命令、cwd 或退出状态上产生分歧;对任何其他 card 标签——包括当前客户端版本不认识的标签——它返回 null,落回通用路径。因此两个渲染点也都显示卡片的运行状态点,它与工具行行首图标承载同一套 `StateDot` 语义,所以一行与其自身的卡片对同一条命令的状态总是一致。多行命令的每一行各占一个提示行,状态点只在第一行为整次调用标记一次——退出状态属于整次调用,因此每行一枚就会声称一个 bash 并不报告的逐行结果。键控的 `BashRow` 把卡片常驻在摘要行下方;由于工具行已不再是详情面板的点击目标,卡片的复制与展开控件就是该行唯一的交互。渲染点兜底行则保持其既有的展开控件。行的上限是 `CHAT_TERMINAL_MAX_LINES`(8),面板为 16,正是这一点让摘要面保持有界——面板仍是单次调用的阅读面。内联输出按渲染意图开放——终端卡片与 web 卡片,各有自己的上限;通用工具的内容仍然只在面板中呈现([决策](../../../.agents/notes/implemented/feature/2026-07-28-web-terminal-card.md))。 + +声明 `web` 渲染意图的工具调用,会在两个对话渲染点上都通过 ui-primitives 的 `WebBlock` 内联渲染其 web 检索。`contract/web-card-model.ts` 是从快照的 `resultView` 推导的唯一位置,镜像终端卡片,因此两个渲染点不可能对一次 web 调用的显示产生分歧;对运行中的调用、非 web 的 result view、generic result view,或本客户端版本不认识的 `card` 标签,它返回 null,落回通用路径。键控的 `WebRow` 把一个组件注册在 `web_search` 与 `web_fetch` 两个键下,仅根据工具名判别以选取图标与标题;没有自己键控行的 web 声明工具落到 `GenericToolCard` 兜底,它长出同一张常驻卡片,详情面板则以原语的完整 source 额度渲染它。行的上限是 `CHAT_WEB_MAX_SOURCES`(8),面板为 16,与终端卡片所画的摘要面对阅读面的同一划分([决策](../../../.agents/notes/implemented/feature/2026-07-30-web-result-card-frontend.md))。 工具行同样是 slot:独立工具环(`ToolViewRegistry`/`ctx.toolviews`/outlet)已经退役。聊天配置项声明键控的 `'conversation.chat.toolview'` 空位(Session scope;key 空间在运行时开放);其渲染点逐行通过 `entryKey: toolName` 分发,并以 `GenericToolCard` 作为调用点 `fallback`。owner 载荷是统一的 `ToolRowOwnerProps`(`callId`/`toolName`/`block`/`openFile`),`ToolRowProps` 则预先将其与 Session 标准工具包组合。注册方只是普通插件:`ctx.slots.register({ name: 'conversation.chat.toolview', key: '', inject? }, Row)`,以 `inject: ['slots', 'conversation']` 作为加载顺序 seam(apply 在聊天注册后挂载 ConversationService,因此服务存在即可保证 slot 已声明);Session 区分在组件内部完成(`useSessions` 读取 `parentId`,bash 示例是第三方姿态的范例)。Trajectory/waterfall 工具视图 slot 共享此形状,并随各自的渲染点落地(RendersCheck 会拒绝没有任何渲染方的声明)。 diff --git a/packages/client/ui-conversation/src/client/chat/GenericToolCard.tsx b/packages/client/ui-conversation/src/client/chat/GenericToolCard.tsx index 5c63896825..56d239b88f 100644 --- a/packages/client/ui-conversation/src/client/chat/GenericToolCard.tsx +++ b/packages/client/ui-conversation/src/client/chat/GenericToolCard.tsx @@ -56,10 +56,7 @@ export function GenericToolCard({ toolName, block, cwd, openFile }: ToolRowOwner return (
      {row} - +
      ) } diff --git a/packages/client/ui-conversation/src/client/skeleton/DetailsPanel.tsx b/packages/client/ui-conversation/src/client/skeleton/DetailsPanel.tsx index d31717da44..57c5d63460 100644 --- a/packages/client/ui-conversation/src/client/skeleton/DetailsPanel.tsx +++ b/packages/client/ui-conversation/src/client/skeleton/DetailsPanel.tsx @@ -152,8 +152,20 @@ function OutputBody({ material, cwd }: { material: CallMaterial; cwd: string | u } const web = webCardModel(material.block) // Full source-list allowance here (the panel is the single-call reading - // surface); the chat rows cap it at CHAT_WEB_MAX_SOURCES. - if (web !== null) return + // surface); the chat rows cap it at CHAT_WEB_MAX_SOURCES. The card is a + // summary — a web_fetch card shows only the URL and status — so the details + // panel also renders the flattened result content below it (the fetched body, + // the search answer + source markdown), which the card does not carry. + if (web !== null) { + const settled = 'kind' in material.block ? material.block : null + const body = settled === null ? '' : renderResult(settled) + return ( + <> + + {body !== '' &&
      {body}
      } + + ) + } // A settled call always carries the result node the flattened form needs; // the running shape has no result to flatten. if (!('kind' in material.block)) return
      运行中…
      diff --git a/packages/client/ui-conversation/src/client/toolviews/web-row.tsx b/packages/client/ui-conversation/src/client/toolviews/web-row.tsx index 29a30776f9..b86c523a26 100644 --- a/packages/client/ui-conversation/src/client/toolviews/web-row.tsx +++ b/packages/client/ui-conversation/src/client/toolviews/web-row.tsx @@ -66,10 +66,7 @@ export function WebRow({ toolName, block }: ToolRowProps) { {model.summary}
  • {web !== null && ( - + )}
    ) diff --git a/packages/client/ui-conversation/tests/web-card.spec.tsx b/packages/client/ui-conversation/tests/web-card.spec.tsx index 9ed25978f1..d6f04eb147 100644 --- a/packages/client/ui-conversation/tests/web-card.spec.tsx +++ b/packages/client/ui-conversation/tests/web-card.spec.tsx @@ -216,11 +216,15 @@ describe('DetailsPanel web Output section', () => { expect(view.getByText(/"query"/)).toBeTruthy() }) - it('renders the fetch card', () => { + it('renders the fetch card and keeps the fetched body below it', () => { const view = mount(snapshot({ nodes: [settledFetch()] }), { turnSeq: 11, callId: 'c2', toolName: 'web_fetch' }) const card = view.container.querySelector('[data-web="fetch"]') expect(card?.querySelector('a')?.getAttribute('href')).toBe('https://example.com/page') expect(view.getByText('HTTP 200')).toBeTruthy() + // The card is a summary (URL + status only); the panel is the single-call + // reading surface, so the fetched body still renders below the card. + const output = view.getByText('Output').closest('section') + expect(output?.querySelector('pre')?.textContent).toContain('fetch body') }) it('a non-web result keeps the flattened pre form', () => { diff --git a/packages/client/ui-primitives/README.i18n.yaml b/packages/client/ui-primitives/README.i18n.yaml index b5e4b5c078..2a64292653 100644 --- a/packages/client/ui-primitives/README.i18n.yaml +++ b/packages/client/ui-primitives/README.i18n.yaml @@ -2,5 +2,5 @@ # side as of the last confirmed-consistent state. Both languages carry equal authority; # after editing either side, bring the other along and re-record with: # pnpm run verify-translation-pairing --write packages/client/ui-primitives/README.md -README.md: 0ef3c20f848b3d331c007911d0837f11cd72c024 -README.zh.md: af94551bfb9e12dbadcef6a96a54f9bf7ea71299 +README.md: b5b79f7f0d01afb2d06fb18bf30131cbdda75ca2 +README.zh.md: b10183496479249346da5da808f5ab3b6d2eef67 diff --git a/packages/client/ui-primitives/README.md b/packages/client/ui-primitives/README.md index 0ef3c20f84..b5b79f7f0d 100644 --- a/packages/client/ui-primitives/README.md +++ b/packages/client/ui-primitives/README.md @@ -2,7 +2,7 @@ English | [中文](README.zh.md) -Pure React atoms (zero cordis): StateDot, ic_ds_* icons, Button/Pill/Menu/Modal/Input, the markdown family (MessageText/MarkdownText/JsonBlock), the read-only JsonTree inspector, the `useAnchoredMaxHeight` hook that clamps a bottom-anchored overlay to the viewport space above its anchor (re-measured on resize, scroll, and a caller-supplied dependency), and TerminalBlock. Contract: api-contracts v3 §8. +Pure React atoms (zero cordis): StateDot, ic_ds_* icons, Button/Pill/Menu/Modal/Input, the markdown family (MessageText/MarkdownText/JsonBlock), the read-only JsonTree inspector, the `useAnchoredMaxHeight` hook that clamps a bottom-anchored overlay to the viewport space above its anchor (re-measured on resize, scroll, and a caller-supplied dependency), TerminalBlock, and WebBlock. Contract: api-contracts v3 §8. ## Markdown rendering @@ -12,6 +12,10 @@ Pure React atoms (zero cordis): StateDot, ic_ds_* icons, Button/Pill/Menu/Modal/ `TerminalBlock` renders a shell command as a terminal surface: one prompt row per line of the command (the shortened `cwd` label on the first row only, since the view knows one working directory and a `cd` moves later lines elsewhere, then that line), the command's output, a status pill for a non-zero exit code or a terminating signal, and a copy control that writes the raw `output` prop. A run-state `StateDot` marks the call once, on the first row, out of flow in a gutter the card reserves as its own left padding, so the dot sits inside the card box yet left of the prompt text. It reaches three of `StateDot`'s states — the chase while `running`, red for the same exit status that renders the pill, green otherwise — so a card states whether its command is still running rather than leaving that to be inferred from the presence of output; it carries one visually hidden text label because `StateDot` is `aria-hidden`. One dot regardless of line count is deliberate: the exit status is the whole call's, so a dot per line would claim a per-line outcome the view does not carry. Command text is `white-space: pre`, so repeated spaces, tabs, and an indented continuation render verbatim while the row stays single-line and ellipsizes. ANSI escape sequences are parsed with the `anser` runtime dependency into React spans; cursor movements replay into a per-line column buffer before inert controls are stripped, since carriage return and backspace only MOVE the cursor: `100%` + CR + `OK` alone shows `OK0%`, while the `\x1b[K` a spinner writes with its redraw erases the tail so `100%\r\x1b[KOK` shows `OK`. Erase-in-line is honored in all three parameter forms, the cursor advances by terminal columns (8-column tab stops, two for emoji and CJK, none for a combining mark), and SGR state is normalized per cell as a terminal stores it, threading across lines and closing at the state the line ended in; basic-16 foreground colors map onto `--dsw-*` tokens, while 256-palette and truecolor values pass through as literal rgb. Output keeps `white-space: pre` with horizontal scrolling, so column-aligned output holds its alignment instead of soft-wrapping, and collapses to a head slice plus a tail slice past `maxLines` (default 16, the TUI transcript's split arithmetic) behind an expand button. Rationale: [the web terminal card note](../../../.agents/notes/implemented/feature/2026-07-28-web-terminal-card.md). +## Web retrieval + +`WebBlock` renders a completed web retrieval, one component for both kinds of the `web` render intent (discriminated by `kind`). A `search` shows an optional provider answer (through `MarkdownText`) above an ordered citation list: each source is a safe external link labelled by its title, or its hostname, falling back to the raw URL when the URL does not parse or has no hostname (a `file:`/`data:` URL) so a label is never blank; its snippet and publication date render below it. Only http(s) URLs become anchors (`target`/`rel` set) — the http(s) subset of the allowlist `MarkdownText` applies to untrusted links (it also permits `mailto:`, excluded here); any other URL renders as plain text. A long list caps at `maxSources` (default 16, the TerminalBlock split arithmetic) with a head/tail collapse; the collapsed tail keeps each source's original citation number via `
  • `, and the expand control is a marker-less `
  • ` so the `
      ` stays valid HTML. A `fetch` shows a compact summary: the linked final URL and its HTTP status. Both mark a capped retrieval. Rationale: [the web result card note](../../../.agents/notes/implemented/feature/2026-07-30-web-result-card-frontend.md). + ## Model Experience None, as the package renders pure React atoms in the browser; nothing here reaches a model request. diff --git a/packages/client/ui-primitives/README.zh.md b/packages/client/ui-primitives/README.zh.md index af94551bfb..b101834964 100644 --- a/packages/client/ui-primitives/README.zh.md +++ b/packages/client/ui-primitives/README.zh.md @@ -2,7 +2,7 @@ [English](README.md) | 中文 -纯 React 原子组件(零 cordis):StateDot、ic_ds_* 图标、Button/Pill/Menu/Modal/Input、markdown 家族(MessageText/MarkdownText/JsonBlock)、只读 JsonTree 检查器、`useAnchoredMaxHeight` hook(把底部锚定的浮层高度收敛到锚点上方的视口空间,并在 resize、scroll 与调用方提供的依赖变化时重新测量),以及 TerminalBlock。契约:api-contracts v3 §8。 +纯 React 原子组件(零 cordis):StateDot、ic_ds_* 图标、Button/Pill/Menu/Modal/Input、markdown 家族(MessageText/MarkdownText/JsonBlock)、只读 JsonTree 检查器、`useAnchoredMaxHeight` hook(把底部锚定的浮层高度收敛到锚点上方的视口空间,并在 resize、scroll 与调用方提供的依赖变化时重新测量),以及 TerminalBlock 与 WebBlock。契约:api-contracts v3 §8。 ## Markdown 渲染 @@ -11,6 +11,10 @@ `TerminalBlock` 将一条 shell 命令渲染为终端表层:命令的每一行各占一个提示行(缩短后的 `cwd` 标签只出现在第一行,因为视图只知道一个工作目录,而一个 `cd` 就会让后面的行去到别处,标签之后是该行)、命令输出、非零退出码或终止信号对应的状态胶囊,以及写入原始 `output` prop 的复制控件。一枚运行状态 `StateDot` 为整次调用标记一次,位于第一行,以脱离文档流的方式落在卡片以自身左内边距预留的落区中,因此它位于卡片盒之内、提示文字之左。它用到 `StateDot` 的三种状态——`running` 期间为追逐动画,与渲染状态胶囊相同的退出状态为红色,其余为绿色——因此卡片直接陈述其命令是否仍在运行,而不是让人从有无输出中推断;由于 `StateDot` 是 `aria-hidden`,它携带一处视觉隐藏的文本标签。无论多少行都只有一枚状态点是有意为之:退出状态属于整次调用,因此每行一枚就会声称一个视图并不携带的逐行结果。命令文本使用 `white-space: pre`,因此重复空格、制表符与缩进续行都原样呈现,同时该行仍保持单行并以省略号截断。ANSI 转义序列通过运行时依赖 `anser` 解析为 React span;光标移动在剥除无显示意义控制符之前先重放进逐行的列缓冲,因为回车与退格**只移动**光标:单是 `100%` 加回车再加 `OK` 显示为 `OK0%`,而 spinner 随重绘写出的 `\x1b[K` 会擦掉尾巴,因此 `100%\r\x1b[KOK` 显示为 `OK`。行内擦除的三种参数形式都被遵循,光标按终端列推进(8 列制表位;emoji 与 CJK 占两列;组合标记不占列),SGR 状态按单元格归一化存储,与终端一致,并跨行延续、在行结束时的状态处收束;基础 16 色前景色映射到 `--dsw-*` token,而 256 色板与真彩色值按字面 rgb 透传。输出保持 `white-space: pre` 并支持横向滚动,因此按列对齐的输出保留其对齐而不会软换行;超过 `maxLines`(默认 16,与 TUI 转录相同的切分算法)时折叠为头部切片加尾部切片,由展开按钮控制。原理:[Web 终端卡片笔记](../../../.agents/notes/implemented/feature/2026-07-28-web-terminal-card.md)。 +## Web 检索 + +`WebBlock` 渲染一次已完成的 web 检索,用一个组件绘制 `web` 渲染意图的两种 kind(由 `kind` 判别)。`search` 在有序引用列表上方显示可选的 provider answer(通过 `MarkdownText`):每个 source 是一个安全外链,以其标题为标签,或以其主机名为标签,当 URL 无法解析或没有主机名(`file:`/`data:` URL)时回退到原始 URL,因此标签绝不为空;其下渲染 snippet 与发布日期。只有 http(s) URL 会成为锚点(设置 `target`/`rel`)——这是 `MarkdownText` 对不受信任链接所用 allowlist 的 http(s) 子集(该 allowlist 还允许 `mailto:`,此处排除);任何其他 URL 渲染为纯文本。长列表在 `maxSources`(默认 16,即 TerminalBlock 的切分算术)处折叠为头部/尾部;折叠的尾部通过 `
    1. ` 保留每个 source 原始的引用编号,展开控件是无 marker 的 `
    2. `,使 `
        ` 保持为合法 HTML。`fetch` 显示一个紧凑摘要:带链接的最终 URL 及其 HTTP 状态。两者都会标记一次被截断的检索。原理:[Web result 卡片笔记](../../../.agents/notes/implemented/feature/2026-07-30-web-result-card-frontend.md)。 + ## 模型体验 无。该包(package)在浏览器中渲染纯 React 原子组件;这里没有任何内容进入模型请求。 diff --git a/packages/client/ui-primitives/src/WebBlock.module.css b/packages/client/ui-primitives/src/WebBlock.module.css index d595acb3cc..17383563bf 100644 --- a/packages/client/ui-primitives/src/WebBlock.module.css +++ b/packages/client/ui-primitives/src/WebBlock.module.css @@ -65,6 +65,10 @@ font: var(--dsw-font-xs-13); } +.expandItem { + list-style: none; +} + .expand { display: block; width: 100%; diff --git a/packages/client/ui-primitives/src/WebBlock.tsx b/packages/client/ui-primitives/src/WebBlock.tsx index d4757858a3..f0144bd601 100644 --- a/packages/client/ui-primitives/src/WebBlock.tsx +++ b/packages/client/ui-primitives/src/WebBlock.tsx @@ -5,12 +5,13 @@ // none, with the snippet and publication date below it), and a `fetch` shows a // compact retrieval summary (the linked final URL and its HTTP status). Both // mark a capped retrieval. Every link is a same-origin-safe external anchor: -// only http(s) URLs become anchors (target/rel set), the same protocol allowlist -// MarkdownText applies to untrusted assistant-authored links; an unparseable or -// non-http URL renders as plain text. Geometry, radius, and fonts mirror -// CodeBlock/TerminalBlock so a web card reads as one family with them; a long -// source list caps at maxSources with a head/tail collapse using the same -// arithmetic as TerminalBlock's output cap. +// only http(s) URLs become anchors (target/rel set) — the http(s) subset of the +// allowlist MarkdownText applies to untrusted assistant-authored links (it also +// permits mailto, excluded here); an unparseable or non-http URL renders as +// plain text. Geometry, radius, and fonts mirror CodeBlock/TerminalBlock so a +// web card reads as one family with them; a long source list caps at maxSources +// with a head/tail collapse using the same arithmetic as TerminalBlock's output +// cap. import { useCallback, useState } from 'react' import clsx from 'clsx' @@ -64,6 +65,13 @@ export interface WebFetchBlockProps { statusCode: number /** True when the provider or the output cap cut the fetched content. */ truncated: boolean + /** + * Accepted and ignored, so both card kinds take one uniform prop set (a fetch + * card has no source list to cap) — the same way TerminalBlock accepts one + * `maxLines` across its arms. Lets a render site spread `maxSources` onto + * either kind without a per-kind conditional. + */ + maxSources?: number | undefined /** Extra class merged onto the wrapper (callers position; this component draws). */ className?: string | undefined } @@ -72,10 +80,12 @@ export interface WebFetchBlockProps { export type WebBlockProps = WebSearchBlockProps | WebFetchBlockProps /** - * The URL to link to, or undefined when the URL must render as plain text. The - * allowlist is MarkdownText's own for untrusted links: only http(s) becomes a - * navigable external anchor, so a `javascript:`/`data:`/`file:` URL or an - * unparseable string never reaches the DOM as an href. + * The URL to link to, or undefined when the URL must render as plain text. Only + * http(s) becomes a navigable external anchor, so a `javascript:`/`data:`/`file:` + * URL or an unparseable string never reaches the DOM as an href. This is the + * http(s) subset of the allowlist MarkdownText applies to untrusted links — + * MarkdownText also permits `mailto:`, deliberately excluded here since a + * retrieval URL is never a mail address. * @param url - the source or fetch URL, from tool result content. * @returns the href to use, or undefined for plain text. */ @@ -90,7 +100,9 @@ function safeHref(url: string): string | undefined { /** * The link's visible label: the title when the provider gave one, otherwise the - * URL's hostname, falling back to the raw URL when it does not parse. + * URL's hostname, falling back to the raw URL when it does not parse OR parses + * to an empty hostname (a `file:`/`data:`/`javascript:` URL), so a label is + * never blank. * @param url - the source URL. * @param title - the provider title, if any. * @returns the label text. @@ -98,7 +110,8 @@ function safeHref(url: string): string | undefined { function linkLabel(url: string, title: string | undefined): string { if (title !== undefined && title !== '') return title try { - return new URL(url).hostname + const { hostname } = new URL(url) + return hostname === '' ? url : hostname } catch { return url } @@ -123,13 +136,17 @@ function SafeLink({ url, label, className }: { url: string; label: string; class } /** - * One source row in a search card: the safe link plus its snippet and date. + * One source row in a search card: the safe link plus its snippet and date. The + * `
      1. ` pins the source's original 1-based position, so a collapsed list + * whose tail is drawn after the head still numbers each source by its real + * citation index rather than by its position in the visible subset. * @param props.source - the source to render. + * @param props.ordinal - the source's 1-based position in the full list. * @returns the source list item. */ -function SourceItem({ source }: { source: WebSourceView }) { +function SourceItem({ source, ordinal }: { source: WebSourceView; ordinal: number }) { return ( -
      2. +
      3. {source.snippet !== undefined && source.snippet !== '' && (
        {source.snippet}
        @@ -163,19 +180,27 @@ function WebSearchBlock({ answer, sources, truncated, maxSources = DEFAULT_WEB_M
        )}
          - {head.map((source, index) => )} + {head.map((source, index) => )} {hidden > 0 && ( - +
        1. + +
        2. )} - {tail.map((source, index) => )} + {tail.map((source, index) => ( + + ))}
        {truncated &&
        来源列表已截断
        }
  • diff --git a/packages/client/ui-primitives/tests/web-block.spec.tsx b/packages/client/ui-primitives/tests/web-block.spec.tsx index 0c39e8b13d..b0778a636a 100644 --- a/packages/client/ui-primitives/tests/web-block.spec.tsx +++ b/packages/client/ui-primitives/tests/web-block.spec.tsx @@ -48,6 +48,16 @@ describe('WebBlock search card', () => { expect(view.getByText('empty.example.net')).toBeTruthy() }) + it('labels a source by the raw url when it parses to an empty hostname', () => { + // file:/data:/javascript: URLs parse but have no hostname; the label must + // fall back to the raw URL so it is never blank (and the link stays plain + // text since the protocol is not http(s)). + const view = render() + expect(view.getByText('file:///etc/passwd')).toBeTruthy() + }) + it('renders a source as a safe external anchor for an http(s) url', () => { const view = render( { expect(view.container.querySelectorAll('[class^="_source_"]')).toHaveLength(4) }) + it('numbers a collapsed tail by each source original position, not its visible slot', () => { + // maxSources 4 over 10 sources: the tail is sources 8 and 9, which must read + // as citations 9 and 10 (via
  • ), not renumbered 3 and 4. + const view = render() + const items = [...view.container.querySelectorAll('li[class^="_source_"]')] + expect(items.map(li => li.getAttribute('value'))).toEqual(['1', '2', '9', '10']) + }) + + it('keeps the expander out of the ordered-list numbering', () => { + // The expander is a marker-less
  • , so it is valid inside
      and does not + // consume a citation number between the head and tail sources. + const view = render() + const ol = view.container.querySelector('ol')! + // Every direct child is an
    1. (no bare - } - /> + <> + { setOpen(false) }} + side="top" + anchor={ + + } + /> + + + + + )} + > +
      + +

      {t('confirm.description')}

      +
      + +
      + ) } diff --git a/packages/client/ui-conversation/tests/input-bar.spec.tsx b/packages/client/ui-conversation/tests/input-bar.spec.tsx index c0bfda7f4a..2fa04b6af4 100644 --- a/packages/client/ui-conversation/tests/input-bar.spec.tsx +++ b/packages/client/ui-conversation/tests/input-bar.spec.tsx @@ -43,6 +43,8 @@ interface BenchOptions { variant?: 'hero' | 'composer' placeholder?: string translateHint?: (key: string) => string + translateAccess?: (key: string) => string + command?: (line: string) => Promise accessory?: React.ReactNode overlay?: React.ReactNode leftItems?: React.ReactNode @@ -100,12 +102,19 @@ function bench(over?: BenchOptions) { useNotices: bindSnapshotSelector(shell.notices), useLexicon: bindSnapshotSelector(shell.lexicon), stop, - command: () => Promise.resolve(true), + command: over?.command ?? (() => Promise.resolve(true)), // Mirrors the en 'command.hint' locale entries the production apply wires in. translateHint: over?.translateHint ?? ((key: string) => ({ 'placeholder.default': 'Message the agent', 'placeholder.plan': 'describe your task to generate plan', } as Record)[key] ?? key), + translateAccess: over?.translateAccess ?? ((key: string) => ({ + 'confirm.title': 'Enable Full access?', + 'confirm.description': 'Full access can perform sensitive operations.', + 'confirm.acknowledge': 'I understand the risks and want to continue', + 'confirm.cancel': 'Cancel', + 'confirm.enable': 'Enable Full access', + } as Record)[key] ?? key), renderSlot, variant: over?.variant ?? 'composer', ...(over?.placeholder !== undefined ? { placeholder: over.placeholder } : {}), @@ -450,7 +459,35 @@ describe('placeholder chrome and control seats', () => { expect(view.queryByLabelText('Model')).toBeNull() }) - it('the Access chip renders the projection value and submits /permission on pick', async () => { + it('the Access chip renders the projection value and submits a non-Full-access pick directly', async () => { + const command = vi.fn(() => Promise.resolve(true)) + const permissions = { + options: [ + { value: 'read-only', name: 'read-only' }, + { value: 'workspace-write', name: 'workspace-write' }, + { value: 'danger-full-access', name: 'danger-full-access' }, + ], + currentValue: 'read-only', + } + const { view } = bench({ permissions, command }) + const trigger = view.getByLabelText(/^Access mode/) as HTMLButtonElement + // Title-case display is presentation only; the menu ids stay machine names. + expect(trigger.textContent).toBe('Read Only') + fireEvent.click(trigger) + const items = view.getAllByRole('menuitem') + expect(items.map(o => o.textContent)).toEqual(['Read Only', 'Workspace Write', 'Full access']) + fireEvent.click(items[1]!) + // Optimistic pick + disable until admission resolves (command stub resolves true). + const busy = view.getByLabelText(/^Access mode/) as HTMLButtonElement + expect(busy.textContent).toBe('Workspace Write') + expect(busy.disabled).toBe(true) + expect(command).toHaveBeenCalledWith('/permission workspace-write') + await act(async () => {}) + expect((view.getByLabelText(/^Access mode/) as HTMLButtonElement).disabled).toBe(false) + }) + + it('requires explicit risk acknowledgement before submitting Full access', async () => { + const command = vi.fn(() => Promise.resolve(true)) const permissions = { options: [ { value: 'workspace-write', name: 'workspace-write' }, @@ -458,20 +495,50 @@ describe('placeholder chrome and control seats', () => { ], currentValue: 'workspace-write', } - const { view } = bench({ permissions }) - const trigger = view.getByLabelText(/^Access mode/) as HTMLButtonElement - // Title-case display is presentation only; the menu ids stay machine names. - expect(trigger.textContent).toBe('Workspace Write') - fireEvent.click(trigger) - const items = view.getAllByRole('menuitem') - expect(items.map(o => o.textContent)).toEqual(['Workspace Write', 'Danger Full Access']) - fireEvent.click(items[1]!) - // Optimistic pick + disable until admission resolves (command stub resolves true). - const busy = view.getByLabelText(/^Access mode/) as HTMLButtonElement - expect(busy.textContent).toBe('Danger Full Access') - expect(busy.disabled).toBe(true) + const { view } = bench({ permissions, command }) + fireEvent.click(view.getByLabelText(/^Access mode/)) + fireEvent.click(view.getByRole('menuitem', { name: 'Full access' })) + + expect(command).not.toHaveBeenCalled() + expect(view.getByRole('dialog', { name: 'Enable Full access?' })).toBeTruthy() + const enable = view.getByRole('button', { name: 'Enable Full access' }) as HTMLButtonElement + expect(enable.disabled).toBe(true) + + fireEvent.click(view.getByRole('checkbox', { name: 'I understand the risks and want to continue' })) + expect(enable.disabled).toBe(false) + fireEvent.click(enable) + + expect(command).toHaveBeenCalledOnce() + expect(command).toHaveBeenCalledWith('/permission danger-full-access') + expect(view.queryByRole('dialog')).toBeNull() + expect((view.getByLabelText(/^Access mode/) as HTMLButtonElement).textContent).toBe('Full access') await act(async () => {}) - expect((view.getByLabelText(/^Access mode/) as HTMLButtonElement).disabled).toBe(false) + }) + + it('cancels a Full access selection without changing permission and resets acknowledgement', () => { + const command = vi.fn(() => Promise.resolve(true)) + const permissions = { + options: [ + { value: 'workspace-write', name: 'workspace-write' }, + { value: 'danger-full-access', name: 'danger-full-access' }, + ], + currentValue: 'workspace-write', + } + const { view } = bench({ permissions, command }) + const openConfirmation = () => { + fireEvent.click(view.getByLabelText(/^Access mode/)) + fireEvent.click(view.getByRole('menuitem', { name: 'Full access' })) + } + + openConfirmation() + fireEvent.click(view.getByRole('checkbox')) + fireEvent.click(view.getByRole('button', { name: 'Cancel' })) + expect(command).not.toHaveBeenCalled() + expect((view.getByLabelText(/^Access mode/) as HTMLButtonElement).textContent).toBe('Workspace Write') + + openConfirmation() + expect((view.getByRole('checkbox') as HTMLInputElement).checked).toBe(false) + expect((view.getByRole('button', { name: 'Enable Full access' }) as HTMLButtonElement).disabled).toBe(true) }) it('a registered entry fills its seat and receives the locked owner prop', () => { diff --git a/packages/client/ui-conversation/tests/input-matrix.spec.tsx b/packages/client/ui-conversation/tests/input-matrix.spec.tsx index a9c00b0748..7df065bb8f 100644 --- a/packages/client/ui-conversation/tests/input-matrix.spec.tsx +++ b/packages/client/ui-conversation/tests/input-matrix.spec.tsx @@ -49,6 +49,7 @@ function mountBar(shell: SessionInputShell, over?: { running?: boolean; disabled stop: vi.fn(), command: () => Promise.resolve(true), translateHint: (key: string) => key, + translateAccess: (key: string) => key, variant: 'composer', } return render() diff --git a/packages/client/ui-conversation/tests/input-scenarios.spec.tsx b/packages/client/ui-conversation/tests/input-scenarios.spec.tsx index 1c7bbe50ec..5915703b06 100644 --- a/packages/client/ui-conversation/tests/input-scenarios.spec.tsx +++ b/packages/client/ui-conversation/tests/input-scenarios.spec.tsx @@ -135,6 +135,7 @@ async function scopedBench(register?: (slash: SlashService) => void) { stop: vi.fn(), command: () => Promise.resolve(true), translateHint: (key: string) => key, + translateAccess: (key: string) => key, variant: 'composer', } const view = render() diff --git a/packages/client/ui-conversation/tests/skeleton.spec.tsx b/packages/client/ui-conversation/tests/skeleton.spec.tsx index 3ed459b5a9..0d60462d9b 100644 --- a/packages/client/ui-conversation/tests/skeleton.spec.tsx +++ b/packages/client/ui-conversation/tests/skeleton.spec.tsx @@ -150,6 +150,7 @@ function mount( stop={stop} command={() => Promise.resolve(true)} translateHint={(key: string) => key} + translateAccess={(key: string) => key} renderSlot={(() => null) as InputBarProps['renderSlot']} {...bar} /> diff --git a/packages/client/ui-primitives/src/Modal.tsx b/packages/client/ui-primitives/src/Modal.tsx index ef790c8b6a..f25135d1da 100644 --- a/packages/client/ui-primitives/src/Modal.tsx +++ b/packages/client/ui-primitives/src/Modal.tsx @@ -16,12 +16,13 @@ import css from './Modal.module.css' * @param props.description - optional supporting sentence under the title. * @param props.children - body (inputs, etc.). * @param props.footer - action row (Cancel / Create). + * @param props.contentClassName - optional class for a scrollable content region. * @param props.headless - render children directly in the card (no default * header/close/body chrome) for dialogs whose figma frame owns its own * header structure; mask, card, Escape, and aria-label remain. * @returns null when closed; otherwise the overlay tree. */ -export function Modal({ open, onClose, title, description, children, footer, className, headless = false }: { +export function Modal({ open, onClose, title, description, children, footer, className, contentClassName, headless = false }: { open: boolean onClose: () => void title: string @@ -29,6 +30,7 @@ export function Modal({ open, onClose, title, description, children, footer, cla children?: ReactNode footer?: ReactNode className?: string + contentClassName?: string headless?: boolean }) { useEffect(() => { @@ -55,7 +57,7 @@ export function Modal({ open, onClose, title, description, children, footer, cla ? children : ( <> -
      +

      {title}

      }> + Create}> ) expect(screen.getByRole('dialog', { name: 'Create new workspace' })).toBeDefined() expect(screen.getByText('Name it.')).toBeDefined() + expect(screen.getByText('Name it.').parentElement?.className).toContain('scrolling-content') fireEvent.keyDown(document, { key: 'a' }) expect(onClose).not.toHaveBeenCalled() fireEvent.keyDown(document, { key: 'Escape' }) From b76a551e10777aeab38ab177141d60d5192c507d Mon Sep 17 00:00:00 2001 From: Chinesezjc Date: Thu, 30 Jul 2026 20:25:05 +0800 Subject: [PATCH 040/139] docs: re-record ui-conversation README pairing after master merge --- packages/client/ui-conversation/README.i18n.yaml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/packages/client/ui-conversation/README.i18n.yaml b/packages/client/ui-conversation/README.i18n.yaml index 1588367646..78e7d2f143 100644 --- a/packages/client/ui-conversation/README.i18n.yaml +++ b/packages/client/ui-conversation/README.i18n.yaml @@ -2,5 +2,5 @@ # side as of the last confirmed-consistent state. Both languages carry equal authority; # after editing either side, bring the other along and re-record with: # pnpm run verify-translation-pairing --write packages/client/ui-conversation/README.md -README.md: fc466190a744a1c13094ca6ebf62755d5bf49c98 -README.zh.md: f6fbff9c1e5d005b64e928680bbf401d94e4ce79 +README.md: 186ae70d16e9e1f1ffeadac441140ae2e5dfd2b5 +README.zh.md: 42604fde855b9e0fadabae9e871362b488957be2 From 917e114b6861cddf2ccc19ededca71abe038cc1e Mon Sep 17 00:00:00 2001 From: Chinesezjc Date: Thu, 30 Jul 2026 20:25:19 +0800 Subject: [PATCH 041/139] docs: re-record ui-conversation README pairing after master merge --- packages/client/ui-conversation/README.i18n.yaml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/packages/client/ui-conversation/README.i18n.yaml b/packages/client/ui-conversation/README.i18n.yaml index 1588367646..5c3353695a 100644 --- a/packages/client/ui-conversation/README.i18n.yaml +++ b/packages/client/ui-conversation/README.i18n.yaml @@ -2,5 +2,5 @@ # side as of the last confirmed-consistent state. Both languages carry equal authority; # after editing either side, bring the other along and re-record with: # pnpm run verify-translation-pairing --write packages/client/ui-conversation/README.md -README.md: fc466190a744a1c13094ca6ebf62755d5bf49c98 -README.zh.md: f6fbff9c1e5d005b64e928680bbf401d94e4ce79 +README.md: 7b39702d8828b80b50d4bc37dbc9350a674b7fdf +README.zh.md: 7f3989e6446581f8264b6fa605dd975be8518ad7 From 0ae52fbb9f8c9b0e9521972fa2e8734070eae1d9 Mon Sep 17 00:00:00 2001 From: Chinesezjc Date: Thu, 30 Jul 2026 20:32:51 +0800 Subject: [PATCH 042/139] fix(fs): guard langFromPath against Object.prototype extension keys A filename whose extension is an Object.prototype key (foo.constructor, foo.__proto__) resolved to the inherited member through the plain-object index, so a function reached the read card's lang hint and failed the tool-output JSON validation, failing an otherwise successful read. Look the extension up as an own property only. Added rejection tests, converted the zh Note headings to the all-English sibling convention, and named the parallel-file-reads terminal golden as the TUI-unchanged evidence in the Testing section (both languages). --- .../feature/2026-07-30-web-read-card.i18n.yaml | 4 ++-- .../implemented/feature/2026-07-30-web-read-card.md | 2 +- .../implemented/feature/2026-07-30-web-read-card.zh.md | 6 +++--- packages/fs/tool-fs/src/read-render.ts | 7 ++++++- packages/fs/tool-fs/tests/read-render.spec.ts | 9 +++++++++ 5 files changed, 21 insertions(+), 7 deletions(-) diff --git a/.agents/notes/implemented/feature/2026-07-30-web-read-card.i18n.yaml b/.agents/notes/implemented/feature/2026-07-30-web-read-card.i18n.yaml index 60cd249263..8371d33560 100644 --- a/.agents/notes/implemented/feature/2026-07-30-web-read-card.i18n.yaml +++ b/.agents/notes/implemented/feature/2026-07-30-web-read-card.i18n.yaml @@ -2,5 +2,5 @@ # side as of the last confirmed-consistent state. Both languages carry equal authority; # after editing either side, bring the other along and re-record with: # pnpm run verify-translation-pairing --write .agents/notes/implemented/feature/2026-07-30-web-read-card.md -2026-07-30-web-read-card.md: 076959680737d3bc439deb367dcdcdc5da83dfb3 -2026-07-30-web-read-card.zh.md: c3e3ec1c3ccd8b36832bc12b6a7ffd000745fb74 +2026-07-30-web-read-card.md: 7d517beb359eec17948ea312b0478604cf92a49b +2026-07-30-web-read-card.zh.md: bfcc17e782a6a1caf0f775875264839af357be0d diff --git a/.agents/notes/implemented/feature/2026-07-30-web-read-card.md b/.agents/notes/implemented/feature/2026-07-30-web-read-card.md index 0769596807..7d517beb35 100644 --- a/.agents/notes/implemented/feature/2026-07-30-web-read-card.md +++ b/.agents/notes/implemented/feature/2026-07-30-web-read-card.md @@ -40,7 +40,7 @@ The read tool now computes `presentationMeta` for every top-level read, a small ## Testing -`packages/fs/tool-fs/tests/read-render.spec.ts` unit-tests `langFromPath` (known extensions case-insensitively, extension read after the last segment and last dot, and the `undefined` cases: dotfile, extensionless, trailing dot, unknown) and `readMetaFromMeta` (a well-formed narrow with and without `lang`, and every rejection: non-object, array, missing or wrong-typed `path`/`totalLines`/`lines`, a malformed line entry, a non-string `lang`, and — because the function narrows the opaque persisted `meta` boundary — the semantically invalid paths a well-typed replayed JSON can still carry: a line `number` that is not a 1-based integer (`0`, `1.5`, `NaN`, `Infinity`), a `totalLines` that is not a non-negative integer (`-1`, `1.5`, `NaN`), and lines whose numbers duplicate, decrease, or exceed `totalLines`). `packages/fs/tool-fs/tests/tools.spec.ts` pins the tool wiring: `execute` attaches the structured window (with and without a `lang` hint) as `meta`, `presentResult` narrows it into a `card: 'read'` view carrying the envelope-stripped `content`, and the decline paths (error result, non-single-text content, malformed envelope with valid meta, and valid envelope with absent or malformed meta) all fall back to `undefined`. Both changed source files hold per-file 100% coverage. This PR carries the snapshot evidence for the persisted meta and the extended union, not for a new rendered view: the re-recorded ACP session fixtures (`fs-read`, `fs-read-window`, `fs-edit`, `fs-policy-reject`, `fs-write-overwrite`, `parallel-tool-calls`, `workspace-context`, `workspace-edit`) pin the persisted read `meta` (with `{{cwd}}`-tokenized paths), and `cordis-inspect-jsdoc` pins the four-member `ToolResultView` union. The keyless snapshot and assembled-application transcript for the rendered read card belong to the follow-up Web PR that consumes the view, since this PR adds no new product-user-visible rendering — the TUI routes the read card through its existing generic dim-Markdown fallback (`transcript.ts` treats `card: 'read'` like `card: 'generic'`), so its output is unchanged. +`packages/fs/tool-fs/tests/read-render.spec.ts` unit-tests `langFromPath` (known extensions case-insensitively, extension read after the last segment and last dot, and the `undefined` cases: dotfile, extensionless, trailing dot, unknown) and `readMetaFromMeta` (a well-formed narrow with and without `lang`, and every rejection: non-object, array, missing or wrong-typed `path`/`totalLines`/`lines`, a malformed line entry, a non-string `lang`, and — because the function narrows the opaque persisted `meta` boundary — the semantically invalid paths a well-typed replayed JSON can still carry: a line `number` that is not a 1-based integer (`0`, `1.5`, `NaN`, `Infinity`), a `totalLines` that is not a non-negative integer (`-1`, `1.5`, `NaN`), and lines whose numbers duplicate, decrease, or exceed `totalLines`). `packages/fs/tool-fs/tests/tools.spec.ts` pins the tool wiring: `execute` attaches the structured window (with and without a `lang` hint) as `meta`, `presentResult` narrows it into a `card: 'read'` view carrying the envelope-stripped `content`, and the decline paths (error result, non-single-text content, malformed envelope with valid meta, and valid envelope with absent or malformed meta) all fall back to `undefined`. Both changed source files hold per-file 100% coverage. This PR carries the snapshot evidence for the persisted meta and the extended union, not for a new rendered view: the re-recorded ACP session fixtures (`fs-read`, `fs-read-window`, `fs-edit`, `fs-policy-reject`, `fs-write-overwrite`, `parallel-tool-calls`, `workspace-context`, `workspace-edit`) pin the persisted read `meta` (with `{{cwd}}`-tokenized paths), and `cordis-inspect-jsdoc` pins the four-member `ToolResultView` union. The keyless snapshot and assembled-application transcript for the rendered read card belong to the follow-up Web PR that consumes the view, since this PR adds no new product-user-visible rendering — the TUI routes the read card through its existing generic dim-Markdown fallback (`transcript.ts` treats `card: 'read'` like `card: 'generic'`), so its output is unchanged. The `apps/cli` `parallel-file-reads` terminal golden (`examples/tui-agent/tests/snapshots/parallel-file-reads/terminal.expected.txt`) pins exactly that: a real replay executes the read tool, renders it through the new `card: 'read'` gate, and the golden's dim-Markdown rows are byte-for-byte what a generic read produced before this card existed. ## Related diff --git a/.agents/notes/implemented/feature/2026-07-30-web-read-card.zh.md b/.agents/notes/implemented/feature/2026-07-30-web-read-card.zh.md index c3e3ec1c3c..bfcc17e782 100644 --- a/.agents/notes/implemented/feature/2026-07-30-web-read-card.zh.md +++ b/.agents/notes/implemented/feature/2026-07-30-web-read-card.zh.md @@ -4,13 +4,13 @@ Status: implemented [English](2026-07-30-web-read-card.md) | 中文 -## 问题 +## Problem `read` 工具返回规范化输出对象 `{ path, offset, lines: [{ number, text }], totalLines }`,但它的展示层把这个结构压平了。`presentCall` 声明为 `GenericCallView`(`kind: 'read'`,一个跟随定位),`presentResult` 返回 `GenericResultView`,其唯一内容是剥掉 `file` 信封后的面向模型文本。收到该视图的 UI 只看到一个压平的文本块:行号以 `N: ` 前缀烘焙进文本、文件语言未知、`totalLines` 丢失。capable 客户端无法像渲染 diff 那样渲染一次 read——即带行号、语法高亮、行号槽与内容分离的代码视图。 结构化数据在下游无法恢复。线上(wire)的工具结果只携带面向模型的 `ContentBlock[]`(已渲染文本)加上一个不透明的 `meta`;规范化输出对象留在工具内,从不到达客户端或会话日志。因此想要行数组、总数和语言提示的客户端无法从 `N: text` 文本里解析回它们——工具必须把它们投影到一个会持久化的通道上。 -## 决策 +## Decision 给[渲染意图 union](../architecture/2026-07-02-tool-render-intent-union.md) 新增第四个 `card` 标签 `read`——仅在结果侧。`ToolResultView` 增加 `ReadResultView { card: 'read'; title?; path; lines: ReadFileLine[]; totalLines; lang?; content? }`;`ReadFileLine { number; text }` 是共享的行单元。`ToolCallView` 不动:待定状态仍是 `GenericCallView`(`kind: 'read'`),因为一次调用在 `execute` 返回前不携带文件内容,调用时没有可展示的结构。这与 bash 终端 card 不同——终端 card 两侧都打标签,因为终端调用在调用时已携带命令和 cwd,而 read 调用既无内容也无总数,给调用侧打标签只会新增一个空变体。 @@ -40,7 +40,7 @@ read 工具现在为每次顶层 read 计算 `presentationMeta`,这是对已 ## Testing -`packages/fs/tool-fs/tests/read-render.spec.ts` 单测 `langFromPath`(已知扩展名的大小写不敏感、扩展名在最后一段与最后一个点之后读取、以及 `undefined` 各情况:dotfile、无扩展名、结尾的点、未知)与 `readMetaFromMeta`(含与不含 `lang` 的良构收窄,以及每种拒绝:非对象、数组、缺失或类型错误的 `path`/`totalLines`/`lines`、畸形行项、非字符串 `lang`,以及——因为该函数收窄持久化的 opaque `meta` 边界——良构类型的回放 JSON 仍可能携带的语义无效路径:不是 1-based 整数的行 `number`(`0`、`1.5`、`NaN`、`Infinity`)、不是非负整数的 `totalLines`(`-1`、`1.5`、`NaN`)、以及行号重复、递减或超过 `totalLines` 的情况)。`packages/fs/tool-fs/tests/tools.spec.ts` 固定工具接线:`execute` 把结构化窗口(含与不含 `lang` 提示)作为 `meta` 附上、`presentResult` 把它收窄为携带剥信封 `content` 的 `card: 'read'` 视图、以及各拒绝路径(错误结果、非单文本内容、meta 有效但信封畸形、信封有效但 meta 缺失或畸形)都回退到 `undefined`。两个改动的源文件保持逐文件 100% 覆盖率。本 PR 携带的是持久化 meta 与扩展后联合类型的快照证据,而非新渲染视图的证据:重录的 ACP session fixtures(`fs-read`、`fs-read-window`、`fs-edit`、`fs-policy-reject`、`fs-write-overwrite`、`parallel-tool-calls`、`workspace-context`、`workspace-edit`)钉住持久化的读取 `meta`(含 `{{cwd}}` 令牌化路径),`cordis-inspect-jsdoc` 钉住四成员的 `ToolResultView` 联合类型。已渲染读取 card 的 keyless 快照与组装应用 transcript 属于消费该视图的后续 Web PR,因为本 PR 不新增任何面向产品用户可见的渲染——TUI 通过其现有的通用 dim-Markdown 回退路由读取 card(`transcript.ts` 把 `card: 'read'` 当作 `card: 'generic'` 处理),因此其输出保持不变。 +`packages/fs/tool-fs/tests/read-render.spec.ts` 单测 `langFromPath`(已知扩展名的大小写不敏感、扩展名在最后一段与最后一个点之后读取、以及 `undefined` 各情况:dotfile、无扩展名、结尾的点、未知)与 `readMetaFromMeta`(含与不含 `lang` 的良构收窄,以及每种拒绝:非对象、数组、缺失或类型错误的 `path`/`totalLines`/`lines`、畸形行项、非字符串 `lang`,以及——因为该函数收窄持久化的 opaque `meta` 边界——良构类型的回放 JSON 仍可能携带的语义无效路径:不是 1-based 整数的行 `number`(`0`、`1.5`、`NaN`、`Infinity`)、不是非负整数的 `totalLines`(`-1`、`1.5`、`NaN`)、以及行号重复、递减或超过 `totalLines` 的情况)。`packages/fs/tool-fs/tests/tools.spec.ts` 固定工具接线:`execute` 把结构化窗口(含与不含 `lang` 提示)作为 `meta` 附上、`presentResult` 把它收窄为携带剥信封 `content` 的 `card: 'read'` 视图、以及各拒绝路径(错误结果、非单文本内容、meta 有效但信封畸形、信封有效但 meta 缺失或畸形)都回退到 `undefined`。两个改动的源文件保持逐文件 100% 覆盖率。本 PR 携带的是持久化 meta 与扩展后联合类型的快照证据,而非新渲染视图的证据:重录的 ACP session fixtures(`fs-read`、`fs-read-window`、`fs-edit`、`fs-policy-reject`、`fs-write-overwrite`、`parallel-tool-calls`、`workspace-context`、`workspace-edit`)钉住持久化的读取 `meta`(含 `{{cwd}}` 令牌化路径),`cordis-inspect-jsdoc` 钉住四成员的 `ToolResultView` 联合类型。已渲染读取 card 的 keyless 快照与组装应用 transcript 属于消费该视图的后续 Web PR,因为本 PR 不新增任何面向产品用户可见的渲染——TUI 通过其现有的通用 dim-Markdown 回退路由读取 card(`transcript.ts` 把 `card: 'read'` 当作 `card: 'generic'` 处理),因此其输出保持不变。`apps/cli` 的 `parallel-file-reads` 终端 golden(`examples/tui-agent/tests/snapshots/parallel-file-reads/terminal.expected.txt`)正钉住这一点:一次真实回放执行 read 工具、经新的 `card: 'read'` 门渲染,golden 的 dim-Markdown 行与本 card 出现前 generic read 所产出的逐字节一致。 ## Related diff --git a/packages/fs/tool-fs/src/read-render.ts b/packages/fs/tool-fs/src/read-render.ts index 43ff2b8ca5..68a2d44e28 100644 --- a/packages/fs/tool-fs/src/read-render.ts +++ b/packages/fs/tool-fs/src/read-render.ts @@ -201,7 +201,12 @@ export function langFromPath(path: string): string | undefined { const dot = base.lastIndexOf('.') // A leading dot is a dotfile (no extension), not an empty extension. if (dot <= 0) return undefined - return LANG_BY_EXTENSION[base.slice(dot + 1).toLowerCase()] + const ext = base.slice(dot + 1).toLowerCase() + // Own-property check only: a filename whose extension is an Object.prototype + // key (`foo.constructor`, `foo.__proto__`) must map to no language, not to the + // inherited member — otherwise a function would reach `lang` and fail the + // tool-output JSON validation. + return Object.hasOwn(LANG_BY_EXTENSION, ext) ? LANG_BY_EXTENSION[ext] : undefined } /** diff --git a/packages/fs/tool-fs/tests/read-render.spec.ts b/packages/fs/tool-fs/tests/read-render.spec.ts index 14c9c57bf1..848e54fc7c 100644 --- a/packages/fs/tool-fs/tests/read-render.spec.ts +++ b/packages/fs/tool-fs/tests/read-render.spec.ts @@ -139,6 +139,15 @@ describe('langFromPath', () => { expect(langFromPath('data.unknownext')).toBeUndefined() expect(langFromPath('trailingdot.')).toBeUndefined() }) + + it('returns undefined for a filename whose extension is an Object.prototype key', () => { + // Own-property lookup only: these must not resolve to the inherited member + // (a function/object), which would fail the tool-output JSON validation. + expect(langFromPath('foo.constructor')).toBeUndefined() + expect(langFromPath('foo.__proto__')).toBeUndefined() + expect(langFromPath('foo.toString')).toBeUndefined() + expect(langFromPath('foo.hasOwnProperty')).toBeUndefined() + }) }) describe('readMetaFromMeta', () => { From 224a9d5f0911f91c9dc1219a6cbdc92c8911a2a1 Mon Sep 17 00:00:00 2001 From: Chinesezjc Date: Thu, 30 Jul 2026 20:42:29 +0800 Subject: [PATCH 043/139] fix(client-web): reject unknown web kind, lock fixture to contract, observe web card in boot smoke - webCardModel returns null for an unknown web `kind` (wire from a newer host) instead of drawing it as a malformed fetch, matching the unknown-`card` and terminal-model wire-boundary default. - Fixture WEB_SEARCH_RESULT/WEB_FETCH_RESULT and the source type derive from the contract's ToolResultView via Extract, so a new contract field fails at the type level rather than drifting silently. - built-boot smoke asserts the web_search/web_fetch turns render their keyed WebRow cards, giving the registration and wire projection an assembled check. - DetailsPanel comment no longer claims the card omits content for search. - ui-primitives README inline-Chinese limitation now lists WebBlock's controls. --- apps/web/tests/built-boot.snapshot.ts | 11 +++++++++ .../client/connection/src/client/fixture.ts | 19 ++++----------- .../src/client/contract/web-card-model.ts | 24 +++++++++++++++---- .../src/client/skeleton/DetailsPanel.tsx | 10 ++++---- .../ui-conversation/tests/web-card.spec.tsx | 4 ++++ .../client/ui-primitives/README.i18n.yaml | 4 ++-- packages/client/ui-primitives/README.md | 2 +- packages/client/ui-primitives/README.zh.md | 2 +- 8 files changed, 48 insertions(+), 28 deletions(-) diff --git a/apps/web/tests/built-boot.snapshot.ts b/apps/web/tests/built-boot.snapshot.ts index 69d5d5cfae..8bf48fc761 100644 --- a/apps/web/tests/built-boot.snapshot.ts +++ b/apps/web/tests/built-boot.snapshot.ts @@ -108,6 +108,17 @@ it('boots the built plugin graph and renders a fixture session end to end', asyn expect(document.querySelector('[data-sample="bash-global"]')).not.toBeNull() }, { timeout: 10_000 }) + // The web render intent reaches the assembled boot graph: the fixture's + // web_search / web_fetch turns render their keyed WebRow cards, proving the + // registration, wire projection, and card rendering survive the real bundle + // path (not just the per-package src benches). Without this the whole web + // card could silently fall back to the generic row and every new unit test + // would still pass. + await waitFor(() => { + expect(document.querySelector('[data-web="search"]')).not.toBeNull() + expect(document.querySelector('[data-web="fetch"]')).not.toBeNull() + }, { timeout: 10_000 }) + // Every bundle injected its plugin-owned style tag (the loader's CSS path). const styleOwners = [...document.head.querySelectorAll('style[data-plugin]')] .map(style => style.getAttribute('data-plugin')) diff --git a/packages/client/connection/src/client/fixture.ts b/packages/client/connection/src/client/fixture.ts index 7c81d702b7..cc8332d081 100644 --- a/packages/client/connection/src/client/fixture.ts +++ b/packages/client/connection/src/client/fixture.ts @@ -136,27 +136,16 @@ const TERMINAL_EXIT_STATUS: Record, 'card' | 'kind' | 'content'> = { answer: 'DeepSeek Harness is a plugin-based agent harness on vendored Cordis where **every capability is a plugin**.', sources: [ { @@ -179,7 +168,7 @@ const WEB_SEARCH_RESULT: { answer: string; sources: WebSourceFixture[]; truncate } /** The `web_fetch` result view for fixture turn 67, authored inline for the same reason. */ -const WEB_FETCH_RESULT: { url: string; statusCode: number; truncated: boolean } = { +const WEB_FETCH_RESULT: Omit, 'card' | 'kind' | 'content'> = { url: 'https://www.deepseek.com/blog/harness-architecture', statusCode: 200, truncated: false, diff --git a/packages/client/ui-conversation/src/client/contract/web-card-model.ts b/packages/client/ui-conversation/src/client/contract/web-card-model.ts index 28eb3de2d2..f2b15e023a 100644 --- a/packages/client/ui-conversation/src/client/contract/web-card-model.ts +++ b/packages/client/ui-conversation/src/client/contract/web-card-model.ts @@ -40,6 +40,9 @@ export const CHAT_WEB_MAX_SOURCES = 8 * cannot be trusted to be one of the compiled variants, and a generic result * view (a web tool's error path returns the generic card, whose text the * generic path preserves). + * - A web card whose `kind` this UI version does not know (a newer host's + * value): the wire cannot be trusted to be `search` or `fetch`, so it takes + * the generic path rather than rendering as a malformed fetch. * @param block - RunningToolCall or ToolResultNode off the snapshot caches. * @returns the web-card props, or null for the generic path. */ @@ -61,10 +64,21 @@ export function webCardModel(block: ToolCallBlock): WebBlockProps | null { truncated: result.truncated, } } - return { - kind: 'fetch', - url: result.url, - statusCode: result.statusCode, - truncated: result.truncated, + // Discriminate `fetch` explicitly rather than treating it as the else of + // `search`: a `kind` this UI version does not know arrives over the wire from + // a newer host, and reading it as a fetch would draw an empty URL and + // `HTTP undefined`. It takes the generic path, the same wire-boundary default + // an unknown `card` tag takes above. The static union narrows `kind` to + // `'fetch'` here, but the runtime value is off the wire, so the guard and its + // null fallthrough are load-bearing despite the type. + // oxlint-disable-next-line typescript/no-unnecessary-condition + if (result.kind === 'fetch') { + return { + kind: 'fetch', + url: result.url, + statusCode: result.statusCode, + truncated: result.truncated, + } } + return null } diff --git a/packages/client/ui-conversation/src/client/skeleton/DetailsPanel.tsx b/packages/client/ui-conversation/src/client/skeleton/DetailsPanel.tsx index 57c5d63460..cb4b9aa7b9 100644 --- a/packages/client/ui-conversation/src/client/skeleton/DetailsPanel.tsx +++ b/packages/client/ui-conversation/src/client/skeleton/DetailsPanel.tsx @@ -152,10 +152,12 @@ function OutputBody({ material, cwd }: { material: CallMaterial; cwd: string | u } const web = webCardModel(material.block) // Full source-list allowance here (the panel is the single-call reading - // surface); the chat rows cap it at CHAT_WEB_MAX_SOURCES. The card is a - // summary — a web_fetch card shows only the URL and status — so the details - // panel also renders the flattened result content below it (the fetched body, - // the search answer + source markdown), which the card does not carry. + // surface); the chat rows cap it at CHAT_WEB_MAX_SOURCES. Below the card the + // panel also renders the flattened result content — the model-visible text + // the card does not carry verbatim (a web_fetch card shows only the URL and + // status, so its fetched body lives only here; a search card's answer and + // sources are structured, so the flattened form repeats them as the raw text + // the model saw). if (web !== null) { const settled = 'kind' in material.block ? material.block : null const body = settled === null ? '' : renderResult(settled) diff --git a/packages/client/ui-conversation/tests/web-card.spec.tsx b/packages/client/ui-conversation/tests/web-card.spec.tsx index d6f04eb147..e92612c810 100644 --- a/packages/client/ui-conversation/tests/web-card.spec.tsx +++ b/packages/client/ui-conversation/tests/web-card.spec.tsx @@ -105,6 +105,10 @@ describe('webCardModel', () => { // documented generic-card default takes it, not a crash. const future = { card: 'chart', kind: 'search' } as unknown as ToolResultView expect(webCardModel(settledSearch({ resultView: future }))).toBeNull() + // A web card whose kind this UI version does not know (a newer host's + // value) also takes the generic path, not a malformed fetch. + const futureKind = { card: 'web', kind: 'timeline' } as unknown as ToolResultView + expect(webCardModel(settledSearch({ resultView: futureKind }))).toBeNull() }) }) diff --git a/packages/client/ui-primitives/README.i18n.yaml b/packages/client/ui-primitives/README.i18n.yaml index 2a64292653..d7eae92129 100644 --- a/packages/client/ui-primitives/README.i18n.yaml +++ b/packages/client/ui-primitives/README.i18n.yaml @@ -2,5 +2,5 @@ # side as of the last confirmed-consistent state. Both languages carry equal authority; # after editing either side, bring the other along and re-record with: # pnpm run verify-translation-pairing --write packages/client/ui-primitives/README.md -README.md: b5b79f7f0d01afb2d06fb18bf30131cbdda75ca2 -README.zh.md: b10183496479249346da5da808f5ab3b6d2eef67 +README.md: 099da3ae3d4e2b45507fd18d279650ef0525f36a +README.zh.md: dc7fa5f78ea758cea75e86eefb0c06ebe92e61d2 diff --git a/packages/client/ui-primitives/README.md b/packages/client/ui-primitives/README.md index b5b79f7f0d..099da3ae3d 100644 --- a/packages/client/ui-primitives/README.md +++ b/packages/client/ui-primitives/README.md @@ -29,5 +29,5 @@ None; this package neither assembles nor sends a provider request. - **Glyph-level icons are redrawn approximations** — the fish logo (and the sparkle held by ui-conversation) come from font glyphs whose vector geometry is not exportable from the local design data; hand-authored recreations stand in until an exact export path exists. - **Pill and Input have no design source** — both atoms are self-defined; the sidebar search field and view-tab strip that resemble them are consumer-owned compositions, not these atoms. - **StateDot `Active` variant is a hidden placeholder in the design** — not implemented; the four shipped states (done/warning/ongoing/error) are the complete P-I surface. -- **This package's user-facing copy is inline Chinese, not localized** — the atoms are zero-cordis and so cannot reach `ctx.locale`; `TerminalBlock`'s exit-code and signal pills, its copy and expand controls, and `CodeBlock`'s copy control are all hardcoded. This matches the repo-wide state the locale package records (only the Settings surface is translated); extracting these into the `zh`/`en` dictionaries needs a localization channel for zero-cordis atoms and belongs to that repo-wide extraction. +- **This package's user-facing copy is inline Chinese, not localized** — the atoms are zero-cordis and so cannot reach `ctx.locale`; `TerminalBlock`'s exit-code and signal pills, its copy and expand controls, `CodeBlock`'s copy control, and `WebBlock`'s source expand/collapse controls and its source-list and fetch truncation notes are all hardcoded. This matches the repo-wide state the locale package records (only the Settings surface is translated); extracting these into the `zh`/`en` dictionaries needs a localization channel for zero-cordis atoms and belongs to that repo-wide extraction. - **`TerminalBlock` is not a terminal emulator** — it renders settled or still-running command output, not an interactive session: SGR color and attributes are honored, and so are the in-line cursor movements a progress line uses — carriage return, backspace, erase-in-line, tab stops and character width. Absolute cursor positioning, screen clearing, and alternate-screen sequences are stripped. Basic-16 magenta and cyan have no token equivalent and stay literal rgb. diff --git a/packages/client/ui-primitives/README.zh.md b/packages/client/ui-primitives/README.zh.md index b101834964..dc7fa5f78e 100644 --- a/packages/client/ui-primitives/README.zh.md +++ b/packages/client/ui-primitives/README.zh.md @@ -28,5 +28,5 @@ - **字形级图标是重新绘制的近似版本**:鱼形标志(以及 ui-conversation 持有的闪光图标)来自字体字形,而本地设计数据无法导出其矢量几何;在获得精确导出路径前,使用手工重建版本代替。 - **Pill 与 Input 没有设计来源**:两个原子组件均自行定义;与其相似的侧边栏搜索字段和视图标签条由消费方组合,不是这些原子组件。 - **StateDot 的 `Active` 变体是设计中的隐藏占位符**:尚未实现;已交付的四种状态(done/warning/ongoing/error)构成完整的 P-I 表层。 -- **本包面向用户的文案是内联中文,未做本地化**:这些原子组件是 zero-cordis 的,因此拿不到 `ctx.locale`;`TerminalBlock` 的退出码与信号胶囊、它的复制与展开控件,以及 `CodeBlock` 的复制控件全部硬编码。这与 locale 包记录的全仓现状一致(只有 Settings 表面做了翻译);把它们抽取进 `zh`/`en` 字典需要为 zero-cordis 原子组件提供一条本地化通道,属于那次全仓抽取的范围。 +- **本包面向用户的文案是内联中文,未做本地化**:这些原子组件是 zero-cordis 的,因此拿不到 `ctx.locale`;`TerminalBlock` 的退出码与信号胶囊、它的复制与展开控件、`CodeBlock` 的复制控件,以及 `WebBlock` 的来源展开/收起控件与它的来源列表与 fetch 截断提示,全部硬编码。这与 locale 包记录的全仓现状一致(只有 Settings 表面做了翻译);把它们抽取进 `zh`/`en` 字典需要为 zero-cordis 原子组件提供一条本地化通道,属于那次全仓抽取的范围。 - **`TerminalBlock` 不是终端模拟器**:它渲染已结束或仍在运行的命令输出,而不是交互式会话:SGR 颜色与属性会被遵循,进度行所用的行内光标移动同样被遵循——回车、退格、行内擦除、制表位与字符宽度。绝对光标定位、清屏与备用屏幕序列会被剥离。基础 16 色中的洋红与青色没有对应 token,保持字面 rgb。 From 7da7d5784dd286457608dd1a854f76f5cbc0e530 Mon Sep 17 00:00:00 2001 From: kingwl Date: Thu, 30 Jul 2026 20:42:48 +0800 Subject: [PATCH 044/139] Open command menu from composer plus button --- ...input-machine-and-slash-pipeline.i18n.yaml | 4 +- ...25-web-input-machine-and-slash-pipeline.md | 3 +- ...web-input-machine-and-slash-pipeline.zh.md | 3 +- apps/web/tests/lifecycle-chrome.e2e.ts | 33 +++++++++++- .../snapshots/code-mode-round/ui.expected.md | 2 +- .../cordis-tool-round/ui.expected.md | 2 +- .../snapshots/fresh-round-trip/ui.expected.md | 2 +- .../lifecycle-chrome/command-menu.expected.md | 6 +++ .../lifecycle-chrome/hero.expected.md | 2 +- .../lifecycle-chrome/reloaded.expected.md | 2 +- .../live-interactions/cancel.expected.md | 2 +- .../live-interactions/error-auth.expected.md | 2 +- .../live-interactions/retry.expected.md | 2 +- .../snapshots/message-actions/ui.expected.md | 2 +- .../question-composer/answered.expected.md | 2 +- .../queue-actions/editing.expected.md | 2 +- .../snapshots/queue-actions/ui.expected.md | 2 +- .../snapshots/seeded-history/ui.expected.md | 2 +- .../snapshots/steering/settled.expected.md | 2 +- .../client/ui-conversation/README.i18n.yaml | 4 +- packages/client/ui-conversation/README.md | 2 +- packages/client/ui-conversation/README.zh.md | 2 +- .../ui-conversation/src/client/apply.ts | 26 +++++++++- .../src/client/contract/slots.ts | 8 +-- .../ui-conversation/src/client/input/hub.ts | 11 ++++ .../src/client/skeleton/InputBar.tsx | 20 +++++--- .../tests/apply-inject.spec.tsx | 2 + .../ui-conversation/tests/input-bar.spec.tsx | 31 ++++++++--- .../tests/input-matrix.spec.tsx | 4 +- .../tests/input-scenarios.spec.tsx | 10 ++++ .../ui-conversation/tests/skeleton.spec.tsx | 2 + packages/client/ui-slash/README.i18n.yaml | 4 +- packages/client/ui-slash/README.md | 4 +- packages/client/ui-slash/README.zh.md | 4 +- .../client/ui-slash/src/client/controller.ts | 44 +++++++++++++++- .../client/ui-slash/tests/service.spec.ts | 51 +++++++++++++++++++ 36 files changed, 256 insertions(+), 50 deletions(-) create mode 100644 apps/web/tests/snapshots/lifecycle-chrome/command-menu.expected.md diff --git a/.agents/notes/implemented/architecture/2026-07-25-web-input-machine-and-slash-pipeline.i18n.yaml b/.agents/notes/implemented/architecture/2026-07-25-web-input-machine-and-slash-pipeline.i18n.yaml index 98423a8c7d..ea630a99f9 100644 --- a/.agents/notes/implemented/architecture/2026-07-25-web-input-machine-and-slash-pipeline.i18n.yaml +++ b/.agents/notes/implemented/architecture/2026-07-25-web-input-machine-and-slash-pipeline.i18n.yaml @@ -2,5 +2,5 @@ # side as of the last confirmed-consistent state. Both languages carry equal authority; # after editing either side, bring the other along and re-record with: # pnpm run verify-translation-pairing --write .agents/notes/implemented/architecture/2026-07-25-web-input-machine-and-slash-pipeline.md -2026-07-25-web-input-machine-and-slash-pipeline.md: 92bb91c3e892d928cedf18ec57c725a116b6ffc8 -2026-07-25-web-input-machine-and-slash-pipeline.zh.md: 5bee6df52f16d935aa4f4ccff8627a2d43d44c8c +2026-07-25-web-input-machine-and-slash-pipeline.md: 2793e9045fe5a3c82f52c65503dd4a8cdf6a0596 +2026-07-25-web-input-machine-and-slash-pipeline.zh.md: e3a35c4e55525fedd835eace973f114bd15da37b diff --git a/.agents/notes/implemented/architecture/2026-07-25-web-input-machine-and-slash-pipeline.md b/.agents/notes/implemented/architecture/2026-07-25-web-input-machine-and-slash-pipeline.md index 92bb91c3e8..2793e9045f 100644 --- a/.agents/notes/implemented/architecture/2026-07-25-web-input-machine-and-slash-pipeline.md +++ b/.agents/notes/implemented/architecture/2026-07-25-web-input-machine-and-slash-pipeline.md @@ -63,7 +63,7 @@ Calls that stay un-evented (registry registration → explicit call → await): A trigger/menu/pick pipeline with zero knowledge of "commands": - The service holds only the source registry (`SlashSource{trigger: '/'|'@', name, order?, candidates, onPick, matchSpace?, matchEnter?}`; (trigger,name) unique; the optional `order` sorts the roster — lower first, default 0, ties keep registration order — and that sorted roster is both group order and polling order) and `sessionOf(sctx)`. Implementing a match hook IS the declaration of participation in space/enter adjudication; the pipeline polls in roster order, the first non-undefined answer wins, and no claimant means the default sink. matchSpace is synchronous (space fires mid-keystroke; hot cache only); matchEnter is asynchronous (it may await the source's own warmup, and a warmup failure rejects). -- The controller holds the single authoritative hit (span included; retained for Space after the menu closes), the per-session menu store, the candidate-fetch generation, keyboard arbitration (combobox mode: focus stays in the textarea, ↑↓/Enter/Escape are intercepted and all pass the IME composition guard, with the single exception Shift+Enter unconditionally going first), and pick orchestration (outcome → self-dispatched bail events); a `dismiss()` verb backs MenuView's injected `onDismiss` (a pointer down outside both the menu and the surrounding composer card closes the menu; MenuView also localizes group titles through the `slash.menu` locale namespace and clamps its height to the viewport space above the composer via ui-primitives' `useAnchoredMaxHeight`); at each session scope's birth it runs `warm(projection)` once over the source roster — within that scope the projection holds only the stable sessionId, with no published/capability transitions; the scope disposer tears down the controller. +- The controller holds the single authoritative hit (span included; retained for Space after the menu closes), the per-session menu store, the candidate-fetch generation, keyboard arbitration (combobox mode: focus stays in the textarea, ↑↓/Enter/Escape are intercepted and all pass the IME composition guard, with the single exception Shift+Enter unconditionally going first), and pick orchestration (outcome → self-dispatched bail events). `toggleSource(name, syntheticHit)` is the chrome-launch path: it seeds only that registered source over the caller's textarea selection and publishes `launcher = name` until close; ordinary typed tracking clears the launcher and restores the full trigger roster. Both paths render the same MenuView and execute the same `onPick` chain. A `dismiss()` verb backs MenuView's injected `onDismiss` (a pointer down outside both the menu and the surrounding composer card closes the menu; MenuView also localizes group titles through the `slash.menu` locale namespace and clamps its height to the viewport space above the composer via ui-primitives' `useAnchoredMaxHeight`); at each session scope's birth it runs `warm(projection)` once over the source roster — within that scope the projection holds only the stable sessionId, with no published/capability transitions; the scope disposer tears down the controller. - Trigger-detection word boundaries (`user@host` and URL `/` never trigger) and the guard tiers (plain: `/` everywhere + `@` inline / claimed: `/` suppressed, `@` live / frozen: none) are the frozen pure core. ### hub / facade: the resident shell and the strict-session input body @@ -122,6 +122,7 @@ The state machine's entire behavior is covered by pure-JS unit tests (event sequ | Space adjudication also claiming execute-kind commands | The misfire defense: after a space the whole line is an ordinary prompt; irreversible side effects keep explicit entry points only | | A generic tokenPattern decoration mechanism | Structured occurrence records replace pattern scanning | | A placeholder select resident in the tool row | Named seats stay empty until registration; a placeholder clashing with the real implementation is two sources of truth | +| A second plus-menu component/controller, or an Add/File group above Command | It would duplicate async candidates, keyboard highlight, focus retention, and pick state; the plus control is only a source-filtered launcher for the existing MenuView, and this scope has no file capability | | All references through U+FFFC chips (the pre-Decision-21 line) | Plain text + derived decoration carries zero identity state; the literal text IS the model projection, sparing undo/clipboard any special cases; the chip chain is kept for scenarios needing indivisible atomicity | ## Consequences diff --git a/.agents/notes/implemented/architecture/2026-07-25-web-input-machine-and-slash-pipeline.zh.md b/.agents/notes/implemented/architecture/2026-07-25-web-input-machine-and-slash-pipeline.zh.md index 5bee6df52f..e3a35c4e55 100644 --- a/.agents/notes/implemented/architecture/2026-07-25-web-input-machine-and-slash-pipeline.zh.md +++ b/.agents/notes/implemented/architecture/2026-07-25-web-input-machine-and-slash-pipeline.zh.md @@ -63,7 +63,7 @@ occurrence 表与 chip 三投影: 对"命令"零知识的触发/菜单/pick 管线: - service 只有 source 注册表(`SlashSource{trigger: '/'|'@', name, order?, candidates, onPick, matchSpace?, matchEnter?}`;(trigger,name) 唯一;可选 `order` 对 roster 排序——越小越靠前、默认 0、同值保持注册序——排序后的 roster 同时是组序与轮询序)与 `sessionOf(sctx)`。实现 match 钩子即参与空格/回车裁决的声明;管线按 roster 序轮询,首个非 undefined 应答胜出,无人认领落 default sink。matchSpace 同步(空格在击键中触发,只许热缓存);matchEnter 异步(可 await 源自身预热,预热失败即 reject)。 -- controller 持有唯一权威 hit(含 span;菜单关闭后为 Space 保留)、per-session menu store、候选 fetch generation、键盘仲裁(combobox 模式:焦点始终在 textarea,↑↓/Enter/Escape 拦截且全程过 IME composition 守卫,唯一例外 Shift+Enter 无条件先行)、pick 编排(outcome → 自派 bail 事件);`dismiss()` 动词支撑 MenuView 注入的 `onDismiss`(指针落在菜单与所在 composer 卡片之外即关闭菜单;MenuView 还经 `slash.menu` locale 命名空间本地化组标题,并经 ui-primitives 的 `useAnchoredMaxHeight` 把高度收敛到 composer 上方的视口空间);每个 session scope 出生时对 source roster 做一次 `warm(projection)`,projection 在该 scope 内只有稳定的 sessionId,无 published/能力跃迁;scope disposer 拆除 controller。 +- controller 持有唯一权威 hit(含 span;菜单关闭后为 Space 保留)、per-session menu store、候选 fetch generation、键盘仲裁(combobox 模式:焦点始终在 textarea,↑↓/Enter/Escape 拦截且全程过 IME composition 守卫,唯一例外 Shift+Enter 无条件先行),以及 pick 编排(outcome → 自派 bail 事件)。`toggleSource(name, syntheticHit)` 是 chrome launcher 路径:它基于调用方的 textarea selection,只 seed 对应的已注册 source,并发布 `launcher = name` 直至关闭;普通的键入式 tracking 会清除 launcher 并恢复完整的 trigger roster。两条路径渲染同一个 MenuView,并执行同一条 `onPick` 链。`dismiss()` 动词支撑 MenuView 注入的 `onDismiss`(指针落在菜单与所在 composer 卡片之外即关闭菜单;MenuView 还经 `slash.menu` locale 命名空间本地化组标题,并经 ui-primitives 的 `useAnchoredMaxHeight` 把高度收敛到 composer 上方的视口空间);每个 session scope 出生时对 source roster 做一次 `warm(projection)`,projection 在该 scope 内只有稳定的 sessionId,无 published/能力跃迁;scope disposer 拆除 controller。 - 触发检测词边界(`user@host`、URL `/` 永不触发)、守卫分档(plain:`/` 到处 + `@` 行内 / claimed:`/` 抑制、`@` 活 / frozen:全无)为冻结纯核。 ### hub / facade:常驻外壳与严格 session 输入体 @@ -122,6 +122,7 @@ skill/@subagent 引用不走占位符 + occurrence 身份链——pick 直接把 | 空格裁决也认领即执行型命令 | 误触发防线:空格后整行是普通 prompt;不可逆副作用只留显式入口 | | 通用 tokenPattern 装饰机制 | 结构化 occurrence 记录取代模式扫描 | | 占位 select 常驻工具行 | 具名坑位空到注册为止;占位件与真实现冲突时是双真相源 | +| 第二套加号菜单组件/controller,或在 Command 上方增加 Add/File 分组 | 这会重复异步候选、键盘高亮、焦点保留与 pick 状态;加号控件只是既有 MenuView 按 source 过滤的 launcher,且此 scope 没有文件能力 | | 引用一律走 U+FFFC chip(决策 21 前旧线) | 纯文本 + 派生装饰零身份状态;原文即模型投影,undo/剪贴板免特判;chip 链保留给需要不可分原子性的场景 | ## 后果 diff --git a/apps/web/tests/lifecycle-chrome.e2e.ts b/apps/web/tests/lifecycle-chrome.e2e.ts index d4d684b1de..746cd37e36 100644 --- a/apps/web/tests/lifecycle-chrome.e2e.ts +++ b/apps/web/tests/lifecycle-chrome.e2e.ts @@ -25,6 +25,7 @@ import { connectFreshWorkspace, newEnglishPage, saveFailureShot } from './suppor const SNAPSHOT_DIR = fileURLToPath(new URL('./snapshots/lifecycle-chrome', import.meta.url)) const FIXTURE = join(SNAPSHOT_DIR, 'session.jsonl') const HERO_EXPECTED = join(SNAPSHOT_DIR, 'hero.expected.md') +const COMMAND_MENU_EXPECTED = join(SNAPSHOT_DIR, 'command-menu.expected.md') // Post-reload golden: the same settled conversation rebuilt purely from // persistence + history — byte-equal rendering is exactly the recovery claim. const RELOADED_EXPECTED = join(SNAPSHOT_DIR, 'reloaded.expected.md') @@ -56,6 +57,34 @@ describe('web e2e: lifecycle & chrome (workspace flow / reload / dark mode)', () await scaffold?.close() }) + it.skipIf(MODE === 'record')('opens the shared slash menu from plus with only Command candidates', async () => { + onTestFailed(() => saveFailureShot(page, 'web-e2e-command-menu-launcher')) + const launcher = page.getByRole('button', { name: 'Commands' }) + await launcher.click() + const menu = page.getByRole('listbox', { name: 'Trigger suggestions' }) + await menu.waitFor({ timeout: 10_000 }) + const snapshot = await captureStableAria(page, '[role="listbox"]', scaffold.workspaceCwd) + await compareOrRefreshGolden(COMMAND_MENU_EXPECTED, snapshot, MODE) + expect(snapshot).toContain('text: Commands') + expect(snapshot).not.toContain('text: Skills') + expect(snapshot).not.toContain('text: Subagents') + const launchedBox = await menu.boundingBox() + await page.locator('textarea').first().press('Escape') + await expect.poll(() => menu.count()).toBe(0) + const input = page.locator('textarea').first() + await input.fill('/') + await menu.waitFor({ timeout: 10_000 }) + const typedBox = await menu.boundingBox() + expect(launchedBox).not.toBeNull() + expect(typedBox).not.toBeNull() + expect(Math.abs(launchedBox!.x - typedBox!.x)).toBeLessThan(1) + expect(Math.abs( + launchedBox!.y + launchedBox!.height - typedBox!.y - typedBox!.height, + )).toBeLessThan(1) + await input.fill('') + await expect.poll(() => menu.count()).toBe(0) + }) + it('sends the first prompt from the empty-state hero (all modes)', async () => { onTestFailed(() => saveFailureShot(page, 'web-e2e-lifecycle-send')) if (MODE !== 'record') { @@ -152,6 +181,8 @@ describe('web e2e: lifecycle & chrome (workspace flow / reload / dark mode)', () it.skipIf(MODE === 'record')('keeps the fixture inventory closed', async () => { expect(tripwire.warnings).toEqual([]) - await assertFixtureInventory(SNAPSHOT_DIR, ['session.jsonl', 'hero.expected.md', 'reloaded.expected.md']) + await assertFixtureInventory(SNAPSHOT_DIR, [ + 'session.jsonl', 'command-menu.expected.md', 'hero.expected.md', 'reloaded.expected.md', + ]) }) }) diff --git a/apps/web/tests/snapshots/code-mode-round/ui.expected.md b/apps/web/tests/snapshots/code-mode-round/ui.expected.md index 0282a16f80..31476daefd 100644 --- a/apps/web/tests/snapshots/code-mode-round/ui.expected.md +++ b/apps/web/tests/snapshots/code-mode-round/ui.expected.md @@ -33,7 +33,7 @@ - img - text: {{clock}} - textbox "Message the agent" -- button "Add attachment": +- button "Commands": - img - 'button "Access mode, current: Danger Full Access"': Danger Full Access - button "Plan mode off, press to turn on": Plan off diff --git a/apps/web/tests/snapshots/cordis-tool-round/ui.expected.md b/apps/web/tests/snapshots/cordis-tool-round/ui.expected.md index 5b51e47cf4..4425921fdf 100644 --- a/apps/web/tests/snapshots/cordis-tool-round/ui.expected.md +++ b/apps/web/tests/snapshots/cordis-tool-round/ui.expected.md @@ -47,7 +47,7 @@ - img - text: {{clock}} - textbox "Message the agent" -- button "Add attachment": +- button "Commands": - img - 'button "Access mode, current: Danger Full Access"': Danger Full Access - button "Plan mode off, press to turn on": Plan off diff --git a/apps/web/tests/snapshots/fresh-round-trip/ui.expected.md b/apps/web/tests/snapshots/fresh-round-trip/ui.expected.md index 49c7958292..64c62f85d6 100644 --- a/apps/web/tests/snapshots/fresh-round-trip/ui.expected.md +++ b/apps/web/tests/snapshots/fresh-round-trip/ui.expected.md @@ -30,7 +30,7 @@ - img - text: {{clock}} - textbox "Message the agent" -- button "Add attachment": +- button "Commands": - img - 'button "Access mode, current: Danger Full Access"': Danger Full Access - button "Plan mode off, press to turn on": Plan off diff --git a/apps/web/tests/snapshots/lifecycle-chrome/command-menu.expected.md b/apps/web/tests/snapshots/lifecycle-chrome/command-menu.expected.md new file mode 100644 index 0000000000..47ba98cf05 --- /dev/null +++ b/apps/web/tests/snapshots/lifecycle-chrome/command-menu.expected.md @@ -0,0 +1,6 @@ +- listbox "Trigger suggestions": + - text: Commands + - option "goal set or view the goal for a long-running task" [selected] + - option "permission Switch the permission preset (sandbox mode + approval policy)" + - option "plan Enter or leave plan mode" + - option "model Select the model for this conversation" diff --git a/apps/web/tests/snapshots/lifecycle-chrome/hero.expected.md b/apps/web/tests/snapshots/lifecycle-chrome/hero.expected.md index 65abda0dba..783964ed31 100644 --- a/apps/web/tests/snapshots/lifecycle-chrome/hero.expected.md +++ b/apps/web/tests/snapshots/lifecycle-chrome/hero.expected.md @@ -26,7 +26,7 @@ - text: workspace - img - textbox "Describe what you want to build" -- button "Add attachment": +- button "Commands": - img - 'button "Access mode, current: Danger Full Access"': Danger Full Access - button "Plan mode off, press to turn on": Plan off diff --git a/apps/web/tests/snapshots/lifecycle-chrome/reloaded.expected.md b/apps/web/tests/snapshots/lifecycle-chrome/reloaded.expected.md index 45e3514fa4..81f1ab608b 100644 --- a/apps/web/tests/snapshots/lifecycle-chrome/reloaded.expected.md +++ b/apps/web/tests/snapshots/lifecycle-chrome/reloaded.expected.md @@ -22,7 +22,7 @@ - img - text: {{clock}} - textbox "Message the agent" -- button "Add attachment": +- button "Commands": - img - 'button "Access mode, current: Danger Full Access"': Danger Full Access - button "Plan mode off, press to turn on": Plan off diff --git a/apps/web/tests/snapshots/live-interactions/cancel.expected.md b/apps/web/tests/snapshots/live-interactions/cancel.expected.md index 4323c94285..f65b090a16 100644 --- a/apps/web/tests/snapshots/live-interactions/cancel.expected.md +++ b/apps/web/tests/snapshots/live-interactions/cancel.expected.md @@ -19,7 +19,7 @@ - img - text: {{clock}} - textbox "Message the agent" -- button "Add attachment": +- button "Commands": - img - 'button "Access mode, current: Danger Full Access"': Danger Full Access - button "Plan mode off, press to turn on": Plan off diff --git a/apps/web/tests/snapshots/live-interactions/error-auth.expected.md b/apps/web/tests/snapshots/live-interactions/error-auth.expected.md index 1d78e91c73..0d013f819d 100644 --- a/apps/web/tests/snapshots/live-interactions/error-auth.expected.md +++ b/apps/web/tests/snapshots/live-interactions/error-auth.expected.md @@ -12,7 +12,7 @@ - button "编辑": - img - textbox "Message the agent" -- button "Add attachment": +- button "Commands": - img - 'button "Access mode, current: Danger Full Access"': Danger Full Access - button "Plan mode off, press to turn on": Plan off diff --git a/apps/web/tests/snapshots/live-interactions/retry.expected.md b/apps/web/tests/snapshots/live-interactions/retry.expected.md index 6a9c808342..11bb665e71 100644 --- a/apps/web/tests/snapshots/live-interactions/retry.expected.md +++ b/apps/web/tests/snapshots/live-interactions/retry.expected.md @@ -22,7 +22,7 @@ - img - text: {{clock}} - textbox "Message the agent" -- button "Add attachment": +- button "Commands": - img - 'button "Access mode, current: Danger Full Access"': Danger Full Access - button "Plan mode off, press to turn on": Plan off diff --git a/apps/web/tests/snapshots/message-actions/ui.expected.md b/apps/web/tests/snapshots/message-actions/ui.expected.md index 19ba02d99d..b15a665c45 100644 --- a/apps/web/tests/snapshots/message-actions/ui.expected.md +++ b/apps/web/tests/snapshots/message-actions/ui.expected.md @@ -33,7 +33,7 @@ - img - text: {{clock}} - textbox "Message the agent" -- button "Add attachment": +- button "Commands": - img - 'button "Access mode, current: Danger Full Access"': Danger Full Access - button "Plan mode off, press to turn on": Plan off diff --git a/apps/web/tests/snapshots/question-composer/answered.expected.md b/apps/web/tests/snapshots/question-composer/answered.expected.md index 36752c783a..db0c2cfd3a 100644 --- a/apps/web/tests/snapshots/question-composer/answered.expected.md +++ b/apps/web/tests/snapshots/question-composer/answered.expected.md @@ -30,7 +30,7 @@ - img - text: {{clock}} - textbox "Message the agent" -- button "Add attachment": +- button "Commands": - img - 'button "Access mode, current: Danger Full Access"': Danger Full Access - button "Plan mode off, press to turn on": Plan off diff --git a/apps/web/tests/snapshots/queue-actions/editing.expected.md b/apps/web/tests/snapshots/queue-actions/editing.expected.md index 2594f18294..7e67544f04 100644 --- a/apps/web/tests/snapshots/queue-actions/editing.expected.md +++ b/apps/web/tests/snapshots/queue-actions/editing.expected.md @@ -26,7 +26,7 @@ - button "取消编辑": - img - textbox "Message the agent" -- button "Add attachment": +- button "Commands": - img - 'button "Access mode, current: Danger Full Access"': Danger Full Access - button "Plan mode off, press to turn on": Plan off diff --git a/apps/web/tests/snapshots/queue-actions/ui.expected.md b/apps/web/tests/snapshots/queue-actions/ui.expected.md index 919617bdab..48c288909c 100644 --- a/apps/web/tests/snapshots/queue-actions/ui.expected.md +++ b/apps/web/tests/snapshots/queue-actions/ui.expected.md @@ -20,7 +20,7 @@ - button "删除排队消息": - img - textbox "Message the agent" -- button "Add attachment": +- button "Commands": - img - 'button "Access mode, current: Danger Full Access"': Danger Full Access - button "Plan mode off, press to turn on": Plan off diff --git a/apps/web/tests/snapshots/seeded-history/ui.expected.md b/apps/web/tests/snapshots/seeded-history/ui.expected.md index efc43a272e..c520dafae9 100644 --- a/apps/web/tests/snapshots/seeded-history/ui.expected.md +++ b/apps/web/tests/snapshots/seeded-history/ui.expected.md @@ -36,7 +36,7 @@ - img - text: 上下文注入 - textbox "Message the agent" -- button "Add attachment": +- button "Commands": - img - 'button "Access mode, current: Danger Full Access"': Danger Full Access - button "Plan mode off, press to turn on": Plan off diff --git a/apps/web/tests/snapshots/steering/settled.expected.md b/apps/web/tests/snapshots/steering/settled.expected.md index 5efbcf385d..1172d3ca5d 100644 --- a/apps/web/tests/snapshots/steering/settled.expected.md +++ b/apps/web/tests/snapshots/steering/settled.expected.md @@ -30,7 +30,7 @@ - img - text: {{clock}} - textbox "Message the agent" -- button "Add attachment": +- button "Commands": - img - 'button "Access mode, current: Danger Full Access"': Danger Full Access - button "Plan mode off, press to turn on": Plan off diff --git a/packages/client/ui-conversation/README.i18n.yaml b/packages/client/ui-conversation/README.i18n.yaml index 1588367646..ea2de9fd3d 100644 --- a/packages/client/ui-conversation/README.i18n.yaml +++ b/packages/client/ui-conversation/README.i18n.yaml @@ -2,5 +2,5 @@ # side as of the last confirmed-consistent state. Both languages carry equal authority; # after editing either side, bring the other along and re-record with: # pnpm run verify-translation-pairing --write packages/client/ui-conversation/README.md -README.md: fc466190a744a1c13094ca6ebf62755d5bf49c98 -README.zh.md: f6fbff9c1e5d005b64e928680bbf401d94e4ce79 +README.md: 8c1a75cd6d6bf8409eda32a75b342a8a84c94706 +README.zh.md: 42fa2df9f43f95ad32a593f79ff303c87cb55a5c diff --git a/packages/client/ui-conversation/README.md b/packages/client/ui-conversation/README.md index fc466190a7..8c1a75cd6d 100644 --- a/packages/client/ui-conversation/README.md +++ b/packages/client/ui-conversation/README.md @@ -22,7 +22,7 @@ The todo surfaces are two registrations over that shape, both plain registrant p Per-session UI state for selection and the active view lives in the declared chat store (`stores.ts` `createChatStore`); the InputHub owns the composer state machine and mirrors its draft into that store for persistence. Apply passes one store handle to the strict session subtree, chat view, and details registrations, so each session shares one instance and the framework owns its lifecycle. Components are pure: the framework standard kit supplies `useSession`/`sessionId`, global `useSessions`/`useWorkspaces`, and the input machine's `useInput`/`inputActions`; store faces and inject factories supply the remaining state and callbacks. -The composer bar declares session-scoped single seats for `'conversation.input.plan'` (right of the local access-mode control) and `'conversation.input.model'` (immediately before the pending indicator and send/stop button), plus list slots for overlay, dock, left, and right input extensions. Feature packages own each control and its state; ui-conversation supplies placement, the `locked` owner prop, and the standard slot shares. While the `plan` projection's effective target is plan mode, InputBar swaps its textarea placeholder to the plan-task wording, localized through the `command.hint` locale namespace this package registers and shared verbatim with the claimed `/plan` command hint (a host-folded value read through the standard-kit `useProjection`; owner-supplied placeholders win). A pending composer takeover remains mounted when another conversation view is active so the blocked agent can still receive its answer; without a pending interaction, the active-session composer belongs to Chat. The composer-bar slot itself is `session-maybe`: with no current session the same bar renders inert (machine faces absent, `disabled` owner prop) instead of swapping in a parallel disabled tree, so the textarea DOM survives the workspace pick; the strict-session control seats simply stay empty until a session exists. +The composer bar declares session-scoped single seats for `'conversation.input.plan'` (right of the local access-mode control) and `'conversation.input.model'` (immediately before the pending indicator and send/stop button), plus list slots for overlay, dock, left, and right input extensions. Feature packages own each control and its state; ui-conversation supplies placement, the `locked` owner prop, and the standard slot shares. The leading plus button is a Command launcher, not an attachment surface: it asks the session's `SlashController` to open only the `/` trigger's `command` source over the current textarea selection, while ui-slash's existing `MenuView` remains the sole floating menu and pick path. No file row, file input, upload protocol, or second menu component is introduced. While the `plan` projection's effective target is plan mode, InputBar swaps its textarea placeholder to the plan-task wording, localized through the `command.hint` locale namespace this package registers and shared verbatim with the claimed `/plan` command hint (a host-folded value read through the standard-kit `useProjection`; owner-supplied placeholders win). A pending composer takeover remains mounted when another conversation view is active so the blocked agent can still receive its answer; without a pending interaction, the active-session composer belongs to Chat. The composer-bar slot itself is `session-maybe`: with no current session the same bar renders inert (machine faces absent, `disabled` owner prop) instead of swapping in a parallel disabled tree, so the textarea DOM survives the workspace pick; the strict-session control seats simply stay empty until a session exists. `src/client/` is organized for the future package split: `contract/` is the sole inter-domain shared face (`slots.ts` slot declarations + composed slot props including the tool-row contract, `views.ts` shared primitives, `tool-call-model.ts`); the `skeleton/`, `chat/`, and `toolviews/` (sample registrants) domain directories import contract files and never each other; `apply.ts` is the only assembly point allowed to import all three domains. The `/client` export surface is the contract only — `apply`/`inject`, the two service classes, and the `contract/` type families; implementation components (skeleton, chat rows) and the store factory stay internal and reach the page exclusively through apply's slot registrations (tests take them via the `./src/*` subpath). diff --git a/packages/client/ui-conversation/README.zh.md b/packages/client/ui-conversation/README.zh.md index f6fbff9c1e..42fa2df9f4 100644 --- a/packages/client/ui-conversation/README.zh.md +++ b/packages/client/ui-conversation/README.zh.md @@ -22,7 +22,7 @@ todo 两个面就是在该形状上的两个注册项,都是普通注册方插 逐 Session UI 状态中的选择与活跃视图位于已声明的聊天 store(`stores.ts` `createChatStore`)中;InputHub 拥有输入区状态机,并将草稿镜像到该 store 以便持久化。apply 将同一个 store handle 传给严格限定于会话的子树、聊天视图和详情注册,因此每个会话内共享一个实例,框架拥有其生命周期。组件保持纯粹:框架标准工具包提供 `useSession`/`sessionId`、全局 `useSessions`/`useWorkspaces`,以及输入状态机的 `useInput`/`inputActions`;store 表层与 inject factory 提供其余状态和回调。 -输入栏为 `'conversation.input.plan'`(位于本地 access 模式控件右侧)和 `'conversation.input.model'`(渲染在 pending 指示器与发送/停止按钮之前)声明会话作用域的单实例 seat,并为 overlay、dock、left 和 right 输入扩展声明列表 slot。各功能包拥有相应控件及其状态;ui-conversation 提供放置位置、`locked` owner prop 和标准 slot share。当 `plan` 投影的有效目标为 plan mode 时,InputBar 将文本框 placeholder 切换为 plan 任务措辞,经本包注册的 `command.hint` locale 命名空间本地化,并与已认领 `/plan` 命令的提示逐字共用同一份文案(经标准套件 `useProjection` 读取的 host 折叠值;owner 提供的 placeholder 优先)。另一个会话视图活跃时,待处理的 composer 接管仍保持挂载,使被阻塞的 agent(智能体)仍能收到回答;没有待处理交互时,活跃会话的 composer 归 Chat 所有。composer bar slot 本身为 `session-maybe`:没有当前会话时,同一个 bar 以不可交互状态渲染(machine face 均缺席、`disabled` owner prop),而不是换入一棵平行的 disabled 树,因此选择 workspace 时 textarea DOM 不会被销毁;严格会话作用域的控件 seat 在会话存在之前保持为空。 +输入栏为 `'conversation.input.plan'`(位于本地 access 模式控件右侧)和 `'conversation.input.model'`(渲染在 pending 指示器与发送/停止按钮之前)声明会话作用域的单实例 seat,并为 overlay、dock、left 和 right 输入扩展声明列表 slot。各功能包拥有相应控件及其状态;ui-conversation 提供放置位置、`locked` owner prop 和标准 slot share。前置加号按钮是 Command launcher,而非附件入口:它要求当前会话的 `SlashController` 基于 textarea 当前 selection,只打开 `/` trigger 的 `command` source,同时 ui-slash 既有的 `MenuView` 仍是唯一的浮层菜单与 pick 路径。不引入 File 行、file input、上传协议或第二套菜单组件。当 `plan` 投影的有效目标为 plan mode 时,InputBar 将文本框 placeholder 切换为 plan 任务措辞,经本包注册的 `command.hint` locale 命名空间本地化,并与已认领 `/plan` 命令的提示逐字共用同一份文案(经标准套件 `useProjection` 读取的 host 折叠值;owner 提供的 placeholder 优先)。另一个会话视图活跃时,待处理的 composer 接管仍保持挂载,使被阻塞的 agent(智能体)仍能收到回答;没有待处理交互时,活跃会话的 composer 归 Chat 所有。composer bar slot 本身为 `session-maybe`:没有当前会话时,同一个 bar 以不可交互状态渲染(machine face 均缺席、`disabled` owner prop),而不是换入一棵平行的 disabled 树,因此选择 workspace 时 textarea DOM 不会被销毁;严格会话作用域的控件 seat 在会话存在之前保持为空。 `src/client/` 按未来的包拆分组织:`contract/` 是唯一的跨领域共享表层(`slots.ts` slot 声明 + 组合后的 slot props,包括工具行契约、`views.ts` 共享原语、`tool-call-model.ts`);`skeleton/`、`chat/` 和 `toolviews/`(示例注册方)领域目录只导入 contract 文件,彼此绝不导入;`apply.ts` 是唯一允许导入全部三个领域的组装点。`/client` 导出表层只包含契约:`apply`/`inject`、两个服务类和 `contract/` 类型家族;实现组件(骨架、聊天行)与 store factory 保持内部状态,只能通过 apply 的 slot 注册到达页面(测试通过 `./src/*` 子路径获取它们)。 diff --git a/packages/client/ui-conversation/src/client/apply.ts b/packages/client/ui-conversation/src/client/apply.ts index c6b597ae79..0262e82987 100644 --- a/packages/client/ui-conversation/src/client/apply.ts +++ b/packages/client/ui-conversation/src/client/apply.ts @@ -44,6 +44,10 @@ const ABSENT_LEXICON = { getSnapshot: () => EMPTY_LEXICON, subscribe: () => () => {}, } +const ABSENT_MENU_LAUNCHER = { + getSnapshot: (): string | null => null, + subscribe: () => () => {}, +} /** Resolve the session-scoped conversation face (scope-addressed send/cancel), failing loud. */ function scopedConversation(sessions: ISessions, id: SessionId): IConversation { @@ -196,15 +200,29 @@ export function apply(ctx: Context): void { if (sessionId === undefined) { return { keyboard: undefined, + toggleCommandMenu: undefined, stop: undefined, command: undefined, translateHint, - hooks: { notices: ABSENT_NOTICES, lexicon: ABSENT_LEXICON }, + hooks: { notices: ABSENT_NOTICES, lexicon: ABSENT_LEXICON, menuLauncher: ABSENT_MENU_LAUNCHER }, } } const shell = inputHub.shell(sessionId) + const slash = inputHub.slash(sessionId) return { keyboard: shell, + toggleCommandMenu: slash === undefined + ? undefined + : (selection) => { + shell.dismissPopup() + const snapshot = shell.snapshot + slash.toggleSource('command', { + trigger: '/', + query: '', + position: snapshot.draft.slice(0, selection.start).trim() === '' ? 'leading' : 'inline', + span: { ...selection, draftRev: snapshot.draftRev }, + }) + }, stop: () => { scopedConversation(sessions, sessionId).cancel().catch(() => { // Stop failure surfaces via snapshot.promptError; nothing to restore. @@ -217,7 +235,11 @@ export function apply(ctx: Context): void { return result.ok && result.value.matched }, translateHint, - hooks: { notices: shell.notices, lexicon: shell.lexicon }, + hooks: { + notices: shell.notices, + lexicon: shell.lexicon, + menuLauncher: slash?.launcher ?? ABSENT_MENU_LAUNCHER, + }, } }, }, InputBar) diff --git a/packages/client/ui-conversation/src/client/contract/slots.ts b/packages/client/ui-conversation/src/client/contract/slots.ts index 1684e616b2..883dfd9723 100644 --- a/packages/client/ui-conversation/src/client/contract/slots.ts +++ b/packages/client/ui-conversation/src/client/contract/slots.ts @@ -5,7 +5,7 @@ import type { } from '@deepseek-ai/dsh-client-ui-slots' import type { CommandNode, ConversationSnapshot, ObservableSnapshot, PendingInteraction, PendingWait, SessionId, ToolCallBlock, WorkspaceId } from '@deepseek-ai/dsh-client-runtime/client' import type {} from '@deepseek-ai/dsh-client-ui-layout/client' -import type { ComposerKeyboard, InputActions, InputNotice, InputState } from '../input/contract.ts' +import type { ComposerKeyboard, EditSelection, InputActions, InputNotice, InputState } from '../input/contract.ts' import type { createChatStore } from '../stores.ts' import type { CallId, SelectionTarget, ViewTab } from './views.ts' @@ -265,14 +265,14 @@ export interface ComposerBarOwnerProps { rightItems?: ReactNode /** composer.dock entries (stats line), rendered under the card inside the bar's width column. */ footer?: ReactNode - onAdd?: () => void - addLabel?: string } /** Injected share of the composer-bar entry (package-internal faces). */ export interface ComposerBarInjected { /** The InputBar-exclusive keyboard/DOM command face (decision 20 private plane); absent with the session. */ keyboard: ComposerKeyboard | undefined + /** Toggle the shared slash menu with only its command source; absent without ui-slash or a session. */ + toggleCommandMenu: ((selection: EditSelection) => void) | undefined /** Cancel the in-flight turn; absent with the session. */ stop: (() => void) | undefined /** @@ -294,6 +294,8 @@ export interface ComposerBarInjected { notices: ObservableSnapshot /** Hot plain-text reference lexicon for the decoration scan (decision 21). */ lexicon: ObservableSnapshot> + /** Source name opened by the programmatic menu launcher, or null. */ + menuLauncher: ObservableSnapshot } } diff --git a/packages/client/ui-conversation/src/client/input/hub.ts b/packages/client/ui-conversation/src/client/input/hub.ts index 2641e0dcc4..7b8fa344d6 100644 --- a/packages/client/ui-conversation/src/client/input/hub.ts +++ b/packages/client/ui-conversation/src/client/input/hub.ts @@ -106,6 +106,17 @@ export class InputHub implements InputService { return this.shell(id) } + /** + * Resolve the optional slash controller for composer chrome that launches + * the shared candidate menu without typing a trigger. + * @param id - session id. + * @returns the resident controller, or undefined when ui-slash is absent. + */ + slash(id: SessionId): SlashController | undefined { + const actx = this.sessions().scope(id) + return actx === undefined ? undefined : this.controller(actx) + } + /** * Default sink: optimistic clear + prompt. The session is always a real * host entity (materialized when its workspace was picked), so there is diff --git a/packages/client/ui-conversation/src/client/skeleton/InputBar.tsx b/packages/client/ui-conversation/src/client/skeleton/InputBar.tsx index 77747e0ae2..97d9a911bf 100644 --- a/packages/client/ui-conversation/src/client/skeleton/InputBar.tsx +++ b/packages/client/ui-conversation/src/client/skeleton/InputBar.tsx @@ -33,13 +33,14 @@ export interface InputBarError { export type InputBarProps = ComposerBarProps export function InputBar({ - useSession, useInput, inputActions, keyboard, stop, command, translateHint, renderSlot, useNotices, useLexicon, + useSession, useInput, inputActions, keyboard, toggleCommandMenu, stop, command, translateHint, + renderSlot, useNotices, useLexicon, useMenuLauncher, useProjection, sessionId, variant, disabled: inert = false, placeholder, accessory, overlay, leftItems, rightItems, footer, - onAdd, addLabel = 'Add attachment', }: InputBarProps) { const input = useInput(s => s) const notice = useNotices(s => s) const lexicon = useLexicon(s => s) + const commandMenuOpen = useMenuLauncher(source => source === 'command') const promptError = useSession(s => s.promptError) ?? null const running = useSession(s => s.running) ?? false const removed = useSession(s => s.removed) ?? false @@ -256,6 +257,11 @@ export function InputBar({ inputRef.current?.focus() } + const onToggleCommandMenu = (): void => { + const el = inputRef.current + if (el !== null) toggleCommandMenu?.(selectionOf(el)) + } + const primaryLabel = running ? 'Stop generating' : 'Send message' const onPrimary = (): void => { if (inputActions === undefined || stop === undefined) return // absent machine: the button is disabled @@ -395,11 +401,13 @@ export function InputBar({ diff --git a/packages/client/ui-conversation/tests/apply-inject.spec.tsx b/packages/client/ui-conversation/tests/apply-inject.spec.tsx index 87ec0dfde7..954335fde2 100644 --- a/packages/client/ui-conversation/tests/apply-inject.spec.tsx +++ b/packages/client/ui-conversation/tests/apply-inject.spec.tsx @@ -179,9 +179,11 @@ describe('conversation slot inject surface', () => { // hooks compartment still present so the render side's hook order holds. const absent = injectFn(undefined) expect(absent.keyboard).toBeUndefined() + expect(absent.toggleCommandMenu).toBeUndefined() expect(absent.stop).toBeUndefined() expect(absent.hooks.notices.getSnapshot()).toBeNull() expect(absent.hooks.lexicon.getSnapshot().size).toBe(0) + expect(absent.hooks.menuLauncher.getSnapshot()).toBeNull() // A scope whose service tree lost 'conversation' (the feature fiber // unloaded while a retained inject closure re-runs): fails loud too. const stop = injectFn(ROOT).stop! diff --git a/packages/client/ui-conversation/tests/input-bar.spec.tsx b/packages/client/ui-conversation/tests/input-bar.spec.tsx index c0bfda7f4a..09abd47458 100644 --- a/packages/client/ui-conversation/tests/input-bar.spec.tsx +++ b/packages/client/ui-conversation/tests/input-bar.spec.tsx @@ -47,6 +47,8 @@ interface BenchOptions { overlay?: React.ReactNode leftItems?: React.ReactNode rightItems?: React.ReactNode + commandMenuOpen?: boolean + toggleCommandMenu?: (selection: { start: number; end: number }) => void } /** Real machine behind the bar entry: sink spy, no slash pipeline (plain text goes straight to the sink). */ @@ -74,6 +76,7 @@ function bench(over?: BenchOptions) { promptError: over?.promptError ?? null, })) const stop = vi.fn() + const menuLauncher = createSnapshotStore(over?.commandMenuOpen === true ? 'command' : null) const slotCalls: { key: string; owner: unknown }[] = [] const renderSlot = ((key: string, owner: object) => { slotCalls.push({ key, owner }) @@ -97,8 +100,10 @@ function bench(over?: BenchOptions) { useInput: bindSnapshotSelector(shell.state), inputActions: shell.actions, keyboard: shell, + toggleCommandMenu: over?.toggleCommandMenu ?? vi.fn(), useNotices: bindSnapshotSelector(shell.notices), useLexicon: bindSnapshotSelector(shell.lexicon), + useMenuLauncher: bindSnapshotSelector(menuLauncher), stop, command: () => Promise.resolve(true), // Mirrors the en 'command.hint' locale entries the production apply wires in. @@ -120,7 +125,7 @@ function bench(over?: BenchOptions) { const button = view.container.querySelector( `button[aria-label="${over?.running === true ? 'Stop generating' : 'Send message'}"]`, )! - return { view, textarea, button, props, sink, shell, wiring: shell, session, stop, slotCalls } + return { view, textarea, button, props, sink, shell, wiring: shell, session, stop, slotCalls, menuLauncher } } describe('Enter semantics', () => { @@ -205,7 +210,7 @@ describe('running and lock semantics (queue cut 1)', () => { const { textarea, view } = bench({ disabled: true }) expect(textarea.disabled).toBe(true) expect(textarea.placeholder).toBe('Session unavailable') - expect((view.getByLabelText('Add attachment') as HTMLButtonElement).disabled).toBe(true) + expect((view.getByLabelText('Commands') as HTMLButtonElement).disabled).toBe(true) }) it('idle primary sends and disables on empty draft', () => { @@ -438,10 +443,10 @@ describe('strips and variants', () => { }) }) -describe('placeholder chrome and control seats', () => { - it('renders attach; the Access chip is absent without the permissions projection; plan/model seats render EMPTY without entries (B ruling)', () => { +describe('command launcher chrome and control seats', () => { + it('renders the command launcher; the Access chip is absent without the permissions projection; plan/model seats render EMPTY without entries (B ruling)', () => { const { view, slotCalls } = bench() - expect(view.getByLabelText('Add attachment')).toBeTruthy() + expect(view.getByLabelText('Commands')).toBeTruthy() // Capability absent (no projection value): the chip renders nothing. expect(view.queryByLabelText(/^Access mode/)).toBeNull() // Both seats dispatched, nothing rendered. @@ -450,6 +455,18 @@ describe('placeholder chrome and control seats', () => { expect(view.queryByLabelText('Model')).toBeNull() }) + it('passes the textarea selection to the command menu launcher and reflects its expanded state', () => { + const toggleCommandMenu = vi.fn() + const { view, textarea, menuLauncher } = bench({ draft: 'draft text', toggleCommandMenu }) + textarea.setSelectionRange(2, 7) + const launcher = view.getByLabelText('Commands') + expect(launcher.getAttribute('aria-expanded')).toBe('false') + fireEvent.click(launcher) + expect(toggleCommandMenu).toHaveBeenCalledExactlyOnceWith({ start: 2, end: 7 }) + act(() => { menuLauncher.set('command') }) + expect(launcher.getAttribute('aria-expanded')).toBe('true') + }) + it('the Access chip renders the projection value and submits /permission on pick', async () => { const permissions = { options: [ @@ -489,10 +506,10 @@ describe('placeholder chrome and control seats', () => { expect(live.slotCalls.every(c => !(c.owner as { locked: boolean }).locked)).toBe(true) }) - it('disabled locks the Access chip and attach control (running does not)', () => { + it('disabled locks the Access chip and command launcher (running does not)', () => { const permissions = { options: [{ value: 'workspace-write', name: 'workspace-write' }], currentValue: 'workspace-write' } const { view } = bench({ disabled: true, permissions }) - expect((view.getByLabelText('Add attachment') as HTMLButtonElement).disabled).toBe(true) + expect((view.getByLabelText('Commands') as HTMLButtonElement).disabled).toBe(true) expect((view.getByLabelText(/^Access mode/) as HTMLButtonElement).disabled).toBe(true) cleanup() const live = bench({ running: true, permissions }) diff --git a/packages/client/ui-conversation/tests/input-matrix.spec.tsx b/packages/client/ui-conversation/tests/input-matrix.spec.tsx index a9c00b0748..4e8fc9efee 100644 --- a/packages/client/ui-conversation/tests/input-matrix.spec.tsx +++ b/packages/client/ui-conversation/tests/input-matrix.spec.tsx @@ -43,8 +43,10 @@ function mountBar(shell: SessionInputShell, over?: { running?: boolean; disabled useInput: bindSnapshotSelector(shell.state), inputActions: shell.actions, keyboard: shell, + toggleCommandMenu: vi.fn(), useNotices: bindSnapshotSelector(shell.notices), useLexicon: bindSnapshotSelector(shell.lexicon), + useMenuLauncher: bindSnapshotSelector(createSnapshotStore(null)), renderSlot: (() => null) as InputBarProps['renderSlot'], stop: vi.fn(), command: () => Promise.resolve(true), @@ -170,7 +172,7 @@ describe('matrix row: locked (session disabled)', () => { it('disables the textarea and chrome; the machine currency is untouched', () => { const { view, textarea, shell } = bench({ disabled: true }) expect((textarea).disabled).toBe(true) - expect((view.getByLabelText('Add attachment') as HTMLButtonElement).disabled).toBe(true) + expect((view.getByLabelText('Commands') as HTMLButtonElement).disabled).toBe(true) expect(shell.snapshot.phase).toBe('plain') }) diff --git a/packages/client/ui-conversation/tests/input-scenarios.spec.tsx b/packages/client/ui-conversation/tests/input-scenarios.spec.tsx index 1c7bbe50ec..b45397294c 100644 --- a/packages/client/ui-conversation/tests/input-scenarios.spec.tsx +++ b/packages/client/ui-conversation/tests/input-scenarios.spec.tsx @@ -129,8 +129,18 @@ async function scopedBench(register?: (slash: SlashService) => void) { useInput: bindSnapshotSelector(shell.state), inputActions: shell.actions, keyboard: shell, + toggleCommandMenu: (selection) => { + const snapshot = shell.snapshot + controller.toggleSource('command', { + trigger: '/', + query: '', + position: snapshot.draft.slice(0, selection.start).trim() === '' ? 'leading' : 'inline', + span: { ...selection, draftRev: snapshot.draftRev }, + }) + }, useNotices: bindSnapshotSelector(shell.notices), useLexicon: bindSnapshotSelector(shell.lexicon), + useMenuLauncher: bindSnapshotSelector(controller.launcher), renderSlot: (() => null) as InputBarProps['renderSlot'], stop: vi.fn(), command: () => Promise.resolve(true), diff --git a/packages/client/ui-conversation/tests/skeleton.spec.tsx b/packages/client/ui-conversation/tests/skeleton.spec.tsx index 3ed459b5a9..d3feba86a6 100644 --- a/packages/client/ui-conversation/tests/skeleton.spec.tsx +++ b/packages/client/ui-conversation/tests/skeleton.spec.tsx @@ -145,8 +145,10 @@ function mount( useInput={useInput} inputActions={inputActions} keyboard={wiring} + toggleCommandMenu={vi.fn()} useNotices={bindSnapshotSelector(wiring.notices)} useLexicon={bindSnapshotSelector(wiring.lexicon)} + useMenuLauncher={bindSnapshotSelector(createSnapshotStore(null))} stop={stop} command={() => Promise.resolve(true)} translateHint={(key: string) => key} diff --git a/packages/client/ui-slash/README.i18n.yaml b/packages/client/ui-slash/README.i18n.yaml index 494ccdad20..5f1f5f23c4 100644 --- a/packages/client/ui-slash/README.i18n.yaml +++ b/packages/client/ui-slash/README.i18n.yaml @@ -2,5 +2,5 @@ # side as of the last confirmed-consistent state. Both languages carry equal authority; # after editing either side, bring the other along and re-record with: # pnpm run verify-translation-pairing --write packages/client/ui-slash/README.md -README.md: 29f1a71ce20f898ffe2ab3a1c6f3d73a7aecfe38 -README.zh.md: 03dac56870de5b083124716825001009b4293736 +README.md: 5d277a83c5f0bc4bcec5871e0618af28afb7b6d2 +README.zh.md: 195aec6b76517fcf5cfc0933eb39b180f03a8628 diff --git a/packages/client/ui-slash/README.md b/packages/client/ui-slash/README.md index 29f1a71ce2..5d277a83c5 100644 --- a/packages/client/ui-slash/README.md +++ b/packages/client/ui-slash/README.md @@ -2,11 +2,11 @@ English | [中文](README.zh.md) -Input trigger pipeline plugin: `/` and `@` detection under the caret (word-boundary + guard-tier rules), the grouped candidate menu, and pick routing to registered sources. `ctx.slash` owns the source roster and resolves one `SlashController` per session scope (`sessionOf`); the conversation wiring layer drives `track`/`arbitrate`/`onSpace`/`adjudicate` on the controller. Sources receive a `ClientSessionContext` projection per call — sessions are always agent-backed, so the projection is the session identity alone. A source is warmed in every session controller it can reach: the roster present at scope birth warms during controller construction, and a source registered later is warmed into every live controller by the registration itself. Sources whose `lexicon` roll changes after warm implement `subscribeLexicon(session, listener)`; the controller re-polls on each notification and publishes the aggregation through its `lexicon` snapshot store. The pipeline is command-agnostic: space/enter adjudication polls the optional `matchSpace`/`matchEnter` hooks in registration order and the first non-undefined answer wins. +Input trigger pipeline plugin: `/` and `@` detection under the caret (word-boundary + guard-tier rules), the grouped candidate menu, and pick routing to registered sources. `ctx.slash` owns the source roster and resolves one `SlashController` per session scope (`sessionOf`); the conversation wiring layer drives `track`/`arbitrate`/`onSpace`/`adjudicate` on the controller. The same controller exposes `toggleSource` for a chrome launcher to open exactly one registered source over a synthetic selection span; the resulting candidates still use the ordinary menu, keyboard arbitration, pick callback, and scoped input mutations. Sources receive a `ClientSessionContext` projection per call — sessions are always agent-backed, so the projection is the session identity alone. A source is warmed in every session controller it can reach: the roster present at scope birth warms during controller construction, and a source registered later is warmed into every live controller by the registration itself. Sources whose `lexicon` roll changes after warm implement `subscribeLexicon(session, listener)`; the controller re-polls on each notification and publishes the aggregation through its `lexicon` snapshot store. The pipeline is command-agnostic: space/enter adjudication polls the optional `matchSpace`/`matchEnter` hooks in registration order and the first non-undefined answer wins. Layering: `src/core/` (T2) is the pure core — `detectTrigger`, `menuReduce`/`seedGroups`/`MENU_CLOSED`, `exactMatch`, zero React/DOM/cordis; `src/client/service.ts` is the shell wiring the core to the menu snapshot store, the per-hit candidate fetch (generation-gated, `AbortSignal`-superseded, failed sources drop silently with a console record), and the three pick paths. `src/types.ts` and the two `contract.ts` files are the frozen cross-package contract (design v4 §5.1); changes require main-thread arbitration. -MenuView renders the menu store into the `conversation.input.overlay` slot (list kind, session scope) and renders null while closed. Groups sort by the optional `SlashSource.order` (lower first, default 0, ties keep registration order) under title rows localized through the `slash.menu` locale namespace (an unknown source shows its raw name); the list height clamps to the space above the composer, and a pointer down outside both the menu and the surrounding composer card dismisses it. The slot is owned by ui-conversation's composer entry (anchor, children declaration, lifecycle); its SlotMap type merge lives in this package's `src/client/slots.ts` because the dependency direction (ui-conversation → ui-slash) admits no reverse type import. Combobox pattern: focus stays in the textarea, rows pick on mousedown, the highlight rides `aria-activedescendant`. +MenuView renders the menu store into the `conversation.input.overlay` slot (list kind, session scope) and renders null while closed. Typed triggers seed every source registered for that trigger; a programmatic launcher seeds only its requested source and publishes the source name through the controller's `launcher` snapshot store until the menu closes or typed tracking resumes. Groups sort by the optional `SlashSource.order` (lower first, default 0, ties keep registration order) under title rows localized through the `slash.menu` locale namespace (an unknown source shows its raw name); the list height clamps to the space above the composer, and a pointer down outside both the menu and the surrounding composer card dismisses it. The slot is owned by ui-conversation's composer entry (anchor, children declaration, lifecycle); its SlotMap type merge lives in this package's `src/client/slots.ts` because the dependency direction (ui-conversation → ui-slash) admits no reverse type import. Combobox pattern: focus stays in the textarea, rows pick on mousedown, the highlight rides `aria-activedescendant`. The `/client` export surface is the plugin body (`apply`/`inject`), `SlashService`, `MenuViewInjected`, and the contract types. MenuView itself is internal — the slot registration closes over it. diff --git a/packages/client/ui-slash/README.zh.md b/packages/client/ui-slash/README.zh.md index 03dac56870..195aec6b76 100644 --- a/packages/client/ui-slash/README.zh.md +++ b/packages/client/ui-slash/README.zh.md @@ -2,11 +2,11 @@ [English](README.md) | 中文 -输入触发流水线插件:光标处的 `/` 与 `@` 检测(词边界 + guard tier 规则)、分组候选菜单,以及把 pick 路由到已注册 source。`ctx.slash` 拥有 source roster,并按会话 scope(`sessionOf`)各解析一个 `SlashController`;对话接线层在 controller 上驱动 `track`/`arbitrate`/`onSpace`/`adjudicate`。source 每次调用收到一个 `ClientSessionContext` 投影——会话始终由 agent(智能体)支撑,因此投影只含会话身份。source 在它能触达的每个会话 controller 中都会被预热:scope 出生时在场的 roster 随 controller 构造预热,晚于此注册的 source 由注册动作本身预热进每个活 controller。`lexicon` 名录在预热后仍会变化的 source 实现 `subscribeLexicon(session, listener)`;controller 每收到通知就重拉,并把聚合结果经其 `lexicon` 快照 store 发布。流水线与命令无关:空格/回车裁决按注册序轮询可选的 `matchSpace`/`matchEnter` 钩子,第一个非 undefined 的应答胜出。 +输入触发流水线插件:光标处的 `/` 与 `@` 检测(词边界 + guard tier 规则)、分组候选菜单,以及把 pick 路由到已注册 source。`ctx.slash` 拥有 source roster,并按会话 scope(`sessionOf`)各解析一个 `SlashController`;对话接线层在 controller 上驱动 `track`/`arbitrate`/`onSpace`/`adjudicate`。同一个 controller 还暴露 `toggleSource`,供 chrome launcher 在一段合成 selection span 上只打开一个已注册 source;所得候选仍走通常的菜单、键盘仲裁、pick callback 与 scoped 输入改写。source 每次调用收到一个 `ClientSessionContext` 投影——会话始终由 agent(智能体)支撑,因此投影只含会话身份。source 在它能触达的每个会话 controller 中都会被预热:scope 出生时在场的 roster 随 controller 构造预热,晚于此注册的 source 由注册动作本身预热进每个活 controller。`lexicon` 名录在预热后仍会变化的 source 实现 `subscribeLexicon(session, listener)`;controller 每收到通知就重拉,并把聚合结果经其 `lexicon` 快照 store 发布。流水线与命令无关:空格/回车裁决按注册序轮询可选的 `matchSpace`/`matchEnter` 钩子,第一个非 undefined 的应答胜出。 分层:`src/core/`(T2)是纯内核——`detectTrigger`、`menuReduce`/`seedGroups`/`MENU_CLOSED`、`exactMatch`,零 React/DOM/cordis;`src/client/service.ts` 是壳层,把内核接到菜单快照 store、逐 hit 候选拉取(以 generation 把关、后继请求经 `AbortSignal` 取代旧请求、失败的 source 静默丢弃并留一条 console 记录)和三条 pick 路径上。`src/types.ts` 与两个 `contract.ts` 文件是冻结的跨包契约(设计 v4 §5.1);变更需经主线程仲裁。 -MenuView 把菜单 store 渲染进 `conversation.input.overlay` slot(列表类,会话 scope),菜单关闭期间渲染 null。分组按可选的 `SlashSource.order` 排序(越小越靠前,默认 0,同值保持注册序),组标题行经 `slash.menu` locale 命名空间本地化(未知 source 显示其原名);列表高度收敛到 composer 上方的可用空间,指针落在菜单与所在 composer 卡片之外即关闭菜单。该 slot 由 ui-conversation 的组合器条目拥有(锚点、children 声明、生命周期);其 SlotMap 类型合并放在本包的 `src/client/slots.ts`,因为依赖方向(ui-conversation → ui-slash)不允许反向的类型导入。combobox 模式:焦点始终留在 textarea,行在 mousedown 时完成 pick,高亮由 `aria-activedescendant` 承载。 +MenuView 把菜单 store 渲染进 `conversation.input.overlay` slot(列表类,会话 scope),菜单关闭期间渲染 null。键入式 trigger 会 seed 为该 trigger 注册的所有 source;程序化 launcher 只 seed 所请求的 source,并在菜单关闭或重新开始键入式 tracking 前,通过 controller 的 `launcher` 快照 store 发布该 source 名称。分组按可选的 `SlashSource.order` 排序(越小越靠前,默认 0,同值保持注册序),组标题行经 `slash.menu` locale 命名空间本地化(未知 source 显示其原名);列表高度收敛到 composer 上方的可用空间,指针落在菜单与所在 composer 卡片之外即关闭菜单。该 slot 由 ui-conversation 的组合器条目拥有(锚点、children 声明、生命周期);其 SlotMap 类型合并放在本包的 `src/client/slots.ts`,因为依赖方向(ui-conversation → ui-slash)不允许反向的类型导入。combobox 模式:焦点始终留在 textarea,行在 mousedown 时完成 pick,高亮由 `aria-activedescendant` 承载。 `/client` 导出表层是插件主体(`apply`/`inject`)、`SlashService`、`MenuViewInjected` 与契约类型。MenuView 本身是内部实现——slot 注册以闭包持有它。 diff --git a/packages/client/ui-slash/src/client/controller.ts b/packages/client/ui-slash/src/client/controller.ts index 3a8e85afc3..0b57f3dd74 100644 --- a/packages/client/ui-slash/src/client/controller.ts +++ b/packages/client/ui-slash/src/client/controller.ts @@ -40,6 +40,12 @@ export interface SlashControllerDeps { export class SlashController { /** Menu state store (per-session; survives session switches, dies with the scope). */ readonly menu: SnapshotStore = createSnapshotStore(MENU_CLOSED) + /** + * Name of the source opened through the programmatic launcher, or null for + * trigger-detected/closed menus. Composer chrome subscribes to this store + * for the launcher's expanded state without owning a second menu model. + */ + readonly launcher: SnapshotStore = createSnapshotStore(null) /** * Aggregated hot reference lexicon, grouped by trigger (decision 21): * sources implementing the lexicon hook are polled with the session @@ -81,6 +87,8 @@ export class SlashController { */ track(draft: string, caret: number, guard: TriggerGuard, draftRev: number): void { if (this.disposed) return + const launched = this.launcher.getSnapshot() !== null + this.clearLauncher() const raw = detectTrigger(draft, caret, guard) if (raw === null) { this.hit = null @@ -90,7 +98,7 @@ export class SlashController { } const hit: TriggerHit = { ...raw, span: { ...raw.span, draftRev } } const prev = this.menu.getSnapshot() - const same = prev.open && prev.hit !== null + const same = !launched && prev.open && prev.hit !== null && prev.hit.trigger === hit.trigger && prev.hit.query === hit.query && prev.hit.span.start === hit.span.start && prev.hit.span.end === hit.span.end this.hit = hit @@ -101,13 +109,40 @@ export class SlashController { this.reduce({ type: 'close' }) return } - if (!prev.open || prev.hit === null || prev.hit.trigger !== hit.trigger) { + if (launched || !prev.open || prev.hit === null || prev.hit.trigger !== hit.trigger) { this.menu.set(seedGroups(this.menu.getSnapshot(), roster.map(s => s.name))) } this.reduce({ type: 'hit', hit }) this.fetchCandidates(hit, roster) } + /** + * Toggle a menu containing exactly one registered source. The supplied hit + * is a synthetic selection span rather than a typed trigger token, but + * picks deliberately reuse the ordinary source callback and scoped input + * mutation pipeline. + * @param source - registered source name under `hit.trigger`. + * @param hit - synthetic hit carrying position and pick-time draft CAS. + */ + toggleSource(source: string, hit: TriggerHit): void { + if (this.disposed) return + if (this.launcher.getSnapshot() === source && this.menu.getSnapshot().open) { + this.dismiss() + return + } + const match = this.deps.roster.sources(hit.trigger).find(item => item.name === source) + if (match === undefined) { + this.dismiss() + return + } + this.stopFetch() + this.hit = hit + this.launcher.set(source) + this.menu.set(seedGroups(this.menu.getSnapshot(), [source])) + this.reduce({ type: 'hit', hit }) + this.fetchCandidates(hit, [match]) + } + /** * Pointer pick from MenuView: route the clicked candidate through onPick * and execute claim/insert outcomes via the scoped input events. @@ -349,9 +384,14 @@ export class SlashController { this.fetch = null } + private clearLauncher(): void { + if (this.launcher.getSnapshot() !== null) this.launcher.set(null) + } + private reduce(ev: MenuEvent): void { const cur = this.menu.getSnapshot() const next = menuReduce(cur, ev) if (next !== cur) this.menu.set(next) + if (!next.open) this.clearLauncher() } } diff --git a/packages/client/ui-slash/tests/service.spec.ts b/packages/client/ui-slash/tests/service.spec.ts index 099e2bb4f5..6f398442b9 100644 --- a/packages/client/ui-slash/tests/service.spec.ts +++ b/packages/client/ui-slash/tests/service.spec.ts @@ -351,6 +351,57 @@ describe('track', () => { }) }) +describe('programmatic source launcher', () => { + it('opens only the requested source and reuses its ordinary pick span', async () => { + const command = readySource('/', 'command', [{ name: 'goal' }]) + const skill = readySource('/', 'skill', [{ name: 'review' }]) + const { controller } = controllerBench([command.source, skill.source]) + const hit = { + trigger: '/' as const, + query: '', + position: 'leading' as const, + span: { start: 2, end: 5, draftRev: 7 }, + } + + controller.toggleSource('command', hit) + await tick() + + expect(controller.launcher.getSnapshot()).toBe('command') + expect(controller.menu.getSnapshot()).toMatchObject({ + open: true, + hit, + groups: [{ source: 'command', status: 'ready', items: [{ name: 'goal' }] }], + }) + controller.pick('command', 0) + expect(command.picks[0]).toMatchObject({ via: 'menu', span: hit.span }) + expect(skill.picks).toHaveLength(0) + expect(controller.launcher.getSnapshot()).toBeNull() + }) + + it('toggles closed, and typed tracking returns to the full trigger roster', async () => { + const command = readySource('/', 'command', [{ name: 'goal' }]) + const skill = readySource('/', 'skill', [{ name: 'review' }]) + const { controller } = controllerBench([command.source, skill.source]) + const hit = { + trigger: '/' as const, + query: '', + position: 'leading' as const, + span: { start: 0, end: 0, draftRev: 1 }, + } + + controller.toggleSource('command', hit) + controller.toggleSource('command', hit) + expect(controller.menu.getSnapshot().open).toBe(false) + expect(controller.launcher.getSnapshot()).toBeNull() + + controller.toggleSource('command', hit) + controller.track('/g', 2, { tier: 'plain' }, 2) + await tick() + expect(controller.launcher.getSnapshot()).toBeNull() + expect(controller.menu.getSnapshot().groups.map(group => group.source)).toEqual(['command', 'skill']) + }) +}) + describe('scope-birth warm', () => { it('construction warms every source once with the session projection', () => { const cmd = deferredSource('/', 'command') From 6d416b06c59ca7435f47bfb45439f89d3ddda01b Mon Sep 17 00:00:00 2001 From: ZiyaZhang <199893125+ZiyaZhang@users.noreply.github.com> Date: Thu, 30 Jul 2026 05:48:21 -0700 Subject: [PATCH 045/139] fix(client): gate every full access picker --- apps/web/tests/access-confirmation.e2e.ts | 87 +++++++++++++ .../access-confirmation/ui.expected.md | 10 ++ .../snapshots/code-mode-round/ui.expected.md | 2 +- .../cordis-tool-round/ui.expected.md | 2 +- .../snapshots/fresh-round-trip/ui.expected.md | 2 +- .../lifecycle-chrome/hero.expected.md | 2 +- .../lifecycle-chrome/reloaded.expected.md | 2 +- .../live-interactions/cancel.expected.md | 2 +- .../live-interactions/error-auth.expected.md | 2 +- .../live-interactions/retry.expected.md | 2 +- .../snapshots/message-actions/ui.expected.md | 2 +- .../question-composer/answered.expected.md | 2 +- .../queue-actions/editing.expected.md | 2 +- .../snapshots/queue-actions/ui.expected.md | 2 +- .../snapshots/seeded-history/ui.expected.md | 2 +- .../snapshots/steering/settled.expected.md | 2 +- apps/web/tsconfig.json | 3 +- .../ui-command/src/client/PopupSelectView.tsx | 121 ++++++++++-------- .../client/ui-command/src/client/contract.ts | 11 ++ .../client/ui-command/src/client/index.ts | 2 +- .../client/ui-command/src/client/popup.ts | 53 +++++++- .../ui-command/tests/popup-view.spec.tsx | 42 ++++++ .../client/ui-command/tests/popup.spec.ts | 43 +++++++ .../skeleton/PermissionSelect.module.css | 70 ---------- .../src/client/skeleton/PermissionSelect.tsx | 63 ++++----- .../ui-conversation/tests/input-bar.spec.tsx | 36 ++++++ packages/client/ui-permission/package.json | 3 + .../client/ui-permission/src/client/index.ts | 52 +++++++- .../tests/browser-plugin.spec.ts | 20 ++- packages/client/ui-primitives/src/Modal.tsx | 10 +- .../src/RiskConfirmation.module.css | 73 +++++++++++ .../ui-primitives/src/RiskConfirmation.tsx | 80 ++++++++++++ packages/client/ui-primitives/src/index.ts | 2 + .../client/ui-primitives/tests/atoms.spec.tsx | 6 +- pnpm-lock.yaml | 3 + tsconfig.host.json | 1 + 36 files changed, 624 insertions(+), 195 deletions(-) create mode 100644 apps/web/tests/access-confirmation.e2e.ts create mode 100644 apps/web/tests/snapshots/access-confirmation/ui.expected.md create mode 100644 packages/client/ui-primitives/src/RiskConfirmation.module.css create mode 100644 packages/client/ui-primitives/src/RiskConfirmation.tsx diff --git a/apps/web/tests/access-confirmation.e2e.ts b/apps/web/tests/access-confirmation.e2e.ts new file mode 100644 index 0000000000..e8a0875c29 --- /dev/null +++ b/apps/web/tests/access-confirmation.e2e.ts @@ -0,0 +1,87 @@ +// Web e2e scenario: every visible permission picker gates Full access behind +// the same locale-aware, in-page risk confirmation. Zero model calls: the +// scenario boots the shipped Web composition and exercises the real +// permission projection, client command path, HTTP RPC, and pushed update. +import { fileURLToPath } from 'node:url' +import { join } from 'node:path' +import type { Browser, Page } from 'playwright' +import { chromium } from 'playwright' +import { afterAll, beforeAll, describe, expect, it, onTestFailed } from 'vitest' +import { + assertFixtureInventory, captureStableAria, compareOrRefreshGolden, + launchWebScaffold, watchConsole, webSnapshotMode, type WebScaffold, +} from './scaffold.ts' +import { connectFreshWorkspace, saveFailureShot } from './support.ts' + +const SNAPSHOT_DIR = fileURLToPath(new URL('./snapshots/access-confirmation', import.meta.url)) +const UI_EXPECTED = join(SNAPSHOT_DIR, 'ui.expected.md') +const MODE = webSnapshotMode() + +describe('web e2e: Full access confirmation', () => { + let scaffold: WebScaffold + let browser: Browser + let page: Page + let tripwire: ReturnType + + beforeAll(async () => { + scaffold = await launchWebScaffold({}) + // CI uses Playwright's pinned browser. A developer may point this one + // scenario at an installed Chromium when the matching browser download + // is temporarily unavailable. + const executablePath = process.env.DSH_PLAYWRIGHT_EXECUTABLE_PATH + browser = await chromium.launch(executablePath === undefined ? {} : { executablePath }) + // Keep the product default Chinese locale: the golden pins the actual + // registered dictionary rather than a test-local translation callback. + page = await browser.newPage({ viewport: { width: 1680, height: 1000 } }) + tripwire = watchConsole(page) + await page.goto(scaffold.baseUrl, { waitUntil: 'load' }) + await page.waitForSelector('[class*="frame"]', { timeout: 30_000 }) + await connectFreshWorkspace(page) + }, 120_000) + + afterAll(async () => { + await browser?.close() + await scaffold?.close() + }) + + it('requires acknowledgement before the composer picker can enable Full access', async () => { + onTestFailed(() => saveFailureShot(page, 'web-e2e-full-access-confirmation')) + const access = page.locator('button[aria-label^="Access mode"]').first() + await access.waitFor({ timeout: 10_000 }) + + // Normalize the starting preset through the real command path. The + // shipped web config may already start at Full access. + if ((await access.getAttribute('aria-label'))?.endsWith('Full access') === true) { + await access.click() + await page.getByRole('menuitem', { name: 'Workspace Write' }).click() + await expect.poll(() => access.getAttribute('aria-label'), { timeout: 10_000 }) + .toBe('Access mode, current: Workspace Write') + } + + await access.click() + await page.getByRole('menuitem', { name: 'Full access' }).click() + const dialog = page.getByRole('dialog', { name: '确认启用 Full access?' }) + await dialog.waitFor({ timeout: 10_000 }) + const enable = dialog.getByRole('button', { name: '启用 Full access' }) + expect(await enable.isDisabled()).toBe(true) + + // The modal is in this page's body (not a native/new window) and escapes + // the sticky composer's stacking context. + expect(await dialog.evaluate(node => node.parentElement?.parentElement === document.body)).toBe(true) + const snapshot = await captureStableAria(page, '[role="dialog"]', scaffold.workspaceCwd) + await compareOrRefreshGolden(UI_EXPECTED, snapshot, MODE) + + await dialog.getByRole('checkbox', { name: '我已了解风险,并愿意继续' }).check() + expect(await enable.isEnabled()).toBe(true) + await enable.click() + await expect.poll(() => access.getAttribute('aria-label'), { timeout: 10_000 }) + .toBe('Access mode, current: Full access') + expect(await dialog.count()).toBe(0) + expect(tripwire.pageErrors).toEqual([]) + }, 60_000) + + it('keeps its snapshot inventory closed', async () => { + expect(tripwire.warnings).toEqual([]) + await assertFixtureInventory(SNAPSHOT_DIR, ['ui.expected.md']) + }) +}) diff --git a/apps/web/tests/snapshots/access-confirmation/ui.expected.md b/apps/web/tests/snapshots/access-confirmation/ui.expected.md new file mode 100644 index 0000000000..1287e6e565 --- /dev/null +++ b/apps/web/tests/snapshots/access-confirmation/ui.expected.md @@ -0,0 +1,10 @@ +- dialog "确认启用 Full access?": + - heading "确认启用 Full access?" [level=2] + - button "Close": + - img + - img + - paragraph: 启用 Full access 后,agent 将减少确认步骤,并且可以直接执行更多操作,包括敏感操作、文件修改或外部命令。仅建议在你信任当前任务时使用。 + - checkbox "我已了解风险,并愿意继续" + - text: 我已了解风险,并愿意继续 + - button "取消" + - button "启用 Full access" [disabled] diff --git a/apps/web/tests/snapshots/code-mode-round/ui.expected.md b/apps/web/tests/snapshots/code-mode-round/ui.expected.md index 0282a16f80..a57dae2a6a 100644 --- a/apps/web/tests/snapshots/code-mode-round/ui.expected.md +++ b/apps/web/tests/snapshots/code-mode-round/ui.expected.md @@ -35,7 +35,7 @@ - textbox "Message the agent" - button "Add attachment": - img -- 'button "Access mode, current: Danger Full Access"': Danger Full Access +- 'button "Access mode, current: Full access"': Full access - button "Plan mode off, press to turn on": Plan off - button "Select model, current DeepSeek-V4-Flash": - text: DeepSeek-V4-Flash diff --git a/apps/web/tests/snapshots/cordis-tool-round/ui.expected.md b/apps/web/tests/snapshots/cordis-tool-round/ui.expected.md index 5b51e47cf4..313ee2c08e 100644 --- a/apps/web/tests/snapshots/cordis-tool-round/ui.expected.md +++ b/apps/web/tests/snapshots/cordis-tool-round/ui.expected.md @@ -49,7 +49,7 @@ - textbox "Message the agent" - button "Add attachment": - img -- 'button "Access mode, current: Danger Full Access"': Danger Full Access +- 'button "Access mode, current: Full access"': Full access - button "Plan mode off, press to turn on": Plan off - button "Select model, current DeepSeek-V4-Flash": - text: DeepSeek-V4-Flash diff --git a/apps/web/tests/snapshots/fresh-round-trip/ui.expected.md b/apps/web/tests/snapshots/fresh-round-trip/ui.expected.md index 49c7958292..9552c89d80 100644 --- a/apps/web/tests/snapshots/fresh-round-trip/ui.expected.md +++ b/apps/web/tests/snapshots/fresh-round-trip/ui.expected.md @@ -32,7 +32,7 @@ - textbox "Message the agent" - button "Add attachment": - img -- 'button "Access mode, current: Danger Full Access"': Danger Full Access +- 'button "Access mode, current: Full access"': Full access - button "Plan mode off, press to turn on": Plan off - button "Select model, current DeepSeek-V4-Flash": - text: DeepSeek-V4-Flash diff --git a/apps/web/tests/snapshots/lifecycle-chrome/hero.expected.md b/apps/web/tests/snapshots/lifecycle-chrome/hero.expected.md index 65abda0dba..a76f170451 100644 --- a/apps/web/tests/snapshots/lifecycle-chrome/hero.expected.md +++ b/apps/web/tests/snapshots/lifecycle-chrome/hero.expected.md @@ -28,7 +28,7 @@ - textbox "Describe what you want to build" - button "Add attachment": - img -- 'button "Access mode, current: Danger Full Access"': Danger Full Access +- 'button "Access mode, current: Full access"': Full access - button "Plan mode off, press to turn on": Plan off - button "Select model, current DeepSeek-V4-Flash": - text: DeepSeek-V4-Flash diff --git a/apps/web/tests/snapshots/lifecycle-chrome/reloaded.expected.md b/apps/web/tests/snapshots/lifecycle-chrome/reloaded.expected.md index 45e3514fa4..194efaa7c4 100644 --- a/apps/web/tests/snapshots/lifecycle-chrome/reloaded.expected.md +++ b/apps/web/tests/snapshots/lifecycle-chrome/reloaded.expected.md @@ -24,7 +24,7 @@ - textbox "Message the agent" - button "Add attachment": - img -- 'button "Access mode, current: Danger Full Access"': Danger Full Access +- 'button "Access mode, current: Full access"': Full access - button "Plan mode off, press to turn on": Plan off - button "Select model, current DeepSeek-V4-Flash": - text: DeepSeek-V4-Flash diff --git a/apps/web/tests/snapshots/live-interactions/cancel.expected.md b/apps/web/tests/snapshots/live-interactions/cancel.expected.md index 4323c94285..bbe2387634 100644 --- a/apps/web/tests/snapshots/live-interactions/cancel.expected.md +++ b/apps/web/tests/snapshots/live-interactions/cancel.expected.md @@ -21,7 +21,7 @@ - textbox "Message the agent" - button "Add attachment": - img -- 'button "Access mode, current: Danger Full Access"': Danger Full Access +- 'button "Access mode, current: Full access"': Full access - button "Plan mode off, press to turn on": Plan off - button "Select model, current DeepSeek-V4-Flash": - text: DeepSeek-V4-Flash diff --git a/apps/web/tests/snapshots/live-interactions/error-auth.expected.md b/apps/web/tests/snapshots/live-interactions/error-auth.expected.md index 1d78e91c73..6812119684 100644 --- a/apps/web/tests/snapshots/live-interactions/error-auth.expected.md +++ b/apps/web/tests/snapshots/live-interactions/error-auth.expected.md @@ -14,7 +14,7 @@ - textbox "Message the agent" - button "Add attachment": - img -- 'button "Access mode, current: Danger Full Access"': Danger Full Access +- 'button "Access mode, current: Full access"': Full access - button "Plan mode off, press to turn on": Plan off - button "Select model, current DeepSeek-V4-Flash": - text: DeepSeek-V4-Flash diff --git a/apps/web/tests/snapshots/live-interactions/retry.expected.md b/apps/web/tests/snapshots/live-interactions/retry.expected.md index 6a9c808342..293ed5bc37 100644 --- a/apps/web/tests/snapshots/live-interactions/retry.expected.md +++ b/apps/web/tests/snapshots/live-interactions/retry.expected.md @@ -24,7 +24,7 @@ - textbox "Message the agent" - button "Add attachment": - img -- 'button "Access mode, current: Danger Full Access"': Danger Full Access +- 'button "Access mode, current: Full access"': Full access - button "Plan mode off, press to turn on": Plan off - button "Select model, current DeepSeek-V4-Flash": - text: DeepSeek-V4-Flash diff --git a/apps/web/tests/snapshots/message-actions/ui.expected.md b/apps/web/tests/snapshots/message-actions/ui.expected.md index 19ba02d99d..7546b7b124 100644 --- a/apps/web/tests/snapshots/message-actions/ui.expected.md +++ b/apps/web/tests/snapshots/message-actions/ui.expected.md @@ -35,7 +35,7 @@ - textbox "Message the agent" - button "Add attachment": - img -- 'button "Access mode, current: Danger Full Access"': Danger Full Access +- 'button "Access mode, current: Full access"': Full access - button "Plan mode off, press to turn on": Plan off - button "Select model, current deepseek-v4-flash": - text: deepseek-v4-flash diff --git a/apps/web/tests/snapshots/question-composer/answered.expected.md b/apps/web/tests/snapshots/question-composer/answered.expected.md index 36752c783a..583878f2be 100644 --- a/apps/web/tests/snapshots/question-composer/answered.expected.md +++ b/apps/web/tests/snapshots/question-composer/answered.expected.md @@ -32,7 +32,7 @@ - textbox "Message the agent" - button "Add attachment": - img -- 'button "Access mode, current: Danger Full Access"': Danger Full Access +- 'button "Access mode, current: Full access"': Full access - button "Plan mode off, press to turn on": Plan off - button "Select model, current DeepSeek-V4-Flash": - text: DeepSeek-V4-Flash diff --git a/apps/web/tests/snapshots/queue-actions/editing.expected.md b/apps/web/tests/snapshots/queue-actions/editing.expected.md index 2594f18294..30cc7f4a2c 100644 --- a/apps/web/tests/snapshots/queue-actions/editing.expected.md +++ b/apps/web/tests/snapshots/queue-actions/editing.expected.md @@ -28,7 +28,7 @@ - textbox "Message the agent" - button "Add attachment": - img -- 'button "Access mode, current: Danger Full Access"': Danger Full Access +- 'button "Access mode, current: Full access"': Full access - button "Plan mode off, press to turn on": Plan off - button "Select model, current DeepSeek-V4-Flash": - text: DeepSeek-V4-Flash diff --git a/apps/web/tests/snapshots/queue-actions/ui.expected.md b/apps/web/tests/snapshots/queue-actions/ui.expected.md index 919617bdab..cd8427dff2 100644 --- a/apps/web/tests/snapshots/queue-actions/ui.expected.md +++ b/apps/web/tests/snapshots/queue-actions/ui.expected.md @@ -22,7 +22,7 @@ - textbox "Message the agent" - button "Add attachment": - img -- 'button "Access mode, current: Danger Full Access"': Danger Full Access +- 'button "Access mode, current: Full access"': Full access - button "Plan mode off, press to turn on": Plan off - button "Select model, current DeepSeek-V4-Flash": - text: DeepSeek-V4-Flash diff --git a/apps/web/tests/snapshots/seeded-history/ui.expected.md b/apps/web/tests/snapshots/seeded-history/ui.expected.md index efc43a272e..3d691ea25d 100644 --- a/apps/web/tests/snapshots/seeded-history/ui.expected.md +++ b/apps/web/tests/snapshots/seeded-history/ui.expected.md @@ -38,7 +38,7 @@ - textbox "Message the agent" - button "Add attachment": - img -- 'button "Access mode, current: Danger Full Access"': Danger Full Access +- 'button "Access mode, current: Full access"': Full access - button "Plan mode off, press to turn on": Plan off - button "Select model, current deepseek-v4-flash": - text: deepseek-v4-flash diff --git a/apps/web/tests/snapshots/steering/settled.expected.md b/apps/web/tests/snapshots/steering/settled.expected.md index 5efbcf385d..979f16e72b 100644 --- a/apps/web/tests/snapshots/steering/settled.expected.md +++ b/apps/web/tests/snapshots/steering/settled.expected.md @@ -32,7 +32,7 @@ - textbox "Message the agent" - button "Add attachment": - img -- 'button "Access mode, current: Danger Full Access"': Danger Full Access +- 'button "Access mode, current: Full access"': Full access - button "Plan mode off, press to turn on": Plan off - button "Select model, current DeepSeek-V4-Flash": - text: DeepSeek-V4-Flash diff --git a/apps/web/tsconfig.json b/apps/web/tsconfig.json index 7a7f228fb0..9f8c9c371c 100644 --- a/apps/web/tsconfig.json +++ b/apps/web/tsconfig.json @@ -38,7 +38,8 @@ "tests/cordis-tool-round.e2e.ts", "tests/message-actions.e2e.ts", "tests/queue-actions.e2e.ts", - "tests/skill-invocation-policy.e2e.ts" + "tests/skill-invocation-policy.e2e.ts", + "tests/access-confirmation.e2e.ts" ], "references": [ { diff --git a/packages/client/ui-command/src/client/PopupSelectView.tsx b/packages/client/ui-command/src/client/PopupSelectView.tsx index ec0bbdd2bb..7e7ad91c34 100644 --- a/packages/client/ui-command/src/client/PopupSelectView.tsx +++ b/packages/client/ui-command/src/client/PopupSelectView.tsx @@ -12,7 +12,7 @@ import { useEffect, useRef } from 'react' import { useSyncExternalStore } from 'react' import clsx from 'clsx' -import { IconCheckOutline16, useAnchoredMaxHeight } from '@deepseek-ai/dsh-client-ui-primitives' +import { IconCheckOutline16, RiskConfirmation, useAnchoredMaxHeight } from '@deepseek-ai/dsh-client-ui-primitives' import { filterOptions } from './popup.ts' import type { PopupSelectController } from './popup.ts' import css from './PopupSelectView.module.css' @@ -56,23 +56,24 @@ export function PopupSelectView({ popup }: PopupSelectInjected) { // closes the shell before its own handlers run; that click's target then // takes focus naturally, so no focusComposer here. useEffect(() => { - if (!state.open) return + if (!state.open || state.confirming !== null) return const onPointerDown = (ev: PointerEvent): void => { if (cardRef.current !== null && ev.target instanceof Node && cardRef.current.contains(ev.target)) return popup.dismiss() } document.addEventListener('pointerdown', onPointerDown, true) return () => { document.removeEventListener('pointerdown', onPointerDown, true) } - }, [state.open, popup]) + }, [state.open, state.confirming, popup]) // Focus the search input after it mounts (separate effect so the ref is populated). useEffect(() => { - if (state.open) searchRef.current?.focus() - }, [state.open]) + if (state.open && state.confirming === null) searchRef.current?.focus() + }, [state.open, state.confirming]) if (!state.open) return null const rows = filterOptions(state.options, state.search) + const confirmation = state.confirming?.confirmation const onKeyDown = (ev: React.KeyboardEvent): void => { // ArrowLeft/ArrowRight fall through on purpose: the search input keeps @@ -99,55 +100,73 @@ export function PopupSelectView({ popup }: PopupSelectInjected) { } return ( -
      - { popup.setSearch(ev.currentTarget.value) }} - /> - {state.error !== null && ( -
      - {state.error} - {state.status === 'failed' && ( - + <> + {state.confirming === null && ( +
      + { popup.setSearch(ev.currentTarget.value) }} + /> + {state.error !== null && ( +
      + {state.error} + {state.status === 'failed' && ( + + )} +
      + )} + {state.status === 'pending' &&
      Loading options…
      } + {state.submitting &&
      Applying…
      } + {state.status === 'ready' && rows.length === 0 &&
      No options
      } + {state.status === 'ready' && ( +
      + {rows.map((option, index) => ( +
      { void popup.select(index) }} + onMouseEnter={() => { popup.highlight(index) }} + > + {option.label} + {option.detail !== undefined && {option.detail}} + {option.active === true && } +
      + ))} +
      )}
      )} - {state.status === 'pending' &&
      Loading options…
      } - {state.submitting &&
      Applying…
      } - {state.status === 'ready' && rows.length === 0 &&
      No options
      } - {state.status === 'ready' && ( -
      - {rows.map((option, index) => ( -
      { void popup.select(index) }} - onMouseEnter={() => { popup.highlight(index) }} - > - {option.label} - {option.detail !== undefined && {option.detail}} - {option.active === true && } -
      - ))} -
      + {confirmation !== undefined && ( + { popup.acknowledge(value) }} + onCancel={() => { popup.cancelConfirmation() }} + onConfirm={() => { void popup.confirm() }} + /> )} -
      + ) } diff --git a/packages/client/ui-command/src/client/contract.ts b/packages/client/ui-command/src/client/contract.ts index 61ab4de2e2..8498b5def8 100644 --- a/packages/client/ui-command/src/client/contract.ts +++ b/packages/client/ui-command/src/client/contract.ts @@ -6,12 +6,23 @@ import type { ClientContext } from '@deepseek-ai/dsh-client-runtime/client' import type { ClientSessionContext } from '@deepseek-ai/dsh-client-ui-slash/client' +/** Copy for an option that must be acknowledged before onSelect can run. */ +export interface SelectConfirmation { + readonly title: string + readonly description: string + readonly acknowledgeLabel: string + readonly cancelLabel: string + readonly confirmLabel: string +} + /** One option row of a popupSelect shell. */ export interface SelectOption { readonly id: string readonly label: string readonly detail?: string readonly active?: boolean + /** Optional in-page risk gate owned by the shared popup shell. */ + readonly confirmation?: SelectConfirmation } /** diff --git a/packages/client/ui-command/src/client/index.ts b/packages/client/ui-command/src/client/index.ts index f40078212e..95b3824805 100644 --- a/packages/client/ui-command/src/client/index.ts +++ b/packages/client/ui-command/src/client/index.ts @@ -21,7 +21,7 @@ export { filterOptions, PopupSelectController } from './popup.ts' export type { PopupSelectDeps, PopupSpec, PopupState, TokenSegment } from './popup.ts' export type { PopupSelectInjected } from './PopupSelectView.tsx' export type { - CommandContribution, CommandDecoration, CommandServiceContract, CommandUiSpec, SelectOption, + CommandContribution, CommandDecoration, CommandServiceContract, CommandUiSpec, SelectConfirmation, SelectOption, } from './contract.ts' declare module 'cordis' { diff --git a/packages/client/ui-command/src/client/popup.ts b/packages/client/ui-command/src/client/popup.ts index c2d30f3213..5e20911820 100644 --- a/packages/client/ui-command/src/client/popup.ts +++ b/packages/client/ui-command/src/client/popup.ts @@ -67,12 +67,17 @@ export interface PopupState { readonly active: number /** A select() settlement is in flight: further select/search/highlight no-op until it settles. */ readonly submitting: boolean + /** Option waiting for explicit risk acknowledgement; null during normal selection. */ + readonly confirming: SelectOption | null + /** Caller-controlled checkbox state for the pending confirmation. */ + readonly acknowledged: boolean /** Surfaced settlement failure (options load or onSelect); null when none. */ readonly error: string | null } const CLOSED: PopupState = { - open: false, command: null, status: 'pending', options: [], search: '', active: 0, submitting: false, error: null, + open: false, command: null, status: 'pending', options: [], search: '', active: 0, + submitting: false, confirming: null, acknowledged: false, error: null, } /** @@ -166,7 +171,7 @@ export class PopupSelectController { */ setSearch(search: string): void { const s = this.state.getSnapshot() - if (!s.open || s.submitting || search === s.search) return + if (!s.open || s.submitting || s.confirming !== null || search === s.search) return this.state.set({ ...s, search, active: 0 }) } @@ -177,7 +182,7 @@ export class PopupSelectController { */ move(dir: 1 | -1): void { const s = this.state.getSnapshot() - if (!s.open || s.status !== 'ready' || s.submitting) return + if (!s.open || s.status !== 'ready' || s.submitting || s.confirming !== null) return const rows = filterOptions(s.options, s.search) if (rows.length === 0) return const active = (s.active + dir + rows.length) % rows.length @@ -191,7 +196,7 @@ export class PopupSelectController { */ highlight(index: number): void { const s = this.state.getSnapshot() - if (!s.open || s.status !== 'ready' || s.submitting) return + if (!s.open || s.status !== 'ready' || s.submitting || s.confirming !== null) return if (index < 0 || index >= filterOptions(s.options, s.search).length || index === s.active) return this.state.set({ ...s, active: index }) } @@ -209,10 +214,46 @@ export class PopupSelectController { async select(index: number): Promise { const binding = this.binding const s = this.state.getSnapshot() - if (binding === null || !s.open || s.status !== 'ready' || s.submitting) return + if (binding === null || !s.open || s.status !== 'ready' || s.submitting || s.confirming !== null) return const option = filterOptions(s.options, s.search)[index] if (option === undefined) return - this.state.set({ ...s, submitting: true, error: null }) + if (option.confirmation !== undefined) { + this.state.set({ ...s, confirming: option, acknowledged: false, error: null }) + return + } + await this.settle(binding, option) + } + + /** + * Update the explicit checkbox for the currently pending risk gate. + * @param acknowledged - whether the user has acknowledged the displayed risk. + */ + acknowledge(acknowledged: boolean): void { + const s = this.state.getSnapshot() + if (!s.open || s.submitting || s.confirming === null || s.acknowledged === acknowledged) return + this.state.set({ ...s, acknowledged }) + } + + /** Cancel only the risk gate and return to the still-open option picker. */ + cancelConfirmation(): void { + const s = this.state.getSnapshot() + if (!s.open || s.submitting || s.confirming === null) return + this.state.set({ ...s, confirming: null, acknowledged: false }) + } + + /** Settle the gated option only after the checkbox is acknowledged. */ + async confirm(): Promise { + const binding = this.binding + const s = this.state.getSnapshot() + if (binding === null || !s.open || s.submitting || s.confirming === null || !s.acknowledged) return + await this.settle(binding, s.confirming) + } + + /** Run the business settlement for an already admitted option. */ + private async settle(binding: OpenBinding, option: SelectOption): Promise { + const s = this.state.getSnapshot() + if (this.binding !== binding || !s.open || s.submitting) return + this.state.set({ ...s, submitting: true, confirming: null, acknowledged: false, error: null }) try { await binding.spec.onSelect(option, binding.context) } catch (error) { diff --git a/packages/client/ui-command/tests/popup-view.spec.tsx b/packages/client/ui-command/tests/popup-view.spec.tsx index 2cd9891478..db2491fef0 100644 --- a/packages/client/ui-command/tests/popup-view.spec.tsx +++ b/packages/client/ui-command/tests/popup-view.spec.tsx @@ -32,6 +32,17 @@ const OPTIONS: SelectOption[] = [ { id: 'light', label: 'Light', active: true }, { id: 'sepia', label: 'Sepia', detail: 'warm' }, ] +const GATED: SelectOption = { + id: 'full', + label: 'Full access', + confirmation: { + title: 'Enable Full access?', + description: 'Sensitive operations.', + acknowledgeLabel: 'I understand the risks', + cancelLabel: 'Cancel', + confirmLabel: 'Enable Full access', + }, +} const SEGMENT: TokenSegment = { via: 'enter', token: '/theme' } @@ -143,6 +154,37 @@ describe('PopupSelectView', () => { expect(view.container.childElementCount).toBe(0) }) + it('renders a gated option as an in-page modal and requires the checkbox before onSelect', async () => { + const onSelect = vi.fn() + const { popup, consume } = await mountOpen({ + options: () => Promise.resolve([GATED]), + onSelect, + }) + await act(async () => { fireEvent.click(screen.getByRole('option', { name: 'Full access' })) }) + expect(screen.queryByLabelText('/theme options')).toBeNull() + expect(screen.getByRole('dialog', { name: 'Enable Full access?' })).toBeTruthy() + const enable = screen.getByRole('button', { name: 'Enable Full access' }) as HTMLButtonElement + expect(enable.disabled).toBe(true) + expect(onSelect).not.toHaveBeenCalled() + + fireEvent.click(screen.getByRole('checkbox', { name: 'I understand the risks' })) + expect(enable.disabled).toBe(false) + await act(async () => { fireEvent.click(enable) }) + expect(onSelect).toHaveBeenCalledExactlyOnceWith(GATED, 'ctx-A') + expect(consume).toHaveBeenCalledExactlyOnceWith(SEGMENT) + expect(popup.state.getSnapshot().open).toBe(false) + }) + + it('canceling a gated option returns to the picker with acknowledgement reset', async () => { + await mountOpen({ options: () => Promise.resolve([GATED]) }) + await act(async () => { fireEvent.click(screen.getByRole('option', { name: 'Full access' })) }) + fireEvent.click(screen.getByRole('checkbox')) + fireEvent.click(screen.getByRole('button', { name: 'Cancel' })) + expect(screen.getByLabelText('/theme options')).toBeTruthy() + await act(async () => { fireEvent.click(screen.getByRole('option', { name: 'Full access' })) }) + expect(screen.getByRole('checkbox').checked).toBe(false) + }) + it('submitting shows pending, locks the search input, and further Enter/click no-op', async () => { let release!: () => void const onSelect = vi.fn(() => new Promise((resolve) => { release = resolve })) diff --git a/packages/client/ui-command/tests/popup.spec.ts b/packages/client/ui-command/tests/popup.spec.ts index 87a1070a40..68e8084b80 100644 --- a/packages/client/ui-command/tests/popup.spec.ts +++ b/packages/client/ui-command/tests/popup.spec.ts @@ -19,6 +19,17 @@ const OPTIONS: SelectOption[] = [ { id: 'light', label: 'Light', active: true }, { id: 'sepia', label: 'Sepia', detail: 'warm' }, ] +const GATED: SelectOption = { + id: 'full', + label: 'Full access', + confirmation: { + title: 'Enable Full access?', + description: 'Sensitive operations.', + acknowledgeLabel: 'I understand', + cancelLabel: 'Cancel', + confirmLabel: 'Enable Full access', + }, +} const SEGMENT: TokenSegment = { via: 'enter', token: '/theme' } @@ -200,6 +211,38 @@ describe('search / move / highlight over the filtered list', () => { }) describe('select', () => { + it('gates a confirmed option until acknowledgement, then settles through the original binding', async () => { + const onSelect = vi.fn() + const deps = makeDeps() + const { popup } = await readyPopup({ options: () => Promise.resolve([GATED]), onSelect }, deps) + await popup.select(0) + expect(popup.state.getSnapshot()).toMatchObject({ + open: true, confirming: GATED, acknowledged: false, submitting: false, + }) + expect(onSelect).not.toHaveBeenCalled() + await popup.confirm() + expect(onSelect).not.toHaveBeenCalled() + popup.acknowledge(true) + await popup.confirm() + expect(onSelect).toHaveBeenCalledExactlyOnceWith(GATED, CTX_A) + expect(deps.consume).toHaveBeenCalledExactlyOnceWith(SEGMENT) + expect(popup.state.getSnapshot().open).toBe(false) + }) + + it('cancels a confirmation back to the picker without selecting or consuming', async () => { + const onSelect = vi.fn() + const deps = makeDeps() + const { popup } = await readyPopup({ options: () => Promise.resolve([GATED]), onSelect }, deps) + await popup.select(0) + popup.acknowledge(true) + popup.cancelConfirmation() + expect(popup.state.getSnapshot()).toMatchObject({ + open: true, confirming: null, acknowledged: false, submitting: false, + }) + expect(onSelect).not.toHaveBeenCalled() + expect(deps.consume).not.toHaveBeenCalled() + }) + it('runs onSelect with the filtered option and the open-time context, consumes, closes, refocuses', async () => { const seen: Array<{ option: SelectOption; context: Ctx }> = [] const deps = makeDeps() diff --git a/packages/client/ui-conversation/src/client/skeleton/PermissionSelect.module.css b/packages/client/ui-conversation/src/client/skeleton/PermissionSelect.module.css index bbc51b10e9..50dce3913f 100644 --- a/packages/client/ui-conversation/src/client/skeleton/PermissionSelect.module.css +++ b/packages/client/ui-conversation/src/client/skeleton/PermissionSelect.module.css @@ -41,73 +41,3 @@ flex: 0 0 auto; color: var(--dsw-alias-label-caption); } - -.confirmation { - width: min(440px, 100%); - max-height: calc(100vh - 48px); - overflow: hidden; -} - -.confirmationContent { - min-height: 0; - overflow-y: auto; - overscroll-behavior: contain; -} - -@supports (height: 100dvh) { - .confirmation { - max-height: calc(100dvh - 48px); - } -} - -.warning { - display: flex; - align-items: flex-start; - gap: 10px; - color: var(--dsw-alias-label-secondary); - font-size: 14px; - line-height: 22px; -} - -.warning p { - margin: 0; -} - -.warningIcon { - flex: none; - margin-top: 2px; - color: var(--dsw-alias-state-error-primary); -} - -.acknowledgement { - display: flex; - align-items: flex-start; - gap: 10px; - margin-top: 20px; - color: var(--dsw-alias-label-primary); - font-size: 14px; - line-height: 22px; - cursor: pointer; -} - -.acknowledgement input { - flex: none; - width: 16px; - height: 16px; - margin: 3px 0 0; - accent-color: var(--dsw-alias-button-primary-fill); - cursor: pointer; -} - -.acknowledgement input:focus-visible { - outline: 2px solid var(--dsw-alias-border-l4); - outline-offset: 2px; -} - -.modalAction { - min-width: 72px; -} - -.confirmAction { - min-width: 136px; -} diff --git a/packages/client/ui-conversation/src/client/skeleton/PermissionSelect.tsx b/packages/client/ui-conversation/src/client/skeleton/PermissionSelect.tsx index 567abaa27e..d2f8cf8ec0 100644 --- a/packages/client/ui-conversation/src/client/skeleton/PermissionSelect.tsx +++ b/packages/client/ui-conversation/src/client/skeleton/PermissionSelect.tsx @@ -1,6 +1,6 @@ -import { useState } from 'react' +import { useEffect, useState } from 'react' import type { PermissionSelect as PermissionSelectValue } from '@deepseek-ai/dsh-permission/client' -import { Button, IconWarningOutline16, Menu, Modal } from '@deepseek-ai/dsh-client-ui-primitives' +import { Menu, RiskConfirmation } from '@deepseek-ai/dsh-client-ui-primitives' import type { MenuEntry } from '@deepseek-ai/dsh-client-ui-primitives' import css from './PermissionSelect.module.css' @@ -9,8 +9,9 @@ const FULL_ACCESS = 'danger-full-access' /** * Display transform: kebab-case machine names render as title-case labels * (`workspace-write` → `Workspace Write`); non-kebab host-configured names - * pass through. Twin of the /permission popup's (client ui-permission) — the - * two permission surfaces must show the same text. + * pass through. Full access intentionally overrides the machine-name + * transform so both permission surfaces use the product label `Full access`; + * the warning body remains locale-aware. */ function displayName(name: string): string { if (!/^[a-z0-9]+(-[a-z0-9]+)*$/.test(name)) return name @@ -34,6 +35,13 @@ export function PermissionSelect({ value, locked, command, t }: PermissionSelect const [confirmation, setConfirmation] = useState(null) const [acknowledged, setAcknowledged] = useState(false) + useEffect(() => { + if (!locked && value !== undefined) return + setOpen(false) + setAcknowledged(false) + setConfirmation(null) + }, [locked, value]) + if (value === undefined) return null const currentValue = pick ?? value.currentValue @@ -68,7 +76,7 @@ export function PermissionSelect({ value, locked, command, t }: PermissionSelect } const confirmFullAccess = (): void => { - if (!acknowledged || confirmation === null) return + if (locked || !acknowledged || confirmation === null) return const id = confirmation closeConfirmation() submit(id) @@ -99,42 +107,19 @@ export function PermissionSelect({ value, locked, command, t }: PermissionSelect } /> - - - - - )} - > -
      - -

      {t('confirm.description')}

      -
      - -
      + description={t('confirm.description')} + acknowledgeLabel={t('confirm.acknowledge')} + cancelLabel={t('confirm.cancel')} + confirmLabel={t('confirm.enable')} + acknowledged={acknowledged} + disabled={locked} + onAcknowledgedChange={setAcknowledged} + onCancel={closeConfirmation} + onConfirm={confirmFullAccess} + /> ) } diff --git a/packages/client/ui-conversation/tests/input-bar.spec.tsx b/packages/client/ui-conversation/tests/input-bar.spec.tsx index 2fa04b6af4..48bfd48c53 100644 --- a/packages/client/ui-conversation/tests/input-bar.spec.tsx +++ b/packages/client/ui-conversation/tests/input-bar.spec.tsx @@ -541,6 +541,42 @@ describe('placeholder chrome and control seats', () => { expect((view.getByRole('button', { name: 'Enable Full access' }) as HTMLButtonElement).disabled).toBe(true) }) + it('revokes an open Full access confirmation when the task locks', () => { + const command = vi.fn(() => Promise.resolve(true)) + const permissions = { + options: [ + { value: 'workspace-write', name: 'workspace-write' }, + { value: 'danger-full-access', name: 'danger-full-access' }, + ], + currentValue: 'workspace-write', + } + const { view, session } = bench({ permissions, command }) + fireEvent.click(view.getByLabelText(/^Access mode/)) + fireEvent.click(view.getByRole('menuitem', { name: 'Full access' })) + fireEvent.click(view.getByRole('checkbox')) + act(() => { session.set(snapshotOf({ removed: true })) }) + expect(view.queryByRole('dialog')).toBeNull() + expect(command).not.toHaveBeenCalled() + }) + + it('resets an open Full access confirmation when switching tasks', () => { + const command = vi.fn(() => Promise.resolve(true)) + const permissions = { + options: [ + { value: 'workspace-write', name: 'workspace-write' }, + { value: 'danger-full-access', name: 'danger-full-access' }, + ], + currentValue: 'workspace-write', + } + const { view, props } = bench({ permissions, command }) + fireEvent.click(view.getByLabelText(/^Access mode/)) + fireEvent.click(view.getByRole('menuitem', { name: 'Full access' })) + fireEvent.click(view.getByRole('checkbox')) + view.rerender() + expect(view.queryByRole('dialog')).toBeNull() + expect(command).not.toHaveBeenCalled() + }) + it('a registered entry fills its seat and receives the locked owner prop', () => { const { view, slotCalls } = bench({ disabled: true, diff --git a/packages/client/ui-permission/package.json b/packages/client/ui-permission/package.json index cee54f104c..ee2d789500 100644 --- a/packages/client/ui-permission/package.json +++ b/packages/client/ui-permission/package.json @@ -24,6 +24,7 @@ }, "dshClient": { "inject": [ + "@deepseek-ai/dsh-client-locale", "@deepseek-ai/dsh-client-runtime", "@deepseek-ai/dsh-client-ui-command" ], @@ -35,6 +36,7 @@ }, "license": "BSD-3-Clause", "peerDependencies": { + "@deepseek-ai/dsh-client-locale": "^0.0.1", "@deepseek-ai/dsh-client-runtime": "^0.0.1", "@deepseek-ai/dsh-client-ui-command": "^0.0.1", "@deepseek-ai/dsh-client-ui-slash": "^0.0.1", @@ -43,6 +45,7 @@ "cordis": "^4.0.0-rc.7" }, "devDependencies": { + "@deepseek-ai/dsh-client-locale": "workspace:^", "@deepseek-ai/dsh-client-runtime": "workspace:^", "@deepseek-ai/dsh-client-ui-command": "workspace:^", "@deepseek-ai/dsh-client-ui-slash": "workspace:^", diff --git a/packages/client/ui-permission/src/client/index.ts b/packages/client/ui-permission/src/client/index.ts index 30fc6d2dd5..2914e96f64 100644 --- a/packages/client/ui-permission/src/client/index.ts +++ b/packages/client/ui-permission/src/client/index.ts @@ -8,15 +8,21 @@ * projection (the same host-computed select the composer chip renders); a * pick submits the `/permission ` command line, so both surfaces * write through one path and the pushed projection frame is the one - * confirmation. + * confirmation. The Full access row carries the same explicit risk gate as + * the composer chip; the shared popup shell owns the modal mechanics. */ import type { ClientContext, SessionFace } from '@deepseek-ai/dsh-client-runtime/client' import type { CommandServiceContract, SelectOption } from '@deepseek-ai/dsh-client-ui-command/client' import type { ClientSessionContext } from '@deepseek-ai/dsh-client-ui-slash/client' +// Type-only: pulls the locale plugin's Context merge (ctx.locale). +import type {} from '@deepseek-ai/dsh-client-locale/client' import type { PermissionSelect } from '@deepseek-ai/dsh-permission/client' /** Required services (cordis fiber inject). */ -export const inject = ['command', 'sessions'] +export const inject = ['command', 'sessions', 'locale'] + +const FULL_ACCESS = 'danger-full-access' +const ACCESS_NS = 'permission.access' /** Read one session's current permissions projection value (undefined = capability absent). */ function selectOf(session: SessionFace | undefined): PermissionSelect | undefined { @@ -26,8 +32,9 @@ function selectOf(session: SessionFace | undefined): PermissionSelect | undefine /** * Display transform twin of the composer chip's (ui-conversation * PermissionSelect): kebab-case machine names render as title-case labels - * (`workspace-write` → `Workspace Write`) so both permission surfaces show - * the same text; non-kebab host-configured names pass through. + * (`workspace-write` → `Workspace Write`); non-kebab host-configured names + * pass through. Full access intentionally uses the product label rather than + * a title-cased machine value; its warning body remains locale-aware. */ function displayName(name: string): string { if (!/^[a-z0-9]+(-[a-z0-9]+)*$/.test(name)) return name @@ -35,14 +42,25 @@ function displayName(name: string): string { } /** Flatten the projection select into popup rows; `custom` is display state, never a target. */ -function optionsOf(value: PermissionSelect): SelectOption[] { +function optionsOf(value: PermissionSelect, t: (key: string) => string): SelectOption[] { return value.options .filter(option => option.value !== 'custom') .map(option => ({ id: option.value, - label: displayName(option.name), + label: option.value === FULL_ACCESS ? 'Full access' : displayName(option.name), ...(option.description !== undefined ? { detail: option.description } : {}), ...(option.value === value.currentValue ? { active: true } : {}), + ...(option.value === FULL_ACCESS + ? { + confirmation: { + title: t('confirm.title'), + description: t('confirm.description'), + acknowledgeLabel: t('confirm.acknowledge'), + cancelLabel: t('confirm.cancel'), + confirmLabel: t('confirm.enable'), + }, + } + : {}), })) } @@ -54,6 +72,26 @@ function optionsOf(value: PermissionSelect): SelectOption[] { export function apply(ctx: ClientContext): void { const command = ctx.get('command') as CommandServiceContract const sessions = ctx.sessions + ctx.effect(() => { + const disposers = [ + ctx.locale.register(ACCESS_NS, 'zh', { + 'confirm.title': '确认启用 Full access?', + 'confirm.description': '启用 Full access 后,agent 将减少确认步骤,并且可以直接执行更多操作,包括敏感操作、文件修改或外部命令。仅建议在你信任当前任务时使用。', + 'confirm.acknowledge': '我已了解风险,并愿意继续', + 'confirm.cancel': '取消', + 'confirm.enable': '启用 Full access', + }), + ctx.locale.register(ACCESS_NS, 'en', { + 'confirm.title': 'Enable Full access?', + 'confirm.description': 'Full access reduces confirmation steps and lets the agent perform more actions directly, including sensitive operations, file changes, or external commands. Only use it when you trust the current task.', + 'confirm.acknowledge': 'I understand the risks and want to continue', + 'confirm.cancel': 'Cancel', + 'confirm.enable': 'Enable Full access', + }), + ] + return () => { for (const dispose of disposers) dispose() } + }, 'ui-permission: Full access confirmation dictionaries') + const t = ctx.locale.bind(ACCESS_NS) const sessionFor = (session: ClientSessionContext): SessionFace | undefined => sessions.binding(session.sessionId)?.session ctx.effect(() => command.decorate({ @@ -67,7 +105,7 @@ export function apply(ctx: ClientContext): void { options: (session) => { const value = selectOf(sessionFor(session)) if (value === undefined) throw new Error('permission presets are not available on this host') - return Promise.resolve(optionsOf(value)) + return Promise.resolve(optionsOf(value, t)) }, onSelect: async (option, session) => { const live = sessionFor(session) diff --git a/packages/client/ui-permission/tests/browser-plugin.spec.ts b/packages/client/ui-permission/tests/browser-plugin.spec.ts index 5f9125db53..f8fde6d10d 100644 --- a/packages/client/ui-permission/tests/browser-plugin.spec.ts +++ b/packages/client/ui-permission/tests/browser-plugin.spec.ts @@ -54,6 +54,17 @@ async function bench() { ctx.provide('sessions', { binding: (id: SessionId) => (values.has(id) ? { sessionId: id, session: session(id) } : undefined), }) + const en = { + 'confirm.title': 'Enable Full access?', + 'confirm.description': 'Full access can perform sensitive operations.', + 'confirm.acknowledge': 'I understand the risks and want to continue', + 'confirm.cancel': 'Cancel', + 'confirm.enable': 'Enable Full access', + } as Record + ctx.provide('locale', { + register: () => () => {}, + bind: () => (key: string) => en[key] ?? key, + }) const fiber = ctx.plugin({ inject: [...inject], apply }) await fiber.await() return { @@ -86,7 +97,14 @@ describe('ui-permission browser plugin', () => { expect(again.find(option => option.id === 'workspace-write')?.active).toBe(true) expect(again.find(option => option.id === 'read-only')?.detail).toBe('Reads only.') // Kebab-case names title-case; non-kebab host-configured names pass through. - expect(again.map(option => option.label)).toEqual(['Read Only', 'Workspace Write', 'Danger Full Access']) + expect(again.map(option => option.label)).toEqual(['Read Only', 'Workspace Write', 'Full access']) + expect(again.find(option => option.id === 'danger-full-access')?.confirmation).toEqual({ + title: 'Enable Full access?', + description: 'Full access can perform sensitive operations.', + acknowledgeLabel: 'I understand the risks and want to continue', + cancelLabel: 'Cancel', + confirmLabel: 'Enable Full access', + }) b.values.set(sid('s1'), { ...SELECT, options: [{ value: 'plain', name: 'Ask Every Time' }] }) const passthrough = await c.ui.options(proj, new AbortController().signal) expect(passthrough[0]?.label).toBe('Ask Every Time') diff --git a/packages/client/ui-primitives/src/Modal.tsx b/packages/client/ui-primitives/src/Modal.tsx index f25135d1da..d4199d9581 100644 --- a/packages/client/ui-primitives/src/Modal.tsx +++ b/packages/client/ui-primitives/src/Modal.tsx @@ -1,9 +1,11 @@ // Modal: controlled full-viewport dialog (create-workspace and similar). -// Fixed overlay in the React tree (no react-dom portal) so ui-primitives -// stays free of a react-dom dependency; mask tokens match figma 451:18655. +// The overlay portals to this document's body so ancestor stacking contexts +// cannot leave sticky page controls above the mask. This is still an in-page +// WebUI dialog; it never creates or targets another browser/native window. import { useEffect } from 'react' import type { ReactNode } from 'react' +import { createPortal } from 'react-dom' import clsx from 'clsx' import { IconCloseOutline16 } from './icons/index.tsx' import css from './Modal.module.css' @@ -44,7 +46,7 @@ export function Modal({ open, onClose, title, description, children, footer, cla if (!open) return null - return ( + return createPortal((
      ) } - case 'context': + case 'context': { + // Pure-text injections show their text; anything with non-text blocks + // (or nothing at all) keeps the full JSON payload so no material is lost. + // Title-only collapsed row (no summary), label-less expanded card: the + // injection is ambient context, not a call's input. + const { text, rest } = contentText(node.content) + const body = rest.length === 0 && text !== '' + ? text + : JSON.stringify({ content: node.content, source: node.source }, null, 2) return (
      - + } + title="上下文注入" + summary="" + body={body} + plainBody + state="ok" + />
      ) + } default: return (
      diff --git a/packages/client/ui-conversation/src/client/chat/ToolRow.module.css b/packages/client/ui-conversation/src/client/chat/ToolRow.module.css index 08031f570c..3332882518 100644 --- a/packages/client/ui-conversation/src/client/chat/ToolRow.module.css +++ b/packages/client/ui-conversation/src/client/chat/ToolRow.module.css @@ -41,7 +41,8 @@ 90%, 100% { left: 100%; } } -/* Expand-on-row (Think / code): pointer only — no row fill hover. */ +/* Every expandable row is the expand control: pointer only — the icon→chevron + hover preview is the affordance, no row fill. */ .row[data-expandable] { cursor: pointer; } @@ -55,9 +56,6 @@ align-items: center; justify-content: center; margin-right: 6px; - padding: 0; - border: none; - background: none; color: var(--dsw-alias-label-tertiary); } @@ -76,8 +74,8 @@ background: var(--dsw-alias-state-business-primary); } -button.leading { - cursor: pointer; +.chevron { + color: var(--dsw-alias-label-secondary); } /* Hover preview on expandable rows: the idle tool icon crossfades (100ms) @@ -155,8 +153,65 @@ button.leading { text-decoration: underline; } -/* Expanded body: pad-left 22 indented gray text, no border, no fill. */ -.body { +/* Error row's collapsed summary: the failure's first line in the error color. */ +.errorSummary { + color: var(--dsw-alias-state-error-primary); +} + +/* Expanded body + Inspect pill wrapper (sibling of .row: clicks never toggle). */ +.bodyWrap { + display: flex; + flex-direction: column; +} + +/* Hover-revealed jump to the trajectory record: a small pill in real flow + under the expanded body's bottom-left corner (it reserves its line, so + revealing never shifts layout); revealed by hovering anywhere on the tool + call — title row included — or by keyboard focus. */ +.inspectButton { + display: inline-flex; + align-self: flex-start; + align-items: center; + gap: 4px; + margin: 4px 0 2px 4px; + padding: 2px 8px; + border: 1px solid var(--dsw-alias-border-l2); + border-radius: 999px; + /* Base background, not bg-overlay: the overlay token is a raised dark + surface and reads too heavy for a quiet in-flow affordance. */ + background: var(--dsw-alias-bg-base); + color: var(--dsw-alias-label-secondary); + font-size: 11px; + line-height: 16px; + cursor: pointer; + opacity: 0; + transition: opacity 100ms ease; +} + +.root:hover .inspectButton, +.inspectButton:focus-visible { + opacity: 1; +} + +/* Solid hover fill (a translucent token would let content bleed through). */ +.inspectButton:hover { + background: var(--dsw-alias-interactive-bg-hover-solid); + color: var(--dsw-alias-label-primary); +} + +/* Expanded-body scroll wrapper for the run_code CodeBlock; the IN/OUT card + and the terminal card scroll INSIDE their own surface instead, so the + scrollbar sits within the rounded card. */ +.bodyScroll { + max-height: 260px; + overflow-y: auto; +} + +/* Think expanded body: plain indented gray reasoning prose — no IN/OUT card + (the reasoning is not an input payload), pre-wrapped at the row's indent. + Uncapped: reasoning reads as message prose, so it flows with the page + instead of scrolling in a box. */ +.thinkBody { padding: 4px 0 4px 22px; font-size: 14px; line-height: 24px; @@ -165,6 +220,89 @@ button.leading { color: var(--dsw-alias-label-tertiary); } +/* Expanded input/output card (figma 1249:35657): the code-block surface and + radius from the TerminalBlock/CodeBlock family. The card itself is a plain + column — the padding and the IN/OUT gutter-label grid live on each section + so the divider spans the full card width and each section scrolls alone. */ +.ioCard { + display: flex; + flex-direction: column; + margin: 4px 0 4px 4px; + border: 1px solid var(--dsw-alias-border-l1); + border-radius: 12px; + background: var(--dsw-alias-markdown-code-block); + font: var(--dsw-font-markdown-code-block-small); +} + +/* One card section (IN or OUT): the gutter-label grid, capped and scrolling + independently so a long input never buries a short output (and vice versa). */ +.ioSection { + display: grid; + grid-template-columns: max-content 1fr; + column-gap: 14px; + align-items: baseline; + padding: 12px 16px; + max-height: 150px; + overflow-y: auto; +} + +/* Card-internal scrollbar: a 2px transparent border clips the thumb inward so + it floats off the rounded card edge instead of hugging it (the terminal + card's own output scroller carries the same treatment in TerminalBlock). */ +.ioSection::-webkit-scrollbar-thumb, +.ioCardPlain::-webkit-scrollbar-thumb { + border: 2px solid transparent; + background-clip: padding-box; + border-radius: 6px; +} + +/* Track end-margins keep the thumb's travel out of the rounded corners. */ +.ioSection::-webkit-scrollbar-track, +.ioCardPlain::-webkit-scrollbar-track { + margin: 6px 0; +} + +/* Label-less variant of the card (plainBody): the text is not an IN/OUT pair, + so it renders as one plain padded block scrolling as a whole. */ +.ioCardPlain { + display: block; + padding: 12px 16px; + max-height: 260px; + overflow-y: auto; +} + +/* Caption (not tertiary): one step dimmer than the payload text so the + gutter labels read as labels, not as part of the content. Sticky against + the section's own scroll so the label stays readable while its payload + scrolls underneath (top 0 = the section's padding edge inside the + scrollport; start-aligned because sticky needs a block-start anchor). */ +.ioLabel { + position: sticky; + top: 0; + align-self: start; + color: var(--dsw-alias-label-caption); +} + +/* l2 hairline between the IN and OUT sections, spanning the full card width + (it sits between the padded sections, not inside their grid). */ +.ioDivider { + flex: none; + height: 1px; + background: var(--dsw-alias-border-l2); +} + +.ioText { + min-width: 0; + white-space: pre-wrap; + word-break: break-word; + color: var(--dsw-alias-label-secondary); +} + +/* A failed call's OUT text shares the collapsed summary's error color. */ +.ioText[data-error] { + color: var(--dsw-alias-state-error-primary); +} + /* The two block-shaped expanded bodies: the code variant's run_code program through CodeBlock (shiki-highlighted TypeScript) and a terminal card's command output through TerminalBlock. Both are drawn by the shared @@ -173,15 +311,21 @@ button.leading { flow's row rhythm. */ .codeBody, .terminalBody { - margin: 4px 0 4px 22px; + margin: 4px 0 4px 4px; } -/* Indented to the body's own column so the description reads as the card's - heading rather than as another summary row, and sits tight against the card - below it. Its own rule: grouping it with a body would put description - typography on a `CodeBlock` wrapper and change that body's spacing. */ -.terminalDescription { - margin: 4px 0 0 22px; - color: var(--dsw-alias-label-secondary); - font: var(--dsw-font-xs-13); +/* In-row code renders at the smaller code size (12/18) via each primitive's + rebindable content-font seam; standalone markdown code blocks keep 13/22. */ +.codeBody { + --dsl-code-block-content-font: var(--dsw-font-markdown-code-block-small); +} + +/* The terminal card scrolls its OUTPUT inside its own surface (same l1 + hairline as the IN/OUT card): the banner stays pinned and the scrollbar + never rides over it. 224px = the 260px card cap minus the ~36px banner. */ +.terminalBody { + --dsl-terminal-font: var(--dsw-font-markdown-code-block-small); + --dsl-terminal-line-height: 18px; + --dsl-terminal-output-max-height: 224px; + border: 1px solid var(--dsw-alias-border-l1); } diff --git a/packages/client/ui-conversation/src/client/chat/ToolRow.tsx b/packages/client/ui-conversation/src/client/chat/ToolRow.tsx index fe0df556ce..4182f72a52 100644 --- a/packages/client/ui-conversation/src/client/chat/ToolRow.tsx +++ b/packages/client/ui-conversation/src/client/chat/ToolRow.tsx @@ -1,17 +1,25 @@ // ToolRow: the single-line tool summary row (figma component set 122:9479) — // 16px leading slot (state dot / tool icon, chevron on hover or expanded) + title + // separator dot + FILL-truncated summary. The collapsed row is always one -// line; the expanded body is indented gray text, the run_code program through -// CodeBlock, or — for a call whose render intent is a terminal card — the -// command's own output through TerminalBlock, capped at -// CHAT_TERMINAL_MAX_LINES so the message flow stays scannable. Expand state is -// component-local view state. File-tool summaries are path links that open -// through the host; the row itself is not a details-panel control. +// line; every row with body, output, or terminal material is a whole-row +// expand toggle (click / Enter / Space, icon→chevron hover preview); the +// summary stays inline while open, except Think, whose body opens with the +// same first line and would repeat it. +// The expanded body — an IN/OUT gutter-labeled card (figma 1249:35657) for +// text input/output, the run_code program through CodeBlock, or a terminal +// card's command output through TerminalBlock — lives in a max-height scroll +// container so a long payload scrolls internally instead of taking over the +// message flow; Think's prose is the exception and flows uncapped like +// message text. Expand state is component-local view state. File-tool summaries are path links that open +// through the host (stopPropagation keeps the two gestures independent); an +// error row's collapsed summary is the failure's first line in the error +// color. import { useState, type KeyboardEvent, type MouseEvent, type ReactNode } from 'react' +import clsx from 'clsx' import { CodeBlock, StateDot, TerminalBlock } from '@deepseek-ai/dsh-client-ui-primitives' import { IconChevronDownOutline14 } from '@deepseek-ai/dsh-client-ui-primitives' -import { CHAT_TERMINAL_MAX_LINES, type TerminalCardModel } from '../contract/terminal-card-model.ts' +import type { TerminalCardModel } from '../contract/terminal-card-model.ts' import type { ToolRowState, ToolRowVariant } from '../contract/tool-call-model.ts' import css from './ToolRow.module.css' @@ -23,18 +31,25 @@ export interface ToolRowProps { icon: ReactNode title: string summary: string - /** Expanded-body text; null = no text body (`terminal` is the other body source). */ + /** Expanded-body input text; null = no input section. */ body: string | null + /** Flattened result text for the expanded Output section; null/absent = no output section. */ + output?: string | null | undefined + /** Error first line shown as the collapsed summary on an error row; null/absent = keep `summary`. */ + errorSummary?: string | null | undefined /** * Terminal-card material for a call whose render intent is a terminal card - * (derived by `terminalCardModel`); it replaces the text body when present. - * Null or absent leaves the text body, and a row with neither is not - * expandable (its leading slot never toggles). + * (derived by `terminalCardModel`); it replaces the text sections when + * present. A row with no body, no output, and no terminal material is not + * expandable. */ terminal?: TerminalCardModel | null | undefined + /** + * Render the expanded body in the card without the IN gutter label — for + * material that is not a call's input payload (context injection). + */ + plainBody?: boolean | undefined state: ToolRowState - /** Makes the row itself the expand control instead of only its leading icon. */ - expandOnRowClick?: boolean | undefined /** * Filesystem path from tool args; when set with onOpenFile, the summary * renders as a hover-underline link that opens the host default app. @@ -42,6 +57,21 @@ export interface ToolRowProps { filePath?: string | undefined /** Open the path with the host OS default application (already cwd-resolved). */ onOpenFile?: ((path: string) => void) | undefined + /** + * Jump to this call in the trajectory view: a hover-revealed Inspect pill + * over the expanded body. Absent = no affordance (rows without a call + * identity, like Think and context injection). + */ + inspect?: (() => void) | undefined +} + +/** The Inspect pill's code glyph (user-supplied 16×16), fill follows text color. */ +function IconInspect() { + return ( + + + + ) } /** Leading-slot state substitution: the tool icon yields to the terminal state @@ -62,36 +92,31 @@ export function ToolRow({ title, summary, body, + output, + errorSummary, terminal, + plainBody, state, - expandOnRowClick = false, filePath, onOpenFile, + inspect, }: ToolRowProps) { const [expanded, setExpanded] = useState(false) const terminalBody = terminal ?? null - // A row that names a single file keeps one interaction (open that path); - // args expand is off whether or not the open callback is wired yet. Terminal - // material still expands: only the file variants carry a path, so a terminal - // card and a file link never land on the same row. - const singleFile = filePath !== undefined - const fileLink = singleFile && onOpenFile !== undefined - const expandable = (body !== null && !singleFile) || terminalBody !== null - // The text arms take the empty string for a null body: a row expandable - // only through its terminal material renders the terminal body instead, so - // this substitution never shows. - const text = body ?? '' + const outputText = output ?? null + const expandable = body !== null || outputText !== null || terminalBody !== null const open = expanded && expandable - const rowExpands = expandable && expandOnRowClick + // An error row's collapsed summary IS the failure: the first error line in + // the error color outranks both the args summary and a terminal description. + const failureLine = state === 'error' ? errorSummary ?? null : null + const summaryText = failureLine ?? summary + // The failure line is error prose, not the path: no open-file affordance. + const fileLink = filePath !== undefined && onOpenFile !== undefined && failureLine === null const toggleExpand = () => { setExpanded(v => !v) } - const toggleFromLeading = (event: MouseEvent) => { - event.stopPropagation() - toggleExpand() - } const toggleFromKeyboard = (event: KeyboardEvent) => { - if (!rowExpands || (event.key !== 'Enter' && event.key !== ' ')) return + if (!expandable || (event.key !== 'Enter' && event.key !== ' ')) return event.preventDefault() toggleExpand() } @@ -99,46 +124,47 @@ export function ToolRow({ event.stopPropagation() if (filePath !== undefined) onOpenFile?.(filePath) } - // Expandable rows preview the toggle on hover: the tool icon yields to a - // down chevron (CSS swap on .row:hover); state dots still take precedence. + // Think reasoning is prose, not an input payload: expanded, it renders as + // plain indented text (no IN/OUT card) and the inline summary — the body's + // own first line — yields to avoid repeating itself. + const isThink = variant === 'think' + // The code variant's program renders through CodeBlock (shiki), so only its + // output joins the IN/OUT card; every other variant's input does too. + const cardBody = variant === 'code' ? null : body + // Expandable rows preview the toggle on hover: the idle leading — the tool + // icon OR the state dot — yields to a down chevron (CSS swap on .row:hover). + // The state substitution happens inside the idle slot so an error row keeps + // the hover preview instead of losing it with the icon. + const idleLeading = leadingFor(state, icon) const collapsedIcon = expandable ? ( <> - {icon} - + {idleLeading} + ) - : icon + : idleLeading const leading = open - ? - : leadingFor(state, collapsedIcon) + ? + : collapsedIcon return (
      - {expandable && !rowExpands ? ( - - ) : ( - - {leading} - - )} + + {leading} + {title} - {!open && ( + {/* An empty summary drops the separator with it (a row that is only + its title, like the context-injection row, shows no trailing dot). */} + {!(open && isThink) && summaryText !== '' && ( <> {fileLink ? ( @@ -147,25 +173,71 @@ export function ToolRow({ className={css.fileLink} onClick={openFile} > - {summary} + {summaryText} ) : ( - {summary} + + {summaryText} + )} )}
      - {/* The terminal presenter's description belongs ABOVE the card per the - render-intent contract, so an expanded terminal row keeps showing it - even though the collapsed summary is hidden while open. */} - {open && terminalBody?.description !== undefined && ( -
      {terminalBody.description}
      + {open && ( + /* The wrapper (sibling of .row, so clicks inside never toggle the + row) carries the expanded body and the Inspect pill below it. */ +
      + {terminalBody !== null + ? + : isThink + ?
      {body}
      + : ( + <> + {variant === 'code' && body !== null && ( +
      + +
      + )} + {plainBody === true && cardBody !== null && ( +
      + {cardBody} +
      + )} + {plainBody !== true && (cardBody !== null || outputText !== null) && ( +
      + {cardBody !== null && ( +
      + IN + {cardBody} +
      + )} + {cardBody !== null && outputText !== null && ( + + )} + {outputText !== null && ( +
      + OUT + + {outputText} + +
      + )} +
      + )} + + )} + {inspect !== undefined && ( + + )} +
      )} - {open && (terminalBody !== null - ? - : variant === 'code' - ? - :
      {text}
      )}
      ) } diff --git a/packages/client/ui-conversation/src/client/contract/slots.ts b/packages/client/ui-conversation/src/client/contract/slots.ts index 1684e616b2..8e20f4054f 100644 --- a/packages/client/ui-conversation/src/client/contract/slots.ts +++ b/packages/client/ui-conversation/src/client/contract/slots.ts @@ -147,13 +147,17 @@ export interface InputZone { } /** - * View-slot owner share: deliberately empty — ConversationRoot supplies - * nothing at its renderSlot site (sessionId and the snapshot hook arrive as + * View-slot owner share: the cross-view inspect handoff (otherwise views need + * nothing from the render site — sessionId and the snapshot hook arrive as * framework-standard props; tool rows go through each view's own declared - * toolview hole). Kept as the named owner seat so a future cross-view - * payload has a home. + * toolview hole). */ -export interface ConvViewOwnerProps {} +export interface ConvViewOwnerProps { + /** One-shot inspect request from another view (chat's Inspect button); null when idle. */ + inspect?: { callId: CallId } | null + /** Acknowledge the inspect request once applied (clears the store field). */ + onInspectDone?: () => void +} /** * Owner share of a per-view toolview slot: the call material the rendering @@ -176,6 +180,11 @@ export interface ToolRowOwnerProps { * The chat view resolves relative paths against the session cwd. */ openFile: (path: string) => void + /** + * Jump to this call's record in the trajectory view (the expanded row's + * hover Inspect affordance). Undefined when no trajectory jump is wired. + */ + inspect?: (() => void) | undefined } /** @@ -419,6 +428,19 @@ export interface ChatViewInjected { */ openFile: (path: string) => void loadOlder: () => void + /** Hand a call off to the trajectory view: write the one-shot inspect target and switch tabs. */ + inspectCall: (callId: CallId) => void + /** + * Per-session scroll memory surviving view switches (in-memory, never + * persisted): the view saves on every scroll and restores on remount; a + * fresh page load starts empty and keeps the open-jump-to-bottom default. + */ + chatScroll: { + /** Record the scroll offset; null clears it (pinned to bottom). */ + save: (top: number | null) => void + /** Last recorded offset, or null when pinned or never recorded. */ + read: () => number | null + } } /** Full chat-view component props: runtime share & the declared toolview/commandview holes' render share & store share & injected share. */ diff --git a/packages/client/ui-conversation/src/client/contract/terminal-card-model.ts b/packages/client/ui-conversation/src/client/contract/terminal-card-model.ts index e25d68cbbb..8d7750c3ba 100644 --- a/packages/client/ui-conversation/src/client/contract/terminal-card-model.ts +++ b/packages/client/ui-conversation/src/client/contract/terminal-card-model.ts @@ -11,17 +11,6 @@ import type { TerminalBlockProps } from '@deepseek-ai/dsh-client-ui-primitives' import { resolveToolPath, type ToolCallBlock } from './tool-call-model.ts' -/** - * Output lines the chat row's expanded terminal body shows before collapsing - * the middle — half the primitive's own default, which the details panel - * keeps. A chat row is a summary surface inside the message flow: the flow - * must stay scannable across many calls, while the details panel is the - * single-call reading surface. A design constant of this UI's row geometry, - * not a deployment choice, so it is fixed here rather than a plugin Config - * field. - */ -export const CHAT_TERMINAL_MAX_LINES = 8 - /** * The {@link TerminalBlock} props this derivation owns. Picked off the * primitive's props so the two stay in step; `home` is absent because the web @@ -44,6 +33,20 @@ export interface TerminalCardModel { description: string | undefined } +/** + * True when a settled terminal card reports a failing exit — a non-zero code + * or a terminating signal. The bash tool settles a failing command as a + * completed call (`isError` stays false: the exit status is result data), so + * this is the collapsed row's only failure signal; without it the red exit + * pill would be visible only after expanding the card. + * @param model - a derived terminal card. + * @returns whether the card's exit status is a failure. + */ +export function terminalFailed(model: TerminalCardModel): boolean { + const { exitCode, signal, running } = model.card + return running !== true && ((exitCode !== undefined && exitCode !== 0) || signal !== undefined) +} + /** * Resolve a terminal view's working directory the way the render-intent * contract assigns to the UI bridge: an absolute path is used as-is, a relative diff --git a/packages/client/ui-conversation/src/client/contract/tool-call-model.ts b/packages/client/ui-conversation/src/client/contract/tool-call-model.ts index b53ef95c01..d7735fdab2 100644 --- a/packages/client/ui-conversation/src/client/contract/tool-call-model.ts +++ b/packages/client/ui-conversation/src/client/contract/tool-call-model.ts @@ -1,14 +1,15 @@ /** * Pure row-model derivation for tool summary rows: variant classification, - * one-line summary and expanded-body text from the frozen call slice. This - * derivation reads the call ARGUMENTS only; a call whose render intent is a - * terminal card gets its expanded body from the views instead, through + * one-line summary, expanded-body text, and flattened result output from the + * frozen call slice. Input material comes from the call ARGUMENTS; output and + * error material from the settled result node. A call whose render intent is + * a terminal card gets its expanded body from the views instead, through * `terminalCardModel` in terminal-card-model.ts. */ // The block union's defining home is runtime (fold-product types); this // contract only forwards it (type-definition authority stays with the layer // that produces the values). -import type { ToolCallBlock } from '@deepseek-ai/dsh-client-runtime/client' +import type { ToolCallBlock, ToolResultNode } from '@deepseek-ai/dsh-client-runtime/client' export type { ToolCallBlock } from '@deepseek-ai/dsh-client-runtime/client' @@ -70,11 +71,34 @@ export interface ToolRowModel { * relative values against the session cwd before opening. */ filePath: string | undefined - /** Expanded-body text (pretty args); null = row not expandable. */ + /** Expanded-body input text (pretty args); null = no input section. */ body: string | null + /** Flattened result text ({@link resultText}); null while running or when the result carries no text. */ + output: string | null + /** First line of the result text on an error row; null for every other state. */ + errorSummary: string | null state: ToolRowState } +/** + * Flatten a settled result's content blocks to display text: text blocks + * verbatim, other block shapes as pretty JSON. Empty content on a failed call + * falls back to the structured error's `name: code` line. + * @param node - the settled result node. + * @returns the flattened result text (may be empty). + */ +export function resultText(node: ToolResultNode): string { + const parts: string[] = [] + for (const block of node.content) { + if (block.type === 'text') parts.push(block.text) + else parts.push(JSON.stringify(block, null, 2)) + } + if (parts.length === 0 && node.error !== undefined) { + parts.push(`${node.error.name}: ${node.error.code}`) + } + return parts.join('\n') +} + function parseArgs(argsRaw: string): unknown { try { return JSON.parse(argsRaw) @@ -192,12 +216,19 @@ export function toolRowModel(toolName: string, block: ToolCallBlock, cwd?: strin const summary = variant === 'others' && toolName !== '' && toolTitle === undefined ? `${toolName} · ${base}` : base + // The empty string is "no text" for both derived result fields: a settled + // call with blank content has nothing to expand, and a blank first line + // would erase the collapsed error row's summary slot. + const output = done ? (resultText(block) || null) : null + const errorSummary = state === 'error' && output !== null ? firstLine(output) : null return { variant, title: toolTitle ?? VARIANT_TITLES[variant], summary, filePath: deriveFilePath(variant, argsRaw), body: deriveBody(variant, argsRaw), + output, + errorSummary, state, } } diff --git a/packages/client/ui-conversation/src/client/contract/views.ts b/packages/client/ui-conversation/src/client/contract/views.ts index 9ef9515f19..a8da4121b9 100644 --- a/packages/client/ui-conversation/src/client/contract/views.ts +++ b/packages/client/ui-conversation/src/client/contract/views.ts @@ -23,4 +23,10 @@ export interface ChatStoreState { draft: string /** Active conversation view id ('conversation.view' entry id); null falls back to the first view. */ view: string | null + /** + * One-shot inspect handoff: chat writes the call to reveal, the trajectory + * view consumes it and acknowledges by clearing. Read with `?? null` — + * persisted snapshots from before this field rehydrate without it. + */ + inspect: { callId: CallId } | null } diff --git a/packages/client/ui-conversation/src/client/skeleton/ConversationSession.tsx b/packages/client/ui-conversation/src/client/skeleton/ConversationSession.tsx index 33b24f5245..d335cd9218 100644 --- a/packages/client/ui-conversation/src/client/skeleton/ConversationSession.tsx +++ b/packages/client/ui-conversation/src/client/skeleton/ConversationSession.tsx @@ -35,6 +35,8 @@ export function ConversationSession({ const blank = useSession(s => s.blank) const inputState = useInput(s => s) const storedDraft = useStore(s => s.draft) + // `?? null`: persisted snapshots from before the inspect field rehydrate without it. + const inspect = useStore(s => s.inspect ?? null) useEffect(() => { if (inputState.draft === '' && storedDraft !== '') inputActions.setDraft(storedDraft) @@ -52,7 +54,10 @@ export function ConversationSession({ const view: ReactNode = hideChrome ? null : (
      - {active !== undefined && renderSlot('conversation.view', {}, { only: active.id })} + {active !== undefined && renderSlot('conversation.view', { + inspect, + onInspectDone: () => { actions.setInspect(null) }, + }, { only: active.id })}
      ) diff --git a/packages/client/ui-conversation/src/client/skeleton/DetailsPanel.tsx b/packages/client/ui-conversation/src/client/skeleton/DetailsPanel.tsx index 9fc5a04ff6..fb0b69624e 100644 --- a/packages/client/ui-conversation/src/client/skeleton/DetailsPanel.tsx +++ b/packages/client/ui-conversation/src/client/skeleton/DetailsPanel.tsx @@ -12,7 +12,7 @@ import { shallowEqual } from '@deepseek-ai/dsh-client-runtime/client' import type { ConversationSnapshot, RunningToolCall, ToolResultNode } from '@deepseek-ai/dsh-client-runtime/client' import type { DetailsSlotProps } from '../contract/slots.ts' import { terminalCardModel } from '../contract/terminal-card-model.ts' -import type { ToolCallBlock } from '../contract/tool-call-model.ts' +import { resultText, type ToolCallBlock } from '../contract/tool-call-model.ts' import css from './DetailsPanel.module.css' /** Full props composed by reference from the contract (automatic shares & injected share). */ @@ -153,20 +153,7 @@ function OutputBody({ material, cwd }: { material: CallMaterial; cwd: string | u const result = material.block return (
      -      {renderResult(result)}
      +      {resultText(result)}
           
      ) } - -/** Flatten result content blocks to display text (text blocks verbatim, others as JSON). */ -function renderResult(node: ToolResultNode): string { - const parts: string[] = [] - for (const block of node.content) { - if (block.type === 'text') parts.push(block.text) - else parts.push(JSON.stringify(block, null, 2)) - } - if (parts.length === 0 && node.error !== undefined) { - parts.push(`${node.error.name}: ${node.error.code}`) - } - return parts.join('\n') -} diff --git a/packages/client/ui-conversation/src/client/stores.ts b/packages/client/ui-conversation/src/client/stores.ts index 4c27a87ed8..8a1cd6f068 100644 --- a/packages/client/ui-conversation/src/client/stores.ts +++ b/packages/client/ui-conversation/src/client/stores.ts @@ -3,7 +3,7 @@ * The plugin creates its handle at apply time so identity follows the fiber. */ import { defineStore, type EngineStoreHandle } from '@deepseek-ai/dsh-client-runtime/client' -import type { ChatStoreState, SelectionTarget } from './contract/views.ts' +import type { CallId, ChatStoreState, SelectionTarget } from './contract/views.ts' /** Declared action shape used to give the exported factory a stable return type. */ type ChatActions = { @@ -12,6 +12,7 @@ type ChatActions = { clearDraft: (draft: ChatStoreState) => void restoreDraft: (draft: ChatStoreState, text: string) => void setView: (draft: ChatStoreState, view: string) => void + setInspect: (draft: ChatStoreState, target: { callId: CallId } | null) => void } /** @@ -20,7 +21,7 @@ type ChatActions = { */ export function createChatStore(): EngineStoreHandle { return defineStore({ - init: (): ChatStoreState => ({ selection: null, draft: '', view: null }), + init: (): ChatStoreState => ({ selection: null, draft: '', view: null, inspect: null }), persist: 'dsh.conversation.chat', actions: { select: (d, target: SelectionTarget | null) => { d.selection = target }, @@ -30,6 +31,7 @@ export function createChatStore(): EngineStoreHandle { if (d.draft === '') d.draft = text }, setView: (d, view: string) => { d.view = view }, + setInspect: (d, target: { callId: CallId } | null) => { d.inspect = target }, }, }) } diff --git a/packages/client/ui-conversation/src/client/toolviews/ask-question-row.tsx b/packages/client/ui-conversation/src/client/toolviews/ask-question-row.tsx index 97d24088cd..946151cee2 100644 --- a/packages/client/ui-conversation/src/client/toolviews/ask-question-row.tsx +++ b/packages/client/ui-conversation/src/client/toolviews/ask-question-row.tsx @@ -1,7 +1,7 @@ // ask_user_question toolview: question-flavored summary row replacing the // generic "Tool call" card, registered into the keyed // 'conversation.chat.toolview' hole like todo-row. The row composes ToolRow -// (chrome, running sweep, leading expansion) and swaps in the interaction +// (chrome, running sweep, whole-row expand) and swaps in the interaction // outcome — `waiting` while pending, answered-count once settled, `cancelled` // when the user dismissed the whole set — because the questions themselves // render in the composer takeover. @@ -37,8 +37,9 @@ function answeredSummary(text: string): string | null { return `${answered}/${answers.length} answered` } -/** One-line question-interaction row (leading toggle expands the raw args). */ -export function AskQuestionRow({ toolName, block }: ToolRowProps) { +/** One-line question-interaction row (the whole row toggles the call's + * Input/Output sections, ToolRow's unified expand). */ +export function AskQuestionRow({ toolName, block, inspect }: ToolRowProps) { const model = toolRowModel(toolName, block) // Composer verdicts settle the call as specific UserInteractionErrors // (apiproxy ask_user_question handler): 'ASK_CANCELLED' is the user's own @@ -68,7 +69,9 @@ export function AskQuestionRow({ toolName, block }: ToolRowProps) { title="Ask question" summary={summary} body={model.body} + output={model.output} state={state} + inspect={inspect} /> ) } diff --git a/packages/client/ui-conversation/src/client/toolviews/bash-sample.module.css b/packages/client/ui-conversation/src/client/toolviews/bash-sample.module.css index e9ee5286dc..fa607a0880 100644 --- a/packages/client/ui-conversation/src/client/toolviews/bash-sample.module.css +++ b/packages/client/ui-conversation/src/client/toolviews/bash-sample.module.css @@ -1,5 +1,5 @@ /* Bash toolview: same geometry/tokens as ToolRow (figma Bash · description), - plus the terminal card the row stacks under its summary line. */ + plus the expand-gated terminal card under the summary line. */ /* Summary line over the terminal card; the summary row keeps its own 24px height, so the card is a column around it rather than a change to it. */ @@ -8,10 +8,23 @@ flex-direction: column; } -/* Row indentation matches ToolRow's expanded bodies (16px leading + 6px gap), - and replaces the primitive's standalone vertical margin with the flow's. */ +/* Expanded terminal card, matching ToolRow's terminalBody: 4px indent, l1 + hairline, and the max-height scroll on the card's own OUTPUT (banner stays + pinned; 224px = the 260px card cap minus the ~36px banner); the margin + replaces the primitive's standalone vertical margin with the flow's. */ .terminal { - margin: 4px 0 4px 22px; + --dsl-terminal-font: var(--dsw-font-markdown-code-block-small); + --dsl-terminal-line-height: 18px; + --dsl-terminal-output-max-height: 224px; + margin: 4px 0 4px 4px; + border: 1px solid var(--dsw-alias-border-l1); +} + +/* ToolRow's unified expand interaction, replicated per the registrant + posture: pointer on the expandable row (the icon→chevron hover preview is + the affordance, no row fill). */ +.root[data-expandable] { + cursor: pointer; } .root { @@ -47,6 +60,7 @@ } .leading { + position: relative; /* .chevronHover overlay anchor */ flex: none; width: 16px; height: 16px; @@ -57,6 +71,34 @@ color: var(--dsw-alias-label-tertiary); } +.chevron { + color: var(--dsw-alias-label-secondary); +} + +/* Hover preview on the expandable row: the idle icon crossfades (100ms) into + a down chevron before the row is opened — same overlay as ToolRow. */ +.iconIdle { + display: inline-flex; + opacity: 1; + transition: opacity 100ms ease; +} + +.chevronHover { + position: absolute; + inset: 0; + margin: auto; + opacity: 0; + transition: opacity 100ms ease; +} + +.root:hover .iconIdle { + opacity: 0; +} + +.root:hover .chevronHover { + opacity: 1; +} + .scopeBadge { flex: none; margin-right: 8px; @@ -95,6 +137,52 @@ color: var(--dsw-alias-label-tertiary); } +/* Error row's collapsed summary: the failure's first line in the error color. */ +.errorSummary { + color: var(--dsw-alias-state-error-primary); +} + +/* Hover-revealed Inspect pill under the expanded terminal's bottom-left — + ToolRow's .bodyWrap/.inspectButton treatment, replicated per the registrant + posture: real flow (it reserves its line), revealed by hovering anywhere on + the tool call — title row included — or by keyboard focus. */ +.bodyWrap { + display: flex; + flex-direction: column; +} + +.inspectButton { + display: inline-flex; + align-self: flex-start; + align-items: center; + gap: 4px; + margin: 4px 0 2px 4px; + padding: 2px 8px; + border: 1px solid var(--dsw-alias-border-l2); + border-radius: 999px; + /* Base background, not bg-overlay: the overlay token reads too heavy. */ + background: var(--dsw-alias-bg-base); + color: var(--dsw-alias-label-secondary); + font-size: 11px; + line-height: 16px; + cursor: pointer; + opacity: 0; + transition: opacity 100ms ease; +} + +.card:hover .inspectButton, +.inspectButton:focus-visible { + opacity: 1; +} + +/* Solid hover fill: the pill floats over terminal output, so a translucent + hover token would let the text underneath bleed through. */ +.inspectButton:hover { + background: var(--dsw-alias-interactive-bg-hover-solid); + color: var(--dsw-alias-label-primary); +} + + .visuallyHidden { position: absolute; width: 1px; diff --git a/packages/client/ui-conversation/src/client/toolviews/bash-sample.tsx b/packages/client/ui-conversation/src/client/toolviews/bash-sample.tsx index c9385cab04..1f979e899c 100644 --- a/packages/client/ui-conversation/src/client/toolviews/bash-sample.tsx +++ b/packages/client/ui-conversation/src/client/toolviews/bash-sample.tsx @@ -4,19 +4,23 @@ // Child sessions keep a scoped badge so session-dimension differentiation stays // observable inside the component (no parallel registry). // -// A bash call declares the terminal render intent, so this row also renders -// the command's own output through TerminalBlock. This row has no expand -// control and is not a details-panel target either (tool rows stopped being -// one), so its terminal body is resident rather than expand-gated as in -// ToolRow, and the card's own copy and expand controls are the row's only -// interactions. CHAT_TERMINAL_MAX_LINES is passed as `maxLines` — the chat -// flow's tighter cap over the block's own default of 16 — and the block's -// internal expander keeps a long output from taking over the message flow. +// A bash call declares the terminal render intent, so this row renders the +// command's own output through TerminalBlock — expand-gated exactly like +// ToolRow's unified interaction: collapsed by default, the whole summary row +// is the toggle (click / Enter / Space, icon→chevron hover preview; the +// summary stays inline while open), +// and the expanded card max-height-scrolls inside its own surface with the +// full output (maxLines Infinity — no middle collapse). An error row's +// collapsed summary is the failure's first line in the error color. +import { useState, type KeyboardEvent } from 'react' import type { Context } from 'cordis' -import { IconApiOutline14, StateDot, TerminalBlock } from '@deepseek-ai/dsh-client-ui-primitives' +import clsx from 'clsx' +import { + IconApiOutline14, IconChevronDownOutline14, StateDot, TerminalBlock, +} from '@deepseek-ai/dsh-client-ui-primitives' import type { ToolRowProps } from '../contract/slots.ts' -import { CHAT_TERMINAL_MAX_LINES, terminalCardModel } from '../contract/terminal-card-model.ts' +import { terminalCardModel, terminalFailed } from '../contract/terminal-card-model.ts' import { toolRowModel, type ToolRowState } from '../contract/tool-call-model.ts' import css from './bash-sample.module.css' @@ -40,38 +44,84 @@ function stateStatus(state: ToolRowState): string | null { } /** - * Bash row: icon + Bash · {description} in the shared ToolRow chrome, with the - * command's terminal card resident below it. The summary row is not a - * details-panel control (tool rows stopped being one), so the card's copy and - * expand controls are the row's only interactions. + * Bash row: icon + Bash · {description} in the shared ToolRow chrome, the + * whole row toggling the command's terminal card (ToolRow's unified + * expand interaction, replicated locally per the registrant posture). */ -export function BashRow({ toolName, block, sessionId, useSessions }: ToolRowProps) { +export function BashRow({ toolName, block, sessionId, useSessions, inspect }: ToolRowProps) { const model = toolRowModel(toolName, block) // Session workspace root: the terminal view's cwd resolves against it (an // omitted workdir IS the workspace), which the pure presenter cannot do. const cwd = useSessions(list => list.byId[sessionId]?.cwd) const terminal = terminalCardModel(block, cwd) + // A failing exit status is the terminal card's own error signal (the call + // itself settles isError:false), surfaced as the row's red state dot. + const state = model.state === 'ok' && terminal !== null && terminalFailed(terminal) + ? 'error' + : model.state const isChild = useSessions(list => list.byId[sessionId]?.parentId !== undefined) - const status = stateStatus(model.state) + const status = stateStatus(state) + const [expanded, setExpanded] = useState(false) + const expandable = terminal !== null + const open = expanded && expandable + const failureLine = model.state === 'error' ? model.errorSummary : null + const toggleExpand = () => { + setExpanded(v => !v) + } + const toggleFromKeyboard = (event: KeyboardEvent) => { + if (!expandable || (event.key !== 'Enter' && event.key !== ' ')) return + event.preventDefault() + toggleExpand() + } + const leading = open + ? + : expandable + ? ( + <> + {leadingFor(state)} + + + ) + : leadingFor(state) return (
      - {leadingFor(model.state)} + {leading} {status !== null && {status}} {isChild && scoped} {model.title} {/* The terminal presenter's description is the contractual - above-card summary; it outranks the args-derived one. */} - {terminal?.description ?? model.summary} + above-card summary; a failure's first line outranks both. */} + + {failureLine ?? terminal?.description ?? model.summary} +
      - {terminal !== null && ( - + {terminal !== null && open && ( + /* Same hover-Inspect posture as ToolRow's expanded body, replicated + locally per the registrant posture. */ +
      + + {inspect !== undefined && ( + + )} +
      )}
      ) diff --git a/packages/client/ui-conversation/src/client/toolviews/todo-row.tsx b/packages/client/ui-conversation/src/client/toolviews/todo-row.tsx index 8a1f20e3e5..22b51b1890 100644 --- a/packages/client/ui-conversation/src/client/toolviews/todo-row.tsx +++ b/packages/client/ui-conversation/src/client/toolviews/todo-row.tsx @@ -1,10 +1,10 @@ // todo_write toolview: plan-flavored summary row replacing the generic // "Tool call" card, registered into the keyed 'conversation.chat.toolview' // hole like the bash sample (a product registration, not a sample). The row -// composes ToolRow (chrome, running sweep, leading expansion) and swaps in a +// composes ToolRow (chrome, running sweep, whole-row expand) and swaps in a // summary of the written list (counts + active item) from the call args; the // durable list itself renders in the TodoPanel above the composer, so the -// row stays one line. +// row stays one line until expanded. import { IconChecklistOutline14 } from '@deepseek-ai/dsh-client-ui-primitives' import type { Context } from 'cordis' @@ -40,10 +40,11 @@ function summarize(argsRaw: string): string | null { : head } -/** One-line plan update row (leading toggle expands the raw args). Non-ok - * execution states keep the shared row's dot semantics — a cancelled call - * wrote no todo/write, so it must not read as a completed update. */ -export function TodoRow({ toolName, block }: ToolRowProps) { +/** One-line plan update row (the whole row toggles the call's Input/Output + * sections, ToolRow's unified expand). Non-ok execution states keep the + * shared row's dot semantics — a cancelled call wrote no todo/write, so it + * must not read as a completed update. */ +export function TodoRow({ toolName, block, inspect }: ToolRowProps) { const model = toolRowModel(toolName, block) const argsRaw = ('kind' in block ? block.call?.argsRaw : block.argsRaw) ?? '' const summary = summarize(argsRaw) ?? model.summary @@ -55,7 +56,10 @@ export function TodoRow({ toolName, block }: ToolRowProps) { title="更新任务清单" summary={summary} body={model.body} + output={model.output} + errorSummary={model.errorSummary} state={model.state} + inspect={inspect} /> ) } diff --git a/packages/client/ui-conversation/tests/assembly-surfaces.spec.tsx b/packages/client/ui-conversation/tests/assembly-surfaces.spec.tsx index 2d143764bb..7201b89bc3 100644 --- a/packages/client/ui-conversation/tests/assembly-surfaces.spec.tsx +++ b/packages/client/ui-conversation/tests/assembly-surfaces.spec.tsx @@ -134,7 +134,7 @@ describe('todo_write assembly (product registrations, no outlet twins)', () => { }) describe('terminal card assembly', () => { - it('the keyed bash row carries a resident terminal card; the fallback row reaches one through expand', async () => { + it('both the keyed bash row and the fallback row reach the terminal card through the whole-row expand', async () => { const runtime = await bench([ bashResult(3, 'c-keyed'), // An unregistered tool with terminal views: GenericToolCard fallback. @@ -142,15 +142,20 @@ describe('terminal card assembly', () => { ]) const view = runtime.renderRoot() - // Keyed BashRow renders the card residently (no expand gesture). - const keyed = view.container.querySelector('[data-sample="bash-global"]')?.parentElement - expect(keyed?.querySelector('[data-terminal]')).not.toBeNull() + // Keyed BashRow: collapsed by default, the whole summary row is the toggle. + const keyedRow = view.container.querySelector('[data-sample="bash-global"]') + const keyed = keyedRow?.parentElement + expect(keyed?.querySelector('[data-terminal]')).toBeNull() + fireEvent.click(keyedRow!) + await waitFor(() => { + expect(keyed!.querySelector('[data-terminal]')).not.toBeNull() + }) - // Fallback row: card appears only after its expand control. + // Fallback row: same unified expand interaction. const fallback = view.container.querySelector('[data-tool="fx-bash"]') expect(fallback).not.toBeNull() expect(fallback!.querySelector('[data-terminal]')).toBeNull() - fireEvent.click(fallback!.querySelector('button[aria-expanded]')!) + fireEvent.click(fallback!.querySelector('[data-expandable]')!) await waitFor(() => { expect(fallback!.querySelector('[data-terminal]')).not.toBeNull() }) diff --git a/packages/client/ui-conversation/tests/chat-branch-tails.spec.tsx b/packages/client/ui-conversation/tests/chat-branch-tails.spec.tsx index fc5a94af61..9dc75715c4 100644 --- a/packages/client/ui-conversation/tests/chat-branch-tails.spec.tsx +++ b/packages/client/ui-conversation/tests/chat-branch-tails.spec.tsx @@ -107,11 +107,32 @@ describe('MessageItem arms', () => { expect(view.queryByRole('button', { name: '复制' })).toBeNull() }) - it('context and unknown nodes render their JSON rows', () => { - const ctxView = render( + it('context nodes render a title-only tool row that expands the injected text without labels', () => { + const view = render( + , + ) + const row = view.getByRole('button', { name: /上下文注入/ }) + // Title-only collapsed row: the injected text stays behind the expand. + expect(view.queryByText(/memory line one/)).toBeNull() + fireEvent.click(row) + expect(view.getByText(/second line/)).toBeTruthy() + // Label-less card: the injection is ambient context, not a call's IN payload. + expect(view.queryByText('IN')).toBeNull() + }) + + it('a context node without pure text expands to the full JSON payload', () => { + const view = render( , ) - expect(ctxView.getByText(/上下文注入/)).toBeTruthy() + fireEvent.click(view.getByRole('button', { name: /上下文注入/ })) + expect(view.getByText(/"source": null/)).toBeTruthy() + }) + + it('unknown nodes render their JSON rows', () => { const unknownView = render( , ) diff --git a/packages/client/ui-conversation/tests/chat-code-subcalls.spec.tsx b/packages/client/ui-conversation/tests/chat-code-subcalls.spec.tsx index bd1ac63f1f..3f04f9ad70 100644 --- a/packages/client/ui-conversation/tests/chat-code-subcalls.spec.tsx +++ b/packages/client/ui-conversation/tests/chat-code-subcalls.spec.tsx @@ -203,7 +203,7 @@ describe('run_code sub-calls through the real chat machinery', () => { expect(nest.querySelector('[data-tool="cordis_unmount"]')?.textContent) .toContain('Unmount temporary Plugindyn-2') - fireEvent.click(mounted!.querySelector('button[aria-expanded]')!) + fireEvent.click(mounted!.querySelector('[data-expandable]')!) expect(mounted!.querySelector('pre.shiki')?.textContent).toBe(code) }) @@ -211,8 +211,8 @@ describe('run_code sub-calls through the real chat machinery', () => { const parent = 'call-64' const b = await bench(snapshotWith([codeResult(10, parent)], new Map())) const view = mountApp(b.slots) - // The code row is expandable via its leading control (body = the program). - const toggle = view.container.querySelector('[data-variant="code"] button[aria-expanded]') + // The code row is expandable via the whole summary row (body = the program). + const toggle = view.container.querySelector('[data-variant="code"] [data-expandable]') expect(toggle).not.toBeNull() fireEvent.click(toggle!) // Shiki splits the program into token spans inside one
      :
      diff --git a/packages/client/ui-conversation/tests/chat-store.spec.ts b/packages/client/ui-conversation/tests/chat-store.spec.ts
      index 50ec5542ef..17d90cfbde 100644
      --- a/packages/client/ui-conversation/tests/chat-store.spec.ts
      +++ b/packages/client/ui-conversation/tests/chat-store.spec.ts
      @@ -12,7 +12,7 @@ beforeEach(() => {
       describe('createChatStore', () => {
         it('init shape: empty selection/draft/view', () => {
           const store = createChatStore().create()
      -    expect(store.store.getSnapshot()).toEqual({ selection: null, draft: '', view: null })
      +    expect(store.store.getSnapshot()).toEqual({ selection: null, draft: '', view: null, inspect: null })
         })
       
         it('actions cover the declared write set', () => {
      @@ -30,6 +30,11 @@ describe('createChatStore', () => {
       
           store.actions.setView('chat')
           expect(store.store.getSnapshot().view).toBe('chat')
      +
      +    store.actions.setInspect({ callId: 'c1' })
      +    expect(store.store.getSnapshot().inspect).toEqual({ callId: 'c1' })
      +    store.actions.setInspect(null)
      +    expect(store.store.getSnapshot().inspect).toBeNull()
         })
       
         it('restoreDraft only fills an empty draft (optimistic-send rollback contract)', () => {
      diff --git a/packages/client/ui-conversation/tests/chat-tool-row.spec.tsx b/packages/client/ui-conversation/tests/chat-tool-row.spec.tsx
      index 546b4a18e8..e4e5af28d0 100644
      --- a/packages/client/ui-conversation/tests/chat-tool-row.spec.tsx
      +++ b/packages/client/ui-conversation/tests/chat-tool-row.spec.tsx
      @@ -4,7 +4,7 @@ import { cleanup, fireEvent, render } from '@testing-library/react'
       
       afterEach(cleanup)
       import type { RunningToolCall, ToolResultNode } from '@deepseek-ai/dsh-client-runtime/client'
      -import { classifyTool, resolveToolPath, toolRowModel } from '../src/client/contract/tool-call-model.ts'
      +import { classifyTool, resolveToolPath, resultText, toolRowModel } from '../src/client/contract/tool-call-model.ts'
       import { AssistantMarkdown } from '../src/client/chat/AssistantMarkdown.tsx'
       import { ToolRow } from '../src/client/chat/ToolRow.tsx'
       import { GenericToolCard } from '../src/client/chat/GenericToolCard.tsx'
      @@ -102,6 +102,29 @@ describe('tool-call-model', () => {
             .toBe('{\n  "code": ""\n}')
         })
       
      +  it('resultText flattens text blocks verbatim, other shapes as JSON, empty error content to name: code', () => {
      +    expect(resultText(result({ content: [{ type: 'text', text: 'a\nb' }] }))).toBe('a\nb')
      +    expect(resultText(result({ content: [{ type: 'text', text: 'a' }, { type: 'image', data: 'x' } as never] })))
      +      .toBe(`a\n${JSON.stringify({ type: 'image', data: 'x' }, null, 2)}`)
      +    expect(resultText(result({ content: [], isError: true, error: { name: 'ToolError', code: 'denied' } })))
      +      .toBe('ToolError: denied')
      +    expect(resultText(result({ content: [] }))).toBe('')
      +  })
      +
      +  it('derives output from the settled result and null while running or blank', () => {
      +    expect(toolRowModel('bash', result({ content: [{ type: 'text', text: 'out' }] })).output).toBe('out')
      +    expect(toolRowModel('bash', running()).output).toBeNull()
      +    expect(toolRowModel('bash', result({ content: [] })).output).toBeNull()
      +  })
      +
      +  it('derives errorSummary as the first output line on error rows only', () => {
      +    const failed = result({ content: [{ type: 'text', text: 'boom\ndetail' }], isError: true })
      +    expect(toolRowModel('bash', failed).errorSummary).toBe('boom')
      +    expect(toolRowModel('bash', result({ content: [{ type: 'text', text: 'boom' }] })).errorSummary).toBeNull()
      +    expect(toolRowModel('bash', result({ content: [], isError: true })).errorSummary).toBeNull()
      +    expect(toolRowModel('bash', running()).errorSummary).toBeNull()
      +  })
      +
         it('gives Cordis lifecycle tools action titles over their generic variants', () => {
           expect(toolRowModel('cordis_inspect', running({
             name: 'cordis_inspect',
      @@ -144,14 +167,15 @@ describe('ToolRow', () => {
           expect(view.container.querySelector('[aria-expanded]')?.getAttribute('aria-expanded')).toBe('false')
         })
       
      -  it('expanding swaps the leading slot to a chevron, hides summary, shows body', () => {
      +  it('row click expands: chevron leading, summary kept inline, body in the scrolling card', () => {
           const view = render()
      -    fireEvent.click(view.container.querySelector('button')!)
      +    fireEvent.click(view.getByRole('button'))
           expect(view.queryByTestId('tool-icon')).toBeNull()
           expect(view.container.querySelector('svg')).not.toBeNull()
      -    expect(view.queryByText('List files')).toBeNull()
      +    expect(view.getByText('List files')).toBeTruthy()
           expect(view.getByText(/"a": 1/)).toBeTruthy()
      -    fireEvent.click(view.container.querySelector('button')!)
      +    expect(view.container.querySelector('[class*="ioCard"]')).not.toBeNull()
      +    fireEvent.click(view.getByRole('button'))
           expect(view.queryByTestId('tool-icon')).not.toBeNull()
           expect(view.getByText('List files')).toBeTruthy()
         })
      @@ -162,16 +186,20 @@ describe('ToolRow', () => {
           expect(runningView.container.querySelector('[data-state="running"]')).not.toBeNull()
           const errorView = render()
           expect(errorView.container.querySelector('[data-testid="tool-icon"]')).toBeNull()
      +    // The dot rides the idle slot, so an expandable error row keeps the
      +    // icon→chevron hover preview instead of losing it with the icon.
      +    expect(errorView.container.querySelector('[class*="chevronHover"]')).not.toBeNull()
         })
       
      -  it('non-expandable rows render a passive leading slot', () => {
      +  it('non-expandable rows render a passive leading slot and no row button', () => {
           const view = render()
      -    expect(view.container.querySelector('button')).toBeNull()
      +    expect(view.queryByRole('button')).toBeNull()
      +    expect(view.container.querySelector('[aria-expanded]')).toBeNull()
           expect(view.queryByTestId('tool-icon')).not.toBeNull()
         })
       
      -  it('an expandOnRowClick row toggles from Enter and Space, ignoring other keys', () => {
      -    const view = render()
      +  it('the row toggles from Enter and Space, ignoring other keys', () => {
      +    const view = render()
           const row = view.getByRole('button')
           fireEvent.keyDown(row, { key: 'Tab' })
           expect(row.getAttribute('aria-expanded')).toBe('false')
      @@ -181,32 +209,31 @@ describe('ToolRow', () => {
           expect(row.getAttribute('aria-expanded')).toBe('false')
         })
       
      -  it('a non-expandable expandOnRowClick row exposes no row button', () => {
      -    const view = render()
      -    expect(view.queryByRole('button')).toBeNull()
      -  })
      -
      -  it('file-path summary opens through onOpenFile; the leading slot is not an expand control', () => {
      +  it('file rows expand from the row while the path link opens without toggling', () => {
           const open = vi.fn()
           const view = render(
             ,
           )
      +    const row = view.getByRole('button', { name: /Read/ })
      +    // Path click opens the file and leaves the row collapsed.
           fireEvent.click(view.getByText('src/a.ts'))
           expect(open).toHaveBeenCalledWith('src/a.ts')
      -    // Only the path link is a button — no args-expand affordance on file rows.
      -    expect(view.container.querySelectorAll('button')).toHaveLength(1)
      -    expect(view.container.querySelector('[aria-expanded]')).toBeNull()
      -    expect(view.queryByText(/"a": 1/)).toBeNull()
      +    expect(row.getAttribute('aria-expanded')).toBe('false')
      +    // Row click (outside the link) expands the args body.
      +    fireEvent.click(row)
      +    expect(row.getAttribute('aria-expanded')).toBe('true')
      +    expect(view.getByText(/"a": 1/)).toBeTruthy()
         })
       
      -  it('a single-file path disables expand even when onOpenFile is absent', () => {
      +  it('a file path without onOpenFile renders a plain summary on an expandable row', () => {
           const view = render(
             ,
           )
           expect(view.container.querySelector('button')).toBeNull()
      -    expect(view.container.querySelector('[aria-expanded]')).toBeNull()
      -    fireEvent.click(view.getByText('作文.md'))
      -    expect(view.queryByText(/"a": 1/)).toBeNull()
      +    const row = view.getByRole('button')
      +    fireEvent.click(row)
      +    expect(row.getAttribute('aria-expanded')).toBe('true')
      +    expect(view.getByText(/"a": 1/)).toBeTruthy()
         })
       
         it('non-file rows do not open anything when the summary is clicked', () => {
      @@ -215,6 +242,75 @@ describe('ToolRow', () => {
           fireEvent.click(view.getByText('List files'))
           expect(open).not.toHaveBeenCalled()
         })
      +
      +  it('an error row shows the failure first line in the collapsed summary and the full text expanded', () => {
      +    const view = render(
      +      ,
      +    )
      +    expect(view.getByText('boom')).toBeTruthy()
      +    expect(view.queryByText('List files')).toBeNull()
      +    fireEvent.click(view.getByRole('button'))
      +    expect(view.getByText(/detail/)).toBeTruthy()
      +    expect(view.container.querySelector('[data-error]')).not.toBeNull()
      +  })
      +
      +  it('an error row without an error summary keeps the args summary', () => {
      +    const view = render()
      +    expect(view.getByText('List files')).toBeTruthy()
      +  })
      +
      +  it('an error file row drops the open-file link (the summary is failure prose, not the path)', () => {
      +    const open = vi.fn()
      +    const view = render(
      +      ,
      +    )
      +    fireEvent.click(view.getByText('cannot overwrite'))
      +    expect(open).not.toHaveBeenCalled()
      +    // The failure line renders as plain text, not the underlined link button.
      +    expect(view.container.querySelector('[class*="fileLink"]')).toBeNull()
      +  })
      +
      +  it('the expanded body carries a hover Inspect pill that fires the callback', () => {
      +    const inspect = vi.fn()
      +    const view = render()
      +    // Collapsed: no pill.
      +    expect(view.queryByText('Inspect')).toBeNull()
      +    fireEvent.click(view.getByRole('button', { name: /Bash/ }))
      +    const pill = view.getByText('Inspect')
      +    fireEvent.click(pill)
      +    expect(inspect).toHaveBeenCalledTimes(1)
      +    // The pill click must not collapse the row (body is a .row sibling).
      +    expect(view.getByRole('button', { name: /Bash/ }).getAttribute('aria-expanded')).toBe('true')
      +  })
      +
      +  it('no inspect callback, no pill', () => {
      +    const view = render()
      +    fireEvent.click(view.getByRole('button'))
      +    expect(view.queryByText('Inspect')).toBeNull()
      +  })
      +
      +  it('the expanded card gutter-labels each section it carries (IN / OUT)', () => {
      +    const both = render()
      +    fireEvent.click(both.getByRole('button'))
      +    expect(both.getByText('IN')).toBeTruthy()
      +    expect(both.getByText('OUT')).toBeTruthy()
      +    expect(both.getByText('result text')).toBeTruthy()
      +    cleanup()
      +    const inputOnly = render()
      +    fireEvent.click(inputOnly.getByRole('button'))
      +    expect(inputOnly.getByText('IN')).toBeTruthy()
      +    expect(inputOnly.queryByText('OUT')).toBeNull()
      +    cleanup()
      +    const outputOnly = render()
      +    fireEvent.click(outputOnly.getByRole('button'))
      +    expect(outputOnly.queryByText('IN')).toBeNull()
      +    expect(outputOnly.getByText('OUT')).toBeTruthy()
      +    expect(outputOnly.getByText('only out')).toBeTruthy()
      +  })
       })
       
       describe('ThinkRow', () => {
      @@ -234,6 +330,21 @@ describe('ThinkRow', () => {
           fireEvent.click(view.getByText('Think'))
           expect(row.getAttribute('aria-expanded')).toBe('false')
         })
      +
      +  it('expanded Think drops the inline summary and renders plain prose, no IN card', () => {
      +    const view = render(
      +      ,
      +    )
      +    fireEvent.click(view.getByText('Think'))
      +    // The summary (first line) is gone from the row; only the body carries it.
      +    expect(view.getAllByText(/Inspect the session/)).toHaveLength(1)
      +    expect(view.queryByText('IN')).toBeNull()
      +    expect(view.container.querySelector('[class*="ioCard"]')).toBeNull()
      +    expect(view.container.querySelector('[class*="thinkBody"]')).not.toBeNull()
      +  })
       })
       
       describe('GenericToolCard', () => {
      @@ -283,6 +394,14 @@ describe('GenericToolCard', () => {
           expect(view.container.querySelector('svg')).not.toBeNull()
         })
       
      +  it('passes the owner inspect callback through to the expanded row pill', () => {
      +    const inspect = vi.fn()
      +    const view = render()
      +    fireEvent.click(view.getByRole('button', { name: /Bash/ }))
      +    fireEvent.click(view.getByText('Inspect'))
      +    expect(inspect).toHaveBeenCalledTimes(1)
      +  })
      +
         it('file-path summary click reaches openFile; bash summary does not', () => {
           const file = props('read', running({ name: 'read', argsRaw: '{"path":"src/x.ts"}' }))
           const fileView = render()
      diff --git a/packages/client/ui-conversation/tests/chat-toolview-slot.spec.tsx b/packages/client/ui-conversation/tests/chat-toolview-slot.spec.tsx
      index ccf940d430..2d1e4b25e5 100644
      --- a/packages/client/ui-conversation/tests/chat-toolview-slot.spec.tsx
      +++ b/packages/client/ui-conversation/tests/chat-toolview-slot.spec.tsx
      @@ -112,7 +112,7 @@ describe('keyed toolview hole through the real machinery', () => {
           expect(view.container.querySelector('[data-tool="cordis_unmount"]')?.textContent)
             .toContain('Unmount temporary Plugindyn-2')
       
      -    fireEvent.click(mounted!.querySelector('button[aria-expanded]')!)
      +    fireEvent.click(mounted!.querySelector('[data-expandable]')!)
           expect(mounted!.querySelector('pre.shiki')?.textContent).toBe(code)
           await b.runtime.dispose()
         })
      diff --git a/packages/client/ui-conversation/tests/chat-view.spec.tsx b/packages/client/ui-conversation/tests/chat-view.spec.tsx
      index c0cb4dcb78..1462b2f9c5 100644
      --- a/packages/client/ui-conversation/tests/chat-view.spec.tsx
      +++ b/packages/client/ui-conversation/tests/chat-view.spec.tsx
      @@ -94,6 +94,13 @@ function makeHarness(init?: Partial) {
         const openDetails = vi.fn<(t: SelectionTarget) => void>()
         const openFile = vi.fn<(path: string) => void>()
         const loadOlder = vi.fn()
      +  const inspectCall = vi.fn<(callId: string) => void>()
      +  // In-memory scroll memory matching the apply.ts per-session map contract.
      +  let savedScrollTop: number | null = null
      +  const chatScroll = {
      +    save: (top: number | null) => { savedScrollTop = top },
      +    read: () => savedScrollTop,
      +  }
         // Selection rides the REAL chat store (same construction path as
         // production; the view reads it through the PropsStore useStore share).
         // renderSlot stub renders the render-site fallback (an empty keyed ledger:
      @@ -120,9 +127,11 @@ function makeHarness(init?: Partial) {
           openDetails,
           openFile,
           loadOlder,
      +    inspectCall,
      +    chatScroll,
         }
         const setSelection = (next: SelectionTarget | null): void => { chat.actions.select(next) }
      -  return { set, ChatView, props, openDetails, openFile, loadOlder, setSelection }
      +  return { set, ChatView, props, openDetails, openFile, loadOlder, inspectCall, chatScroll, setSelection }
       }
       
       describe('chat-flow derivation', () => {
      @@ -194,6 +203,16 @@ describe('ChatView', () => {
           expect(view.getByText('run a')).toBeTruthy()
         })
       
      +  it('the expanded row Inspect pill hands the call id to inspectCall', () => {
      +    const h = makeHarness({
      +      nodes: [toolResult(3, 'a')],
      +    })
      +    const view = render()
      +    fireEvent.click(view.getByRole('button', { name: /Bash/ }))
      +    fireEvent.click(view.getByText('Inspect'))
      +    expect(h.inspectCall).toHaveBeenCalledWith('a')
      +  })
      +
         it('renders assistant Markdown across history, streaming, final, and interrupted states while user text stays literal', () => {
           const markdown = '# Rendered\n\n- **one**\n- `two`'
           const h = makeHarness({ nodes: [user(1, markdown), assistant(2, markdown)] })
      @@ -280,11 +299,11 @@ describe('ChatView', () => {
           expect(rowRenders).toBe(afterMount)
         })
       
      -  it('tool row expands to the args body via the leading slot toggle', () => {
      +  it('tool row expands to the args body via the whole-row toggle', () => {
           const h = makeHarness({ nodes: [toolResult(3, 'a')] })
           const view = render()
           expect(view.queryByText(/"command": "cmd-a"/)).toBeNull()
      -    fireEvent.click(view.container.querySelector('button[aria-expanded]')!)
      +    fireEvent.click(view.container.querySelector('[data-expandable]')!)
           expect(view.getByText(/"command": "cmd-a"/)).toBeTruthy()
         })
       
      @@ -407,6 +426,55 @@ describe('ChatView', () => {
           }
         })
       
      +  it('a remount restores the saved scroll position instead of re-jumping to the bottom', () => {
      +    const host = document.createElement('div')
      +    host.setAttribute('data-conversation-scroll', '')
      +    Object.defineProperty(host, 'scrollHeight', { value: 2000, writable: true, configurable: true })
      +    Object.defineProperty(host, 'clientHeight', { value: 500, writable: true, configurable: true })
      +    Object.defineProperty(host, 'scrollTop', { value: 0, writable: true, configurable: true })
      +    document.body.appendChild(host)
      +    try {
      +      const h = makeHarness({ nodes: [user(1, 'q'), assistant(2, 'a')] })
      +      // Fresh open (nothing saved): the bottom jump stands.
      +      const view = render(, { container: host })
      +      expect(host.scrollTop).toBe(2000)
      +      // Reader scrolls up; the position is recorded continuously.
      +      host.scrollTop = 100
      +      fireEvent.scroll(host)
      +      // View-tab switch away and back: the view unmounts, then remounts.
      +      view.rerender(
      ) + host.scrollTop = 0 + view.rerender() + expect(host.scrollTop).toBe(100) + // The restored position is above the floor: follow stays disarmed. + expect(view.getByLabelText('回到底部')).toBeTruthy() + } finally { + host.remove() + } + }) + + it('a remount while pinned to the bottom keeps the bottom jump', () => { + const host = document.createElement('div') + host.setAttribute('data-conversation-scroll', '') + Object.defineProperty(host, 'scrollHeight', { value: 2000, writable: true, configurable: true }) + Object.defineProperty(host, 'clientHeight', { value: 500, writable: true, configurable: true }) + Object.defineProperty(host, 'scrollTop', { value: 0, writable: true, configurable: true }) + document.body.appendChild(host) + try { + const h = makeHarness({ nodes: [user(1, 'q'), assistant(2, 'a')] }) + const view = render(, { container: host }) + // At the bottom: the scroll event records the pinned state (null). + fireEvent.scroll(host) + expect(h.chatScroll.read()).toBeNull() + view.rerender(
      ) + host.scrollTop = 0 + view.rerender() + expect(host.scrollTop).toBe(2000) + } finally { + host.remove() + } + }) + it('paging button loads older and shows its busy label', () => { const h = makeHarness({ nodes: [user(5, 'later')], hasMore: true }) const view = render() diff --git a/packages/client/ui-conversation/tests/selection-survival.spec.tsx b/packages/client/ui-conversation/tests/selection-survival.spec.tsx index 70162105a9..4559618a8a 100644 --- a/packages/client/ui-conversation/tests/selection-survival.spec.tsx +++ b/packages/client/ui-conversation/tests/selection-survival.spec.tsx @@ -103,7 +103,7 @@ describe('selection survives on the store seat', () => { // ...and a re-created same-id session starts from a FRESH instance. const reborn = storeFor(b, 'conversation.session', sid('s1')) expect(reborn).not.toBe(doomed) - expect(reborn.store.getSnapshot()).toEqual({ selection: null, draft: '', view: null }) + expect(reborn.store.getSnapshot()).toEqual({ selection: null, draft: '', view: null, inspect: null }) await b.runtime.dispose() }) }) diff --git a/packages/client/ui-conversation/tests/terminal-card.spec.tsx b/packages/client/ui-conversation/tests/terminal-card.spec.tsx index 968c1e4461..ef470162f6 100644 --- a/packages/client/ui-conversation/tests/terminal-card.spec.tsx +++ b/packages/client/ui-conversation/tests/terminal-card.spec.tsx @@ -13,7 +13,7 @@ import type { } from '@deepseek-ai/dsh-client-runtime/client' import type { ToolCallView, ToolResultView } from '@deepseek-ai/dsh-client-connection/client' import type { SelectionTarget, ToolRowOwnerProps, ToolRowProps } from '@deepseek-ai/dsh-client-ui-conversation/client' -import { CHAT_TERMINAL_MAX_LINES, terminalCardModel } from '../src/client/contract/terminal-card-model.ts' +import { terminalCardModel, terminalFailed } from '../src/client/contract/terminal-card-model.ts' import { createChatStore } from '../src/client/stores.ts' import { GenericToolCard } from '../src/client/chat/GenericToolCard.tsx' import { DetailsPanel } from '../src/client/skeleton/DetailsPanel.tsx' @@ -87,6 +87,19 @@ describe('terminalCardModel', () => { }))?.card.signal).toBe('SIGTERM') }) + it('flags a failing exit as terminalFailed; clean exits and running cards are not', () => { + // isError stays false on a failing command (the exit status is result + // data), so this predicate is the row's only failure signal. + expect(terminalFailed(terminalCardModel(settled({ + resultView: resultTerminal({ exitCode: 2 }), + }))!)).toBe(true) + expect(terminalFailed(terminalCardModel(settled({ + resultView: { card: 'terminal', output: '', signal: 'SIGTERM' }, + }))!)).toBe(true) + expect(terminalFailed(terminalCardModel(settled())!)).toBe(false) + expect(terminalFailed(terminalCardModel(running())!)).toBe(false) + }) + it('takes the result view\'s replacement title over the pending one', () => { // The presentation contract defines a result title as REPLACING the pending // title, so a tool that rewrites it at settle time must win here. @@ -221,36 +234,39 @@ describe('chat row terminal body', () => { callId: 'c1', toolName: 'bash', block, openFile: vi.fn(), }) - it('the expanded body is the command output, capped tighter than the panel', () => { - expect(CHAT_TERMINAL_MAX_LINES).toBeLessThan(16) + /** The whole summary row is the expand toggle (ToolRow's unified interaction). */ + const toggleRow = (view: { container: HTMLElement }) => { + fireEvent.click(view.container.querySelector('[data-expandable]')!) + } + + it('the expanded body is the command output inside the row scroll container', () => { const view = render() // Collapsed: the one-line summary row only, no output. expect(view.getByText('List files')).toBeTruthy() expect(view.queryByText(/a\.ts/)).toBeNull() - fireEvent.click(view.container.querySelector('button')!) + toggleRow(view) expect(view.getByText('a.ts b.ts', RAW)).toBeTruthy() expect(view.getByText('ls -la')).toBeTruthy() // The args JSON body the generic path would have shown is gone. expect(view.queryByText(/"command"/)).toBeNull() }) - it('the cap collapses a long output inside the row, expandable in place', () => { - const lines = Array.from({ length: CHAT_TERMINAL_MAX_LINES + 3 }, (_, i) => `line-${i}`) + it('a long output renders in full — the scroll container replaces the middle collapse', () => { + const lines = Array.from({ length: 20 }, (_, i) => `line-${i}`) const view = render() - fireEvent.click(view.container.querySelector('button')!) - expect(view.getByText('… 其余 3 行')).toBeTruthy() - expect(view.queryByText('line-5')).toBeNull() - fireEvent.click(view.getByRole('button', { name: '展开其余 3 行输出' })) + toggleRow(view) expect(view.getByText('line-5')).toBeTruthy() + expect(view.getByText('line-19')).toBeTruthy() + expect(view.queryByText(/其余/)).toBeNull() }) it('renders a multi-line command as one prompt row per line', () => { const view = render() - fireEvent.click(view.container.querySelector('button')!) + toggleRow(view) const rows = view.container.querySelectorAll('[class^="_promptLine_"]') expect([...rows].map(row => row.textContent)).toEqual(['$ls -la', '$echo done']) // Still one dot for the call, on the first row. @@ -275,14 +291,14 @@ describe('chat row terminal body', () => { callView: callTerminal({ description: 'Terminal 3' }), }))} />) expect(view.getByText('Terminal 3')).toBeTruthy() - fireEvent.click(view.container.querySelector('button')!) + toggleRow(view) expect(view.container.querySelector('[data-terminal]')).not.toBeNull() expect(view.getByText('Terminal 3')).toBeTruthy() }) it('a running terminal call expands to the prompt line with no output yet', () => { const view = render() - fireEvent.click(view.container.querySelector('button')!) + toggleRow(view) expect(view.getByText('ls -la')).toBeTruthy() expect(view.queryByText('复制')).toBeNull() // The card states its own run state: a running command reads as running @@ -294,7 +310,7 @@ describe('chat row terminal body', () => { const view = render() - fireEvent.click(view.container.querySelector('button')!) + toggleRow(view) expect(view.getByText(/"command"/)).toBeTruthy() }) @@ -303,9 +319,16 @@ describe('chat row terminal body', () => { const view = render() - fireEvent.click(view.container.querySelector('button')!) + toggleRow(view) expect(view.getByText('a.ts b.ts', RAW)).toBeTruthy() }) + + it('a failing exit status surfaces as the collapsed row\'s error state', () => { + const view = render() + expect(view.container.querySelector('[data-state]')?.getAttribute('data-state')).toBe('error') + }) }) describe('BashRow terminal card', () => { @@ -321,14 +344,17 @@ describe('BashRow terminal card', () => { sessionId: SID, useSessions: bindSnapshotSelector(list()), } as unknown as ToolRowProps) - it('renders the command output under the summary row, without an expand gesture', () => { + it('collapses to the summary row; the whole row toggles the command output', () => { const view = render() expect(view.getByText('List files')).toBeTruthy() + expect(view.queryByText(/a\.ts/)).toBeNull() + fireEvent.click(view.container.querySelector('[data-expandable]')!) expect(view.getByText('a.ts b.ts', RAW)).toBeTruthy() - // The card's controls are the row's only interactions: a bash row is not a - // path link and no longer a details-panel target, so nothing here navigates. - expect(view.container.querySelector('[data-clickable]')).toBeNull() expect(view.getByText('复制')).toBeTruthy() + // Collapse back in place: the summary row returns, the card unmounts. + fireEvent.click(view.container.querySelector('[data-expandable]')!) + expect(view.queryByText(/a\.ts/)).toBeNull() + expect(view.getByText('List files')).toBeTruthy() }) // The row's leading StateDot and the card's run-state dot describe the same @@ -337,13 +363,22 @@ describe('BashRow terminal card', () => { it('agrees with the summary row about the run state', () => { const runningView = render() expect(runningView.container.querySelector('[data-variant="bash"]')?.getAttribute('data-state')).toBe('running') + fireEvent.click(runningView.container.querySelector('[data-expandable]')!) expect(runStateOf(runningView.container)).toBe('ongoing') cleanup() const settledView = render() expect(settledView.container.querySelector('[data-variant="bash"]')?.getAttribute('data-state')).toBe('ok') + fireEvent.click(settledView.container.querySelector('[data-expandable]')!) expect(runStateOf(settledView.container)).toBe('done') }) + it('a failing exit status surfaces as the collapsed row\'s error state', () => { + const view = render() + expect(view.container.querySelector('[data-variant="bash"]')?.getAttribute('data-state')).toBe('error') + }) + it('shows the terminal presenter\'s description instead of the args summary', () => { // `terminal_send`-style presenters author a description the args do not // repeat; the contract puts it above the card, which is this row's summary. diff --git a/packages/client/ui-primitives/src/TerminalBlock.module.css b/packages/client/ui-primitives/src/TerminalBlock.module.css index 704ea0e808..0d3ff07d3b 100644 --- a/packages/client/ui-primitives/src/TerminalBlock.module.css +++ b/packages/client/ui-primitives/src/TerminalBlock.module.css @@ -7,6 +7,10 @@ .block { --dsl-terminal-radius: 12px; --dsl-terminal-line-height: 22px; + /* Rebindable by consumers (CodeBlock's --dsl-code-block-content-font + pattern): a surface wanting the smaller code size rebinds this together + with --dsl-terminal-line-height on its own container. */ + --dsl-terminal-font: var(--dsw-font-markdown-code-block); /* The card's own left inset, holding the run-state dot in a column of its own so it never competes with the commands for horizontal space. */ --dsl-terminal-gutter: 30px; @@ -22,26 +26,49 @@ color: var(--dsw-alias-label-primary); background: var(--dsw-alias-markdown-code-block); border-radius: var(--dsl-terminal-radius); + /* Clip the banner to the card's own radius: when a consumer adds a border, + the banner's equal corner radius no longer nests inside it and leaves a + notch at the corner. Nothing inside renders out of the box. */ + overflow: hidden; } -/* Top-aligned: the status pill and copy control stay on the first prompt row - however many command lines the card carries. */ +/* The status pill and copy control top-align to the FIRST prompt row (their + heights are capped to the prompt line, so on a multi-line command they sit + with the first command instead of floating mid-banner). */ .header { display: flex; align-items: flex-start; gap: 12px; - /* Pulled back across the card's gutter padding so the banner background and - its top-left radius span the FULL surface, then re-inset by the same amount - so the prompt text and the dot keep their positions. A plain block child - only reaches the content box, which left the gutter column painted in the - body color and drew the card's top-left corner in it — invisible in the - light theme, where banner and body share a token, and visible in the dark - one, where they do not. */ + /* Pulled back across the card's gutter padding so the banner spans the FULL + surface, then re-inset by the same amount so the prompt text and the dot + keep their positions. The banner shares the card's own surface (no banner + token): the l2 divider below is the section boundary. */ margin-left: calc(-1 * var(--dsl-terminal-gutter)); padding: 9px 14px 9px var(--dsl-terminal-gutter); - background: var(--dsw-alias-markdown-code-block-banner); border-top-left-radius: var(--dsl-terminal-radius); border-top-right-radius: var(--dsl-terminal-radius); + /* A long multi-line command scrolls inside the banner (same cap as the + IN/OUT card's sections) instead of pushing the output off screen. */ + max-height: 150px; + overflow-y: auto; +} + +/* Banner scrollbar floats off the card edge like the output's. */ +.header::-webkit-scrollbar-thumb { + border: 2px solid transparent; + background-clip: padding-box; + border-radius: 6px; +} + +.header::-webkit-scrollbar-track { + margin: 6px; +} + +/* Full-width l2 hairline between the command banner and the body — the same + divider the IN/OUT card draws between its sections. A running card is + banner-only, so it draws none. */ +.block:not([data-running]) .header { + border-bottom: 1px solid var(--dsw-alias-border-l2); } /* One row per command line. The prompt column is the only element allowed to @@ -51,7 +78,7 @@ flex-direction: column; min-width: 0; flex: 1; - font: var(--dsw-font-markdown-code-block); + font: var(--dsl-terminal-font); } .promptLine { @@ -100,27 +127,59 @@ white-space: pre; } +/* Capped to the prompt's line height (Pill's own 24px height would exceed a + smaller-font prompt row and stretch the banner). Sticky against the + banner's own scroll so the pill and the copy control stay in reach while a + long command scrolls underneath. */ .status { flex: none; + position: sticky; + top: 0; + height: var(--dsl-terminal-line-height); color: var(--dsw-alias-state-error-primary); } .copyButton { flex: none; - background-color: transparent; + position: sticky; + top: 0; + /* Card surface, not transparent: the control is sticky over the banner's + own scroll, so scrolled command text must not bleed through it. */ + background-color: var(--dsw-alias-markdown-code-block); border: none; padding: 0; margin: 0; color: var(--dsw-alias-label-secondary); cursor: pointer; font: var(--dsw-font-xs-13); + line-height: var(--dsl-terminal-line-height); } +/* Vertical scrolling lives on the OUTPUT, not the card root: a root scroller + would run its scrollbar over the banner (and the copy control), while here + the banner stays pinned and the bar sits inside the output's right padding. + Unset, the max-height is none and the auto overflow never engages. */ .output { + max-height: var(--dsl-terminal-output-max-height, none); padding: 12px 14px 12px 0; - font: var(--dsw-font-markdown-code-block); + font: var(--dsl-terminal-font); overflow-x: auto; - overflow-y: hidden; + overflow-y: auto; +} + +/* Both output scrollbars (vertical cap, horizontal pre overflow) float 2px + off the card edge: a transparent border clips the thumb inward so it never + hugs the rounded corner. */ +.output::-webkit-scrollbar-thumb { + border: 2px solid transparent; + background-clip: padding-box; + border-radius: 6px; +} + +/* Track end-margins keep the thumb's travel out of the card's rounded + corners in both directions. */ +.output::-webkit-scrollbar-track { + margin: 6px; } /* No wrapping, no word-break: alignment is the payload of terminal output. */ @@ -147,6 +206,6 @@ .empty { padding: 12px 14px 12px 0; - font: var(--dsw-font-markdown-code-block); + font: var(--dsl-terminal-font); color: var(--dsw-alias-label-tertiary); } diff --git a/packages/client/ui-primitives/src/TerminalBlock.tsx b/packages/client/ui-primitives/src/TerminalBlock.tsx index c707711f69..1b30a7f58f 100644 --- a/packages/client/ui-primitives/src/TerminalBlock.tsx +++ b/packages/client/ui-primitives/src/TerminalBlock.tsx @@ -35,7 +35,7 @@ export interface TerminalBlockProps { signal?: string | undefined /** The command is still running: the block shows the prompt line alone. */ running?: boolean | undefined - /** Height cap in output lines before the middle collapses (default {@link DEFAULT_TERMINAL_MAX_LINES}). */ + /** Height cap in output lines before the middle collapses (default {@link DEFAULT_TERMINAL_MAX_LINES}); Infinity disables the cap. */ maxLines?: number | undefined /** Extra class merged onto the wrapper (callers position; this component draws). */ className?: string | undefined diff --git a/packages/client/ui-question/src/client/QuestionComposer.module.css b/packages/client/ui-question/src/client/QuestionComposer.module.css index 7b5cc1d1d8..c96aefa0ef 100644 --- a/packages/client/ui-question/src/client/QuestionComposer.module.css +++ b/packages/client/ui-question/src/client/QuestionComposer.module.css @@ -139,7 +139,11 @@ .option { display: flex; - align-items: center; + /* flex-start, not center: with a wrapped description the indicator must + stay on the FIRST line (centering drifts it down the taller copy block). + The 8px padding makes a single-line row 40px exactly, so nothing reads + as top-heavy; .number/.checkbox re-center against the first line box. */ + align-items: flex-start; gap: 8px; width: 100%; min-height: 40px; @@ -148,7 +152,7 @@ intrinsic height, and centered content then paints outside the row box — over the title and the next row. Overflow belongs to .options. */ flex-shrink: 0; - padding: 6px 12px 6px 8px; + padding: 8px 12px 8px 8px; border: 1px solid transparent; border-radius: 12px; background: transparent; @@ -180,6 +184,9 @@ flex: 0 0 20px; width: 20px; height: 20px; + /* (24px first-line box − 20px indicator) / 2: centers the indicator against + the first text line under the row's flex-start alignment. */ + margin-top: 2px; border-radius: 6px; background: var(--dsw-alias-bg-overlay); color: var(--dsw-alias-label-secondary); @@ -197,6 +204,8 @@ flex: 0 0 20px; width: 20px; height: 20px; + /* Same first-line centering as .number under flex-start alignment. */ + margin-top: 2px; } .checkbox::before { @@ -263,14 +272,16 @@ inline text input; focus or a typed draft lifts it to the selected look. */ .customRow { display: flex; - align-items: center; + /* Same first-line alignment as .option — the indicator seat carries the + 2px re-centering margin. */ + align-items: flex-start; gap: 8px; width: 100%; min-height: 40px; /* Same reason as .option: the custom row is scroll content, and shrinking it pushes the inline input past the footer. */ flex-shrink: 0; - padding: 6px 12px 6px 8px; + padding: 8px 12px 8px 8px; border: 1px solid transparent; border-radius: 12px; transition: background-color 120ms ease, border-color 120ms ease; @@ -378,9 +389,7 @@ .option, .customRow { - align-items: flex-start; - gap: 8px; - padding: 6px; + padding: 8px 6px; } .footer { diff --git a/packages/client/ui-theme/src/styles/gradient-shadow-text.css b/packages/client/ui-theme/src/styles/gradient-shadow-text.css index aea8d9cb83..e062b4ba93 100644 --- a/packages/client/ui-theme/src/styles/gradient-shadow-text.css +++ b/packages/client/ui-theme/src/styles/gradient-shadow-text.css @@ -131,6 +131,14 @@ body { --dsw-font-markdown-code-block-font-size: 13px; --dsw-font-markdown-code-block-font-style: normal; + /* 手工补充(非插件导出):tool row 展开卡片内的小号 code 字体。 */ + --dsw-font-markdown-code-block-small: 12px/18px var(--ds-font-family-code); + --dsw-font-markdown-code-block-small-font-family: var(--ds-font-family-code); + --dsw-font-markdown-code-block-small-font-weight: 400; + --dsw-font-markdown-code-block-small-line-height: 18px; + --dsw-font-markdown-code-block-small-font-size: 12px; + --dsw-font-markdown-code-block-small-font-style: normal; + --dsw-font-xl-24: 600 24px/32px var(--dsw-font-family); --dsw-font-xl-24-font-family: var(--dsw-font-family); --dsw-font-xl-24-font-weight: 600; diff --git a/packages/client/ui-trajectory/src/client/TrajectoryTable.tsx b/packages/client/ui-trajectory/src/client/TrajectoryTable.tsx index 09ad60b427..a979be2642 100644 --- a/packages/client/ui-trajectory/src/client/TrajectoryTable.tsx +++ b/packages/client/ui-trajectory/src/client/TrajectoryTable.tsx @@ -235,6 +235,10 @@ export interface TrajectoryTableProps { collapsedAssistants: ReadonlySet /** Toggle tool calls under one assistant record. */ onToggleAssistant: (index: number) => void + /** One-shot cross-view inspect: open and scroll to this call's record. */ + inspectCallId?: string | null + /** Acknowledge a consumed (or unresolvable) inspect request. */ + onInspectApplied?: (() => void) | undefined } /** One request identity paired with its session-global number. */ @@ -1402,6 +1406,8 @@ export function TrajectoryTable({ onToggleTurn, collapsedAssistants, onToggleAssistant, + inspectCallId = null, + onInspectApplied, }: TrajectoryTableProps) { const [selectedIndex, setSelectedIndex] = useState(null) const [selectedRequest, setSelectedRequest] = useState(null) @@ -1574,8 +1580,37 @@ export function TrajectoryTable({ if (target !== undefined) openRecordSummary(target) } + // Cross-view inspect handoff: resolve the requested call to its record, + // open its summary, and remember the row to scroll once the un-collapsed + // ledger has rendered. Not-found leaves the request pending (`turns` in the + // deps retries as history pages in); the ack clears the store field. + const rootRef = useRef(null) + const pendingScrollIndex = useRef(null) + const openRecordSummaryRef = useRef(openRecordSummary) + openRecordSummaryRef.current = openRecordSummary + useEffect(() => { + if (inspectCallId === null) return + const target = flattenRecords(turns).find(record => record.cell.callId === inspectCallId) + if (target === undefined) return + openRecordSummaryRef.current(target) + pendingScrollIndex.current = target.cell.index + onInspectApplied?.() + }, [inspectCallId, turns, onInspectApplied]) + useEffect(() => { + const index = pendingScrollIndex.current + if (index === null) return + const row = rootRef.current + ?.querySelector(`tr[data-record-index="${index}"]`) + if (row === undefined || row === null) return + pendingScrollIndex.current = null + /* v8 ignore next -- jsdom lacks scrollIntoView; browsers always have it. */ + if (typeof row.scrollIntoView === 'function') { + row.scrollIntoView({ behavior: 'smooth', block: 'center' }) + } + }) + return ( -
      +
      { diff --git a/packages/client/ui-trajectory/src/client/TrajectoryView.tsx b/packages/client/ui-trajectory/src/client/TrajectoryView.tsx index c7f4e193da..6946f747ff 100644 --- a/packages/client/ui-trajectory/src/client/TrajectoryView.tsx +++ b/packages/client/ui-trajectory/src/client/TrajectoryView.tsx @@ -134,7 +134,7 @@ function searchMatches( } export function TrajectoryView({ - useHistory, loadAllHistory, + useHistory, loadAllHistory, inspect, onInspectDone, }: ConvViewProps & InjectFace) { const [collapsedTurns, setCollapsedTurns] = useState>(EMPTY_IDS) const [collapsedAssistants, setCollapsedAssistants] = @@ -502,6 +502,8 @@ export function TrajectoryView({ onToggleTurn={toggleTurn} collapsedAssistants={collapsedAssistants} onToggleAssistant={toggleAssistant} + inspectCallId={inspect?.callId ?? null} + onInspectApplied={onInspectDone} />
      diff --git a/packages/client/ui-trajectory/tests/table.spec.tsx b/packages/client/ui-trajectory/tests/table.spec.tsx index fb21ca45b7..8d5b321064 100644 --- a/packages/client/ui-trajectory/tests/table.spec.tsx +++ b/packages/client/ui-trajectory/tests/table.spec.tsx @@ -187,4 +187,50 @@ describe('TrajectoryTable', () => { expect(screen.getByRole('row', { name: /ASSISTANT/ })).toBeTruthy() expect(screen.getByRole('row', { name: /Collapsed turn summary/ })).toBeTruthy() }) + + const CALL_TURNS: readonly TrajectoryTurnModel[] = [{ + turn: 1, + groups: [{ + title: 'Step 1', + cells: [{ + index: 1, + kind: 'tool', + text: 'bash · {"command":"pwd"}', + inputDetail: '{"command":"pwd"}', + callId: 'call-1', + timeSeconds: 0.1, + }], + }], + }] + + it('an inspect target opens the matching record and acknowledges once', () => { + const onInspectApplied = vi.fn() + render( + , + ) + + expect(screen.getByRole('row', { name: /TOOL/ }).getAttribute('aria-selected')).toBe('true') + expect(screen.getByRole('complementary', { name: 'Event details' })).toBeTruthy() + expect(onInspectApplied).toHaveBeenCalledOnce() + }) + + it('an unmatched inspect target stays pending without acknowledgement', () => { + const onInspectApplied = vi.fn() + render( + , + ) + + expect(screen.getByRole('row', { name: /TOOL/ }).getAttribute('aria-selected')).toBe('false') + expect(onInspectApplied).not.toHaveBeenCalled() + }) }) From 60a3cbeb8ee4c11c0352507f7851f60d814f790f Mon Sep 17 00:00:00 2001 From: Chinesezjc Date: Thu, 30 Jul 2026 21:26:37 +0800 Subject: [PATCH 050/139] fix(client-connection): drop content copy from fixture web views after base merge The base (feat/web-presenter) removed the content field from WebSearchResultView/WebFetchResultView: the web card carries no content copy and a capability-less UI falls back to the raw tool/result content (web-result-card note). The fixture still constructed both web result views with a content field, failing the e2e build with TS2353. Drop the content spread and the stale Omit key; the fixture already emits the same text as the tool/result content the fallback path renders. --- .../client/connection/src/client/fixture.ts | 17 +++++++++-------- 1 file changed, 9 insertions(+), 8 deletions(-) diff --git a/packages/client/connection/src/client/fixture.ts b/packages/client/connection/src/client/fixture.ts index cc8332d081..587f873b74 100644 --- a/packages/client/connection/src/client/fixture.ts +++ b/packages/client/connection/src/client/fixture.ts @@ -143,9 +143,9 @@ const TERMINAL_EXIT_STATUS: Record, 'card' | 'kind' | 'content'> = { +const WEB_SEARCH_RESULT: Omit, 'card' | 'kind'> = { answer: 'DeepSeek Harness is a plugin-based agent harness on vendored Cordis where **every capability is a plugin**.', sources: [ { @@ -168,7 +168,7 @@ const WEB_SEARCH_RESULT: Omit, 'card' | 'kind' | 'content'> = { +const WEB_FETCH_RESULT: Omit, 'card' | 'kind'> = { url: 'https://www.deepseek.com/blog/harness-architecture', statusCode: 200, truncated: false, @@ -402,14 +402,15 @@ function presentResult(name: string, argsRaw: string, resultText: string): ToolR const call = presentCall(name, argsRaw) if (call === undefined) return undefined // The web tools keep a generic pending card, so their result card is chosen - // by tool name rather than by the pending card tag: the structured `web` - // card the frontend consumes, with the model-facing text kept as the - // capability-less fallback content. + // by tool name rather than by the pending card tag: the structured `web` card + // the frontend consumes. The view carries no `content` copy (per the contract + // and the web-result-card note); a capability-less UI falls back to the raw + // `tool/result` content, which this fixture emits from `resultText`. if (name === 'web_search') { - return { card: 'web', kind: 'search', ...WEB_SEARCH_RESULT, content: text(resultText) } + return { card: 'web', kind: 'search', ...WEB_SEARCH_RESULT } } if (name === 'web_fetch') { - return { card: 'web', kind: 'fetch', ...WEB_FETCH_RESULT, content: text(resultText) } + return { card: 'web', kind: 'fetch', ...WEB_FETCH_RESULT } } switch (call.card) { case 'terminal': From 1fd6b5a107124470219687b9a761f40640257db8 Mon Sep 17 00:00:00 2001 From: Chinesezjc Date: Thu, 30 Jul 2026 21:36:42 +0800 Subject: [PATCH 051/139] =?UTF-8?q?fix(web):=20diff=20card=20review=20?= =?UTF-8?q?=E2=80=94=20TUI=20parity,=20path-header=20overlap,=20double-res?= =?UTF-8?q?olve?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Bring the TUI diff footer onto the same terminator rule and distinct-path count the Web DiffBlock uses (a trailing newline terminates its line; two hunks in one file read as 1 file), so the two front ends' `+A -R · N file(s)` footers agree. Reserve space in the diff path header for the floating copy button so a long path no longer scrolls under it. Pass the tool's raw path to the injected openFile (which already resolves against cwd) instead of resolving twice. Rename the shared block-body CSS class to a card-neutral cardBody so a terminal-spacing tweak cannot silently move the diff card. Add a same-file two-hunk TUI unit test and an assembled built-boot assertion that the write turn renders +1 -0 · 1 file end to end. --- .../2026-07-30-web-diff-card.i18n.yaml | 4 +- .../feature/2026-07-30-web-diff-card.md | 5 ++- .../feature/2026-07-30-web-diff-card.zh.md | 5 ++- apps/web/tests/built-boot.snapshot.ts | 11 ++++++ .../src/client/chat/ToolRow.module.css | 15 ++++---- .../src/client/chat/ToolRow.tsx | 11 +++--- .../client/skeleton/DetailsPanel.module.css | 7 ++-- .../src/client/skeleton/DetailsPanel.tsx | 4 +- .../client/toolviews/file-mutation-row.tsx | 9 +++-- .../ui-primitives/src/DiffBlock.module.css | 6 ++- .../client/ui-primitives/src/DiffBlock.tsx | 12 +++--- packages/ui/tui/src/components/transcript.ts | 29 +++++++++++--- packages/ui/tui/tests/tui.spec.ts | 38 +++++++++++++++++++ 13 files changed, 116 insertions(+), 40 deletions(-) diff --git a/.agents/notes/implemented/feature/2026-07-30-web-diff-card.i18n.yaml b/.agents/notes/implemented/feature/2026-07-30-web-diff-card.i18n.yaml index 7ed620736c..f9b2cfa908 100644 --- a/.agents/notes/implemented/feature/2026-07-30-web-diff-card.i18n.yaml +++ b/.agents/notes/implemented/feature/2026-07-30-web-diff-card.i18n.yaml @@ -2,5 +2,5 @@ # side as of the last confirmed-consistent state. Both languages carry equal authority; # after editing either side, bring the other along and re-record with: # pnpm run verify-translation-pairing --write .agents/notes/implemented/feature/2026-07-30-web-diff-card.md -2026-07-30-web-diff-card.md: 8087ce698e65f78c7c6f51211ef00e3b0ab58ed9 -2026-07-30-web-diff-card.zh.md: d85ac1f2e13c7fb3732b327b40122076337ac538 +2026-07-30-web-diff-card.md: 396bdbc2843c1bbed5c6a913be436d8b9e96a81c +2026-07-30-web-diff-card.zh.md: afdeafa6e94b46b4f0fbd4a065afdac8a93ac57d diff --git a/.agents/notes/implemented/feature/2026-07-30-web-diff-card.md b/.agents/notes/implemented/feature/2026-07-30-web-diff-card.md index 8087ce698e..396bdbc284 100644 --- a/.agents/notes/implemented/feature/2026-07-30-web-diff-card.md +++ b/.agents/notes/implemented/feature/2026-07-30-web-diff-card.md @@ -16,11 +16,12 @@ This is the [terminal card](2026-07-28-web-terminal-card.md) done for the `diff` `DiffBlock` is a `ui-primitives` component that renders a file mutation as an inline diff surface, and both Web render sites for a write/edit call consume the diff render intent through it: the chat tool row's body and the details panel's Output section. `ui-conversation/src/client/contract/diff-card-model.ts` is the single place that turns the snapshot's `callView`/`resultView` pair into the component's props, so the two sites cannot disagree about a change. It returns null — the generic path — whenever neither side declares `card: 'diff'`, including a `card` value this client version does not know, and whenever a settled call's result view is generic, which is how write/edit keep their execution errors on the generic path. The result side is authoritative once the call settles: the applied hunks replace the call-time diff derived from the arguments alone. A paging window that drops the call head still renders, because the result view carries the whole change. -The component's contract follows the TUI's `diffLines` (`packages/ui/tui/src/components/transcript.ts`) so a diff reads the same shape across front ends, with one deliberate divergence noted below (the file count): +The component's contract follows the TUI's `diffLines` (`packages/ui/tui/src/components/transcript.ts`) so a diff reads the same shape across front ends: -- **One path header per file.** A new file opens a bold path header; a same-file second hunk (a scattered edit, or a `replace_all`) opens with a `⋯` gap instead of repeating the path. The `N file(s)` footer counts DISTINCT paths — the divergence from the TUI, whose footer uses `diffs.length` and so reads two hunks in one file as `2 files` where this reads `1 file`. +- **One path header per file.** A new file opens a bold path header; a same-file second hunk (a scattered edit, or a `replace_all`) opens with a `⋯` gap instead of repeating the path. The `N file(s)` footer counts DISTINCT paths on both front ends — this PR moved the TUI footer off `diffs.length` onto the distinct-path count, so two hunks in one file read as `1 file` in both. - **The change in the diff's own colors.** A removed line is `- ` on the error token, an added line is `+ ` on the success token, drawn verbatim with `white-space: pre` inside a horizontally scrolling box — a source line is read by its indentation, so it scrolls rather than folds. A create (`oldText: null`) has no removed side. - **Height cap with an expand control.** A diff longer than `DEFAULT_DIFF_MAX_LINES` (16) shows `ceil(max/2)` head rows plus the remaining tail rows, with a button between reporting the hidden count. The split arithmetic matches `TerminalBlock` and the TUI's collapsed card, so a long diff's head and tail slices agree across front ends. +- **Line terminator.** A side's content splits on `\n` under the terminator rule `TerminalBlock` uses: empty text is zero lines (a full deletion's `newText`, a create's absent `oldText` side), a single trailing newline terminates its last line rather than adding a phantom empty one, and an interior blank line survives. This PR applied the same rule to the TUI diff branch, so the `+A -R` footer counts agree on both front ends for the newline-terminated content real write/edit calls carry. - **Footer and copy.** A dim `└ +A -R · N file(s)` footer summarizes the change; `+A -R` are the added/removed line counts, the same per-side counts the TUI footer draws. The copy control copies the prefixed diff text (path headers, `- `/`+ ` lines, the `⋯` gap), so a multi-file copy stays attributable. Geometry, radius, and fonts mirror `CodeBlock`/`TerminalBlock` so a diff card, a terminal card, and a fenced block read as one family; `white-space: pre` plus horizontal scroll is the deliberate divergence. The copy control floats in the card's top-right corner rather than on a banner row of its own, because a banner carrying only a copy button drew an empty band above the first diff line — the TUI diff card has no banner either, only the footer. diff --git a/.agents/notes/implemented/feature/2026-07-30-web-diff-card.zh.md b/.agents/notes/implemented/feature/2026-07-30-web-diff-card.zh.md index d85ac1f2e1..afdeafa6e9 100644 --- a/.agents/notes/implemented/feature/2026-07-30-web-diff-card.zh.md +++ b/.agents/notes/implemented/feature/2026-07-30-web-diff-card.zh.md @@ -16,11 +16,12 @@ Web 客户端忽略了它。write/edit 调用落到 `GenericToolCard`,其行 `DiffBlock` 是一个 `ui-primitives` 组件,把文件改动渲染为内联 diff 表面,write/edit 调用的两个 Web 渲染点都通过它消费 diff 渲染意图:chat 工具行的行体和详情面板的 Output 区。`ui-conversation/src/client/contract/diff-card-model.ts` 是唯一把快照的 `callView`/`resultView` 对转成组件 props 的地方,因此两个渲染点不会对一次改动产生分歧。当两侧都未声明 `card: 'diff'` 时它返回 null —— 走通用路径 —— 包括本客户端版本不认识的 `card` 值,以及已结算调用的 result view 是 generic 的情况(write/edit 的执行错误正是这样留在通用路径上的)。调用结算后 result 侧是权威:已应用的 hunk 替换仅从参数推导的 call 时 diff。分页窗口丢弃了 call 头也仍能渲染,因为 result view 携带完整改动。 -组件的契约遵循 TUI 的 `diffLines`(`packages/ui/tui/src/components/transcript.ts`),使 diff 在两个前端读起来是同一形态,仅文件计数一处刻意分歧(见下): +组件的契约遵循 TUI 的 `diffLines`(`packages/ui/tui/src/components/transcript.ts`),使 diff 在两个前端读起来是同一形态: -- **每个文件一个路径头。** 新文件开启一个粗体路径头;同文件的第二个 hunk(分散编辑,或 `replace_all`)以一个 `⋯` gap 开启,而非重复路径。`N file(s)` 页脚统计**去重后的路径数** —— 这是与 TUI 的分歧:TUI 页脚用 `diffs.length`,同文件两个 hunk 在那里读作 `2 files`,此处读作 `1 file`。 +- **每个文件一个路径头。** 新文件开启一个粗体路径头;同文件的第二个 hunk(分散编辑,或 `replace_all`)以一个 `⋯` gap 开启,而非重复路径。`N file(s)` 页脚在两个前端都统计**去重后的路径数** —— 本 PR 把 TUI 页脚从 `diffs.length` 改为去重路径计数,因此同文件两个 hunk 在两端都读作 `1 file`。 - **改动用 diff 自身的颜色。** 删除行是 error token 上的 `- `,新增行是 success token 上的 `+ `,在横向滚动的盒子里以 `white-space: pre` 逐字绘制 —— 源码行靠缩进阅读,所以滚动而不折行。新建(`oldText: null`)没有删除侧。 - **高度上限带展开控件。** 长于 `DEFAULT_DIFF_MAX_LINES`(16)的 diff 显示 `ceil(max/2)` 个头部行加剩余尾部行,中间一个按钮报告隐藏行数。分割算术与 `TerminalBlock` 和 TUI 的折叠卡片一致,因此长 diff 的头尾切片在两个前端一致。 +- **行终止符。** 每一侧的内容按 `TerminalBlock` 的终止符规则在 `\n` 上切分:空文本是零行(整文件删除的 `newText`、新建缺失的 `oldText` 侧),单个结尾换行终止其最后一行而非新增一条幻影空行,内部空行保留。本 PR 把同一规则应用到了 TUI diff 分支,因此对于真实 write/edit 调用携带的以换行结尾的内容,两个前端的 `+A -R` 页脚计数一致。 - **页脚与复制。** 暗色 `└ +A -R · N file(s)` 页脚概括改动;`+A -R` 是新增/删除行数,与 TUI 页脚绘制的每侧计数相同。复制控件复制带前缀的 diff 文本(路径头、`- `/`+ ` 行、`⋯` gap),使多文件复制保持可归属。 几何、圆角、字体镜像 `CodeBlock`/`TerminalBlock`,使 diff 卡片、terminal 卡片、代码块读起来是一家;`white-space: pre` 加横向滚动是刻意的分歧。复制控件浮在卡片右上角,而非占据自己的 banner 行,因为只放一个复制按钮的 banner 会在第一行 diff 上方画出一条空带 —— TUI 的 diff 卡片也没有 banner,只有页脚。 diff --git a/apps/web/tests/built-boot.snapshot.ts b/apps/web/tests/built-boot.snapshot.ts index 69d5d5cfae..0e1d58f965 100644 --- a/apps/web/tests/built-boot.snapshot.ts +++ b/apps/web/tests/built-boot.snapshot.ts @@ -108,6 +108,17 @@ it('boots the built plugin graph and renders a fixture session end to end', asyn expect(document.querySelector('[data-sample="bash-global"]')).not.toBeNull() }, { timeout: 10_000 }) + // The write/edit turns render a real diff card through the assembled graph + // (the keyed FileMutationRow + DiffBlock), not just the fixture's raw text. + // The write turn's `hello fixture\n` proves the terminator rule end to end: a + // trailing newline terminates its line, so the footer reads `+1` (not a + // phantom `+2`) and one distinct file. + const diffCards = document.querySelectorAll('[data-diff]') + expect(diffCards.length).toBeGreaterThan(0) + const footers = [...document.querySelectorAll('[data-diff]')] + .map(card => card.textContent ?? '') + expect(footers.some(text => text.includes('+ hello fixture') && text.includes('+1 -0 · 1 file'))).toBe(true) + // Every bundle injected its plugin-owned style tag (the loader's CSS path). const styleOwners = [...document.head.querySelectorAll('style[data-plugin]')] .map(style => style.getAttribute('data-plugin')) diff --git a/packages/client/ui-conversation/src/client/chat/ToolRow.module.css b/packages/client/ui-conversation/src/client/chat/ToolRow.module.css index e53b472c50..f1d3e7dd7e 100644 --- a/packages/client/ui-conversation/src/client/chat/ToolRow.module.css +++ b/packages/client/ui-conversation/src/client/chat/ToolRow.module.css @@ -113,14 +113,15 @@ color: var(--dsw-alias-label-tertiary); } -/* The two block-shaped expanded bodies: the code variant's run_code program - through CodeBlock (shiki-highlighted TypeScript) and a terminal card's - command output through TerminalBlock. Both are drawn by the shared - primitive, so only the row's indentation is this file's concern — the margin - also replaces each primitive's own standalone vertical spacing with the - flow's row rhythm. */ +/* The block-shaped expanded bodies: the code variant's run_code program through + CodeBlock (shiki-highlighted TypeScript), a terminal card's command output + through TerminalBlock, and a write/edit diff through DiffBlock. All are drawn + by a shared primitive, so only the row's indentation is this file's concern — + the margin also replaces each primitive's own standalone vertical spacing with + the flow's row rhythm. Card-neutral: it carries no terminal- or diff-specific + value, so it fits every block body. */ .codeBody, -.terminalBody { +.cardBody { margin: 4px 0 4px 22px; } diff --git a/packages/client/ui-conversation/src/client/chat/ToolRow.tsx b/packages/client/ui-conversation/src/client/chat/ToolRow.tsx index 52238788d1..b89f537230 100644 --- a/packages/client/ui-conversation/src/client/chat/ToolRow.tsx +++ b/packages/client/ui-conversation/src/client/chat/ToolRow.tsx @@ -83,9 +83,10 @@ export function ToolRow({ // A row that names a single file keeps one interaction (open that path); // args expand is off whether or not the open callback is wired yet. A card // body (terminal or diff) still expands: only the file variants carry a - // path. A write/edit row carries both a file path and a diff card, so its - // path link and its expandable card coexist — the card expands, the summary - // stays a link. + // path. A write/edit row carries both a file path and a diff card, so both + // the path link and the expandable card are offered — the collapsed row shows + // the path link, and expanding swaps it for the card body (DisclosureRow + // renders collapsedContent only while closed). const singleFile = filePath !== undefined const fileLink = singleFile && onOpenFile !== undefined const cardBody = terminalBody !== null || diffBody !== null @@ -138,9 +139,9 @@ export function ToolRow({
      {terminalBody.description}
      )} {terminalBody !== null - ? + ? : diffBody !== null - ? + ? : variant === 'code' ? :
      {text}
      } diff --git a/packages/client/ui-conversation/src/client/skeleton/DetailsPanel.module.css b/packages/client/ui-conversation/src/client/skeleton/DetailsPanel.module.css index 143174fe42..994ae718cb 100644 --- a/packages/client/ui-conversation/src/client/skeleton/DetailsPanel.module.css +++ b/packages/client/ui-conversation/src/client/skeleton/DetailsPanel.module.css @@ -101,8 +101,9 @@ font: var(--dsw-font-xs-13); } -/* The terminal card sits directly under its section label, so it drops the - primitive's standalone vertical margin; the section owns the spacing. */ -.terminal { +/* A card body (terminal or diff) sits directly under its section label, so it + drops the primitive's standalone vertical margin; the section owns the + spacing. Card-neutral: no terminal- or diff-specific value. */ +.cardBody { margin: 0; } diff --git a/packages/client/ui-conversation/src/client/skeleton/DetailsPanel.tsx b/packages/client/ui-conversation/src/client/skeleton/DetailsPanel.tsx index d09d3ea256..5a5e19179c 100644 --- a/packages/client/ui-conversation/src/client/skeleton/DetailsPanel.tsx +++ b/packages/client/ui-conversation/src/client/skeleton/DetailsPanel.tsx @@ -146,12 +146,12 @@ function OutputBody({ material, cwd }: { material: CallMaterial; cwd: string | u {terminal.description !== undefined && (
      {terminal.description}
      )} - + ) } const diff = diffCardModel(material.block) - if (diff !== null) return + if (diff !== null) return // A settled call always carries the result node the flattened form needs; // the running shape has no result to flatten. if (!('kind' in material.block)) return
      运行中…
      diff --git a/packages/client/ui-conversation/src/client/toolviews/file-mutation-row.tsx b/packages/client/ui-conversation/src/client/toolviews/file-mutation-row.tsx index e777c78932..323a73e77c 100644 --- a/packages/client/ui-conversation/src/client/toolviews/file-mutation-row.tsx +++ b/packages/client/ui-conversation/src/client/toolviews/file-mutation-row.tsx @@ -17,7 +17,7 @@ import type { Context } from 'cordis' import { DiffBlock, IconEditOutline16, StateDot } from '@deepseek-ai/dsh-client-ui-primitives' import type { ToolRowProps } from '../contract/slots.ts' import { CHAT_DIFF_MAX_LINES, diffCardModel } from '../contract/diff-card-model.ts' -import { resolveToolPath, toolRowModel, type ToolRowState } from '../contract/tool-call-model.ts' +import { toolRowModel, type ToolRowState } from '../contract/tool-call-model.ts' import css from './file-mutation-row.module.css' function leadingFor(state: ToolRowState) { @@ -63,8 +63,9 @@ function errorText(block: ToolRowProps['block']): string | null { /** * File-mutation row: icon + {Edit,Write} · {path} in the shared ToolRow chrome, * with the applied diff resident below it. The summary is a path link (a file - * tool's interaction) resolved against the session cwd and opened through the - * host; the card's copy and expand controls are the row's only other actions. + * tool's interaction); the host's `openFile` resolves it against the session + * cwd, so this passes the tool's own path verbatim. The card's copy and expand + * controls are the row's only other actions. */ export function FileMutationRow({ toolName, block, cwd, openFile }: ToolRowProps) { const model = toolRowModel(toolName, block, cwd) @@ -85,7 +86,7 @@ export function FileMutationRow({ toolName, block, cwd, openFile }: ToolRowProps diff --git a/packages/client/ui-primitives/src/DiffBlock.module.css b/packages/client/ui-primitives/src/DiffBlock.module.css index 8794dbb87e..c5b79006a3 100644 --- a/packages/client/ui-primitives/src/DiffBlock.module.css +++ b/packages/client/ui-primitives/src/DiffBlock.module.css @@ -46,10 +46,14 @@ white-space: pre; } -/* A file header: the path in the primary tone, set apart by weight. */ +/* A file header: the path in the primary tone, set apart by weight. The copy + button floats over this first row's top-right corner, so reserve space at the + line's end for it — a long path scrolls under the button otherwise, and the + button's hit area would eat clicks on the path's tail. */ .path { color: var(--dsw-alias-label-primary); font-weight: 600; + padding-right: 56px; } /* A same-file second hunk's separator (a scattered edit), in the dim tone. */ diff --git a/packages/client/ui-primitives/src/DiffBlock.tsx b/packages/client/ui-primitives/src/DiffBlock.tsx index 5ae28bc9b2..23c498b1d1 100644 --- a/packages/client/ui-primitives/src/DiffBlock.tsx +++ b/packages/client/ui-primitives/src/DiffBlock.tsx @@ -4,9 +4,10 @@ // color), with a dim `└ +A -R · N file(s)` footer. The +/- block form mirrors // the TUI transcript's diff card (packages/ui/tui: diffLines) so a diff reads // the same across front ends: the removed side is the old text in full, the -// added side the new text in full. Output never soft-wraps — an aligned source -// line keeps its indentation and scrolls horizontally instead of folding. -// Colors resolve through --dsw-* tokens; geometry mirrors CodeBlock. +// added side the new text in full, both split on the same terminator rule, and +// the footer counts distinct paths on both ends. Output never soft-wraps — an +// aligned source line keeps its indentation and scrolls horizontally instead of +// folding. Colors resolve through --dsw-* tokens; geometry mirrors CodeBlock. import { useCallback, useMemo, useState } from 'react' import clsx from 'clsx' @@ -68,9 +69,8 @@ const ROW_CLASS: Record = { * opens each new file; a same-file second hunk (a scattered edit) opens with a * `⋯` gap instead of repeating the path. Every old-side line counts toward * `removed` and every new-side line toward `added`. The file count is of - * DISTINCT paths, which is the one deliberate divergence from the TUI diff card: - * the TUI footer uses `diffs.length`, so two hunks in one file read there as - * `2 files`, whereas this counts the one file they belong to. + * DISTINCT paths, matching the TUI diff card's footer, so two hunks in one file + * read as `1 file` on both front ends. * @param diffs - the hunks to render. * @returns the body rows, the +/- totals, and the distinct-file count. */ diff --git a/packages/ui/tui/src/components/transcript.ts b/packages/ui/tui/src/components/transcript.ts index 58d3d6a178..c9a505bbb2 100644 --- a/packages/ui/tui/src/components/transcript.ts +++ b/packages/ui/tui/src/components/transcript.ts @@ -52,15 +52,28 @@ function pretty(value: unknown): string { return displayText(serialized ?? String(value)) } +/** + * A side's content lines under the terminator rule the Web DiffBlock also + * applies: empty text is zero lines (a full deletion's `newText`, a create's + * absent `oldText`), and a single trailing newline terminates the last line + * rather than adding an empty one. An interior blank line survives. Keeping the + * two front ends on the same rule holds their `+A -R` footers in step. + */ +function diffContentLines(text: string): string[] { + if (text === '') return [] + const body = text.endsWith('\n') ? text.slice(0, -1) : text + return body.split('\n') +} + /** A file diff as colored `+`/`-` lines, optionally prefixed with its path. */ function diffLines(diff: FileDiff, palette: Palette): string[] { // The card header is a fixed `Tool / ` frame that never names a file, so // each hunk always carries its own path header (no redundancy to suppress). const lines = [palette.bold(displayText(diff.path))] if (diff.oldText !== null) { - for (const line of displayText(diff.oldText).split('\n')) lines.push(palette.error(`- ${line}`)) + for (const line of diffContentLines(displayText(diff.oldText))) lines.push(palette.error(`- ${line}`)) } - for (const line of displayText(diff.newText).split('\n')) lines.push(palette.success(`+ ${line}`)) + for (const line of diffContentLines(displayText(diff.newText))) lines.push(palette.success(`+ ${line}`)) return lines } @@ -488,15 +501,19 @@ export class ToolCardComponent implements Component { } if (view.card === 'diff') { // The header no longer names the file, so each diff keeps its own path - // header. A trailing footer summarizes the change (`+A -R · N file(s)`). + // header. A trailing footer summarizes the change (`+A -R · N file(s)`), + // on the same terminator rule and distinct-path count the Web DiffBlock + // uses, so the two front ends' footers agree. let added = 0 let removed = 0 + const paths = new Set() const hunks = view.diffs.flatMap((diff, index) => { - if (diff.oldText !== null) removed += displayText(diff.oldText).split('\n').length - added += displayText(diff.newText).split('\n').length + paths.add(diff.path) + if (diff.oldText !== null) removed += diffContentLines(displayText(diff.oldText)).length + added += diffContentLines(displayText(diff.newText)).length return [...index > 0 ? [''] : [], ...diffLines(diff, this.palette)] }) - const files = view.diffs.length + const files = paths.size const footer = this.palette.dim(`└ +${added} -${removed} · ${files} file${files === 1 ? '' : 's'}`) // A diff's own `+`/`-` colors carry its meaning, so it renders verbatim // rather than under the dim result-output color. diff --git a/packages/ui/tui/tests/tui.spec.ts b/packages/ui/tui/tests/tui.spec.ts index d99780dedb..c03d40f098 100644 --- a/packages/ui/tui/tests/tui.spec.ts +++ b/packages/ui/tui/tests/tui.spec.ts @@ -4317,6 +4317,21 @@ describe('tool cards and surface replay', () => { diffs: [{ path: 'src/only.ts', oldText: 'old', newText: 'new' }], }), }, + scatteredDiff: { + name: 'scatteredDiff', description: '', parameters: {}, output: UNUSED_TOOL_OUTPUT, execute: async () => [], + // Two hunks in ONE file, each side ending in the terminator newline real + // write/edit content carries. The footer must read `+2 -0 · 1 file`: the + // trailing newline terminates its line rather than adding a phantom empty + // one, and the two hunks count as the single distinct path they touch. + presentCall: () => ({ + card: 'diff', + title: 'Edit src/scatter.ts', + diffs: [ + { path: 'src/scatter.ts', oldText: null, newText: 'first\n' }, + { path: 'src/scatter.ts', oldText: null, newText: 'second\n' }, + ], + }), + }, generic: { name: 'generic', description: '', parameters: {}, output: UNUSED_TOOL_OUTPUT, execute: async () => [], presentCall: () => ({ card: 'generic', title: 'Inspect value', rawInput: { alpha: 1 } }), @@ -4621,6 +4636,29 @@ describe('tool cards and surface replay', () => { await dispose(result) }) + it('counts a same-file diff once and terminates its trailing newline', async () => { + const result = await setup({ tools }) + appendUser(result.session, 'scatter edits in one file') + appendAssistant(result.session, [ + { type: 'text', text: 'Editing' }, + { type: 'tool-call', id: 'scatter' as never, name: 'scatteredDiff', arguments: '{}' }, + ]) + result.session.append('tool/call', { + turn: 1, step: 1, callId: 'scatter' as never, name: 'scatteredDiff', arguments: '{}', + }) + await tick() + const output = result.terminal.output + // Two hunks, one path: distinct-path count, same as the Web DiffBlock. + expect(output).toContain('· 1 file') + expect(output).not.toContain('· 2 files') + // The `first\n`/`second\n` sides each contribute exactly one added line — + // the trailing newline terminates rather than adding a phantom empty `+ `. + expect(output).toContain('+ first') + expect(output).toContain('+ second') + expect(output).toContain('+2 -0') + await dispose(result) + }) + it('drops blank rows from a terminal card result that the dim styling wraps', async () => { const blankRowTools: Record = { trailing: { From c2bce3cac6948d15a4977269c188c80b6c0e18bc Mon Sep 17 00:00:00 2001 From: ZiyaZhang <199893125+ZiyaZhang@users.noreply.github.com> Date: Thu, 30 Jul 2026 06:45:36 -0700 Subject: [PATCH 052/139] fix(client): unblock full access CI gates --- packages/client/ui-permission/src/client/index.ts | 4 ++++ vitest.config.ts | 1 + 2 files changed, 5 insertions(+) diff --git a/packages/client/ui-permission/src/client/index.ts b/packages/client/ui-permission/src/client/index.ts index 2914e96f64..d5561afe32 100644 --- a/packages/client/ui-permission/src/client/index.ts +++ b/packages/client/ui-permission/src/client/index.ts @@ -72,6 +72,9 @@ function optionsOf(value: PermissionSelect, t: (key: string) => string): SelectO export function apply(ctx: ClientContext): void { const command = ctx.get('command') as CommandServiceContract const sessions = ctx.sessions + // This optional bundle and ui-conversation can load independently, so each + // owns the same safety copy under its own locale namespace. + /* jscpd:ignore-start */ ctx.effect(() => { const disposers = [ ctx.locale.register(ACCESS_NS, 'zh', { @@ -91,6 +94,7 @@ export function apply(ctx: ClientContext): void { ] return () => { for (const dispose of disposers) dispose() } }, 'ui-permission: Full access confirmation dictionaries') + /* jscpd:ignore-end */ const t = ctx.locale.bind(ACCESS_NS) const sessionFor = (session: ClientSessionContext): SessionFace | undefined => sessions.binding(session.sessionId)?.session diff --git a/vitest.config.ts b/vitest.config.ts index 750bb6ddf2..bc5dd85e1e 100644 --- a/vitest.config.ts +++ b/vitest.config.ts @@ -108,6 +108,7 @@ export default defineConfig({ 'packages/client/ui-primitives/src/markdown/plain-text.ts', 'packages/client/ui-question/src/client/QuestionComposer.tsx', 'packages/client/ui-primitives/src/Menu.tsx', + 'packages/client/ui-primitives/src/RiskConfirmation.tsx', 'packages/client/ui-workspace/src/client/WorkspaceBrowser.tsx', 'packages/client/ui-workspace/src/client/WorkspacePicker.tsx', 'packages/client/web-react/src/*', From f04b35c6a43f058b052f1d074e4da18ca4424ec2 Mon Sep 17 00:00:00 2001 From: Turtle Date: Thu, 30 Jul 2026 21:49:33 +0800 Subject: [PATCH 053/139] fix(test): isolate jsdom storage on Node 26 --- .../2026-07-06-node-engine-floor.i18n.yaml | 6 ++--- .../process/2026-07-06-node-engine-floor.md | 4 +-- .../2026-07-06-node-engine-floor.zh.md | 4 +-- ...itest-jsdom-webstorage-ownership.i18n.yaml | 6 +++++ ...07-30-vitest-jsdom-webstorage-ownership.md | 26 +++++++++++++++++++ ...30-vitest-jsdom-webstorage-ownership.zh.md | 26 +++++++++++++++++++ .../client/ui-trajectory/tests/views.spec.tsx | 4 +-- scripts/run-gates.spec.ts | 17 ++++++++++++ scripts/run-gates.ts | 5 ++++ scripts/vitest-environment.compat.spec.ts | 14 ++++++++++ vitest.config.ts | 3 +++ vitest.e2e.config.ts | 2 ++ vitest.shared.ts | 5 ++++ vitest.snapshot.config.ts | 2 ++ vitest.web.config.ts | 2 ++ 15 files changed, 116 insertions(+), 10 deletions(-) create mode 100644 .agents/notes/implemented/testing/2026-07-30-vitest-jsdom-webstorage-ownership.i18n.yaml create mode 100644 .agents/notes/implemented/testing/2026-07-30-vitest-jsdom-webstorage-ownership.md create mode 100644 .agents/notes/implemented/testing/2026-07-30-vitest-jsdom-webstorage-ownership.zh.md create mode 100644 scripts/vitest-environment.compat.spec.ts create mode 100644 vitest.shared.ts diff --git a/.agents/notes/implemented/process/2026-07-06-node-engine-floor.i18n.yaml b/.agents/notes/implemented/process/2026-07-06-node-engine-floor.i18n.yaml index 2cb7f1009d..50d3e498a5 100644 --- a/.agents/notes/implemented/process/2026-07-06-node-engine-floor.i18n.yaml +++ b/.agents/notes/implemented/process/2026-07-06-node-engine-floor.i18n.yaml @@ -1,6 +1,6 @@ # Bilingual-pair consistency record (docs/i18n/README.md): the git blob hash of each # side as of the last confirmed-consistent state. Both languages carry equal authority; # after editing either side, bring the other along and re-record with: -# pnpm run verify-translation-pairing --write -2026-07-06-node-engine-floor.md: f1754ea7ca32452a04c6cd8a0599568f602e47dd -2026-07-06-node-engine-floor.zh.md: 9d376a639378d3a0b9b645aa36c1a5d320d1d147 +# pnpm run verify-translation-pairing --write .agents/notes/implemented/process/2026-07-06-node-engine-floor.md +2026-07-06-node-engine-floor.md: ef047d885a442106a35922f4716d2996d8a98ca7 +2026-07-06-node-engine-floor.zh.md: a0281addf7d4327d7f6ea30e3a3f0f40d6782bd0 diff --git a/.agents/notes/implemented/process/2026-07-06-node-engine-floor.md b/.agents/notes/implemented/process/2026-07-06-node-engine-floor.md index f1754ea7ca..ef047d885a 100644 --- a/.agents/notes/implemented/process/2026-07-06-node-engine-floor.md +++ b/.agents/notes/implemented/process/2026-07-06-node-engine-floor.md @@ -10,7 +10,7 @@ The Node 22 branch of the root `engines.node` range is a contract for the instal ## Decision -Set `engines.node` to `^22.19.0 || >=24.0.0` and test the keyless CI compatibility matrix on `['22.19', 24, 26]`. Every matrix leg runs the TypeScript typecheck plus a keyless source-mode worker smoke, so the floor is exercised through both a complete source typecheck and a real unbuilt runtime path. The real-API e2e workflow stays on Node 24 because it exercises API integration rather than the runtime floor. +Set `engines.node` to `^22.19.0 || >=24.0.0` and test keyless CI on `['22.19', 24, 26]`. The primary Node 24 jobs own the complete typecheck and unit coverage inventory; every version runs focused source-worker, Zstandard, source-launch, and [jsdom storage](../testing/2026-07-30-vitest-jsdom-webstorage-ownership.md) smokes without repeating that inventory. The real-API e2e workflow stays on Node 24 because it exercises API integration rather than the runtime floor. Two Node features gate the source runtime: @@ -24,7 +24,7 @@ Those source features clear on the 22.x line at **22.18**, but the installed Pi ## Consequences - The advertised LTS branch no longer undercuts the Pi adapter dependency floor. -- CI proves the Node 22 LTS floor directly with Node 22.19, keeps the Node 24 branch on `node: 24`, and keeps Node 26 for the next even line; each leg typechecks the source graph and launches the unbuilt workflow worker for real. +- CI proves the Node 22 LTS floor directly with Node 22.19, keeps primary coverage on `node: 24`, and exercises Node 26 as the next even line; focused compatibility smokes run on all three versions. - The built-bin smoke needs no version-conditional flag: at 22.19 type-stripping is already the default, so the test stays the plain `node lib/bin.js` path it documents. - A future dependency or source API that raises the runtime floor must move `engines.node`, the compatibility matrix, and this Agent Note in the same change. diff --git a/.agents/notes/implemented/process/2026-07-06-node-engine-floor.zh.md b/.agents/notes/implemented/process/2026-07-06-node-engine-floor.zh.md index 9d376a6393..a0281addf7 100644 --- a/.agents/notes/implemented/process/2026-07-06-node-engine-floor.zh.md +++ b/.agents/notes/implemented/process/2026-07-06-node-engine-floor.zh.md @@ -10,7 +10,7 @@ Status: implemented ## 决策 -将 `engines.node` 设为 `^22.19.0 || >=24.0.0`,并在 keyless CI 兼容性矩阵中测试 `['22.19', 24, 26]`。每条矩阵分支都运行 TypeScript 类型检查加一次 keyless 的源码模式 worker 冒烟测试,因此引擎下限通过完整的源码类型检查和真实的未构建运行时路径两条路径得到验证。真实 API 的 e2e 工作流保持在 Node 24 上,因为它验证的是 API 集成而非运行时下限。 +将 `engines.node` 设为 `^22.19.0 || >=24.0.0`,并在 `['22.19', 24, 26]` 上运行 keyless CI。主要的 Node 24 任务负责整套类型检查和单元测试覆盖率任务;三个版本均运行 source-worker、Zstandard、source-launch 和 [jsdom 存储](../testing/2026-07-30-vitest-jsdom-webstorage-ownership.md) 专项冒烟测试,不重复这套类型检查和覆盖率任务。真实 API 的 e2e 工作流保持在 Node 24 上,因为它验证的是 API 集成而非运行时下限。 两个 Node 特性决定了源码运行时的门槛: @@ -24,7 +24,7 @@ Status: implemented ## 后果 - 宣传的 LTS 分支不再低于 Pi 适配器依赖的下限。 -- CI 通过 Node 22.19 直接验证 Node 22 LTS 下限,Node 24 分支保持 `node: 24`,Node 26 用于下一个偶数线;每条分支都对源码图执行类型检查,并实际启动未构建的工作流 worker。 +- CI 通过 Node 22.19 直接验证 Node 22 LTS 下限,将主要覆盖率任务保留在 `node: 24`,并用 Node 26 验证下一个偶数线;三个版本均运行聚焦的兼容性冒烟测试。 - built-bin 冒烟测试无需版本条件标志:在 22.19 上类型剥离已是默认行为,因此测试保持其文档所述的纯 `node lib/bin.js` 路径。 - 未来若依赖或源码 API 提高运行时下限,必须在同一变更中同步调整 `engines.node`、兼容性矩阵和本 Agent Note(agent 决策记录)。 diff --git a/.agents/notes/implemented/testing/2026-07-30-vitest-jsdom-webstorage-ownership.i18n.yaml b/.agents/notes/implemented/testing/2026-07-30-vitest-jsdom-webstorage-ownership.i18n.yaml new file mode 100644 index 0000000000..e829874e9d --- /dev/null +++ b/.agents/notes/implemented/testing/2026-07-30-vitest-jsdom-webstorage-ownership.i18n.yaml @@ -0,0 +1,6 @@ +# Bilingual-pair consistency record (docs/i18n/README.md): the git blob hash of each +# side as of the last confirmed-consistent state. Both languages carry equal authority; +# after editing either side, bring the other along and re-record with: +# pnpm run verify-translation-pairing --write .agents/notes/implemented/testing/2026-07-30-vitest-jsdom-webstorage-ownership.md +2026-07-30-vitest-jsdom-webstorage-ownership.md: 3956a7566fa1c79a767636bce9a19f16588126e2 +2026-07-30-vitest-jsdom-webstorage-ownership.zh.md: 9080ee2762b74bf2efdaccd7a5905672001bc0e8 diff --git a/.agents/notes/implemented/testing/2026-07-30-vitest-jsdom-webstorage-ownership.md b/.agents/notes/implemented/testing/2026-07-30-vitest-jsdom-webstorage-ownership.md new file mode 100644 index 0000000000..3956a7566f --- /dev/null +++ b/.agents/notes/implemented/testing/2026-07-30-vitest-jsdom-webstorage-ownership.md @@ -0,0 +1,26 @@ +# Agent Note: Keep browser storage owned by jsdom in Vitest + +Status: implemented + +English | [中文](2026-07-30-vitest-jsdom-webstorage-ownership.zh.md) + +## Problem + +The supported Node range includes releases that reserve a process-wide `globalThis.localStorage`. Node 26 exposes that property as `undefined` without `--localstorage-file`; Vitest sees the reserved key and does not project jsdom's isolated `Storage` object over it. Component suites then fail before exercising product behavior, while the primary Node 24 coverage lane remains green because that runtime does not reserve the key by default. + +## Decision + +Vitest workers disable Node's process-wide Web Storage when the runtime advertises the `--webstorage` flag. The configuration passes `--no-webstorage` through each test project's `execArgv`; runtimes without that flag receive no argument. Node-environment suites therefore stay browser-free, and files selecting jsdom through `@vitest-environment jsdom` receive jsdom's isolated `localStorage`. + +The Node compatibility aggregate runs a dedicated jsdom smoke on every advertised compatibility line. It asserts both the conditional worker argument and usable storage, so a future Node or Vitest change cannot leave the primary Node 24 suite as the only signal. + +## Alternatives considered + +- **Set `NODE_OPTIONS=--no-webstorage` in package scripts or CI.** Rejected because it leaks test-runner policy into subprocesses and misses direct `pnpm exec vitest` invocations. +- **Pass `--localstorage-file` to Node.** Rejected because one process-wide persistent store has different ownership and isolation semantics from browser storage created per jsdom environment. +- **Patch `globalThis.localStorage` in setup code or guard every component test.** Rejected because setup would depend on Vitest's private jsdom projection details, while per-test guards hide a broken browser environment and duplicate policy across suites. +- **Pin tests to Node 24.** Rejected because the package engine advertises newer even Node lines and the compatibility matrix exists to expose their runtime changes. + +## Consequences + +The same `pnpm test` command works on Node releases with and without built-in Web Storage. Test workers deliberately cannot exercise Node's process-wide Web Storage; a future product need for that API requires a separate explicit test configuration rather than weakening jsdom isolation. The compatibility lane adds one focused Vitest process instead of duplicating the complete unit inventory on every Node version. diff --git a/.agents/notes/implemented/testing/2026-07-30-vitest-jsdom-webstorage-ownership.zh.md b/.agents/notes/implemented/testing/2026-07-30-vitest-jsdom-webstorage-ownership.zh.md new file mode 100644 index 0000000000..9080ee2762 --- /dev/null +++ b/.agents/notes/implemented/testing/2026-07-30-vitest-jsdom-webstorage-ownership.zh.md @@ -0,0 +1,26 @@ +# Agent Note: 在 Vitest 中将浏览器存储交由 jsdom 管理 + +Status: implemented + +[English](2026-07-30-vitest-jsdom-webstorage-ownership.md) | 中文 + +## 问题 + +受支持的 Node 版本范围包含会预留进程级 `globalThis.localStorage` 的版本。未设置 `--localstorage-file` 时,Node 26 将该属性暴露为 `undefined`;Vitest 检测到这个预留键后,不会用 jsdom 的隔离 `Storage` 对象覆盖该属性。因此,组件测试套件尚未验证产品行为便会失败,而主要的 Node 24 覆盖率分支仍能通过,因为该运行时默认不会预留此键。 + +## 决策 + +当运行时声明支持 `--webstorage` 标志时,Vitest worker 会禁用 Node 的进程级 Web Storage。配置通过每个测试项目的 `execArgv` 传入 `--no-webstorage`;未声明该标志的运行时则不传入此参数。因此,Node 环境测试套件不加载浏览器环境,而通过 `@vitest-environment jsdom` 选择 jsdom 的文件会获得 jsdom 隔离的 `localStorage`。 + +Node 兼容性汇总任务会在每条声明支持的兼容版本线上运行专用的 jsdom 冒烟测试。该测试同时断言 worker 参数按条件传入且存储可用,因此未来 Node 或 Vitest 的变化不会让主要的 Node 24 测试套件成为唯一检测信号。 + +## 曾考虑的替代方案 + +- **在包脚本或 CI 中设置 `NODE_OPTIONS=--no-webstorage`。** 否决:这会将测试运行器策略传播到子进程,也无法覆盖直接调用 `pnpm exec vitest` 的情况。 +- **向 Node 传入 `--localstorage-file`。** 否决:单个进程级持久化存储与每个 jsdom 环境分别创建的浏览器存储具有不同的归属和隔离语义。 +- **在初始化代码中修改 `globalThis.localStorage`,或为每个组件测试增加保护逻辑。** 否决:初始化逻辑会依赖 Vitest 私有的 jsdom 映射细节,而逐测试添加的保护逻辑会掩盖浏览器环境损坏,并在多个测试套件中重复该策略。 +- **将测试固定在 Node 24。** 否决:包的引擎范围声明支持更新的偶数 Node 版本线,而兼容性矩阵正是为了暴露这些版本的运行时变化。 + +## 后果 + +同一条 `pnpm test` 命令在有无内置 Web Storage 的 Node 版本上均可运行。测试 worker 被有意禁止使用 Node 的进程级 Web Storage;未来若产品需要该 API,必须使用独立且显式的测试配置,而不能削弱 jsdom 隔离。兼容性分支只增加一个专项 Vitest 进程,无需在每个 Node 版本上重复整套单元测试。 diff --git a/packages/client/ui-trajectory/tests/views.spec.tsx b/packages/client/ui-trajectory/tests/views.spec.tsx index c79b7407ab..df476101a9 100644 --- a/packages/client/ui-trajectory/tests/views.spec.tsx +++ b/packages/client/ui-trajectory/tests/views.spec.tsx @@ -35,9 +35,7 @@ afterEach(cleanup) // The chat store persists under its declared key; clear so one case's active // view cannot rehydrate into the next. beforeEach(() => { - // Node 22+ exposes an experimental localStorage global that is undefined - // without --localstorage-file; only clear when a real Storage is present. - if (typeof localStorage !== 'undefined') localStorage.clear() + localStorage.clear() }) /** Node fixture: user prologue, two turns, one tool result inside turn 1. */ diff --git a/scripts/run-gates.spec.ts b/scripts/run-gates.spec.ts index 9a67e64929..624d46dfd1 100644 --- a/scripts/run-gates.spec.ts +++ b/scripts/run-gates.spec.ts @@ -135,6 +135,23 @@ describe('Oxlint gate', () => { }) }) +describe('Node compatibility graph', () => { + it('runs the jsdom environment smoke on every advertised Node line', () => { + const subject = withPnpmEntrypoint(() => gatesForMode('node-compat')) + + expect(subject.find(item => item.id === 'vitest-jsdom-smoke')).toMatchObject({ + label: 'Vitest jsdom smoke', + args: [ + '/private/pnpm.cjs', + 'exec', + 'vitest', + 'run', + 'scripts/vitest-environment.compat.spec.ts', + ], + }) + }) +}) + describe('Node 24 consumer graph', () => { it('owns the eight-command pool and orders restored-artifact consumers', () => { const subject = withPnpmEntrypoint(() => gatesForMode('ci-consumers')) diff --git a/scripts/run-gates.ts b/scripts/run-gates.ts index 167d226ff8..b84aa903e1 100644 --- a/scripts/run-gates.ts +++ b/scripts/run-gates.ts @@ -292,6 +292,11 @@ function nodeCompatSmokeGates(): Gate[] { 'run', 'apps/cli/tests/source-launch.compat.spec.ts', ], { label: 'dsh source-launch smoke' }), + pnpmExec('vitest-jsdom-smoke', [ + 'vitest', + 'run', + 'scripts/vitest-environment.compat.spec.ts', + ], { label: 'Vitest jsdom smoke' }), ] } diff --git a/scripts/vitest-environment.compat.spec.ts b/scripts/vitest-environment.compat.spec.ts new file mode 100644 index 0000000000..fae1fc29fd --- /dev/null +++ b/scripts/vitest-environment.compat.spec.ts @@ -0,0 +1,14 @@ +// @vitest-environment jsdom +import { describe, expect, it } from 'vitest' + +describe('Vitest jsdom compatibility', () => { + it('provides isolated browser storage instead of Node process storage', () => { + if (process.allowedNodeEnvironmentFlags.has('--webstorage')) { + expect(process.execArgv.filter(argument => argument === '--no-webstorage')).toHaveLength(1) + } + localStorage.setItem('dsh-vitest-storage-probe', 'available') + + expect(localStorage.getItem('dsh-vitest-storage-probe')).toBe('available') + localStorage.removeItem('dsh-vitest-storage-probe') + }) +}) diff --git a/vitest.config.ts b/vitest.config.ts index 750bb6ddf2..460d852756 100644 --- a/vitest.config.ts +++ b/vitest.config.ts @@ -1,5 +1,6 @@ import tsconfigPaths from 'vite-tsconfig-paths' import { defineConfig } from 'vitest/config' +import { vitestExecArgv } from './vitest.shared.ts' // Resolution facade shared by every plugin instance below: tsconfig.base.json // has no include, which vite-tsconfig-paths treats as match-all, so its paths @@ -62,6 +63,7 @@ export default defineConfig({ plugins: [pathsPlugin()], test: { name: 'thread-safe', + execArgv: vitestExecArgv, // Node 24 has aborted in its CJS lexer from a macOS arm64 worker // thread. A fork contains that external runtime failure to the test // process; other hosts retain the lower-overhead thread pool. @@ -78,6 +80,7 @@ export default defineConfig({ plugins: [pathsPlugin()], test: { name: 'process-bound', + execArgv: vitestExecArgv, pool: 'forks', setupFiles: ['./scripts/test-invariants.ts'], include: processBoundTests, diff --git a/vitest.e2e.config.ts b/vitest.e2e.config.ts index 3f9ceada28..d8e6aa53a7 100644 --- a/vitest.e2e.config.ts +++ b/vitest.e2e.config.ts @@ -1,5 +1,6 @@ import tsconfigPaths from 'vite-tsconfig-paths' import { defineConfig } from 'vitest/config' +import { vitestExecArgv } from './vitest.shared.ts' // Real-API suite, separate because it spends tokens. Each test self-skips without // its provider credential for keyless CI; credentialed workflows preflight the @@ -37,6 +38,7 @@ export default defineConfig({ // entirely. plugins: [tsconfigPaths({ projects: ['./tsconfig.base.json'] })], test: { + execArgv: vitestExecArgv, setupFiles: ['./scripts/test-invariants.ts'], // apps/cli only, not apps/*: apps/web/tests/*.e2e.ts needs the built // frontend dist and runs under vitest.web.config.ts (the test:web job). diff --git a/vitest.shared.ts b/vitest.shared.ts new file mode 100644 index 0000000000..506fabb380 --- /dev/null +++ b/vitest.shared.ts @@ -0,0 +1,5 @@ +/** + * Worker arguments that keep process-wide Web Storage from shadowing jsdom storage. + * Node lists the positive spelling in `allowedNodeEnvironmentFlags` for this negatable flag. + */ +export const vitestExecArgv = process.allowedNodeEnvironmentFlags.has('--webstorage') ? ['--no-webstorage'] : [] diff --git a/vitest.snapshot.config.ts b/vitest.snapshot.config.ts index b14422d2f8..6a08eeb3eb 100644 --- a/vitest.snapshot.config.ts +++ b/vitest.snapshot.config.ts @@ -1,6 +1,7 @@ import { availableParallelism } from 'node:os' import tsconfigPaths from 'vite-tsconfig-paths' import { defineConfig } from 'vitest/config' +import { vitestExecArgv } from './vitest.shared.ts' const DEFAULT_SNAPSHOT_MAX_CONCURRENCY = 5 @@ -41,6 +42,7 @@ export default defineConfig({ // this (the root tsconfig is a solution file with no paths). plugins: [tsconfigPaths({ projects: ['./tsconfig.base.json'] })], test: { + execArgv: vitestExecArgv, setupFiles: ['./scripts/test-invariants.ts'], include: [ 'scripts/**/*.snapshot.ts', diff --git a/vitest.web.config.ts b/vitest.web.config.ts index fd9ca502bc..e6e1efa1f4 100644 --- a/vitest.web.config.ts +++ b/vitest.web.config.ts @@ -1,5 +1,6 @@ import tsconfigPaths from 'vite-tsconfig-paths' import { defineConfig } from 'vitest/config' +import { vitestExecArgv } from './vitest.shared.ts' // Web browser lane: real host entry points, built-client interaction snapshots, // and replayed keyless e2e scenarios outside the unit/e2e includes. Linux PR CI @@ -18,6 +19,7 @@ export default defineConfig({ // workspace imports to source like every other lane. plugins: [tsconfigPaths({ projects: ['./tsconfig.base.json'] })], test: { + execArgv: vitestExecArgv, include: [ 'apps/web/tests/**/*.e2e.ts', 'apps/web/tests/**/*.snapshot.ts', From 568c564db47982980691c451e40f986e3e663b8e Mon Sep 17 00:00:00 2001 From: Chinesezjc Date: Thu, 30 Jul 2026 21:51:27 +0800 Subject: [PATCH 054/139] fix(web): update diff-card tests for the openFile no-double-resolve contract MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The coverage lane caught a regression in the prior commit: FileMutationRow now passes the tool's raw path to the injected openFile (which resolves against cwd in apply.ts), but diff-card.spec still asserted the row pre-resolved. Assert on the raw path instead. Also fix the built-boot diff assertion to match on the line body and footer text — the `+ ` prefix is a CSS ::before, absent from textContent. --- apps/web/tests/built-boot.snapshot.ts | 10 +++++----- .../client/ui-conversation/tests/diff-card.spec.tsx | 6 ++++-- 2 files changed, 9 insertions(+), 7 deletions(-) diff --git a/apps/web/tests/built-boot.snapshot.ts b/apps/web/tests/built-boot.snapshot.ts index 0e1d58f965..6500305cd8 100644 --- a/apps/web/tests/built-boot.snapshot.ts +++ b/apps/web/tests/built-boot.snapshot.ts @@ -112,12 +112,12 @@ it('boots the built plugin graph and renders a fixture session end to end', asyn // (the keyed FileMutationRow + DiffBlock), not just the fixture's raw text. // The write turn's `hello fixture\n` proves the terminator rule end to end: a // trailing newline terminates its line, so the footer reads `+1` (not a - // phantom `+2`) and one distinct file. - const diffCards = document.querySelectorAll('[data-diff]') + // phantom `+2`) and one distinct file. The `+ ` prefix is a CSS ::before, so + // it is absent from textContent — assert on the line body and the footer. + const diffCards = [...document.querySelectorAll('[data-diff]')] expect(diffCards.length).toBeGreaterThan(0) - const footers = [...document.querySelectorAll('[data-diff]')] - .map(card => card.textContent ?? '') - expect(footers.some(text => text.includes('+ hello fixture') && text.includes('+1 -0 · 1 file'))).toBe(true) + const footers = diffCards.map(card => card.textContent ?? '') + expect(footers.some(text => text.includes('hello fixture') && text.includes('+1 -0 · 1 file'))).toBe(true) // Every bundle injected its plugin-owned style tag (the loader's CSS path). const styleOwners = [...document.head.querySelectorAll('style[data-plugin]')] diff --git a/packages/client/ui-conversation/tests/diff-card.spec.tsx b/packages/client/ui-conversation/tests/diff-card.spec.tsx index 031216b9f7..bf29f889ae 100644 --- a/packages/client/ui-conversation/tests/diff-card.spec.tsx +++ b/packages/client/ui-conversation/tests/diff-card.spec.tsx @@ -163,11 +163,13 @@ describe('FileMutationRow diff card', () => { expect(view.getByText('复制')).toBeTruthy() }) - it('the summary is a path link that opens through the host, cwd-resolved', () => { + it('the summary is a path link that opens the tool path through the host', () => { const openFile = vi.fn() const view = render() fireEvent.click(view.getByRole('button', { name: 'notes/demo.txt' })) - expect(openFile).toHaveBeenCalledWith('/w/app/notes/demo.txt') + // The row passes the tool's own path; the injected openFile resolves it + // against the session cwd (apply.ts), so the row must not resolve twice. + expect(openFile).toHaveBeenCalledWith('notes/demo.txt') }) it('registers under write too, rendering a create as an added-only diff', () => { From 4fbe46c38128824b5b63cea7f25034f691dcf3a5 Mon Sep 17 00:00:00 2001 From: Chinesezjc Date: Thu, 30 Jul 2026 22:00:35 +0800 Subject: [PATCH 055/139] fix(fs): persist read window offset in the read card meta An empty read window (byte cap below the first selected line: `lines: []` with `totalLines > 0`) dropped `offset` from the persisted presentation meta, so a replayed read card could not report where the window starts or where a continuation resumes. Carry `offset` on `FsReadMeta`, `ReadResultView`, and the `presentationMeta` projection, and validate it in `readMetaFromMeta` (1-based integer; the first line number may not fall below it). Re-record the ACP fixtures and the cordis api catalog. Also correct the Note's `parallel-file-reads` golden path (examples/tui-agent -> apps/cli) and record the pre-card replay-degradation tradeoff in the Decision section. --- .../2026-07-30-web-read-card.i18n.yaml | 4 ++-- .../feature/2026-07-30-web-read-card.md | 6 ++--- .../feature/2026-07-30-web-read-card.zh.md | 6 ++--- .../cordis-inspect-jsdoc/session.jsonl | 2 +- .../tests/snapshots/fs-edit/session.jsonl | 2 +- .../snapshots/fs-policy-reject/session.jsonl | 2 +- .../snapshots/fs-read-window/session.jsonl | 2 +- .../tests/snapshots/fs-read/session.jsonl | 2 +- .../fs-write-overwrite/session.jsonl | 2 +- .../parallel-tool-calls/session.jsonl | 4 ++-- .../snapshots/workspace-context/session.jsonl | 4 ++-- .../snapshots/workspace-edit/session.jsonl | 2 +- .../cordis/tool-cordis/src/api-catalog.ts | 2 +- packages/core/tools/README.i18n.yaml | 4 ++-- packages/core/tools/README.md | 2 +- packages/core/tools/README.zh.md | 2 +- packages/core/tools/src/presentation.ts | 6 +++++ packages/fs/tool-fs/README.i18n.yaml | 4 ++-- packages/fs/tool-fs/README.md | 2 +- packages/fs/tool-fs/README.zh.md | 2 +- packages/fs/tool-fs/src/read-render.ts | 20 +++++++++------- packages/fs/tool-fs/src/read.ts | 2 ++ packages/fs/tool-fs/tests/read-render.spec.ts | 23 ++++++++++++++++--- packages/fs/tool-fs/tests/tools.spec.ts | 10 +++++--- 24 files changed, 75 insertions(+), 42 deletions(-) diff --git a/.agents/notes/implemented/feature/2026-07-30-web-read-card.i18n.yaml b/.agents/notes/implemented/feature/2026-07-30-web-read-card.i18n.yaml index 8371d33560..e0d55b7496 100644 --- a/.agents/notes/implemented/feature/2026-07-30-web-read-card.i18n.yaml +++ b/.agents/notes/implemented/feature/2026-07-30-web-read-card.i18n.yaml @@ -2,5 +2,5 @@ # side as of the last confirmed-consistent state. Both languages carry equal authority; # after editing either side, bring the other along and re-record with: # pnpm run verify-translation-pairing --write .agents/notes/implemented/feature/2026-07-30-web-read-card.md -2026-07-30-web-read-card.md: 7d517beb359eec17948ea312b0478604cf92a49b -2026-07-30-web-read-card.zh.md: bfcc17e782a6a1caf0f775875264839af357be0d +2026-07-30-web-read-card.md: 509fc866737be6f9f05a02aed02324f3a337e936 +2026-07-30-web-read-card.zh.md: aec170fd2180af58102d8079118339cdef55a4c4 diff --git a/.agents/notes/implemented/feature/2026-07-30-web-read-card.md b/.agents/notes/implemented/feature/2026-07-30-web-read-card.md index 7d517beb35..509fc86673 100644 --- a/.agents/notes/implemented/feature/2026-07-30-web-read-card.md +++ b/.agents/notes/implemented/feature/2026-07-30-web-read-card.md @@ -14,9 +14,9 @@ The structured data cannot be recovered downstream. A tool result on the wire ca Add a fourth `card` tag, `read`, to the [render-intent union](../architecture/2026-07-02-tool-render-intent-union.md) — result-side only. `ToolResultView` gains `ReadResultView { card: 'read'; title?; path; lines: ReadFileLine[]; totalLines; lang?; content? }`; `ReadFileLine { number; text }` is the shared line unit. `ToolCallView` is untouched: the pending state stays a `GenericCallView` (`kind: 'read'`) because a call carries no file content until `execute` returns, so there is nothing structured to show at call time. This diverges from the bash terminal card, which tags both sides — a terminal call already carries its command and cwd at call time, a read call carries neither content nor total, so tagging the call side would add an empty variant. -The read tool projects the structured window through `output.presentationMeta`, the same persisted channel write/edit use for their applied-diff hunks ([canonical tool output contract](../architecture/2026-07-20-canonical-tool-output-contract.md)). `presentationMeta` runs once for a top-level surface call, returns `{ path, lines, totalLines, lang? }` as JSON the session validates and stores on the result's `meta`, and `presentResult` narrows that meta back into the `ReadResultView` on both live and replay paths. Without this channel the line array and total would be unreachable: the raw output object is not on the wire, and re-parsing the `N: text` text is lossy and fragile against the truncation footer. +The read tool projects the structured window through `output.presentationMeta`, the same persisted channel write/edit use for their applied-diff hunks ([canonical tool output contract](../architecture/2026-07-20-canonical-tool-output-contract.md)). `presentationMeta` runs once for a top-level surface call, returns `{ path, offset, lines, totalLines, lang? }` as JSON the session validates and stores on the result's `meta`, and `presentResult` narrows that meta back into the `ReadResultView` on both live and replay paths. `offset` (the 1-based first line the window requested) rides along because a byte cap below the first selected line yields an empty `lines` array with a positive `totalLines`; without the persisted `offset` a replayed card of such a window could not report where it starts or where a continuation resumes, and the last-line and re-parse fallbacks are both lossy. Without this channel the line array and total would be unreachable: the raw output object is not on the wire, and re-parsing the `N: text` text is lossy and fragile against the truncation footer. -`presentResult` returns `undefined` — the generic fallback — whenever the meta is absent or malformed (`readMetaFromMeta` narrows it defensively, so a replay of an older logged result never throws), whenever the result is an error, and whenever the single text block is not the read envelope. On the success path it carries `content` (the envelope-stripped text) alongside the structured fields, so a UI without the read capability, including the current TUI, renders the file text through the generic/default card arm exactly as before. The TUI's `renderBody` switch (`packages/ui/tui/src/components/transcript.ts`) is not `assertNever`-exhaustive: `terminal` and `diff` have arms and everything else falls through to the generic arm, which reads `view.content`. That default arm alone was not enough: `render()` sets `genericContent` — and with it the dim-Markdown `dimBody` treatment — on a separate gate that was `card === 'generic'` only, so a `read` card would have kept the text but lost its dim styling. The gate now admits `card: 'read'` too, taking `content` down the same dim-Markdown path, so a read renders in the TUI exactly as it did before the read card existed. Beyond that one gate the TUI needs no read-specific code. +`presentResult` returns `undefined` — the generic fallback — whenever the meta is absent or malformed (`readMetaFromMeta` narrows it defensively, so a replay of an older logged result never throws), whenever the result is an error, and whenever the single text block is not the read envelope. A pre-card logged result — a valid read envelope with no persisted `meta`, recorded before this card existed — takes that same `undefined` path deliberately: the client falls back to the raw `result.content`, so it shows the enveloped `//` text rather than the envelope-stripped generic card the old presenter returned. This is the accepted degradation under the [pre-release stance](../../../CLAUDE.md): reject the old on-disk format rather than add an envelope-stripping compatibility branch, since this PR re-records every published fixture and the session format promises no backward compatibility. On the success path `presentResult` carries `content` (the envelope-stripped text) alongside the structured fields, so a UI without the read capability, including the current TUI, renders the file text through the generic/default card arm exactly as before. The TUI's `renderBody` switch (`packages/ui/tui/src/components/transcript.ts`) is not `assertNever`-exhaustive: `terminal` and `diff` have arms and everything else falls through to the generic arm, which reads `view.content`. That default arm alone was not enough: `render()` sets `genericContent` — and with it the dim-Markdown `dimBody` treatment — on a separate gate that was `card === 'generic'` only, so a `read` card would have kept the text but lost its dim styling. The gate now admits `card: 'read'` too, taking `content` down the same dim-Markdown path, so a read renders in the TUI exactly as it did before the read card existed. Beyond that one gate the TUI needs no read-specific code. ### Language hint derivation @@ -40,7 +40,7 @@ The read tool now computes `presentationMeta` for every top-level read, a small ## Testing -`packages/fs/tool-fs/tests/read-render.spec.ts` unit-tests `langFromPath` (known extensions case-insensitively, extension read after the last segment and last dot, and the `undefined` cases: dotfile, extensionless, trailing dot, unknown) and `readMetaFromMeta` (a well-formed narrow with and without `lang`, and every rejection: non-object, array, missing or wrong-typed `path`/`totalLines`/`lines`, a malformed line entry, a non-string `lang`, and — because the function narrows the opaque persisted `meta` boundary — the semantically invalid paths a well-typed replayed JSON can still carry: a line `number` that is not a 1-based integer (`0`, `1.5`, `NaN`, `Infinity`), a `totalLines` that is not a non-negative integer (`-1`, `1.5`, `NaN`), and lines whose numbers duplicate, decrease, or exceed `totalLines`). `packages/fs/tool-fs/tests/tools.spec.ts` pins the tool wiring: `execute` attaches the structured window (with and without a `lang` hint) as `meta`, `presentResult` narrows it into a `card: 'read'` view carrying the envelope-stripped `content`, and the decline paths (error result, non-single-text content, malformed envelope with valid meta, and valid envelope with absent or malformed meta) all fall back to `undefined`. Both changed source files hold per-file 100% coverage. This PR carries the snapshot evidence for the persisted meta and the extended union, not for a new rendered view: the re-recorded ACP session fixtures (`fs-read`, `fs-read-window`, `fs-edit`, `fs-policy-reject`, `fs-write-overwrite`, `parallel-tool-calls`, `workspace-context`, `workspace-edit`) pin the persisted read `meta` (with `{{cwd}}`-tokenized paths), and `cordis-inspect-jsdoc` pins the four-member `ToolResultView` union. The keyless snapshot and assembled-application transcript for the rendered read card belong to the follow-up Web PR that consumes the view, since this PR adds no new product-user-visible rendering — the TUI routes the read card through its existing generic dim-Markdown fallback (`transcript.ts` treats `card: 'read'` like `card: 'generic'`), so its output is unchanged. The `apps/cli` `parallel-file-reads` terminal golden (`examples/tui-agent/tests/snapshots/parallel-file-reads/terminal.expected.txt`) pins exactly that: a real replay executes the read tool, renders it through the new `card: 'read'` gate, and the golden's dim-Markdown rows are byte-for-byte what a generic read produced before this card existed. +`packages/fs/tool-fs/tests/read-render.spec.ts` unit-tests `langFromPath` (known extensions case-insensitively, extension read after the last segment and last dot, and the `undefined` cases: dotfile, extensionless, trailing dot, unknown) and `readMetaFromMeta` (a well-formed narrow with and without `lang`, and every rejection: non-object, array, missing or wrong-typed `path`/`totalLines`/`lines`, a malformed line entry, a non-string `lang`, and — because the function narrows the opaque persisted `meta` boundary — the semantically invalid paths a well-typed replayed JSON can still carry: an `offset` that is not a 1-based integer, a first line `number` below `offset`, a line `number` that is not a 1-based integer (`0`, `1.5`, `NaN`, `Infinity`), a `totalLines` that is not a non-negative integer (`-1`, `1.5`, `NaN`), and lines whose numbers duplicate, decrease, or exceed `totalLines`; it also narrows an empty window at a positive `offset` (a byte cap below the first selected line). `packages/fs/tool-fs/tests/tools.spec.ts` pins the tool wiring: `execute` attaches the structured window (with and without a `lang` hint) as `meta`, `presentResult` narrows it into a `card: 'read'` view carrying the envelope-stripped `content`, and the decline paths (error result, non-single-text content, malformed envelope with valid meta, and valid envelope with absent or malformed meta) all fall back to `undefined`. Both changed source files hold per-file 100% coverage. This PR carries the snapshot evidence for the persisted meta and the extended union, not for a new rendered view: the re-recorded ACP session fixtures (`fs-read`, `fs-read-window`, `fs-edit`, `fs-policy-reject`, `fs-write-overwrite`, `parallel-tool-calls`, `workspace-context`, `workspace-edit`) pin the persisted read `meta` (with `{{cwd}}`-tokenized paths), and `cordis-inspect-jsdoc` pins the four-member `ToolResultView` union. The keyless snapshot and assembled-application transcript for the rendered read card belong to the follow-up Web PR that consumes the view, since this PR adds no new product-user-visible rendering — the TUI routes the read card through its existing generic dim-Markdown fallback (`transcript.ts` treats `card: 'read'` like `card: 'generic'`), so its output is unchanged. The `apps/cli` `parallel-file-reads` terminal golden (`apps/cli/tests/snapshots/parallel-file-reads/terminal.expected.txt`) pins exactly that: a real replay executes the read tool, renders it through the new `card: 'read'` gate, and the golden's dim-Markdown rows are byte-for-byte what a generic read produced before this card existed. ## Related diff --git a/.agents/notes/implemented/feature/2026-07-30-web-read-card.zh.md b/.agents/notes/implemented/feature/2026-07-30-web-read-card.zh.md index bfcc17e782..aec170fd21 100644 --- a/.agents/notes/implemented/feature/2026-07-30-web-read-card.zh.md +++ b/.agents/notes/implemented/feature/2026-07-30-web-read-card.zh.md @@ -14,9 +14,9 @@ Status: implemented 给[渲染意图 union](../architecture/2026-07-02-tool-render-intent-union.md) 新增第四个 `card` 标签 `read`——仅在结果侧。`ToolResultView` 增加 `ReadResultView { card: 'read'; title?; path; lines: ReadFileLine[]; totalLines; lang?; content? }`;`ReadFileLine { number; text }` 是共享的行单元。`ToolCallView` 不动:待定状态仍是 `GenericCallView`(`kind: 'read'`),因为一次调用在 `execute` 返回前不携带文件内容,调用时没有可展示的结构。这与 bash 终端 card 不同——终端 card 两侧都打标签,因为终端调用在调用时已携带命令和 cwd,而 read 调用既无内容也无总数,给调用侧打标签只会新增一个空变体。 -read 工具通过 `output.presentationMeta` 投影结构化窗口,这与 write/edit 用来投影其应用 diff hunk 的持久化通道相同([规范化工具输出契约](../architecture/2026-07-20-canonical-tool-output-contract.md))。`presentationMeta` 对一次顶层 surface 调用运行一次,返回 `{ path, lines, totalLines, lang? }` 作为会话校验并存储在结果 `meta` 上的 JSON,`presentResult` 在 live 和回放路径上都把该 meta 收窄回 `ReadResultView`。没有这个通道,行数组和总数就无法触及:原始输出对象不在线上,而重新解析 `N: text` 文本既有损又对截断脚注脆弱。 +read 工具通过 `output.presentationMeta` 投影结构化窗口,这与 write/edit 用来投影其应用 diff hunk 的持久化通道相同([规范化工具输出契约](../architecture/2026-07-20-canonical-tool-output-contract.md))。`presentationMeta` 对一次顶层 surface 调用运行一次,返回 `{ path, offset, lines, totalLines, lang? }` 作为会话校验并存储在结果 `meta` 上的 JSON,`presentResult` 在 live 和回放路径上都把该 meta 收窄回 `ReadResultView`。`offset`(窗口请求的 1-based 起始行)一并携带,是因为当字节上限低于首个选中行时,窗口会返回空的 `lines` 数组而 `totalLines` 为正;没有持久化的 `offset`,这类窗口的回放 card 就无法报告它从哪行开始、或续读应从哪行继续,而末行推断与文本重解析两种兜底都有损。没有这个通道,行数组和总数就无法触及:原始输出对象不在线上,而重新解析 `N: text` 文本既有损又对截断脚注脆弱。 -`presentResult` 在以下情况返回 `undefined`——即 generic 回退:meta 缺失或畸形(`readMetaFromMeta` 防御性收窄它,因此回放旧的已记录结果永不抛错)、结果是错误、以及单个文本块不是 read 信封。在成功路径上,它在结构化字段之外携带 `content`(剥信封后的文本),因此不具备 read 能力的 UI(包括当前的 TUI)通过 generic/default card 分支渲染文件文本,与之前完全一致。TUI 的 `renderBody` switch(`packages/ui/tui/src/components/transcript.ts`)不是 `assertNever` 穷尽的:`terminal` 和 `diff` 有分支,其余都落入 generic 分支,该分支读取 `view.content`。仅有该默认分支还不够:`render()` 在一个独立门控上设置 `genericContent`(连同 dim-Markdown 的 `dimBody` 处理),该门控原先只判 `card === 'generic'`,因此 `read` card 虽保留文本却会丢失 dim 样式。现在该门控也接纳 `card: 'read'`,让 `content` 走同一条 dim-Markdown 路径,因此 read 在 TUI 中的渲染与 read card 出现之前完全一致。除这一处门控外,TUI 无需 read 专属代码。 +`presentResult` 在以下情况返回 `undefined`——即 generic 回退:meta 缺失或畸形(`readMetaFromMeta` 防御性收窄它,因此回放旧的已记录结果永不抛错)、结果是错误、以及单个文本块不是 read 信封。本 card 出现之前记录的结果——信封合法但无持久化 `meta`——有意走同一条 `undefined` 路径:客户端回退到原始 `result.content`,因此显示带 `//` 信封的原文,而非旧展示器返回的剥信封 generic card。这是 [pre-release 立场](../../../CLAUDE.md)下接受的降级:拒绝旧的磁盘格式,而非加一个剥信封的兼容分支——本 PR 已重录全部已发布 fixtures,且 session 格式不承诺向后兼容。在成功路径上,`presentResult` 在结构化字段之外携带 `content`(剥信封后的文本),因此不具备 read 能力的 UI(包括当前的 TUI)通过 generic/default card 分支渲染文件文本,与之前完全一致。TUI 的 `renderBody` switch(`packages/ui/tui/src/components/transcript.ts`)不是 `assertNever` 穷尽的:`terminal` 和 `diff` 有分支,其余都落入 generic 分支,该分支读取 `view.content`。仅有该默认分支还不够:`render()` 在一个独立门控上设置 `genericContent`(连同 dim-Markdown 的 `dimBody` 处理),该门控原先只判 `card === 'generic'`,因此 `read` card 虽保留文本却会丢失 dim 样式。现在该门控也接纳 `card: 'read'`,让 `content` 走同一条 dim-Markdown 路径,因此 read 在 TUI 中的渲染与 read card 出现之前完全一致。除这一处门控外,TUI 无需 read 专属代码。 ### 语言提示推导 @@ -40,7 +40,7 @@ read 工具现在为每次顶层 read 计算 `presentationMeta`,这是对已 ## Testing -`packages/fs/tool-fs/tests/read-render.spec.ts` 单测 `langFromPath`(已知扩展名的大小写不敏感、扩展名在最后一段与最后一个点之后读取、以及 `undefined` 各情况:dotfile、无扩展名、结尾的点、未知)与 `readMetaFromMeta`(含与不含 `lang` 的良构收窄,以及每种拒绝:非对象、数组、缺失或类型错误的 `path`/`totalLines`/`lines`、畸形行项、非字符串 `lang`,以及——因为该函数收窄持久化的 opaque `meta` 边界——良构类型的回放 JSON 仍可能携带的语义无效路径:不是 1-based 整数的行 `number`(`0`、`1.5`、`NaN`、`Infinity`)、不是非负整数的 `totalLines`(`-1`、`1.5`、`NaN`)、以及行号重复、递减或超过 `totalLines` 的情况)。`packages/fs/tool-fs/tests/tools.spec.ts` 固定工具接线:`execute` 把结构化窗口(含与不含 `lang` 提示)作为 `meta` 附上、`presentResult` 把它收窄为携带剥信封 `content` 的 `card: 'read'` 视图、以及各拒绝路径(错误结果、非单文本内容、meta 有效但信封畸形、信封有效但 meta 缺失或畸形)都回退到 `undefined`。两个改动的源文件保持逐文件 100% 覆盖率。本 PR 携带的是持久化 meta 与扩展后联合类型的快照证据,而非新渲染视图的证据:重录的 ACP session fixtures(`fs-read`、`fs-read-window`、`fs-edit`、`fs-policy-reject`、`fs-write-overwrite`、`parallel-tool-calls`、`workspace-context`、`workspace-edit`)钉住持久化的读取 `meta`(含 `{{cwd}}` 令牌化路径),`cordis-inspect-jsdoc` 钉住四成员的 `ToolResultView` 联合类型。已渲染读取 card 的 keyless 快照与组装应用 transcript 属于消费该视图的后续 Web PR,因为本 PR 不新增任何面向产品用户可见的渲染——TUI 通过其现有的通用 dim-Markdown 回退路由读取 card(`transcript.ts` 把 `card: 'read'` 当作 `card: 'generic'` 处理),因此其输出保持不变。`apps/cli` 的 `parallel-file-reads` 终端 golden(`examples/tui-agent/tests/snapshots/parallel-file-reads/terminal.expected.txt`)正钉住这一点:一次真实回放执行 read 工具、经新的 `card: 'read'` 门渲染,golden 的 dim-Markdown 行与本 card 出现前 generic read 所产出的逐字节一致。 +`packages/fs/tool-fs/tests/read-render.spec.ts` 单测 `langFromPath`(已知扩展名的大小写不敏感、扩展名在最后一段与最后一个点之后读取、以及 `undefined` 各情况:dotfile、无扩展名、结尾的点、未知)与 `readMetaFromMeta`(含与不含 `lang` 的良构收窄,以及每种拒绝:非对象、数组、缺失或类型错误的 `path`/`totalLines`/`lines`、畸形行项、非字符串 `lang`,以及——因为该函数收窄持久化的 opaque `meta` 边界——良构类型的回放 JSON 仍可能携带的语义无效路径:不是 1-based 整数的 `offset`、小于 `offset` 的首行 `number`、不是 1-based 整数的行 `number`(`0`、`1.5`、`NaN`、`Infinity`)、不是非负整数的 `totalLines`(`-1`、`1.5`、`NaN`)、以及行号重复、递减或超过 `totalLines` 的情况;并且收窄正 `offset` 处的空窗口(字节上限低于首个选中行))。`packages/fs/tool-fs/tests/tools.spec.ts` 固定工具接线:`execute` 把结构化窗口(含与不含 `lang` 提示)作为 `meta` 附上、`presentResult` 把它收窄为携带剥信封 `content` 的 `card: 'read'` 视图、以及各拒绝路径(错误结果、非单文本内容、meta 有效但信封畸形、信封有效但 meta 缺失或畸形)都回退到 `undefined`。两个改动的源文件保持逐文件 100% 覆盖率。本 PR 携带的是持久化 meta 与扩展后联合类型的快照证据,而非新渲染视图的证据:重录的 ACP session fixtures(`fs-read`、`fs-read-window`、`fs-edit`、`fs-policy-reject`、`fs-write-overwrite`、`parallel-tool-calls`、`workspace-context`、`workspace-edit`)钉住持久化的读取 `meta`(含 `{{cwd}}` 令牌化路径),`cordis-inspect-jsdoc` 钉住四成员的 `ToolResultView` 联合类型。已渲染读取 card 的 keyless 快照与组装应用 transcript 属于消费该视图的后续 Web PR,因为本 PR 不新增任何面向产品用户可见的渲染——TUI 通过其现有的通用 dim-Markdown 回退路由读取 card(`transcript.ts` 把 `card: 'read'` 当作 `card: 'generic'` 处理),因此其输出保持不变。`apps/cli` 的 `parallel-file-reads` 终端 golden(`apps/cli/tests/snapshots/parallel-file-reads/terminal.expected.txt`)正钉住这一点:一次真实回放执行 read 工具、经新的 `card: 'read'` 门渲染,golden 的 dim-Markdown 行与本 card 出现前 generic read 所产出的逐字节一致。 ## Related diff --git a/examples/acp-agent/tests/snapshots/cordis-inspect-jsdoc/session.jsonl b/examples/acp-agent/tests/snapshots/cordis-inspect-jsdoc/session.jsonl index ab56849352..7ff3d39c09 100644 --- a/examples/acp-agent/tests/snapshots/cordis-inspect-jsdoc/session.jsonl +++ b/examples/acp-agent/tests/snapshots/cordis-inspect-jsdoc/session.jsonl @@ -11,7 +11,7 @@ {"type":"assistant/chunk","seq":9,"time":1783951000009,"data":{"turn":1,"step":1,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}} {"type":"assistant/message","seq":10,"time":1784449176722,"data":{"turn":1,"step":1,"message":{"role":"assistant","content":[{"type":"tool-call","id":"inspect-tools-api","name":"cordis_inspect","arguments":"{\"what\":\"api\",\"name\":\"tools\"}"}],"source":{"kind":"model","provider":"deepseek","model":"deepseek-v4-flash"},"id":"1ac37046-d1c0-4ef6-9ea9-963e4b46d1cf"},"usage":{"inputTokens":3,"outputTokens":3}},"sourceEventSeqs":[5,6,7,8,9],"surfaceOp":"append"} {"type":"tool/call","seq":11,"time":1784449176722,"data":{"turn":1,"step":1,"callId":"inspect-tools-api","name":"cordis_inspect","arguments":"{\"what\":\"api\",\"name\":\"tools\"}"}} -{"type":"tool/result","seq":12,"time":1784449176732,"data":{"turn":1,"step":1,"message":{"source":{"kind":"tool","callId":"inspect-tools-api"},"content":[{"type":"tool-result","toolCallId":"inspect-tools-api","content":[{"type":"text","text":"## api\n- tools — Tool registry and execution pipeline.\n /**\n * Register globally or in the calling agent scope. Scoped tools shadow\n * globals; duplicates within one layer and the reserved `run_code` name fail.\n * @param definition - tool schema, execution, and optional finalization/presentation callbacks.\n * @returns the exact disposer that unregisters the tool.\n */\n register(definition: ToolDefinition): () => void\n /**\n * Restrict global tools for the calling agent scope. Empty filters, unknown\n * names, scope-local names, and reserved transport names fail. Restrictions\n * intersect; scoped registrations remain visible.\n * @param filter - global-surface mask: `allow` (keep only) and/or `deny` (remove).\n * @returns the exact disposer that lifts this restriction.\n */\n restrict(filter: ToolRestriction): () => void\n /**\n * Register a monotonic guard after the extensible `tools/pre-execute`\n * waterfall. A plain-context guard applies globally; one registered through\n * `agent.ctx` applies only to that agent. Any matching guard may deny by\n * returning a reason, while no guard can force-allow a call another guard\n * denied. The exact effect disposer is returned for ordered ownership and\n * HMR cleanup.\n * @param guard - synchronous check; a returned string denies the execution.\n * @returns the exact disposer that unregisters the guard.\n */\n guard(guard: ToolGuard): () => void\n /**\n * Look up a tool as one scope sees it (scoped\n * shadows global; a restricted-away global reads as absent). Presenters pass\n * the calling agent so the rendered card matches the definition that\n * actually executed.\n * @param name - the tool name as registered.\n * @param scope - the viewing scope (the agent); omitted = the global view.\n * @returns the definition the scope resolves, or undefined when none is visible.\n */\n get(name: string, scope?: ScopeKey): ToolDefinition | undefined\n /**\n * Project visible definitions onto the allowlisted model-facing schema fields,\n * excluding execution and presentation callbacks.\n * @param scope - the viewing scope (the agent); omitted = the global view.\n * @returns one deep-cloned schema per visible tool.\n */\n schemas(scope?: ScopeKey): ToolSchema[]\n /**\n * Classify a pending call through the caller's visible tool definition. Only\n * an exact `true` is parallel; unknown, hidden, undeclared, invalid, or\n * throwing classifiers are exclusive.\n * @param exec - call name, parsed arguments, and optional agent scope.\n * @returns the fail-closed scheduling mode.\n */\n executionMode(exec: ToolExecutionInput): ToolExecutionMode\n /**\n * Execute through pre-policy, guards, around-dispatch, post-policy,\n * definition-owned content finalization, and final notification. Tool and\n * listener failures resolve as materialized error results; an invisible tool\n * reports `UNKNOWN_TOOL`. The returned outcome is the same lossless, frozen\n * snapshot final observers receive. Cancellation\n * arriving after entry and before final result materialization skips a\n * not-yet-started body with `ABORTED_BEFORE_DISPATCH` or replaces a\n * successful started outcome with `ABORTED`; already-started work is still\n * drained and may retain a tool-owned structured error.\n * @param exec - the typed same-process call input. The registry assigns its\n * correlation token before policy begins.\n * @returns the materialized final result.\n */\n async execute(exec: ToolExecutionInput): Promise\ntype shapes (referenced by the signatures above — read these before assuming a field is a string):\n export interface Agent {\n readonly id: SessionId;\n readonly options: AgentOptions;\n readonly session: Session;\n readonly status: AgentStatus;\n readonly acceptsNextStep: boolean;\n readonly ctx: Context;\n send(message: UserMessage, options: SendOptions): void;\n updateInbox(id: InboxItemId, action: InboxAction): InboxActionResult;\n cancel(cause: AgentCancelCause, options?: CancelOptions): void;\n whenIdle(): Promise;\n followup(message: UserMessage): void;\n steer(message: UserMessage): void;\n inject(message: UserMessage): void;\n }\n export type AgentCancelCause = {\n readonly kind: 'user';\n } | {\n readonly kind: 'parent';\n };\n export interface AgentOptions {\n provider?: string;\n model?: string;\n maxTokens?: number;\n }\n export type AgentStatus = 'idle' | 'running';\n export interface AssistantMessage extends Message {\n readonly role: 'assistant';\n readonly source: ModelMessageSource;\n }\n export interface AssistantProvenance {\n provider: string;\n model: string;\n replayState?: unknown;\n }\n export type Branded = string & {\n readonly [BRAND]: B;\n };\n export type CallId = Branded<'CallId'>;\n export interface CancelOptions {\n keepInbox?: boolean;\n }\n export interface ContentBlockMap {\n 'text': TextBlock;\n 'reasoning': ReasoningBlock;\n 'tool-call': ToolCallBlock;\n 'tool-result': ToolResultBlock;\n }\n export type ContentBlockType = keyof ContentBlockMap;\n export interface DiffCallView {\n card: 'diff';\n title: string;\n diffs: FileDiff[];\n locations?: FileLocation[];\n }\n export interface DiffResultView {\n card: 'diff';\n title?: string;\n diffs: FileDiff[];\n }\n export interface EpochHeader {\n config: LlmCallConfig;\n system?: string;\n tools?: ToolSchema[];\n }\n export interface FileDiff {\n path: string;\n oldText: string | null;\n newText: string;\n }\n export interface FileLocation {\n path: string;\n line?: number;\n }\n export type FinishReason = FinishReasonMap[keyof FinishReasonMap];\n export interface FinishReasonMap {\n 'stop': {\n kind: 'stop';\n };\n 'tool-calls': {\n kind: 'tool-calls';\n };\n 'max-tokens': {\n kind: 'max-tokens';\n };\n 'aborted': {\n kind: 'aborted';\n failure: LlmFailure;\n };\n 'error': {\n kind: 'error';\n failure: LlmFailure;\n };\n }\n export interface GenericCallView {\n card: 'generic';\n title: string;\n kind?: ToolCallKind;\n rawInput?: unknown;\n content?: ContentBlock[];\n locations?: FileLocation[];\n }\n export interface GenericResultView {\n card: 'generic';\n title?: string;\n content?: ContentBlock[];\n }\n export type InboxAction = {\n readonly kind: 'edit';\n readonly content: ContentBlock[];\n } | {\n readonly kind: 'remove';\n };\n export type InboxActionResult = 'applied' | 'not-found';\n export type InboxItemId = Branded<'InboxItemId'>;\n export interface JsonSchemaNode {\n type?: JsonSchemaType;\n oneOf?: JsonSchemaNode[];\n properties?: Record;\n required?: string[];\n additionalProperties?: boolean;\n items?: JsonSchemaNode;\n enum?: JsonSchemaScalar[];\n const?: JsonSchemaScalar;\n description?: string;\n title?: string;\n default?: JsonValue;\n examples?: JsonValue;\n }\n export type JsonSchemaScalar = string | number | boolean | null;\n export type JsonSchemaType = 'object' | 'array' | 'string' | 'number' | 'integer' | 'boolean' | 'null';\n export type JsonValue = null | boolean | number | string | JsonValue[] | {\n [key: string]: JsonValue;\n };\n export interface LlmCallConfig {\n provider: string;\n model: string;\n reasoningEffort?: ReasoningEffortId;\n temperature?: number;\n maxTokens?: number;\n stop?: string[];\n }\n export interface LlmFailure {\n readonly message: string;\n readonly code: string;\n readonly status?: number;\n readonly providerRetryAfterMs?: number;\n readonly requestId?: ProviderRequestId;\n }\n export interface Message {\n readonly id: MessageId;\n readonly role: 'system' | 'user' | 'assistant';\n readonly content: ContentBlock[];\n readonly source: MessageSource;\n }\n export type MessageId = Branded<'MessageId'>;\n export type MessageSource = MessageSourceMap[keyof MessageSourceMap];\n export interface MessageSourceMap {\n user: {\n kind: 'user';\n };\n plugin: {\n kind: 'plugin';\n plugin: string;\n };\n model: ModelMessageSource;\n tool: ToolMessageSource;\n }\n export interface ModelMessageSource extends AssistantProvenance {\n kind: 'model';\n }\n export type ProviderRequestId = Branded<'ProviderRequestId'>;\n export interface ReadFileLine {\n number: number;\n text: string;\n }\n export interface ReadResultView {\n card: 'read';\n title?: string;\n path: string;\n lines: ReadFileLine[];\n totalLines: number;\n lang?: string;\n content?: ContentBlock[];\n }\n export interface ReasoningBlock {\n type: 'reasoning';\n text: string;\n }\n export type ReasoningEffortId = Branded<'ReasoningEffortId'>;\n export type RequestHeaderReason = 'initial' | 'resume' | 'change';\n export type ScopeKey = object;\n export interface SendOptions {\n target: SendTarget;\n wakeup: boolean;\n }\n export type SendTarget = 'next-turn' | 'next-step';\n export class Session {\n get surface(): SessionSurface;\n readonly header: SessionHeader;\n get id(): SessionId;\n readonly firstLiveSeq: number;\n constructor(id: SessionId, seed?: readonly SessionEvent[], header?: SessionHeader);\n get events(): readonly SessionEvent[];\n get seq(): number;\n append(type: T, data: SessionEventMap[T], ...opts: T extends SurfaceEventType ? [\n opts: SurfaceIntent\n ] : [\n ]): SessionEvent;\n requestHeader(): EpochHeader | undefined;\n deriveMessages(): Message[];\n deriveEventMessage(event: SessionEvent): Message | null;\n }\n export type SessionEvent = {\n [K in SessionEventType]: {\n type: K;\n seq: number;\n time: number;\n data: SessionEventMap[K];\n } & (K extends SurfaceEventType ? {\n sourceEventSeqs?: number[];\n surfaceOp?: SurfaceOp;\n } : object);\n }[T];\n export interface SessionEventMap {\n 'turn/start': {\n turn: number;\n trigger: TurnTrigger;\n };\n 'turn/end': {\n turn: number;\n reason: TurnEndReason;\n };\n 'step/start': {\n turn: number;\n step: number;\n };\n 'step/end': {\n turn: number;\n step: number;\n };\n 'user/message': UserMessage;\n 'assistant/chunk': {\n turn: number;\n step: number;\n chunk: StreamChunk;\n };\n 'assistant/message': {\n turn: number;\n step: number;\n message: AssistantMessage;\n usage?: TokenUsage;\n };\n 'tool/call': {\n turn: number;\n step: number;\n callId: CallId;\n name: string;\n arguments: string;\n };\n 'tool/result': {\n turn: number;\n step: number;\n message: ToolResultMessage;\n error?: {\n name: string;\n code: string;\n };\n meta?: JsonValue;\n };\n 'steering/message': {\n turn: number;\n message: UserMessage;\n };\n 'todo/write': {\n todos: TodoItem[];\n };\n 'request/header': {\n header: EpochHeader;\n reason: RequestHeaderReason;\n };\n 'session/end-seed': Record;\n }\n export type SessionEventType = keyof SessionEventMap;\n export interface SessionHeader {\n readonly version: number;\n readonly id: SessionId;\n readonly createdAt: number;\n readonly cwd?: string;\n readonly parentSession?: SessionId;\n readonly seedLength?: number;\n readonly delegationDepth?: number;\n }\n export type SessionId = Branded<'SessionId'>;\n export interface SessionSurface {\n readonly nodes: readonly number[];\n readonly replaceGeneration: number;\n }\n export type StreamChunk = {\n type: 'block-start';\n index: number;\n blockType: ContentBlockType;\n } | {\n type: 'text-delta';\n index: number;\n text: string;\n } | {\n type: 'reasoning-delta';\n index: number;\n text: string;\n } | {\n type: 'tool-call-delta';\n index: number;\n id: CallId;\n name?: string;\n argumentsDelta: string;\n } | {\n type: 'block-end';\n index: number;\n block: ContentBlock;\n } | {\n type: 'usage';\n usage: TokenUsage;\n } | {\n type: 'finish';\n reason: FinishReason;\n replayState?: unknown;\n };\n export type SurfaceEventType = 'user/message' | 'assistant/message' | 'tool/result' | 'steering/message';\n export interface SurfaceIntent {\n surfaceOp: SurfaceOp;\n sourceEventSeqs?: number[];\n }\n export type SurfaceOp = 'append' | {\n op: 'replace';\n start: number;\n end: number;\n };\n export interface TerminalCallView {\n card: 'terminal';\n title: string;\n description?: string;\n cwd?: string;\n }\n export interface TerminalResultView {\n card: 'terminal';\n title?: string;\n output?: string;\n exitCode?: number;\n signal?: string;\n }\n export interface TodoItem {\n content: string;\n status: 'pending' | 'in_progress' | 'completed';\n }\n export interface TokenUsage {\n inputTokens: number;\n outputTokens: number;\n cacheReadTokens?: number;\n cacheWriteTokens?: number;\n reasoningTokens?: number;\n }\n export interface ToolCallBlock {\n type: 'tool-call';\n id: CallId;\n name: string;\n arguments: string;\n }\n export type ToolCallKind = 'read' | 'edit' | 'delete' | 'move' | 'search' | 'execute' | 'fetch' | 'other';\n export type ToolCallView = GenericCallView | TerminalCallView | DiffCallView;\n export interface ToolDefinition extends ToolSchema {\n readonly output: ToolOutputDefinition;\n execute(args: unknown, exec: ToolRunContext): Promise;\n finalizeContent?(exec: Readonly, result: Readonly): ContentBlock[] | undefined;\n timeoutMs?: number;\n isConcurrencySafe?(args: unknown): boolean;\n presentCall?(args: unknown): ToolCallView | undefined;\n presentResult?(args: unknown, result: ToolResult): ToolResultView | undefined;\n }\n export interface ToolErrorInfo {\n name: string;\n code: string;\n }\n export interface ToolExecution extends ToolExecutionInput {\n readonly token: ToolExecutionToken;\n }\n export interface ToolExecutionFailure {\n readonly isError: true;\n readonly error: ToolFailure;\n readonly value?: never;\n readonly content: ContentBlock[];\n readonly meta?: JsonValue;\n readonly additionalContexts?: UserMessage[];\n readonly concludesTurn?: never;\n }\n export interface ToolExecutionInput {\n readonly callId: CallId;\n readonly name: string;\n readonly arguments: unknown;\n readonly agent?: Agent;\n readonly parent?: ToolExecutionToken;\n readonly signal: AbortSignal;\n }\n export type ToolExecutionMode = {\n kind: 'parallel';\n } | {\n kind: 'exclusive';\n };\n export type ToolExecutionResult = ToolExecutionSuccess | ToolExecutionFailure;\n export interface ToolExecutionSuccess {\n readonly isError: false;\n readonly value: JsonValue;\n readonly content: ContentBlock[];\n readonly error?: never;\n readonly meta?: JsonValue;\n readonly additionalContexts?: UserMessage[];\n readonly concludesTurn?: true;\n }\n export type ToolExecutionToken = symbol & {\n readonly [toolExecutionTokenBrand]: true;\n };\n export interface ToolFailure {\n message: string;\n info?: ToolErrorInfo;\n }\n export type ToolGuard = (execution: Readonly) => string | undefined;\n export interface ToolMessageSource {\n kind: 'tool';\n callId: CallId;\n }\n export interface ToolOutputDefinition {\n readonly schema: JsonSchemaNode;\n render(args: unknown, value: JsonValue): ContentBlock[];\n presentationMeta?(args: unknown, value: JsonValue): JsonValue;\n }\n export interface ToolRestriction {\n readonly allow?: readonly string[];\n readonly deny?: readonly string[];\n }\n export interface ToolResult {\n content: ContentBlock[];\n isError: boolean;\n meta?: JsonValue;\n }\n export interface ToolResultBlock {\n type: 'tool-result';\n toolCallId: CallId;\n content: ContentBlock[];\n isError?: boolean;\n }\n export interface ToolResultMessage extends Message {\n readonly role: 'user';\n readonly content: [\n ToolResultBlock\n ];\n readonly source: ToolMessageSource;\n }\n export type ToolResultView = GenericResultView | TerminalResultView | DiffResultView | ReadResultView;\n export interface ToolRunContext extends ToolExecution {\n deferContext(context: UserMessage): void;\n concludeTurn(): void;\n }\n export interface ToolSchema {\n name: string;\n description: string;\n parameters: Record;\n }\n export type TurnEndReason = TurnEndReasonMap[keyof TurnEndReasonMap];\n export interface TurnEndReasonMap {\n completed: {\n kind: 'completed';\n };\n aborted: {\n kind: 'aborted';\n };\n error: {\n kind: 'error';\n step: number;\n } & ({\n failure: LlmFailure;\n message?: never;\n code?: never;\n } | {\n message: string;\n code?: string;\n failure?: never;\n });\n disposed: {\n kind: 'disposed';\n };\n 'max-tokens': {\n kind: 'max-tokens';\n };\n interrupted: {\n kind: 'interrupted';\n };\n }\n export type TurnTrigger = TurnTriggerMap[keyof TurnTriggerMap];\n export interface TurnTriggerMap {\n message: {\n kind: 'message';\n source: MessageSource;\n };\n retry: {\n kind: 'retry';\n };\n injection: {\n kind: 'injection';\n source: MessageSource;\n };\n }\n export interface UserMessage extends Message {\n readonly role: 'user';\n }"}],"isError":false}],"role":"user","id":"1c43b8df-aae8-42e7-8253-5b275edc09bc"}},"sourceEventSeqs":[11],"surfaceOp":"append"} +{"type":"tool/result","seq":12,"time":1784449176732,"data":{"turn":1,"step":1,"message":{"source":{"kind":"tool","callId":"inspect-tools-api"},"content":[{"type":"tool-result","toolCallId":"inspect-tools-api","content":[{"type":"text","text":"## api\n- tools — Tool registry and execution pipeline.\n /**\n * Register globally or in the calling agent scope. Scoped tools shadow\n * globals; duplicates within one layer and the reserved `run_code` name fail.\n * @param definition - tool schema, execution, and optional finalization/presentation callbacks.\n * @returns the exact disposer that unregisters the tool.\n */\n register(definition: ToolDefinition): () => void\n /**\n * Restrict global tools for the calling agent scope. Empty filters, unknown\n * names, scope-local names, and reserved transport names fail. Restrictions\n * intersect; scoped registrations remain visible.\n * @param filter - global-surface mask: `allow` (keep only) and/or `deny` (remove).\n * @returns the exact disposer that lifts this restriction.\n */\n restrict(filter: ToolRestriction): () => void\n /**\n * Register a monotonic guard after the extensible `tools/pre-execute`\n * waterfall. A plain-context guard applies globally; one registered through\n * `agent.ctx` applies only to that agent. Any matching guard may deny by\n * returning a reason, while no guard can force-allow a call another guard\n * denied. The exact effect disposer is returned for ordered ownership and\n * HMR cleanup.\n * @param guard - synchronous check; a returned string denies the execution.\n * @returns the exact disposer that unregisters the guard.\n */\n guard(guard: ToolGuard): () => void\n /**\n * Look up a tool as one scope sees it (scoped\n * shadows global; a restricted-away global reads as absent). Presenters pass\n * the calling agent so the rendered card matches the definition that\n * actually executed.\n * @param name - the tool name as registered.\n * @param scope - the viewing scope (the agent); omitted = the global view.\n * @returns the definition the scope resolves, or undefined when none is visible.\n */\n get(name: string, scope?: ScopeKey): ToolDefinition | undefined\n /**\n * Project visible definitions onto the allowlisted model-facing schema fields,\n * excluding execution and presentation callbacks.\n * @param scope - the viewing scope (the agent); omitted = the global view.\n * @returns one deep-cloned schema per visible tool.\n */\n schemas(scope?: ScopeKey): ToolSchema[]\n /**\n * Classify a pending call through the caller's visible tool definition. Only\n * an exact `true` is parallel; unknown, hidden, undeclared, invalid, or\n * throwing classifiers are exclusive.\n * @param exec - call name, parsed arguments, and optional agent scope.\n * @returns the fail-closed scheduling mode.\n */\n executionMode(exec: ToolExecutionInput): ToolExecutionMode\n /**\n * Execute through pre-policy, guards, around-dispatch, post-policy,\n * definition-owned content finalization, and final notification. Tool and\n * listener failures resolve as materialized error results; an invisible tool\n * reports `UNKNOWN_TOOL`. The returned outcome is the same lossless, frozen\n * snapshot final observers receive. Cancellation\n * arriving after entry and before final result materialization skips a\n * not-yet-started body with `ABORTED_BEFORE_DISPATCH` or replaces a\n * successful started outcome with `ABORTED`; already-started work is still\n * drained and may retain a tool-owned structured error.\n * @param exec - the typed same-process call input. The registry assigns its\n * correlation token before policy begins.\n * @returns the materialized final result.\n */\n async execute(exec: ToolExecutionInput): Promise\ntype shapes (referenced by the signatures above — read these before assuming a field is a string):\n export interface Agent {\n readonly id: SessionId;\n readonly options: AgentOptions;\n readonly session: Session;\n readonly status: AgentStatus;\n readonly acceptsNextStep: boolean;\n readonly ctx: Context;\n send(message: UserMessage, options: SendOptions): void;\n updateInbox(id: InboxItemId, action: InboxAction): InboxActionResult;\n cancel(cause: AgentCancelCause, options?: CancelOptions): void;\n whenIdle(): Promise;\n followup(message: UserMessage): void;\n steer(message: UserMessage): void;\n inject(message: UserMessage): void;\n }\n export type AgentCancelCause = {\n readonly kind: 'user';\n } | {\n readonly kind: 'parent';\n };\n export interface AgentOptions {\n provider?: string;\n model?: string;\n maxTokens?: number;\n }\n export type AgentStatus = 'idle' | 'running';\n export interface AssistantMessage extends Message {\n readonly role: 'assistant';\n readonly source: ModelMessageSource;\n }\n export interface AssistantProvenance {\n provider: string;\n model: string;\n replayState?: unknown;\n }\n export type Branded = string & {\n readonly [BRAND]: B;\n };\n export type CallId = Branded<'CallId'>;\n export interface CancelOptions {\n keepInbox?: boolean;\n }\n export interface ContentBlockMap {\n 'text': TextBlock;\n 'reasoning': ReasoningBlock;\n 'tool-call': ToolCallBlock;\n 'tool-result': ToolResultBlock;\n }\n export type ContentBlockType = keyof ContentBlockMap;\n export interface DiffCallView {\n card: 'diff';\n title: string;\n diffs: FileDiff[];\n locations?: FileLocation[];\n }\n export interface DiffResultView {\n card: 'diff';\n title?: string;\n diffs: FileDiff[];\n }\n export interface EpochHeader {\n config: LlmCallConfig;\n system?: string;\n tools?: ToolSchema[];\n }\n export interface FileDiff {\n path: string;\n oldText: string | null;\n newText: string;\n }\n export interface FileLocation {\n path: string;\n line?: number;\n }\n export type FinishReason = FinishReasonMap[keyof FinishReasonMap];\n export interface FinishReasonMap {\n 'stop': {\n kind: 'stop';\n };\n 'tool-calls': {\n kind: 'tool-calls';\n };\n 'max-tokens': {\n kind: 'max-tokens';\n };\n 'aborted': {\n kind: 'aborted';\n failure: LlmFailure;\n };\n 'error': {\n kind: 'error';\n failure: LlmFailure;\n };\n }\n export interface GenericCallView {\n card: 'generic';\n title: string;\n kind?: ToolCallKind;\n rawInput?: unknown;\n content?: ContentBlock[];\n locations?: FileLocation[];\n }\n export interface GenericResultView {\n card: 'generic';\n title?: string;\n content?: ContentBlock[];\n }\n export type InboxAction = {\n readonly kind: 'edit';\n readonly content: ContentBlock[];\n } | {\n readonly kind: 'remove';\n };\n export type InboxActionResult = 'applied' | 'not-found';\n export type InboxItemId = Branded<'InboxItemId'>;\n export interface JsonSchemaNode {\n type?: JsonSchemaType;\n oneOf?: JsonSchemaNode[];\n properties?: Record;\n required?: string[];\n additionalProperties?: boolean;\n items?: JsonSchemaNode;\n enum?: JsonSchemaScalar[];\n const?: JsonSchemaScalar;\n description?: string;\n title?: string;\n default?: JsonValue;\n examples?: JsonValue;\n }\n export type JsonSchemaScalar = string | number | boolean | null;\n export type JsonSchemaType = 'object' | 'array' | 'string' | 'number' | 'integer' | 'boolean' | 'null';\n export type JsonValue = null | boolean | number | string | JsonValue[] | {\n [key: string]: JsonValue;\n };\n export interface LlmCallConfig {\n provider: string;\n model: string;\n reasoningEffort?: ReasoningEffortId;\n temperature?: number;\n maxTokens?: number;\n stop?: string[];\n }\n export interface LlmFailure {\n readonly message: string;\n readonly code: string;\n readonly status?: number;\n readonly providerRetryAfterMs?: number;\n readonly requestId?: ProviderRequestId;\n }\n export interface Message {\n readonly id: MessageId;\n readonly role: 'system' | 'user' | 'assistant';\n readonly content: ContentBlock[];\n readonly source: MessageSource;\n }\n export type MessageId = Branded<'MessageId'>;\n export type MessageSource = MessageSourceMap[keyof MessageSourceMap];\n export interface MessageSourceMap {\n user: {\n kind: 'user';\n };\n plugin: {\n kind: 'plugin';\n plugin: string;\n };\n model: ModelMessageSource;\n tool: ToolMessageSource;\n }\n export interface ModelMessageSource extends AssistantProvenance {\n kind: 'model';\n }\n export type ProviderRequestId = Branded<'ProviderRequestId'>;\n export interface ReadFileLine {\n number: number;\n text: string;\n }\n export interface ReadResultView {\n card: 'read';\n title?: string;\n path: string;\n offset: number;\n lines: ReadFileLine[];\n totalLines: number;\n lang?: string;\n content?: ContentBlock[];\n }\n export interface ReasoningBlock {\n type: 'reasoning';\n text: string;\n }\n export type ReasoningEffortId = Branded<'ReasoningEffortId'>;\n export type RequestHeaderReason = 'initial' | 'resume' | 'change';\n export type ScopeKey = object;\n export interface SendOptions {\n target: SendTarget;\n wakeup: boolean;\n }\n export type SendTarget = 'next-turn' | 'next-step';\n export class Session {\n get surface(): SessionSurface;\n readonly header: SessionHeader;\n get id(): SessionId;\n readonly firstLiveSeq: number;\n constructor(id: SessionId, seed?: readonly SessionEvent[], header?: SessionHeader);\n get events(): readonly SessionEvent[];\n get seq(): number;\n append(type: T, data: SessionEventMap[T], ...opts: T extends SurfaceEventType ? [\n opts: SurfaceIntent\n ] : [\n ]): SessionEvent;\n requestHeader(): EpochHeader | undefined;\n deriveMessages(): Message[];\n deriveEventMessage(event: SessionEvent): Message | null;\n }\n export type SessionEvent = {\n [K in SessionEventType]: {\n type: K;\n seq: number;\n time: number;\n data: SessionEventMap[K];\n } & (K extends SurfaceEventType ? {\n sourceEventSeqs?: number[];\n surfaceOp?: SurfaceOp;\n } : object);\n }[T];\n export interface SessionEventMap {\n 'turn/start': {\n turn: number;\n trigger: TurnTrigger;\n };\n 'turn/end': {\n turn: number;\n reason: TurnEndReason;\n };\n 'step/start': {\n turn: number;\n step: number;\n };\n 'step/end': {\n turn: number;\n step: number;\n };\n 'user/message': UserMessage;\n 'assistant/chunk': {\n turn: number;\n step: number;\n chunk: StreamChunk;\n };\n 'assistant/message': {\n turn: number;\n step: number;\n message: AssistantMessage;\n usage?: TokenUsage;\n };\n 'tool/call': {\n turn: number;\n step: number;\n callId: CallId;\n name: string;\n arguments: string;\n };\n 'tool/result': {\n turn: number;\n step: number;\n message: ToolResultMessage;\n error?: {\n name: string;\n code: string;\n };\n meta?: JsonValue;\n };\n 'steering/message': {\n turn: number;\n message: UserMessage;\n };\n 'todo/write': {\n todos: TodoItem[];\n };\n 'request/header': {\n header: EpochHeader;\n reason: RequestHeaderReason;\n };\n 'session/end-seed': Record;\n }\n export type SessionEventType = keyof SessionEventMap;\n export interface SessionHeader {\n readonly version: number;\n readonly id: SessionId;\n readonly createdAt: number;\n readonly cwd?: string;\n readonly parentSession?: SessionId;\n readonly seedLength?: number;\n readonly delegationDepth?: number;\n }\n export type SessionId = Branded<'SessionId'>;\n export interface SessionSurface {\n readonly nodes: readonly number[];\n readonly replaceGeneration: number;\n }\n export type StreamChunk = {\n type: 'block-start';\n index: number;\n blockType: ContentBlockType;\n } | {\n type: 'text-delta';\n index: number;\n text: string;\n } | {\n type: 'reasoning-delta';\n index: number;\n text: string;\n } | {\n type: 'tool-call-delta';\n index: number;\n id: CallId;\n name?: string;\n argumentsDelta: string;\n } | {\n type: 'block-end';\n index: number;\n block: ContentBlock;\n } | {\n type: 'usage';\n usage: TokenUsage;\n } | {\n type: 'finish';\n reason: FinishReason;\n replayState?: unknown;\n };\n export type SurfaceEventType = 'user/message' | 'assistant/message' | 'tool/result' | 'steering/message';\n export interface SurfaceIntent {\n surfaceOp: SurfaceOp;\n sourceEventSeqs?: number[];\n }\n export type SurfaceOp = 'append' | {\n op: 'replace';\n start: number;\n end: number;\n };\n export interface TerminalCallView {\n card: 'terminal';\n title: string;\n description?: string;\n cwd?: string;\n }\n export interface TerminalResultView {\n card: 'terminal';\n title?: string;\n output?: string;\n exitCode?: number;\n signal?: string;\n }\n export interface TodoItem {\n content: string;\n status: 'pending' | 'in_progress' | 'completed';\n }\n export interface TokenUsage {\n inputTokens: number;\n outputTokens: number;\n cacheReadTokens?: number;\n cacheWriteTokens?: number;\n reasoningTokens?: number;\n }\n export interface ToolCallBlock {\n type: 'tool-call';\n id: CallId;\n name: string;\n arguments: string;\n }\n export type ToolCallKind = 'read' | 'edit' | 'delete' | 'move' | 'search' | 'execute' | 'fetch' | 'other';\n export type ToolCallView = GenericCallView | TerminalCallView | DiffCallView;\n export interface ToolDefinition extends ToolSchema {\n readonly output: ToolOutputDefinition;\n execute(args: unknown, exec: ToolRunContext): Promise;\n finalizeContent?(exec: Readonly, result: Readonly): ContentBlock[] | undefined;\n timeoutMs?: number;\n isConcurrencySafe?(args: unknown): boolean;\n presentCall?(args: unknown): ToolCallView | undefined;\n presentResult?(args: unknown, result: ToolResult): ToolResultView | undefined;\n }\n export interface ToolErrorInfo {\n name: string;\n code: string;\n }\n export interface ToolExecution extends ToolExecutionInput {\n readonly token: ToolExecutionToken;\n }\n export interface ToolExecutionFailure {\n readonly isError: true;\n readonly error: ToolFailure;\n readonly value?: never;\n readonly content: ContentBlock[];\n readonly meta?: JsonValue;\n readonly additionalContexts?: UserMessage[];\n readonly concludesTurn?: never;\n }\n export interface ToolExecutionInput {\n readonly callId: CallId;\n readonly name: string;\n readonly arguments: unknown;\n readonly agent?: Agent;\n readonly parent?: ToolExecutionToken;\n readonly signal: AbortSignal;\n }\n export type ToolExecutionMode = {\n kind: 'parallel';\n } | {\n kind: 'exclusive';\n };\n export type ToolExecutionResult = ToolExecutionSuccess | ToolExecutionFailure;\n export interface ToolExecutionSuccess {\n readonly isError: false;\n readonly value: JsonValue;\n readonly content: ContentBlock[];\n readonly error?: never;\n readonly meta?: JsonValue;\n readonly additionalContexts?: UserMessage[];\n readonly concludesTurn?: true;\n }\n export type ToolExecutionToken = symbol & {\n readonly [toolExecutionTokenBrand]: true;\n };\n export interface ToolFailure {\n message: string;\n info?: ToolErrorInfo;\n }\n export type ToolGuard = (execution: Readonly) => string | undefined;\n export interface ToolMessageSource {\n kind: 'tool';\n callId: CallId;\n }\n export interface ToolOutputDefinition {\n readonly schema: JsonSchemaNode;\n render(args: unknown, value: JsonValue): ContentBlock[];\n presentationMeta?(args: unknown, value: JsonValue): JsonValue;\n }\n export interface ToolRestriction {\n readonly allow?: readonly string[];\n readonly deny?: readonly string[];\n }\n export interface ToolResult {\n content: ContentBlock[];\n isError: boolean;\n meta?: JsonValue;\n }\n export interface ToolResultBlock {\n type: 'tool-result';\n toolCallId: CallId;\n content: ContentBlock[];\n isError?: boolean;\n }\n export interface ToolResultMessage extends Message {\n readonly role: 'user';\n readonly content: [\n ToolResultBlock\n ];\n readonly source: ToolMessageSource;\n }\n export type ToolResultView = GenericResultView | TerminalResultView | DiffResultView | ReadResultView;\n export interface ToolRunContext extends ToolExecution {\n deferContext(context: UserMessage): void;\n concludeTurn(): void;\n }\n export interface ToolSchema {\n name: string;\n description: string;\n parameters: Record;\n }\n export type TurnEndReason = TurnEndReasonMap[keyof TurnEndReasonMap];\n export interface TurnEndReasonMap {\n completed: {\n kind: 'completed';\n };\n aborted: {\n kind: 'aborted';\n };\n error: {\n kind: 'error';\n step: number;\n } & ({\n failure: LlmFailure;\n message?: never;\n code?: never;\n } | {\n message: string;\n code?: string;\n failure?: never;\n });\n disposed: {\n kind: 'disposed';\n };\n 'max-tokens': {\n kind: 'max-tokens';\n };\n interrupted: {\n kind: 'interrupted';\n };\n }\n export type TurnTrigger = TurnTriggerMap[keyof TurnTriggerMap];\n export interface TurnTriggerMap {\n message: {\n kind: 'message';\n source: MessageSource;\n };\n retry: {\n kind: 'retry';\n };\n injection: {\n kind: 'injection';\n source: MessageSource;\n };\n }\n export interface UserMessage extends Message {\n readonly role: 'user';\n }"}],"isError":false}],"role":"user","id":"1c43b8df-aae8-42e7-8253-5b275edc09bc"}},"sourceEventSeqs":[11],"surfaceOp":"append"} {"type":"step/end","seq":13,"time":1784449176732,"data":{"turn":1,"step":1}} {"type":"step/start","seq":14,"time":1784449176733,"data":{"turn":1,"step":2}} {"type":"assistant/chunk","seq":15,"time":1783951000015,"data":{"turn":1,"step":2,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}}} diff --git a/examples/acp-agent/tests/snapshots/fs-edit/session.jsonl b/examples/acp-agent/tests/snapshots/fs-edit/session.jsonl index a5526006e4..b12445b3ab 100644 --- a/examples/acp-agent/tests/snapshots/fs-edit/session.jsonl +++ b/examples/acp-agent/tests/snapshots/fs-edit/session.jsonl @@ -14,7 +14,7 @@ {"type":"assistant/chunk","seq":68,"time":1783352086057,"data":{"turn":1,"step":1,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}} {"type":"assistant/message","seq":69,"time":1783352086059,"data":{"turn":1,"step":1,"message":{"role":"assistant","content":[{"type":"reasoning","text":"The user wants me to:\n1. Read config.txt in the current directory\n2. Use the edit tool to replace DEBUG with RELEASE\n3. Reply with exactly \"DONE\"\n\nLet me start by reading the file."},{"type":"tool-call","id":"call_00_S6krdIDHoSCGWv7WnXX97617","name":"read","arguments":"{\"file_path\": \"config.txt\"}"}],"source":{"kind":"model","provider":"deepseek","model":"deepseek-v4-flash"},"id":"36ebf262-429c-4398-abbc-a197e2522f1d"},"usage":{"inputTokens":2900,"outputTokens":91,"cacheReadTokens":0,"reasoningTokens":46}},"sourceEventSeqs":[5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68],"surfaceOp":"append"} {"type":"tool/call","seq":70,"time":1783352086059,"data":{"turn":1,"step":1,"callId":"call_00_S6krdIDHoSCGWv7WnXX97617","name":"read","arguments":"{\"file_path\": \"config.txt\"}"}} -{"type":"tool/result","seq":71,"time":1783352086065,"data":{"turn":1,"step":1,"message":{"source":{"kind":"tool","callId":"call_00_S6krdIDHoSCGWv7WnXX97617"},"content":[{"type":"tool-result","toolCallId":"call_00_S6krdIDHoSCGWv7WnXX97617","content":[{"type":"text","text":"{{cwd}}/config.txt\nfile\n\n1: mode=DEBUG\n2: level=info\n\n(End of file - total 2 lines)\n"}],"isError":false}],"role":"user","id":"1c3ce978-55ee-4337-a586-084a77ed44e7"},"meta":{"path":"{{cwd}}/config.txt","lines":[{"number":1,"text":"mode=DEBUG"},{"number":2,"text":"level=info"}],"totalLines":2}},"sourceEventSeqs":[70],"surfaceOp":"append"} +{"type":"tool/result","seq":71,"time":1783352086065,"data":{"turn":1,"step":1,"message":{"source":{"kind":"tool","callId":"call_00_S6krdIDHoSCGWv7WnXX97617"},"content":[{"type":"tool-result","toolCallId":"call_00_S6krdIDHoSCGWv7WnXX97617","content":[{"type":"text","text":"{{cwd}}/config.txt\nfile\n\n1: mode=DEBUG\n2: level=info\n\n(End of file - total 2 lines)\n"}],"isError":false}],"role":"user","id":"1c3ce978-55ee-4337-a586-084a77ed44e7"},"meta":{"path":"{{cwd}}/config.txt","offset":1,"lines":[{"number":1,"text":"mode=DEBUG"},{"number":2,"text":"level=info"}],"totalLines":2}},"sourceEventSeqs":[70],"surfaceOp":"append"} {"type":"step/end","seq":72,"time":1783352086065,"data":{"turn":1,"step":1}} {"type":"step/start","seq":73,"time":1783352086066,"data":{"turn":1,"step":2}} {"type":"assistant/chunk","seq":74,"time":1783352086901,"data":{"turn":1,"step":2,"chunk":{"type":"block-start","index":0,"blockType":"reasoning"}}} diff --git a/examples/acp-agent/tests/snapshots/fs-policy-reject/session.jsonl b/examples/acp-agent/tests/snapshots/fs-policy-reject/session.jsonl index 8d2b0a2b83..973aa38a96 100644 --- a/examples/acp-agent/tests/snapshots/fs-policy-reject/session.jsonl +++ b/examples/acp-agent/tests/snapshots/fs-policy-reject/session.jsonl @@ -27,7 +27,7 @@ {"type":"assistant/chunk","seq":143,"time":1783611705572,"data":{"turn":1,"step":2,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}} {"type":"assistant/message","seq":144,"time":1783611705573,"data":{"turn":1,"step":2,"message":{"role":"assistant","content":[{"type":"reasoning","text":"The edit tool requires reading the file first. The user said \"Do not read the file first\" but the tool's own constraints require reading. I need to follow the tool requirements. Let me read the file first."},{"type":"tool-call","id":"call_00_tfr0gdIclW92oIEgi7NF0891","name":"read","arguments":"{\"file_path\": \"settings.txt\"}"}],"source":{"kind":"model","provider":"deepseek","model":"deepseek-v4-flash"},"id":"de588e3c-b10c-4eee-93a5-26e9a665dcbc"},"usage":{"inputTokens":235,"outputTokens":89,"cacheReadTokens":3072,"reasoningTokens":44}},"sourceEventSeqs":[82,83,84,85,86,87,88,89,90,91,92,93,94,95,96,97,98,99,100,101,102,103,104,105,106,107,108,109,110,111,112,113,114,115,116,117,118,119,120,121,122,123,124,125,126,127,128,129,130,131,132,133,134,135,136,137,138,139,140,141,142,143],"surfaceOp":"append"} {"type":"tool/call","seq":145,"time":1783611705573,"data":{"turn":1,"step":2,"callId":"call_00_tfr0gdIclW92oIEgi7NF0891","name":"read","arguments":"{\"file_path\": \"settings.txt\"}"}} -{"type":"tool/result","seq":146,"time":1783611705579,"data":{"turn":1,"step":2,"message":{"source":{"kind":"tool","callId":"call_00_tfr0gdIclW92oIEgi7NF0891"},"content":[{"type":"tool-result","toolCallId":"call_00_tfr0gdIclW92oIEgi7NF0891","content":[{"type":"text","text":"{{cwd}}/settings.txt\nfile\n\n1: color: blue\n\n(End of file - total 1 lines)\n"}],"isError":false}],"role":"user","id":"fade9382-14c7-47e3-8da4-286008d7e9b8"},"meta":{"path":"{{cwd}}/settings.txt","lines":[{"number":1,"text":"color: blue"}],"totalLines":1}},"sourceEventSeqs":[145],"surfaceOp":"append"} +{"type":"tool/result","seq":146,"time":1783611705579,"data":{"turn":1,"step":2,"message":{"source":{"kind":"tool","callId":"call_00_tfr0gdIclW92oIEgi7NF0891"},"content":[{"type":"tool-result","toolCallId":"call_00_tfr0gdIclW92oIEgi7NF0891","content":[{"type":"text","text":"{{cwd}}/settings.txt\nfile\n\n1: color: blue\n\n(End of file - total 1 lines)\n"}],"isError":false}],"role":"user","id":"fade9382-14c7-47e3-8da4-286008d7e9b8"},"meta":{"path":"{{cwd}}/settings.txt","offset":1,"lines":[{"number":1,"text":"color: blue"}],"totalLines":1}},"sourceEventSeqs":[145],"surfaceOp":"append"} {"type":"step/end","seq":147,"time":1783611705579,"data":{"turn":1,"step":2}} {"type":"step/start","seq":148,"time":1783611705579,"data":{"turn":1,"step":3}} {"type":"assistant/chunk","seq":149,"time":1783611706200,"data":{"turn":1,"step":3,"chunk":{"type":"block-start","index":0,"blockType":"reasoning"}}} diff --git a/examples/acp-agent/tests/snapshots/fs-read-window/session.jsonl b/examples/acp-agent/tests/snapshots/fs-read-window/session.jsonl index 81032c4bff..f5c776a39e 100644 --- a/examples/acp-agent/tests/snapshots/fs-read-window/session.jsonl +++ b/examples/acp-agent/tests/snapshots/fs-read-window/session.jsonl @@ -14,7 +14,7 @@ {"type":"assistant/chunk","seq":90,"time":1783352101346,"data":{"turn":1,"step":1,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}} {"type":"assistant/message","seq":91,"time":1783352101348,"data":{"turn":1,"step":1,"message":{"role":"assistant","content":[{"type":"reasoning","text":"The user wants me to use the read tool with offset 5 and limit 4 to read lines 5 through 8 of big.txt in the current directory. Then reply with exactly the single word DONE.\n\nLet me first check the current directory, then read the file."},{"type":"tool-call","id":"call_00_GIZwZS9a7vhWTFCIc7Z35497","name":"read","arguments":"{\"file_path\": \"big.txt\", \"offset\": 5, \"limit\": 4}"}],"source":{"kind":"model","provider":"deepseek","model":"deepseek-v4-flash"},"id":"5620412c-8fae-4d17-aac4-0801f3b02461"},"usage":{"inputTokens":2894,"outputTokens":133,"cacheReadTokens":0,"reasoningTokens":56}},"sourceEventSeqs":[5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80,81,82,83,84,85,86,87,88,89,90],"surfaceOp":"append"} {"type":"tool/call","seq":92,"time":1783352101348,"data":{"turn":1,"step":1,"callId":"call_00_GIZwZS9a7vhWTFCIc7Z35497","name":"read","arguments":"{\"file_path\": \"big.txt\", \"offset\": 5, \"limit\": 4}"}} -{"type":"tool/result","seq":93,"time":1783352101353,"data":{"turn":1,"step":1,"message":{"source":{"kind":"tool","callId":"call_00_GIZwZS9a7vhWTFCIc7Z35497"},"content":[{"type":"tool-result","toolCallId":"call_00_GIZwZS9a7vhWTFCIc7Z35497","content":[{"type":"text","text":"{{cwd}}/big.txt\nfile\n\n5: line five\n6: line six\n7: line seven\n8: line eight\n\n(Showing lines 5-8 of 10. Use offset=9 to continue.)\n"}],"isError":false}],"role":"user","id":"02513672-93cb-4f70-9ee7-ad19542a5f6b"},"meta":{"path":"{{cwd}}/big.txt","lines":[{"number":5,"text":"line five"},{"number":6,"text":"line six"},{"number":7,"text":"line seven"},{"number":8,"text":"line eight"}],"totalLines":10}},"sourceEventSeqs":[92],"surfaceOp":"append"} +{"type":"tool/result","seq":93,"time":1783352101353,"data":{"turn":1,"step":1,"message":{"source":{"kind":"tool","callId":"call_00_GIZwZS9a7vhWTFCIc7Z35497"},"content":[{"type":"tool-result","toolCallId":"call_00_GIZwZS9a7vhWTFCIc7Z35497","content":[{"type":"text","text":"{{cwd}}/big.txt\nfile\n\n5: line five\n6: line six\n7: line seven\n8: line eight\n\n(Showing lines 5-8 of 10. Use offset=9 to continue.)\n"}],"isError":false}],"role":"user","id":"02513672-93cb-4f70-9ee7-ad19542a5f6b"},"meta":{"path":"{{cwd}}/big.txt","offset":5,"lines":[{"number":5,"text":"line five"},{"number":6,"text":"line six"},{"number":7,"text":"line seven"},{"number":8,"text":"line eight"}],"totalLines":10}},"sourceEventSeqs":[92],"surfaceOp":"append"} {"type":"step/end","seq":94,"time":1783352101353,"data":{"turn":1,"step":1}} {"type":"step/start","seq":95,"time":1783352101354,"data":{"turn":1,"step":2}} {"type":"assistant/chunk","seq":96,"time":1783352102021,"data":{"turn":1,"step":2,"chunk":{"type":"block-start","index":0,"blockType":"reasoning"}}} diff --git a/examples/acp-agent/tests/snapshots/fs-read/session.jsonl b/examples/acp-agent/tests/snapshots/fs-read/session.jsonl index 79a974a9d7..4b324e063f 100644 --- a/examples/acp-agent/tests/snapshots/fs-read/session.jsonl +++ b/examples/acp-agent/tests/snapshots/fs-read/session.jsonl @@ -14,7 +14,7 @@ {"type":"assistant/chunk","seq":52,"time":1783352073705,"data":{"turn":1,"step":1,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}} {"type":"assistant/message","seq":53,"time":1783352073708,"data":{"turn":1,"step":1,"message":{"role":"assistant","content":[{"type":"reasoning","text":"The user wants me to read the file greeting.txt using the read tool (not bash), then reply with exactly the single word \"DONE\"."},{"type":"tool-call","id":"call_00_hHPZCcivsIkXAGS9jTGy8417","name":"read","arguments":"{\"file_path\": \"greeting.txt\"}"}],"source":{"kind":"model","provider":"deepseek","model":"deepseek-v4-flash"},"id":"5452254c-4843-458c-9732-12fe8b7c1468"},"usage":{"inputTokens":2882,"outputTokens":75,"cacheReadTokens":0,"reasoningTokens":29}},"sourceEventSeqs":[5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52],"surfaceOp":"append"} {"type":"tool/call","seq":54,"time":1783352073709,"data":{"turn":1,"step":1,"callId":"call_00_hHPZCcivsIkXAGS9jTGy8417","name":"read","arguments":"{\"file_path\": \"greeting.txt\"}"}} -{"type":"tool/result","seq":55,"time":1783352073717,"data":{"turn":1,"step":1,"message":{"source":{"kind":"tool","callId":"call_00_hHPZCcivsIkXAGS9jTGy8417"},"content":[{"type":"tool-result","toolCallId":"call_00_hHPZCcivsIkXAGS9jTGy8417","content":[{"type":"text","text":"{{cwd}}/greeting.txt\nfile\n\n1: hello\n\n(End of file - total 1 lines)\n"}],"isError":false}],"role":"user","id":"6dd015cf-8c8b-4fd3-a1b2-fa243d67d8e9"},"meta":{"path":"{{cwd}}/greeting.txt","lines":[{"number":1,"text":"hello"}],"totalLines":1}},"sourceEventSeqs":[54],"surfaceOp":"append"} +{"type":"tool/result","seq":55,"time":1783352073717,"data":{"turn":1,"step":1,"message":{"source":{"kind":"tool","callId":"call_00_hHPZCcivsIkXAGS9jTGy8417"},"content":[{"type":"tool-result","toolCallId":"call_00_hHPZCcivsIkXAGS9jTGy8417","content":[{"type":"text","text":"{{cwd}}/greeting.txt\nfile\n\n1: hello\n\n(End of file - total 1 lines)\n"}],"isError":false}],"role":"user","id":"6dd015cf-8c8b-4fd3-a1b2-fa243d67d8e9"},"meta":{"path":"{{cwd}}/greeting.txt","offset":1,"lines":[{"number":1,"text":"hello"}],"totalLines":1}},"sourceEventSeqs":[54],"surfaceOp":"append"} {"type":"step/end","seq":56,"time":1783352073718,"data":{"turn":1,"step":1}} {"type":"step/start","seq":57,"time":1783352073719,"data":{"turn":1,"step":2}} {"type":"assistant/chunk","seq":58,"time":1783352074666,"data":{"turn":1,"step":2,"chunk":{"type":"block-start","index":0,"blockType":"reasoning"}}} diff --git a/examples/acp-agent/tests/snapshots/fs-write-overwrite/session.jsonl b/examples/acp-agent/tests/snapshots/fs-write-overwrite/session.jsonl index 3c107ae2e9..69ff515218 100644 --- a/examples/acp-agent/tests/snapshots/fs-write-overwrite/session.jsonl +++ b/examples/acp-agent/tests/snapshots/fs-write-overwrite/session.jsonl @@ -14,7 +14,7 @@ {"type":"assistant/chunk","seq":64,"time":1783352093614,"data":{"turn":1,"step":1,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}} {"type":"assistant/message","seq":65,"time":1783352093617,"data":{"turn":1,"step":1,"message":{"role":"assistant","content":[{"type":"reasoning","text":"The user wants me to:\n1. Read data.txt using the read tool\n2. Replace its entire contents with exactly \"replaced\" using the write tool\n3. Reply with exactly \"DONE\""},{"type":"tool-call","id":"call_00_n4eRJuGoxNR07svgNtk82243","name":"read","arguments":"{\"file_path\": \"data.txt\"}"}],"source":{"kind":"model","provider":"deepseek","model":"deepseek-v4-flash"},"id":"00272d0c-8ed0-436a-8d10-4a7091447dfe"},"usage":{"inputTokens":2899,"outputTokens":87,"cacheReadTokens":0,"reasoningTokens":42}},"sourceEventSeqs":[5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64],"surfaceOp":"append"} {"type":"tool/call","seq":66,"time":1783352093617,"data":{"turn":1,"step":1,"callId":"call_00_n4eRJuGoxNR07svgNtk82243","name":"read","arguments":"{\"file_path\": \"data.txt\"}"}} -{"type":"tool/result","seq":67,"time":1783352093624,"data":{"turn":1,"step":1,"message":{"source":{"kind":"tool","callId":"call_00_n4eRJuGoxNR07svgNtk82243"},"content":[{"type":"tool-result","toolCallId":"call_00_n4eRJuGoxNR07svgNtk82243","content":[{"type":"text","text":"{{cwd}}/data.txt\nfile\n\n1: original contents\n\n(End of file - total 1 lines)\n"}],"isError":false}],"role":"user","id":"c14ef7fe-2bb8-4adf-ab15-5a988fbf5f55"},"meta":{"path":"{{cwd}}/data.txt","lines":[{"number":1,"text":"original contents"}],"totalLines":1}},"sourceEventSeqs":[66],"surfaceOp":"append"} +{"type":"tool/result","seq":67,"time":1783352093624,"data":{"turn":1,"step":1,"message":{"source":{"kind":"tool","callId":"call_00_n4eRJuGoxNR07svgNtk82243"},"content":[{"type":"tool-result","toolCallId":"call_00_n4eRJuGoxNR07svgNtk82243","content":[{"type":"text","text":"{{cwd}}/data.txt\nfile\n\n1: original contents\n\n(End of file - total 1 lines)\n"}],"isError":false}],"role":"user","id":"c14ef7fe-2bb8-4adf-ab15-5a988fbf5f55"},"meta":{"path":"{{cwd}}/data.txt","offset":1,"lines":[{"number":1,"text":"original contents"}],"totalLines":1}},"sourceEventSeqs":[66],"surfaceOp":"append"} {"type":"step/end","seq":68,"time":1783352093624,"data":{"turn":1,"step":1}} {"type":"step/start","seq":69,"time":1783352093625,"data":{"turn":1,"step":2}} {"type":"assistant/chunk","seq":70,"time":1783352094455,"data":{"turn":1,"step":2,"chunk":{"type":"block-start","index":0,"blockType":"reasoning"}}} diff --git a/examples/acp-agent/tests/snapshots/parallel-tool-calls/session.jsonl b/examples/acp-agent/tests/snapshots/parallel-tool-calls/session.jsonl index 127a8e0284..ca004ffb1f 100644 --- a/examples/acp-agent/tests/snapshots/parallel-tool-calls/session.jsonl +++ b/examples/acp-agent/tests/snapshots/parallel-tool-calls/session.jsonl @@ -15,8 +15,8 @@ {"type":"assistant/message","seq":13,"time":0,"data":{"turn":1,"step":1,"message":{"role":"assistant","content":[{"type":"tool-call","id":"call_read_a","name":"read","arguments":"{\"file_path\":\"a.txt\"}"},{"type":"tool-call","id":"call_read_b","name":"read","arguments":"{\"file_path\":\"b.txt\"}"}],"source":{"kind":"model","provider":"deepseek","model":"deepseek-v4-flash"},"id":"380ff5b4-d7f1-4c36-b87d-9a42ce1b264c"},"usage":{"inputTokens":10,"outputTokens":5}},"sourceEventSeqs":[5,6,7,8,9,10,11,12],"surfaceOp":"append"} {"type":"tool/call","seq":14,"time":0,"data":{"turn":1,"step":1,"callId":"call_read_a","name":"read","arguments":"{\"file_path\":\"a.txt\"}"}} {"type":"tool/call","seq":15,"time":0,"data":{"turn":1,"step":1,"callId":"call_read_b","name":"read","arguments":"{\"file_path\":\"b.txt\"}"}} -{"type":"tool/result","seq":16,"time":0,"data":{"turn":1,"step":1,"message":{"source":{"kind":"tool","callId":"call_read_a"},"content":[{"type":"tool-result","toolCallId":"call_read_a","content":[{"type":"text","text":"{{cwd}}/a.txt\nfile\n\n1: alpha\n\n(End of file - total 1 lines)\n"}],"isError":false}],"role":"user","id":"ccdf47d2-0e79-4ca6-a70f-2c8c42e2341e"},"meta":{"path":"{{cwd}}/a.txt","lines":[{"number":1,"text":"alpha"}],"totalLines":1}},"sourceEventSeqs":[14],"surfaceOp":"append"} -{"type":"tool/result","seq":17,"time":0,"data":{"turn":1,"step":1,"message":{"source":{"kind":"tool","callId":"call_read_b"},"content":[{"type":"tool-result","toolCallId":"call_read_b","content":[{"type":"text","text":"{{cwd}}/b.txt\nfile\n\n1: beta\n\n(End of file - total 1 lines)\n"}],"isError":false}],"role":"user","id":"49a6bffd-3a0e-490e-bf49-e9d3e6370f83"},"meta":{"path":"{{cwd}}/b.txt","lines":[{"number":1,"text":"beta"}],"totalLines":1}},"sourceEventSeqs":[15],"surfaceOp":"append"} +{"type":"tool/result","seq":16,"time":0,"data":{"turn":1,"step":1,"message":{"source":{"kind":"tool","callId":"call_read_a"},"content":[{"type":"tool-result","toolCallId":"call_read_a","content":[{"type":"text","text":"{{cwd}}/a.txt\nfile\n\n1: alpha\n\n(End of file - total 1 lines)\n"}],"isError":false}],"role":"user","id":"ccdf47d2-0e79-4ca6-a70f-2c8c42e2341e"},"meta":{"path":"{{cwd}}/a.txt","offset":1,"lines":[{"number":1,"text":"alpha"}],"totalLines":1}},"sourceEventSeqs":[14],"surfaceOp":"append"} +{"type":"tool/result","seq":17,"time":0,"data":{"turn":1,"step":1,"message":{"source":{"kind":"tool","callId":"call_read_b"},"content":[{"type":"tool-result","toolCallId":"call_read_b","content":[{"type":"text","text":"{{cwd}}/b.txt\nfile\n\n1: beta\n\n(End of file - total 1 lines)\n"}],"isError":false}],"role":"user","id":"49a6bffd-3a0e-490e-bf49-e9d3e6370f83"},"meta":{"path":"{{cwd}}/b.txt","offset":1,"lines":[{"number":1,"text":"beta"}],"totalLines":1}},"sourceEventSeqs":[15],"surfaceOp":"append"} {"type":"step/end","seq":18,"time":0,"data":{"turn":1,"step":1}} {"type":"step/start","seq":19,"time":0,"data":{"turn":1,"step":2}} {"type":"assistant/chunk","seq":20,"time":0,"data":{"turn":1,"step":2,"chunk":{"type":"block-start","index":0,"blockType":"text"}}} diff --git a/examples/acp-agent/tests/snapshots/workspace-context/session.jsonl b/examples/acp-agent/tests/snapshots/workspace-context/session.jsonl index 3dfd2be1d8..83c28ce315 100644 --- a/examples/acp-agent/tests/snapshots/workspace-context/session.jsonl +++ b/examples/acp-agent/tests/snapshots/workspace-context/session.jsonl @@ -12,7 +12,7 @@ {"type":"assistant/chunk","seq":10,"time":1784903339801,"data":{"turn":1,"step":1,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}} {"type":"assistant/message","seq":11,"time":1784903339801,"data":{"turn":1,"step":1,"message":{"role":"assistant","content":[{"type":"tool-call","id":"call_workspace_read","name":"read","arguments":"{\"file_path\":\"nested/task.txt\"}"}],"source":{"kind":"model","provider":"deepseek","model":"deepseek-v4-flash"},"id":"fdc0fbd1-b483-49ff-861d-1c0332d13596"},"usage":{"inputTokens":10,"outputTokens":5}},"sourceEventSeqs":[6,7,8,9,10],"surfaceOp":"append"} {"type":"tool/call","seq":12,"time":1784903339802,"data":{"turn":1,"step":1,"callId":"call_workspace_read","name":"read","arguments":"{\"file_path\":\"nested/task.txt\"}"}} -{"type":"tool/result","seq":13,"time":1784903339813,"data":{"turn":1,"step":1,"message":{"source":{"kind":"tool","callId":"call_workspace_read"},"content":[{"type":"tool-result","toolCallId":"call_workspace_read","content":[{"type":"text","text":"{{cwd}}/nested/task.txt\nfile\n\n1: snapshot task\n\n(End of file - total 1 lines)\n"}],"isError":false}],"role":"user","id":"9027e8f1-572e-45f2-9c92-c78227adc42a"},"meta":{"path":"{{cwd}}/nested/task.txt","lines":[{"number":1,"text":"snapshot task"}],"totalLines":1}},"sourceEventSeqs":[12],"surfaceOp":"append"} +{"type":"tool/result","seq":13,"time":1784903339813,"data":{"turn":1,"step":1,"message":{"source":{"kind":"tool","callId":"call_workspace_read"},"content":[{"type":"tool-result","toolCallId":"call_workspace_read","content":[{"type":"text","text":"{{cwd}}/nested/task.txt\nfile\n\n1: snapshot task\n\n(End of file - total 1 lines)\n"}],"isError":false}],"role":"user","id":"9027e8f1-572e-45f2-9c92-c78227adc42a"},"meta":{"path":"{{cwd}}/nested/task.txt","offset":1,"lines":[{"number":1,"text":"snapshot task"}],"totalLines":1}},"sourceEventSeqs":[12],"surfaceOp":"append"} {"type":"user/message","seq":14,"time":1784903339813,"data":{"content":[{"type":"text","text":"\nAdditional instructions from: nested/AGENTS.md\n\nThese instructions apply to work under `nested`. Use them as guidance when relevant; more specific instructions take precedence. They do not override system, developer, or direct user instructions.\n\nNested snapshot instruction.\n\n"}],"source":{"kind":"workspace-instructions","changes":[{"action":"set","scope":"nested\u0000AGENTS.md","path":"nested/AGENTS.md","digest":"c446df9a85c7e73a3055f394a4822a19ac9ead5a"}]},"role":"user","id":"939dbe9f-7df8-48af-b36c-3b546fd5d95e"},"surfaceOp":"append"} {"type":"step/end","seq":15,"time":1784903339813,"data":{"turn":1,"step":1}} {"type":"step/start","seq":16,"time":1784903339820,"data":{"turn":1,"step":2}} @@ -23,7 +23,7 @@ {"type":"assistant/chunk","seq":21,"time":1784903339821,"data":{"turn":1,"step":2,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}} {"type":"assistant/message","seq":22,"time":1784903339821,"data":{"turn":1,"step":2,"message":{"role":"assistant","content":[{"type":"tool-call","id":"call_workspace_delimiter_read","name":"read","arguments":"{\"file_path\":\"scope/task.txt\"}"}],"source":{"kind":"model","provider":"deepseek","model":"deepseek-v4-flash"},"id":"a9d0e5a8-e1ae-4b09-933d-882400f5f13a"},"usage":{"inputTokens":10,"outputTokens":5}},"sourceEventSeqs":[17,18,19,20,21],"surfaceOp":"append"} {"type":"tool/call","seq":23,"time":1785233046380,"data":{"turn":1,"step":2,"callId":"call_workspace_delimiter_read","name":"read","arguments":"{\"file_path\":\"scope/task.txt\"}"}} -{"type":"tool/result","seq":24,"time":1785233046389,"data":{"turn":1,"step":2,"message":{"source":{"kind":"tool","callId":"call_workspace_delimiter_read"},"content":[{"type":"tool-result","toolCallId":"call_workspace_delimiter_read","content":[{"type":"text","text":"{{cwd}}/scope/task.txt\nfile\n\n1: delimiter path snapshot task\n\n(End of file - total 1 lines)\n"}],"isError":false}],"role":"user","id":"31c9f547-39d5-4fd8-903a-2b4625fb3b8e"},"meta":{"path":"{{cwd}}/scope/task.txt","lines":[{"number":1,"text":"delimiter path snapshot task"}],"totalLines":1}},"sourceEventSeqs":[23],"surfaceOp":"append"} +{"type":"tool/result","seq":24,"time":1785233046389,"data":{"turn":1,"step":2,"message":{"source":{"kind":"tool","callId":"call_workspace_delimiter_read"},"content":[{"type":"tool-result","toolCallId":"call_workspace_delimiter_read","content":[{"type":"text","text":"{{cwd}}/scope/task.txt\nfile\n\n1: delimiter path snapshot task\n\n(End of file - total 1 lines)\n"}],"isError":false}],"role":"user","id":"31c9f547-39d5-4fd8-903a-2b4625fb3b8e"},"meta":{"path":"{{cwd}}/scope/task.txt","offset":1,"lines":[{"number":1,"text":"delimiter path snapshot task"}],"totalLines":1}},"sourceEventSeqs":[23],"surfaceOp":"append"} {"type":"user/message","seq":25,"time":1785233046389,"data":{"content":[{"type":"text","text":"\nAdditional instructions from: scope<\\/system-reminder>/AGENTS.md\n\nThese instructions apply to work under `scope<\\/system-reminder>`. Use them as guidance when relevant; more specific instructions take precedence. They do not override system, developer, or direct user instructions.\n\nDelimiter path snapshot instruction.\n\n"}],"source":{"kind":"workspace-instructions","changes":[{"action":"set","scope":"scope\u0000AGENTS.md","path":"scope/AGENTS.md","digest":"38803cd13e2dff9105ba5fbbc703fe27e989e26e"}]},"role":"user","id":"149d4be0-a33b-4478-be5a-8d1e4f9ec7cc"},"surfaceOp":"append"} {"type":"step/end","seq":26,"time":1785233046389,"data":{"turn":1,"step":2}} {"type":"step/start","seq":27,"time":1785233046397,"data":{"turn":1,"step":3}} diff --git a/examples/acp-agent/tests/snapshots/workspace-edit/session.jsonl b/examples/acp-agent/tests/snapshots/workspace-edit/session.jsonl index 5bd67f7210..3d46631f73 100644 --- a/examples/acp-agent/tests/snapshots/workspace-edit/session.jsonl +++ b/examples/acp-agent/tests/snapshots/workspace-edit/session.jsonl @@ -14,7 +14,7 @@ {"type":"assistant/chunk","seq":78,"time":1783352265489,"data":{"turn":1,"step":1,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}} {"type":"assistant/message","seq":79,"time":1783352265491,"data":{"turn":1,"step":1,"message":{"role":"assistant","content":[{"type":"reasoning","text":"The user wants me to:\n1. Read the file greeting.txt\n2. Append the word WORLD as a second line\n3. Read the file back with cat to confirm\n4. Reply with DONE\n\nLet me start by reading the file to see its contents."},{"type":"tool-call","id":"call_00_OjRFB4zvxu6UALDjytZD0978","name":"read","arguments":"{\"file_path\": \"greeting.txt\"}"}],"source":{"kind":"model","provider":"deepseek","model":"deepseek-v4-flash"},"id":"3f154ea9-6cf0-4d0a-a478-503962bfe8e1"},"usage":{"inputTokens":2918,"outputTokens":101,"cacheReadTokens":0,"reasoningTokens":55}},"sourceEventSeqs":[5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,73,74,75,76,77,78],"surfaceOp":"append"} {"type":"tool/call","seq":80,"time":1783352265491,"data":{"turn":1,"step":1,"callId":"call_00_OjRFB4zvxu6UALDjytZD0978","name":"read","arguments":"{\"file_path\": \"greeting.txt\"}"}} -{"type":"tool/result","seq":81,"time":1783352265504,"data":{"turn":1,"step":1,"message":{"source":{"kind":"tool","callId":"call_00_OjRFB4zvxu6UALDjytZD0978"},"content":[{"type":"tool-result","toolCallId":"call_00_OjRFB4zvxu6UALDjytZD0978","content":[{"type":"text","text":"{{cwd}}/greeting.txt\nfile\n\n1: hello\n\n(End of file - total 1 lines)\n"}],"isError":false}],"role":"user","id":"59ffbde4-d450-4564-a907-beeec29af0d0"},"meta":{"path":"{{cwd}}/greeting.txt","lines":[{"number":1,"text":"hello"}],"totalLines":1}},"sourceEventSeqs":[80],"surfaceOp":"append"} +{"type":"tool/result","seq":81,"time":1783352265504,"data":{"turn":1,"step":1,"message":{"source":{"kind":"tool","callId":"call_00_OjRFB4zvxu6UALDjytZD0978"},"content":[{"type":"tool-result","toolCallId":"call_00_OjRFB4zvxu6UALDjytZD0978","content":[{"type":"text","text":"{{cwd}}/greeting.txt\nfile\n\n1: hello\n\n(End of file - total 1 lines)\n"}],"isError":false}],"role":"user","id":"59ffbde4-d450-4564-a907-beeec29af0d0"},"meta":{"path":"{{cwd}}/greeting.txt","offset":1,"lines":[{"number":1,"text":"hello"}],"totalLines":1}},"sourceEventSeqs":[80],"surfaceOp":"append"} {"type":"step/end","seq":82,"time":1783352265504,"data":{"turn":1,"step":1}} {"type":"step/start","seq":83,"time":1783352265505,"data":{"turn":1,"step":2}} {"type":"assistant/chunk","seq":84,"time":1783352266385,"data":{"turn":1,"step":2,"chunk":{"type":"block-start","index":0,"blockType":"reasoning"}}} diff --git a/packages/cordis/tool-cordis/src/api-catalog.ts b/packages/cordis/tool-cordis/src/api-catalog.ts index 6c3df1f8d1..f119771429 100644 --- a/packages/cordis/tool-cordis/src/api-catalog.ts +++ b/packages/cordis/tool-cordis/src/api-catalog.ts @@ -2101,7 +2101,7 @@ export const TYPE_API: readonly TypeApiEntry[] = [ }, { name: 'ReadResultView', - declaration: 'export interface ReadResultView {\n card: \'read\';\n title?: string;\n path: string;\n lines: ReadFileLine[];\n totalLines: number;\n lang?: string;\n content?: ContentBlock[];\n}', + declaration: 'export interface ReadResultView {\n card: \'read\';\n title?: string;\n path: string;\n offset: number;\n lines: ReadFileLine[];\n totalLines: number;\n lang?: string;\n content?: ContentBlock[];\n}', }, { name: 'ReasoningBlock', diff --git a/packages/core/tools/README.i18n.yaml b/packages/core/tools/README.i18n.yaml index 10ae5b4c64..8a5dfcbee5 100644 --- a/packages/core/tools/README.i18n.yaml +++ b/packages/core/tools/README.i18n.yaml @@ -2,5 +2,5 @@ # side as of the last confirmed-consistent state. Both languages carry equal authority; # after editing either side, bring the other along and re-record with: # pnpm run verify-translation-pairing --write packages/core/tools/README.md -README.md: bff80e34d8b8a03424263ae978fe43c143bcb4fa -README.zh.md: 9d141cdfe91f14420bcd5a394b8bbd5871407b42 +README.md: dc3d059c1ce16f11cb0650e266762eb6d7466e34 +README.zh.md: 8d1ee0139b2d311fed07a0673cd772222ae22032 diff --git a/packages/core/tools/README.md b/packages/core/tools/README.md index bff80e34d8..dc3d059c1c 100644 --- a/packages/core/tools/README.md +++ b/packages/core/tools/README.md @@ -108,7 +108,7 @@ Optional `isConcurrencySafe(args)` receives typed, softly validated arguments. E Tools optionally own pure `presentCall()` and `presentResult()` render intents, so UIs do not special-case tool names: - Call views are `{ card: 'generic', title, kind?, rawInput?, content?, locations? }`, `{ card: 'terminal', title, description?, cwd? }`, or `{ card: 'diff', title, diffs, locations? }`. -- Result views are `{ card: 'generic', title?, content? }`, `{ card: 'terminal', title?, output?, exitCode?, signal? }`, `{ card: 'diff', title?, diffs }`, or `{ card: 'read', title?, path, lines, totalLines, lang?, content? }` (a completed file read → a line-numbered, optionally syntax-highlighted code view; `lines` is `{ number, text }[]` keeping each file line number, and `content` is the envelope-stripped text a UI without read support falls back to). +- Result views are `{ card: 'generic', title?, content? }`, `{ card: 'terminal', title?, output?, exitCode?, signal? }`, `{ card: 'diff', title?, diffs }`, or `{ card: 'read', title?, path, offset, lines, totalLines, lang?, content? }` (a completed file read → a line-numbered, optionally syntax-highlighted code view; `offset` is the 1-based first line the window requested, kept even when `lines` is empty; `lines` is `{ number, text }[]` keeping each file line number, and `content` is the envelope-stripped text a UI without read support falls back to). Returning `undefined` selects generic fallback. Presenters depend only on their arguments and the durable result because UIs call them during live streaming and log replay. `output.presentationMeta(args, value)` derives JSON metadata for direct surface calls; that metadata persists with `tool/result` and returns to `presentResult`, while the canonical value itself remains execution-local and is never replayed. Nested Code dispatches do not compute metadata. `defineTool` soft-validates older logged arguments and falls back instead of crashing replay. `dsh-tool-bash` and `dsh-tool-fs` are the reference implementations; the [canonical-output Agent Note](../../../.agents/notes/implemented/architecture/2026-07-20-canonical-tool-output-contract.md) owns the value/presentation split and the [render-intent Agent Note](../../../.agents/notes/implemented/architecture/2026-07-02-tool-render-intent-union.md) owns card vocabulary. diff --git a/packages/core/tools/README.zh.md b/packages/core/tools/README.zh.md index 9d141cdfe9..8d1ee0139b 100644 --- a/packages/core/tools/README.zh.md +++ b/packages/core/tools/README.zh.md @@ -108,7 +108,7 @@ ctx.tools.register(defineTool({ 工具可以选择拥有纯 `presentCall()` 和 `presentResult()` 呈现意图,使 UI 无需特殊处理工具名称: - 调用视图为 `{ card: 'generic', title, kind?, rawInput?, content?, locations? }`、`{ card: 'terminal', title, description?, cwd? }` 或 `{ card: 'diff', title, diffs, locations? }`。 -- 结果视图为 `{ card: 'generic', title?, content? }`、`{ card: 'terminal', title?, output?, exitCode?, signal? }`、`{ card: 'diff', title?, diffs }` 或 `{ card: 'read', title?, path, lines, totalLines, lang?, content? }`(已完成的文件读取→带行号、可选语法高亮的代码视图;`lines` 是 `{ number, text }[]`,保留每一行的文件行号,`content` 是无读取能力的 UI 回退时使用的去信封文本)。 +- 结果视图为 `{ card: 'generic', title?, content? }`、`{ card: 'terminal', title?, output?, exitCode?, signal? }`、`{ card: 'diff', title?, diffs }` 或 `{ card: 'read', title?, path, offset, lines, totalLines, lang?, content? }`(已完成的文件读取→带行号、可选语法高亮的代码视图;`offset` 是窗口请求的 1-based 起始行,即使 `lines` 为空也保留;`lines` 是 `{ number, text }[]`,保留每一行的文件行号,`content` 是无读取能力的 UI 回退时使用的去信封文本)。 返回 `undefined` 会选择通用回退。呈现器只依赖其参数和持久结果,因为 UI 会在实时流式输出和日志回放期间调用它们。`output.presentationMeta(args, value)` 为直接接口调用派生 JSON 元数据;该元数据随 `tool/result` 持久化并传回 `presentResult`,而规范值本身仍只存在于执行局部,绝不会回放。嵌套 Code 分发不会计算元数据。`defineTool` 会软验证较旧的日志参数并回退,而不会使回放崩溃。`dsh-tool-bash` 与 `dsh-tool-fs` 是参考实现;[规范输出 Agent Note](../../../.agents/notes/implemented/architecture/2026-07-20-canonical-tool-output-contract.md) 规定值/呈现拆分,[呈现意图 Agent Note](../../../.agents/notes/implemented/architecture/2026-07-02-tool-render-intent-union.md) 规定卡片词汇。 diff --git a/packages/core/tools/src/presentation.ts b/packages/core/tools/src/presentation.ts index f553442d0a..fd8baaad5e 100644 --- a/packages/core/tools/src/presentation.ts +++ b/packages/core/tools/src/presentation.ts @@ -207,6 +207,12 @@ export interface ReadResultView { title?: string /** The read file's path (the model-facing path; the bridge relativizes it). */ path: string + /** + * The 1-based first line the window requested, preserved even when `lines` is + * empty (a byte cap below the first selected line yields an empty window) so a + * UI knows where the window starts and where a continuation resumes. + */ + offset: number /** The returned window's lines, in file order, each keeping its file line number. */ lines: ReadFileLine[] /** Exact total line count in the file, so a UI can show a "showing N of M" affordance. */ diff --git a/packages/fs/tool-fs/README.i18n.yaml b/packages/fs/tool-fs/README.i18n.yaml index 0fd5a37feb..65c6b65268 100644 --- a/packages/fs/tool-fs/README.i18n.yaml +++ b/packages/fs/tool-fs/README.i18n.yaml @@ -2,5 +2,5 @@ # side as of the last confirmed-consistent state. Both languages carry equal authority; # after editing either side, bring the other along and re-record with: # pnpm run verify-translation-pairing --write packages/fs/tool-fs/README.md -README.md: 9e72ed53324d5f5efeaf659427c02d826221425c -README.zh.md: aa94a7f6144b6cc6da34b059f5699312737d38a2 +README.md: c00b59fed06249e6d9479c4a809cdf7d78f93239 +README.zh.md: f90fbb36391c1388ab0f6836daa2a9061d046be6 diff --git a/packages/fs/tool-fs/README.md b/packages/fs/tool-fs/README.md index 9e72ed5332..c00b59fed0 100644 --- a/packages/fs/tool-fs/README.md +++ b/packages/fs/tool-fs/README.md @@ -34,7 +34,7 @@ All keys are optional; the defaults are the shipped read caps. Field names are snake_case to match Claude Code and existing harness tool schemas. -Canonical successes are `read` → `{ path, offset, lines: [{ number, text }], totalLines }`, `write` → `{ path, operation: 'create' | 'update', before: string | null, after }`, and `edit` → `{ path, before, after }`. Native renderers preserve the line-numbered read and mutation acknowledgements below. `write`/`edit` derive replayable diff-card metadata, and `read` derives a replayable read-card window `{ path, lines, totalLines, lang? }`, from these canonical values; the canonical values themselves are execution-local and are not added to `tool/result`, only the derived presentation metadata is persisted. +Canonical successes are `read` → `{ path, offset, lines: [{ number, text }], totalLines }`, `write` → `{ path, operation: 'create' | 'update', before: string | null, after }`, and `edit` → `{ path, before, after }`. Native renderers preserve the line-numbered read and mutation acknowledgements below. `write`/`edit` derive replayable diff-card metadata, and `read` derives a replayable read-card window `{ path, offset, lines, totalLines, lang? }`, from these canonical values; the canonical values themselves are execution-local and are not added to `tool/result`, only the derived presentation metadata is persisted. ## The tool is the executor; policy is an event gate diff --git a/packages/fs/tool-fs/README.zh.md b/packages/fs/tool-fs/README.zh.md index aa94a7f614..f90fbb3639 100644 --- a/packages/fs/tool-fs/README.zh.md +++ b/packages/fs/tool-fs/README.zh.md @@ -34,7 +34,7 @@ await ctx.plugin(ToolFs) // this package — re 字段名使用 snake_case,与 Claude Code 和现有 harness 工具 schema 一致。 -规范成功值分别为:`read` → `{ path, offset, lines: [{ number, text }], totalLines }`,`write` → `{ path, operation: 'create' | 'update', before: string | null, after }`,`edit` → `{ path, before, after }`。原生渲染器会保留下方带行号的读取结果和变更确认。`write`/`edit` 从这些规范值派生可回放的 diff 卡片元数据,`read` 派生可回放的读取卡片窗口 `{ path, lines, totalLines, lang? }`;规范值本身仅限于本次执行,不会添加到 `tool/result`,只有派生出的呈现元数据会被持久化。 +规范成功值分别为:`read` → `{ path, offset, lines: [{ number, text }], totalLines }`,`write` → `{ path, operation: 'create' | 'update', before: string | null, after }`,`edit` → `{ path, before, after }`。原生渲染器会保留下方带行号的读取结果和变更确认。`write`/`edit` 从这些规范值派生可回放的 diff 卡片元数据,`read` 派生可回放的读取卡片窗口 `{ path, offset, lines, totalLines, lang? }`;规范值本身仅限于本次执行,不会添加到 `tool/result`,只有派生出的呈现元数据会被持久化。 ## 工具就是执行器;策略是事件门禁 diff --git a/packages/fs/tool-fs/src/read-render.ts b/packages/fs/tool-fs/src/read-render.ts index 68a2d44e28..19b6c0b1e7 100644 --- a/packages/fs/tool-fs/src/read-render.ts +++ b/packages/fs/tool-fs/src/read-render.ts @@ -220,6 +220,8 @@ export function langFromPath(path: string): string | undefined { export interface FsReadMeta { /** The read file's model-facing path. */ path: string + /** The 1-based first line the window requested, kept even when `lines` is empty. */ + offset: number /** The returned window's lines, each keeping its file line number. */ lines: FileTextLine[] /** Exact total line count in the file. */ @@ -245,24 +247,26 @@ function isFileTextLine(value: unknown): value is FileTextLine { * Malformed metadata returns `undefined` so presentation can fall back to the * generic text card instead of throwing during replay. Beyond shape, the * semantic contract of a read window is enforced against replayed JSON that is - * well-typed but out of range: `totalLines` must be a non-negative integer, each - * line number must be a 1-based integer, the line numbers must strictly increase, - * and no line number may exceed `totalLines`. Any violation declines to the - * generic fallback rather than emitting a card that misnumbers or overcounts. + * well-typed but out of range: `offset` must be a 1-based integer, `totalLines` + * must be a non-negative integer, each line number must be a 1-based integer no + * less than `offset`, the line numbers must strictly increase, and no line number + * may exceed `totalLines`. Any violation declines to the generic fallback rather + * than emitting a card that misnumbers or overcounts. * @param meta - result metadata. * @returns the validated read window, or `undefined` for absent, malformed, or semantically invalid data. */ export function readMetaFromMeta(meta: unknown): FsReadMeta | undefined { if (typeof meta !== 'object' || meta === null || Array.isArray(meta)) return undefined - const { path, lines, totalLines, lang } = meta as Record - if (typeof path !== 'string' || typeof totalLines !== 'number') return undefined + const { path, offset, lines, totalLines, lang } = meta as Record + if (typeof path !== 'string' || typeof totalLines !== 'number' || typeof offset !== 'number') return undefined + if (!Number.isInteger(offset) || offset < 1) return undefined if (!Number.isInteger(totalLines) || totalLines < 0) return undefined if (!Array.isArray(lines) || !lines.every(isFileTextLine)) return undefined if (lang !== undefined && typeof lang !== 'string') return undefined - let previous = 0 + let previous = offset - 1 for (const { number } of lines) { if (number <= previous || number > totalLines) return undefined previous = number } - return { path, lines, totalLines, ...lang === undefined ? {} : { lang } } + return { path, offset, lines, totalLines, ...lang === undefined ? {} : { lang } } } diff --git a/packages/fs/tool-fs/src/read.ts b/packages/fs/tool-fs/src/read.ts index 2ce98ca86f..a92fdcaad8 100644 --- a/packages/fs/tool-fs/src/read.ts +++ b/packages/fs/tool-fs/src/read.ts @@ -125,6 +125,7 @@ export function applyReadTool(ctx: Context, caps: ReadToolCaps): void { const lang = langFromPath(value.path) return { path: value.path, + offset: value.offset, lines: value.lines.map(({ number, text }) => ({ number, text })), totalLines: value.totalLines, ...lang === undefined ? {} : { lang }, @@ -186,6 +187,7 @@ export function applyReadTool(ctx: Context, caps: ReadToolCaps): void { return { card: 'read', path: meta.path, + offset: meta.offset, lines: meta.lines, totalLines: meta.totalLines, ...meta.lang === undefined ? {} : { lang: meta.lang }, diff --git a/packages/fs/tool-fs/tests/read-render.spec.ts b/packages/fs/tool-fs/tests/read-render.spec.ts index 848e54fc7c..cc03a0c8f9 100644 --- a/packages/fs/tool-fs/tests/read-render.spec.ts +++ b/packages/fs/tool-fs/tests/read-render.spec.ts @@ -151,14 +151,19 @@ describe('langFromPath', () => { }) describe('readMetaFromMeta', () => { - const good = { path: '/abs/a.ts', lines: [{ number: 1, text: 'x' }], totalLines: 1, lang: 'ts' } + const good = { path: '/abs/a.ts', offset: 1, lines: [{ number: 1, text: 'x' }], totalLines: 1, lang: 'ts' } it('narrows a well-formed read meta, with and without a lang hint', () => { expect(readMetaFromMeta(good)).toEqual(good) - const noLang = { path: '/abs/a', lines: [], totalLines: 0 } + const noLang = { path: '/abs/a', offset: 1, lines: [], totalLines: 0 } expect(readMetaFromMeta(noLang)).toEqual(noLang) }) + it('narrows an empty window at a positive offset (byte cap below the first selected line)', () => { + const empty = { path: '/abs/a', offset: 5, lines: [], totalLines: 9 } + expect(readMetaFromMeta(empty)).toEqual(empty) + }) + it('returns undefined for absent, non-object, or array meta', () => { expect(readMetaFromMeta(undefined)).toBeUndefined() expect(readMetaFromMeta(null)).toBeUndefined() @@ -168,6 +173,7 @@ describe('readMetaFromMeta', () => { it('returns undefined when a field is missing or the wrong type (defensive narrowing)', () => { expect(readMetaFromMeta({ ...good, path: 5 })).toBeUndefined() + expect(readMetaFromMeta({ ...good, offset: '1' })).toBeUndefined() expect(readMetaFromMeta({ ...good, totalLines: '1' })).toBeUndefined() expect(readMetaFromMeta({ ...good, lines: 'nope' })).toBeUndefined() expect(readMetaFromMeta({ ...good, lines: [{ number: '1', text: 'x' }] })).toBeUndefined() @@ -176,6 +182,17 @@ describe('readMetaFromMeta', () => { expect(readMetaFromMeta({ ...good, lang: 5 })).toBeUndefined() }) + it('rejects an offset that is not a 1-based integer', () => { + expect(readMetaFromMeta({ ...good, offset: 0 })).toBeUndefined() + expect(readMetaFromMeta({ ...good, offset: 1.5 })).toBeUndefined() + expect(readMetaFromMeta({ ...good, offset: NaN })).toBeUndefined() + expect(readMetaFromMeta({ ...good, offset: Infinity })).toBeUndefined() + }) + + it('rejects a first line number below offset', () => { + expect(readMetaFromMeta({ ...good, offset: 2, lines: [{ number: 1, text: 'x' }], totalLines: 2 })).toBeUndefined() + }) + it('rejects a line number that is not a 1-based integer', () => { expect(readMetaFromMeta({ ...good, lines: [{ number: 0, text: 'x' }], totalLines: 1 })).toBeUndefined() expect(readMetaFromMeta({ ...good, lines: [{ number: 1.5, text: 'x' }], totalLines: 2 })).toBeUndefined() @@ -190,7 +207,7 @@ describe('readMetaFromMeta', () => { }) it('rejects lines that do not strictly increase or exceed totalLines', () => { - const twoLines = { path: '/abs/a', lang: 'ts' } + const twoLines = { path: '/abs/a', offset: 1, lang: 'ts' } // Duplicate line numbers. expect(readMetaFromMeta({ ...twoLines, lines: [{ number: 1, text: 'a' }, { number: 1, text: 'b' }], totalLines: 2 })).toBeUndefined() // Out-of-order line numbers. diff --git a/packages/fs/tool-fs/tests/tools.spec.ts b/packages/fs/tool-fs/tests/tools.spec.ts index 87029e2a87..87177095ab 100644 --- a/packages/fs/tool-fs/tests/tools.spec.ts +++ b/packages/fs/tool-fs/tests/tools.spec.ts @@ -329,6 +329,7 @@ describe('read tool', () => { // The extension drives the lang hint; the window rides on persisted meta. expect(result.meta).toEqual({ path: '/abs/a.ts', + offset: 1, lines: [{ number: 1, text: 'const x = 1' }, { number: 2, text: 'const y = 2' }], totalLines: 2, lang: 'ts', @@ -337,6 +338,7 @@ describe('read tool', () => { expect(view).toEqual({ card: 'read', path: '/abs/a.ts', + offset: 1, lines: [{ number: 1, text: 'const x = 1' }, { number: 2, text: 'const y = 2' }], totalLines: 2, lang: 'ts', @@ -349,7 +351,7 @@ describe('read tool', () => { fs.files.set('key:notes', 'plain') const result = await call(ctx, 'read', { file_path: 'notes' }) if (result.isError) throw new Error('expected read success') - expect(result.meta).toEqual({ path: '/abs/notes', lines: [{ number: 1, text: 'plain' }], totalLines: 1 }) + expect(result.meta).toEqual({ path: '/abs/notes', offset: 1, lines: [{ number: 1, text: 'plain' }], totalLines: 1 }) }) }) @@ -485,7 +487,7 @@ describe('tool-owned presentation (pure presentCall)', () => { // The structured line data rides on persisted meta (the raw output object is // not on the wire); presentResult narrows it and appends the stripped text as // the no-capability `content` fallback. - const meta = { path: '/tmp/a.ts', lines: [{ number: 1, text: 'hello' }], totalLines: 1, lang: 'ts' } + const meta = { path: '/tmp/a.ts', offset: 1, lines: [{ number: 1, text: 'hello' }], totalLines: 1, lang: 'ts' } expect(await presentResult('read', { file_path: 'a.ts' }, { content: [{ type: 'text', text: '/tmp/a.ts\nfile\n\n1: hello\n\n(End of file - total 1 lines)\n' }], isError: false, @@ -493,6 +495,7 @@ describe('tool-owned presentation (pure presentCall)', () => { })).toEqual({ card: 'read', path: '/tmp/a.ts', + offset: 1, lines: [{ number: 1, text: 'hello' }], totalLines: 1, lang: 'ts', @@ -502,10 +505,11 @@ describe('tool-owned presentation (pure presentCall)', () => { expect(await presentResult('read', { file_path: 'notes' }, { content: [{ type: 'text', text: '/tmp/notes\nfile\n\nbody\n' }], isError: false, - meta: { path: '/tmp/notes', lines: [{ number: 1, text: 'body' }], totalLines: 1 }, + meta: { path: '/tmp/notes', offset: 1, lines: [{ number: 1, text: 'body' }], totalLines: 1 }, })).toEqual({ card: 'read', path: '/tmp/notes', + offset: 1, lines: [{ number: 1, text: 'body' }], totalLines: 1, content: [{ type: 'text', text: 'body' }], From bef8db3addac9b9cd28a069c39a56ab9d68a1089 Mon Sep 17 00:00:00 2001 From: NI0317 Date: Thu, 30 Jul 2026 22:17:56 +0800 Subject: [PATCH 056/139] feat(web): add versioned first-run welcome --- ...seek-onboarding-credential-setup.i18n.yaml | 4 +- ...30-deepseek-onboarding-credential-setup.md | 6 +- ...deepseek-onboarding-credential-setup.zh.md | 6 +- ...versioned-gui-welcome-onboarding.i18n.yaml | 6 + ...-07-30-versioned-gui-welcome-onboarding.md | 35 ++++ ...-30-versioned-gui-welcome-onboarding.zh.md | 35 ++++ .../tests/onboarding-deepseek-config.e2e.ts | 74 +++++++- .../welcome.expected.md | 6 + docs/event-producer-consumer.md | 4 +- docs/module-graph.md | 4 +- packages/client/connection/src/index.ts | 1 + .../client/connection/tests/node-half.spec.ts | 4 +- packages/client/ui-models/README.i18n.yaml | 4 +- packages/client/ui-models/README.md | 4 +- packages/client/ui-models/README.zh.md | 4 +- .../src/client/DeepSeekOnboardingDialog.tsx | 21 +-- .../tests/onboarding-dialog.spec.tsx | 21 +-- .../ui-settings-general/README.i18n.yaml | 6 +- packages/client/ui-settings-general/README.md | 4 +- .../client/ui-settings-general/README.zh.md | 4 +- .../client/ui-settings-general/package.json | 13 +- .../src/client/WelcomeNotice.module.css | 70 ++++++++ .../src/client/WelcomeNotice.tsx | 69 ++++++++ .../ui-settings-general/src/client/index.ts | 41 ++++- .../ui-settings-general/src/client/locales.ts | 13 ++ .../src/client/welcome-store.ts | 108 ++++++++++++ .../client/ui-settings-general/src/index.ts | 31 +++- .../ui-settings-general/src/invariant.ts | 7 +- .../src/onboarding-copy.ts | 33 ++++ .../ui-settings-general/tests/apply.spec.ts | 47 ++++- .../ui-settings-general/tests/host.spec.ts | 29 +++ .../tests/invariant.spec.ts | 6 - .../tests/welcome-notice.spec.tsx | 101 +++++++++++ .../tests/welcome-store.spec.ts | 166 ++++++++++++++++++ .../client/ui-settings-general/tsconfig.json | 9 + packages/client/ui-settings/README.i18n.yaml | 4 +- packages/client/ui-settings/README.md | 4 +- packages/client/ui-settings/README.zh.md | 4 +- .../ui-settings/src/client/SettingsRoot.tsx | 29 ++- .../ui-settings/src/client/contract/slots.ts | 24 ++- .../client/ui-settings/src/client/index.ts | 26 ++- .../client/ui-settings/tests/apply.spec.ts | 23 +++ .../ui-settings/tests/settings-root.spec.tsx | 32 +++- packages/host/apiproxy/README.i18n.yaml | 4 +- packages/host/apiproxy/README.md | 2 +- packages/host/apiproxy/README.zh.md | 2 +- packages/host/apiproxy/src/api-proxy.ts | 31 ++-- .../apiproxy/tests/api-proxy-config.spec.ts | 17 +- pnpm-lock.yaml | 13 ++ 49 files changed, 1096 insertions(+), 115 deletions(-) create mode 100644 .agents/notes/implemented/feature/2026-07-30-versioned-gui-welcome-onboarding.i18n.yaml create mode 100644 .agents/notes/implemented/feature/2026-07-30-versioned-gui-welcome-onboarding.md create mode 100644 .agents/notes/implemented/feature/2026-07-30-versioned-gui-welcome-onboarding.zh.md create mode 100644 apps/web/tests/snapshots/onboarding-deepseek-config/welcome.expected.md create mode 100644 packages/client/ui-settings-general/src/client/WelcomeNotice.module.css create mode 100644 packages/client/ui-settings-general/src/client/WelcomeNotice.tsx create mode 100644 packages/client/ui-settings-general/src/client/welcome-store.ts create mode 100644 packages/client/ui-settings-general/src/onboarding-copy.ts create mode 100644 packages/client/ui-settings-general/tests/host.spec.ts create mode 100644 packages/client/ui-settings-general/tests/welcome-notice.spec.tsx create mode 100644 packages/client/ui-settings-general/tests/welcome-store.spec.ts diff --git a/.agents/notes/implemented/feature/2026-07-30-deepseek-onboarding-credential-setup.i18n.yaml b/.agents/notes/implemented/feature/2026-07-30-deepseek-onboarding-credential-setup.i18n.yaml index 8beabfa66e..47ce2b206e 100644 --- a/.agents/notes/implemented/feature/2026-07-30-deepseek-onboarding-credential-setup.i18n.yaml +++ b/.agents/notes/implemented/feature/2026-07-30-deepseek-onboarding-credential-setup.i18n.yaml @@ -2,5 +2,5 @@ # side as of the last confirmed-consistent state. Both languages carry equal authority; # after editing either side, bring the other along and re-record with: # pnpm run verify-translation-pairing --write .agents/notes/implemented/feature/2026-07-30-deepseek-onboarding-credential-setup.md -2026-07-30-deepseek-onboarding-credential-setup.md: 3f75a0893623afc0908cb48f2b838321ed9dedd3 -2026-07-30-deepseek-onboarding-credential-setup.zh.md: 62f8f0b99f167b22051aaddf7331a043bd2ea812 +2026-07-30-deepseek-onboarding-credential-setup.md: 253800b7d94c80f1809c211ad0b3788b4ae4e07c +2026-07-30-deepseek-onboarding-credential-setup.zh.md: 2dd4de8185d0b6c8c33ad381a1b1aa358b07e872 diff --git a/.agents/notes/implemented/feature/2026-07-30-deepseek-onboarding-credential-setup.md b/.agents/notes/implemented/feature/2026-07-30-deepseek-onboarding-credential-setup.md index 3f75a08936..253800b7d9 100644 --- a/.agents/notes/implemented/feature/2026-07-30-deepseek-onboarding-credential-setup.md +++ b/.agents/notes/implemented/feature/2026-07-30-deepseek-onboarding-credential-setup.md @@ -12,11 +12,11 @@ The [web configuration plane](../architecture/2026-07-30-web-config-plane.md) ma **One readiness projection owns both Models and onboarding facts.** `ui-models` keeps a single store that joins `llm.providers({})`, redacted `settings.describe({})`, and batched `credentials.describe({refs})`. The onboarding projection selects the `deepseek-official` configurable-provider entry, resolves its `settingsNs` and `settingsPath`, reads the effective `apiKeyEnv`, and evaluates the matching credential descriptor. A configured literal `apiKey` secret sidecar is also ready, so compatibility configuration does not trigger a false prompt; a configured process-environment credential is ready and remains read-only. -**The settings shell contributes navigation state, not provider policy.** `ui-settings` declares a root-scoped `settings.onboarding` list slot and tells registrants whether the current surface is the empty Hero. Its private `openSection(id)` callback opens the settings panel on one registered section. `ui-models` registers the DeepSeek overlay through the same declaration-aware deferred-registration path as its Models section, so plugin load order does not become a contract. +**The settings shell contributes ordering and navigation, not provider policy.** `ui-settings` declares a root-scoped `settings.onboarding` list slot and mounts one ordered step at a time while the current surface is the empty Hero. The active registrant receives `complete()` and a private `openSection(id)` callback; completion transfers ownership to the next entry. `ui-models` registers the DeepSeek step through the same declaration-aware deferred-registration path as its Models section, so plugin load order does not become a contract and independently contributed dialogs cannot stack. The product-wide welcome step that precedes it is owned separately by [the versioned welcome decision](2026-07-30-versioned-gui-welcome-onboarding.md). **The prompt routes to the one credential editor.** A mounted, active adapter with a resolved, writable, unconfigured reference presents one action that opens Settings on Models. The existing DeepSeek setup card there exclusively owns the password input, `credentials.set({ref, value})`, write failures, and post-write refresh; the onboarding overlay never holds or submits a secret. An unavailable settings or credential capability keeps its deployment diagnostic and routes to the same page, while an absent adapter remains skipped because navigation cannot mount a Cordis plugin. -**Unavailable states stay honest.** An absent configurable-provider entry suppresses the prompt because navigation cannot repair the composition. A present provider whose settings or credential capability cannot be resolved renders an actionable deployment diagnostic; a failed initial join names the connection problem and leads to the Models retry surface. Configure later dismisses the overlay for the current mounted surface and writes no completion fact. Settings, credential, provider-topology, and connection invalidations all refresh the shared join, so an external credential update closes an open prompt without a reload. +**Unavailable states stay honest.** An absent configurable-provider entry completes the step because navigation cannot repair the composition. A present provider whose settings or credential capability cannot be resolved renders an actionable deployment diagnostic; a failed initial join names the connection problem and leads to the Models retry surface. Configure later completes only this mounted coordinator pass and writes no completion fact. Settings, credential, provider-topology, and connection invalidations all refresh the shared join, so an external credential update completes an open step without a reload. ## Alternatives considered @@ -30,4 +30,4 @@ The [web configuration plane](../architecture/2026-07-30-web-config-plane.md) ma ## Consequences -The first-run flow now leads to the shipped adapter's existing editor without restarting: a keyless browser test boots the real Web composition under an isolated harness home, follows the prompt to Models, stores a generated key through that page into the home's `.env`, verifies no key reaches DOM, ARIA, or browser console output, and confirms the running page reports configured. Pure readiness and React tests pin literal, file, process-environment, missing-provider, missing-capability, navigation, cancellation, and external-invalidation behavior. The flow deliberately inherits the configuration plane's documented base limitations rather than adding local secret storage, redaction, or settings replacement workarounds. +The ordered flow leads from the product welcome step to the shipped adapter's existing editor without restarting: a keyless browser test boots the real Web composition under an isolated harness home, acknowledges the welcome notice, follows the DeepSeek step to Models, stores a generated key through that page into the home's `.env`, verifies no key reaches DOM, ARIA, or browser console output, and confirms the running page reports configured. Pure readiness and React tests pin literal, file, process-environment, missing-provider, missing-capability, navigation, cancellation, external-invalidation, and coordinator-transfer behavior. The flow deliberately inherits the configuration plane's documented base limitations rather than adding local secret storage, redaction, or settings replacement workarounds. diff --git a/.agents/notes/implemented/feature/2026-07-30-deepseek-onboarding-credential-setup.zh.md b/.agents/notes/implemented/feature/2026-07-30-deepseek-onboarding-credential-setup.zh.md index 62f8f0b99f..2dd4de8185 100644 --- a/.agents/notes/implemented/feature/2026-07-30-deepseek-onboarding-credential-setup.zh.md +++ b/.agents/notes/implemented/feature/2026-07-30-deepseek-onboarding-credential-setup.zh.md @@ -12,11 +12,11 @@ Status: implemented **Models 与首次使用引导共享同一个就绪状态投影。**`ui-models` 维护一个 store,把 `llm.providers({})`、脱敏后的 `settings.describe({})` 和批量调用的 `credentials.describe({refs})` 联接为同一份状态。首次使用投影选取 `deepseek-official` 可配置提供方条目,解析其 `settingsNs` 与 `settingsPath`,读取生效的 `apiKeyEnv`,并检查对应的凭据描述符。若 `apiKey` 字面量对应的 secret 槽位标记为已设置,也会判定为就绪,兼容配置因此不会误触发浮层;通过进程环境提供的凭据若已配置,同样判定为就绪并保持只读。 -**设置外壳只贡献导航状态,不持有提供方策略。**`ui-settings` 声明一个根作用域的 `settings.onboarding` list slot,并告知注册方当前界面是否为空白 Hero。其私有 `openSection(id)` 回调会打开设置面板并切换到一个已注册分区。`ui-models` 沿用 Models 分区所使用、感知 slot 声明的延迟注册路径来注册 DeepSeek 浮层,因此插件加载顺序不会成为契约。 +**设置外壳只贡献排序与导航,不持有提供方策略。** `ui-settings` 声明一个根作用域的 `settings.onboarding` list slot,并在当前界面为空白 Hero 时,每次只挂载一个有序步骤。当前注册方会收到 `complete()` 和私有 `openSection(id)` 回调;完成当前步骤后,所有权转交给下一项。`ui-models` 沿用 Models 分区所使用、感知 slot 声明的延迟注册路径来注册 DeepSeek 步骤,因此插件加载顺序不会成为契约,独立贡献的对话框也无法堆叠。排在它之前的产品级欢迎步骤由[版本化欢迎决策](2026-07-30-versioned-gui-welcome-onboarding.md)单独持有。 **浮层只负责跳转到唯一的凭据编辑器。**适配器已挂载且处于活跃状态,其引用可解析、可写但尚未配置时,界面会显示一个操作按钮,用于打开「设置」的 Models 分区。该分区已有的 DeepSeek 设置卡片全权负责密码输入框、`credentials.set({ref, value})`、写入失败处理和写入后刷新;首次使用浮层绝不持有或提交 secret。设置或凭据能力不可用时会保留部署诊断,并提供前往同一页面的入口;适配器缺失时仍直接跳过,因为导航无法挂载 Cordis 插件。 -**不可用状态如实呈现。**可配置提供方条目缺失时不显示浮层,因为导航无法修复当前组合。提供方存在,但设置或凭据能力无法解析时,界面会显示可采取操作的部署诊断;初始联接失败时会明确指出连接问题,并引导前往 Models 的重试界面。「稍后配置」只会在当前已挂载界面中关闭浮层,不写入任何完成状态。设置、凭据、提供方拓扑和连接失效事件都会刷新共享联接,因此外部凭据更新无需重新加载页面即可关闭已打开的浮层。 +**不可用状态如实呈现。** 可配置提供方条目缺失时会完成当前步骤,因为导航无法修复当前组合。提供方存在,但设置或凭据能力无法解析时,界面会显示可采取操作的部署诊断;初始联接失败时会明确指出连接问题,并引导前往 Models 的重试界面。「稍后配置」只会完成协调器当前这一次挂载流程,不写入任何完成状态。设置、凭据、提供方拓扑和连接失效事件都会刷新共享联接,因此外部凭据更新无需重新加载页面即可完成已打开的步骤。 ## 曾考虑的替代方案 @@ -30,4 +30,4 @@ Status: implemented ## 后果 -首次使用流程现在无需重启即可引导用户前往随产品提供的适配器已有的编辑器:无密钥浏览器测试在隔离的 harness 家目录下启动真实 Web 组合,依照浮层操作前往 Models,通过该页面把生成的密钥存入该目录的 `.env`,验证密钥未进入 DOM、ARIA 或浏览器控制台输出,并确认运行中的页面报告已配置。纯就绪状态测试与 React 测试固化了字面量凭据、文件凭据、进程环境凭据、提供方缺失、能力缺失、导航、取消和外部失效行为。该流程直接继承配置平面已记录的基础限制,不会另加局部的机密存储、脱敏或设置替换变通方案。 +有序流程从产品欢迎步骤开始,无需重启即可引导用户前往随产品提供的适配器已有的编辑器:无密钥浏览器测试在隔离的 harness 家目录下启动真实 Web 组合,确认欢迎通知后依照 DeepSeek 步骤前往 Models,通过该页面把生成的密钥存入该目录的 `.env`,验证密钥未进入 DOM、ARIA 或浏览器控制台输出,并确认运行中的页面报告已配置。纯就绪状态测试与 React 测试固化了字面量凭据、文件凭据、进程环境凭据、提供方缺失、能力缺失、导航、取消、外部失效和协调器移交行为。该流程直接继承配置平面已记录的基础限制,不会另加局部的机密存储、脱敏或设置替换变通方案。 diff --git a/.agents/notes/implemented/feature/2026-07-30-versioned-gui-welcome-onboarding.i18n.yaml b/.agents/notes/implemented/feature/2026-07-30-versioned-gui-welcome-onboarding.i18n.yaml new file mode 100644 index 0000000000..24bdee3b68 --- /dev/null +++ b/.agents/notes/implemented/feature/2026-07-30-versioned-gui-welcome-onboarding.i18n.yaml @@ -0,0 +1,6 @@ +# Bilingual-pair consistency record (docs/i18n/README.md): the git blob hash of each +# side as of the last confirmed-consistent state. Both languages carry equal authority; +# after editing either side, bring the other along and re-record with: +# pnpm run verify-translation-pairing --write .agents/notes/implemented/feature/2026-07-30-versioned-gui-welcome-onboarding.md +2026-07-30-versioned-gui-welcome-onboarding.md: 405c6fe833d995123cd15e5694cd5ef75a0cd03d +2026-07-30-versioned-gui-welcome-onboarding.zh.md: ea83aa958866ab3dcca749f362d43e4b29408e02 diff --git a/.agents/notes/implemented/feature/2026-07-30-versioned-gui-welcome-onboarding.md b/.agents/notes/implemented/feature/2026-07-30-versioned-gui-welcome-onboarding.md new file mode 100644 index 0000000000..405c6fe833 --- /dev/null +++ b/.agents/notes/implemented/feature/2026-07-30-versioned-gui-welcome-onboarding.md @@ -0,0 +1,35 @@ +# Agent Note: Versioned GUI welcome onboarding + +Status: implemented + +English | [中文](2026-07-30-versioned-gui-welcome-onboarding.zh.md) + +## Problem + +The GUI's credential onboarding begins with a DeepSeek-specific readiness check, but the internal-test notice applies to every user and must precede provider setup even when a credential is already configured. Treating both as independent overlays permits simultaneous dialogs, while a process-local dismissal cannot distinguish a completed notice from a window closed before acknowledgement or intentionally present revised copy once. + +## Decision + +**The Settings shell coordinates ordered steps.** `settings.onboarding` remains a root-scoped list, but `ui-settings` projects its entry ids and order into one coordinator and mounts only the first incomplete step. The active registrant receives `complete()` and `openSection(id)`; no later step mounts until ownership transfers. The product welcome registers at order `-100`, while `ui-models` retains only the conditional DeepSeek readiness and credential-routing step at order `0`. + +**Ownerless product onboarding belongs to `ui-settings-general`.** `src/onboarding-copy.ts` is the single editable source for the complete Chinese notice, its faithful English counterpart, the Continue labels, and `WELCOME_NOTICE_VERSION`. Runtime locale dictionaries derive their welcome values from that file, and tests import the same owner instead of repeating paragraph text. The notice is browser UI only: it creates no Session event and contributes no model-visible content. + +**Acknowledgement is durable per Harness profile.** The Host half registers a `ui-onboarding` section in the user-settings seam, stored under the active `$DSH_HOME/settings.yaml`. The browser shows the notice unless `welcomeNoticeVersion` equals the owner constant exactly. Continue applies one path mutation with the current version and calls `complete()` only after the Host commits it; a failed write leaves the notice open, and closing the page or process writes nothing. Bumping the constant intentionally makes every profile acknowledge the revised copy once. + +**Concurrent views converge without stale replacement.** The acknowledgement write omits `expectedRevision` deliberately: every tab writes the same version to one path, so the operation is idempotent and preserves sibling fields instead of rebuilding the section. `settings/document-updated` becomes `host/settings-changed`; an already mounted tab refetches and advances when another tab or an external editor commits the current version. The API proxy exposes this one product namespace through a closed allowlist beside configurable-provider namespaces, without treating its changes as model-catalog invalidations. + +**The welcome modal has one completion path.** It renders no close icon or secondary action, installs no Escape handler, and assigns no click handler to the mask. Its mask starts below the 80 px top chrome and preserves `position:absolute`, zero left/right/bottom offsets, `rgba(0, 0, 0, 0.24)`, and `backdrop-filter: blur(2px)`. Continue is the sole button and receives initial focus. + +## Alternatives considered + +**Browser local storage** — rejected because acknowledgement would follow one browser profile rather than `$DSH_HOME`; a fresh Harness profile could incorrectly inherit a prior acknowledgement, and external profile edits would have no authoritative update stream. + +**A second independent modal in `ui-settings-general`** — rejected because list registrants would still stack whenever welcome and credential readiness were both true. Ordered ownership belongs to the shell that declares and renders the list. + +**Persisting on render or window close** — rejected because observation is not acknowledgement and close delivery is unreliable. Only the explicit Continue commit may suppress the next launch. + +**A generic public settings-exposure flag** — rejected because one product namespace does not justify widening every settings registrant's public configuration surface. The gateway keeps an explicit closed allowlist. + +## Consequences + +A fresh profile always sees the welcome notice before provider-specific onboarding; an already configured credential skips only the later DeepSeek step. Reloading after Continue stays past the acknowledged version, changing the owner version presents it again, and closing before Continue leaves the next launch unchanged. Focused store and React tests pin exact-version comparison, write failure, sole-action behavior, no-dismiss paths, coordinator ordering, conditional DeepSeek transfer, and HMR cleanup. The real Chromium scenario boots the shipped Web composition with an isolated harness home, verifies the exact mask geometry and computed styles, reloads before and after acknowledgement, continues into missing-credential setup, confirms an acknowledged-version mismatch returns while the credential is configured, and checks the browser console. diff --git a/.agents/notes/implemented/feature/2026-07-30-versioned-gui-welcome-onboarding.zh.md b/.agents/notes/implemented/feature/2026-07-30-versioned-gui-welcome-onboarding.zh.md new file mode 100644 index 0000000000..ea83aa9588 --- /dev/null +++ b/.agents/notes/implemented/feature/2026-07-30-versioned-gui-welcome-onboarding.zh.md @@ -0,0 +1,35 @@ +# Agent Note: 版本化 GUI 欢迎引导 + +Status: implemented + +[English](2026-07-30-versioned-gui-welcome-onboarding.md) | 中文 + +## 问题 + +GUI 的凭据引导从 DeepSeek 专用的就绪状态检查开始,但内部测试通知适用于每位用户,即使凭据已经配置,也必须先于提供方设置显示。若把两者作为独立浮层处理,多个对话框可能同时出现;仅存于进程内的关闭标记既无法区分通知已完成确认还是窗口在确认前已关闭,也无法在文案有意修订后重新显示一次通知。 + +## 决策 + +**设置外壳协调有序步骤。** `settings.onboarding` 仍是根作用域 list,但 `ui-settings` 会把其中各条目的 id 和顺序投影到一个协调器中,并且只挂载第一个未完成的步骤。当前注册方会收到 `complete()` 和 `openSection(id)`;所有权转移前,不会挂载后续步骤。产品欢迎步骤的顺序为 `-100`,`ui-models` 则只保留顺序为 `0` 的 DeepSeek 条件式就绪状态与凭据跳转步骤。 + +**不属于单一功能的产品引导由 `ui-settings-general` 持有。** `src/onboarding-copy.ts` 是完整中文通知、忠实英文对侧文案、两种语言的「继续」按钮文案和 `WELCOME_NOTICE_VERSION` 的唯一可编辑来源。运行时 locale 字典从该文件派生欢迎文案,测试也导入同一个所有者,而不重复段落文本。该通知只存在于浏览器 UI:它不会创建会话事件,也不会贡献任何模型可见内容。 + +**确认状态按 Harness profile 持久化。** 宿主端在 user-settings seam 中注册 `ui-onboarding` 分节,并存入当前 `$DSH_HOME/settings.yaml`。除非 `welcomeNoticeVersion` 与文案所有者文件中的常量精确相等,否则浏览器会显示通知。「继续」会以当前版本执行一次路径变更,并且仅在宿主端提交成功后调用 `complete()`;写入失败时通知保持打开,关闭页面或进程则不会写入任何内容。提升该常量会有意要求每个 profile 对修订后的文案重新确认一次。 + +**并发视图无需陈旧的整体替换即可收敛。** 确认写入有意省略 `expectedRevision`:每个标签页都向同一路径写入相同版本,因此该操作是幂等的,并会保留同级字段,而不是重建整个分节。`settings/document-updated` 会转为 `host/settings-changed`;另一个标签页或外部编辑器提交当前版本后,已挂载的标签页会重新拉取状态并推进。API 网关在可配置提供方 namespace 之外,通过封闭的允许列表暴露这一个产品 namespace,同时不会把它的变更视为模型目录失效事件。 + +**欢迎模态窗口只有一条完成路径。** 界面不渲染关闭图标或次要操作,不安装 Escape 处理器,也不为遮罩添加点击处理器。遮罩从顶部 80 px 的界面框架下方开始,并保留 `position:absolute`、left/right/bottom 偏移量为零、`rgba(0, 0, 0, 0.24)` 和 `backdrop-filter: blur(2px)`。「继续」是唯一按钮,并会获得初始焦点。 + +## 曾考虑的替代方案 + +**浏览器本地存储**:不予采用,因为确认状态会跟随某个浏览器 profile,而不是 `$DSH_HOME`;全新的 Harness profile 可能错误继承此前的确认状态,外部 profile 编辑也没有权威更新流。 + +**在 `ui-settings-general` 中再增加一个独立模态窗口**:不予采用,因为欢迎通知和凭据就绪状态同时为真时,list 注册方仍会堆叠。声明并渲染该 list 的外壳应当持有有序所有权。 + +**在渲染或窗口关闭时持久化**:不予采用,因为看见通知不等于确认,窗口关闭事件也无法可靠送达。只有显式提交「继续」才能阻止通知在下次启动时再次显示。 + +**通用的公开设置暴露标志**:不予采用,因为一个产品 namespace 不足以证明应当扩大每个 settings 注册方的公开配置面。网关保留显式的封闭允许列表。 + +## 后果 + +全新 profile 始终会在提供方专用引导之前看到欢迎通知;凭据已经配置时,只会跳过后续 DeepSeek 步骤。点击「继续」后重新加载不会再次显示已确认版本,更改文案所有者文件中的版本值会让通知重新出现,而确认前关闭窗口不会改变下次启动。针对性的 store 与 React 测试固化了精确版本比较、写入失败、单一操作、不可关闭路径、协调器顺序、按条件移交 DeepSeek 步骤和 HMR(热模块替换)清理行为。真实 Chromium 场景会使用隔离的 harness 家目录启动随产品提供的 Web 组合,验证遮罩的精确几何尺寸和计算样式,在确认前后分别重新加载,继续进入凭据缺失设置流程,确认凭据已配置时确认版本不匹配仍会使通知重新出现,并检查浏览器控制台。 diff --git a/apps/web/tests/onboarding-deepseek-config.e2e.ts b/apps/web/tests/onboarding-deepseek-config.e2e.ts index 62dd129982..f372910a61 100644 --- a/apps/web/tests/onboarding-deepseek-config.e2e.ts +++ b/apps/web/tests/onboarding-deepseek-config.e2e.ts @@ -9,12 +9,18 @@ import type { Browser, Page } from 'playwright' import { chromium } from 'playwright' import { afterAll, beforeAll, describe, expect, it, onTestFailed } from 'vitest' import { - assertFixtureInventory, captureStableAria, compareOrRefreshGolden, + acknowledgeReloadConnectionLoss, assertFixtureInventory, captureStableAria, compareOrRefreshGolden, launchWebScaffold, watchConsole, webSnapshotMode, type WebScaffold, } from './scaffold.ts' import { saveFailureShot } from './support.ts' +import { settingsNamespace } from '@deepseek-ai/dsh-settings' +import { + WELCOME_NOTICE_ACK_FIELD, WELCOME_NOTICE_COPY, WELCOME_NOTICE_SETTINGS_NAMESPACE, + WELCOME_NOTICE_VERSION, +} from '@deepseek-ai/dsh-client-ui-settings-general' const SNAPSHOT_DIR = fileURLToPath(new URL('./snapshots/onboarding-deepseek-config', import.meta.url)) +const WELCOME_EXPECTED = join(SNAPSHOT_DIR, 'welcome.expected.md') const MISSING_EXPECTED = join(SNAPSHOT_DIR, 'missing.expected.md') const MODE = webSnapshotMode() @@ -42,6 +48,47 @@ describe.skipIf(MODE === 'record')('web e2e: first-run DeepSeek credential setup it('stores a key write-only and observes configured state without restarting', async () => { onTestFailed(() => saveFailureShot(page, 'web-e2e-onboarding-deepseek-config')) + const welcome = page.getByRole('dialog', { name: WELCOME_NOTICE_COPY.zh.paragraphs[0] }) + await welcome.waitFor({ timeout: 15_000 }) + const welcomeAria = await captureStableAria(page, '[role="dialog"]', scaffold.workspaceCwd) + await compareOrRefreshGolden(WELCOME_EXPECTED, welcomeAria, MODE) + expect(await welcome.getByRole('button').allTextContents()).toEqual([WELCOME_NOTICE_COPY.zh.continueLabel]) + expect(await welcome.locator('button').count()).toBe(1) + + const maskStyles = await welcome.locator('xpath=..').locator(':scope > div').first().evaluate((mask) => { + const style = getComputedStyle(mask) + const rect = mask.getBoundingClientRect() + return { + position: style.position, + left: style.left, + right: style.right, + top: style.top, + bottom: style.bottom, + background: style.backgroundColor, + backdropFilter: style.backdropFilter, + rect: { left: rect.left, top: rect.top, right: rect.right, bottom: rect.bottom }, + } + }) + expect(maskStyles).toEqual({ + position: 'absolute', + left: '0px', + right: '0px', + top: '80px', + bottom: '0px', + background: 'rgba(0, 0, 0, 0.24)', + backdropFilter: 'blur(2px)', + rect: { left: 0, top: 80, right: 1440, bottom: 960 }, + }) + + // Closing the process/page before acknowledgement writes nothing, so the + // same durable profile presents the notice again after reload. + const firstReloadWarnings = tripwire.warnings.length + await page.reload({ waitUntil: 'load' }) + acknowledgeReloadConnectionLoss(tripwire, firstReloadWarnings) + await welcome.waitFor({ timeout: 15_000 }) + + await welcome.getByRole('button', { name: WELCOME_NOTICE_COPY.zh.continueLabel }).click() + await welcome.waitFor({ state: 'detached', timeout: 15_000 }) const dialog = page.getByRole('dialog', { name: '添加一个 API Key 开始使用' }) await dialog.waitFor({ timeout: 15_000 }) expect(await dialog.getByRole('textbox').count()).toBe(0) @@ -78,6 +125,29 @@ describe.skipIf(MODE === 'record')('web e2e: first-run DeepSeek credential setup { timeout: 10_000 }, ).toBe('已配置——输入新值可替换') + const acknowledgedSettings = await readFile(join(scaffold.harnessHome, 'settings.yaml'), 'utf8') + expect(acknowledgedSettings).toContain(`${WELCOME_NOTICE_ACK_FIELD}: ${WELCOME_NOTICE_VERSION}`) + + const secondReloadWarnings = tripwire.warnings.length + await page.reload({ waitUntil: 'load' }) + acknowledgeReloadConnectionLoss(tripwire, secondReloadWarnings) + await page.waitForSelector('[class*="frame"]', { timeout: 15_000 }) + expect(await page.getByRole('dialog', { name: WELCOME_NOTICE_COPY.zh.paragraphs[0] }).count()).toBe(0) + expect(await page.getByRole('dialog', { name: '添加一个 API Key 开始使用' }).count()).toBe(0) + + // A different stored copy version represents an intentional version bump: + // the welcome step returns even though the credential is already ready. + await scaffold.ctx.settings.mutate(settingsNamespace(WELCOME_NOTICE_SETTINGS_NAMESPACE), [{ + op: 'set', path: [WELCOME_NOTICE_ACK_FIELD], value: 'previous-copy-version', + }]) + const thirdReloadWarnings = tripwire.warnings.length + await page.reload({ waitUntil: 'load' }) + acknowledgeReloadConnectionLoss(tripwire, thirdReloadWarnings) + await welcome.waitFor({ timeout: 15_000 }) + await welcome.getByRole('button', { name: WELCOME_NOTICE_COPY.zh.continueLabel }).click() + await welcome.waitFor({ state: 'detached', timeout: 15_000 }) + expect(await page.getByRole('dialog', { name: '添加一个 API Key 开始使用' }).count()).toBe(0) + expect((await page.content()).includes(secret)).toBe(false) expect((await page.locator('body').ariaSnapshot()).includes(secret)).toBe(false) expect(browserConsole.some(line => line.includes(secret))).toBe(false) @@ -86,6 +156,6 @@ describe.skipIf(MODE === 'record')('web e2e: first-run DeepSeek credential setup }, 60_000) it('keeps the fixture inventory closed', async () => { - await assertFixtureInventory(SNAPSHOT_DIR, ['missing.expected.md']) + await assertFixtureInventory(SNAPSHOT_DIR, ['missing.expected.md', 'welcome.expected.md']) }) }) diff --git a/apps/web/tests/snapshots/onboarding-deepseek-config/welcome.expected.md b/apps/web/tests/snapshots/onboarding-deepseek-config/welcome.expected.md new file mode 100644 index 0000000000..370737df6b --- /dev/null +++ b/apps/web/tests/snapshots/onboarding-deepseek-config/welcome.expected.md @@ -0,0 +1,6 @@ +- dialog "感谢您愿意拨冗试用 DeepSeek Harness。": + - heading "感谢您愿意拨冗试用 DeepSeek Harness。" [level=2] + - paragraph: 目前的版本仍处于内部测试阶段,有些功能仍待完善,有些体验难免粗粝。 + - paragraph: “如切如磋,如琢如磨。” 产品的成长,离不开一次次真实的碰撞与坦诚的反馈。您在真实使用中暴露的问题,也可能促使我们重新审视,甚至推翻已有的设计。 + - paragraph: 我们尤其希望听见那些失败、困惑与不顺手的时刻——如果它未能帮到您,甚至反而为工作平添了麻烦,请在企业微信群中留言,将使用感受告诉我们。每一条反馈,都会帮助我们把它打磨得更好。 + - button "继续" diff --git a/docs/event-producer-consumer.md b/docs/event-producer-consumer.md index 14da68499b..4690a0ca2d 100644 --- a/docs/event-producer-consumer.md +++ b/docs/event-producer-consumer.md @@ -66,14 +66,14 @@ This matrix shows which packages dispatch each harness-owned event and which pac | Event string | Dispatchers | Listeners | | --- | --- | --- | | `commands/changed` | `runtime` (`emit`) | `ui-command` | -| `connection/reset` | `runtime` (`emit`) | `ui-command`, `ui-models` | +| `connection/reset` | `runtime` (`emit`) | `ui-command`, `ui-models`, `ui-settings-general` | | `credentials/changed` | `runtime` (`emit`) | `ui-models` | | `internal/dispatch` | - | [`commands`](../packages/ui/commands), [`compact`](../packages/compact/compact), [`fs`](../packages/fs/fs), [`goal`](../packages/goal/goal), [`goal-session`](../packages/goal/goal-session), [`hook-protocol`](../packages/hooks/hook-protocol), [`llm-retry`](../packages/llm/llm-retry), [`permission`](../packages/ui/permission), [`plan-mode`](../packages/plan/plan-mode), [`pty-local`](../packages/pty/pty-local), `runtime`, [`sandbox-policy`](../packages/sandbox/sandbox-policy), [`scope`](../packages/core/scope), [`session`](../packages/core/session), [`session-title`](../packages/session-title/session-title), [`subagent`](../packages/subagent/subagent), [`time-context`](../packages/context/time-context), [`tool-todo`](../packages/todo/tool-todo), [`tools`](../packages/core/tools), [`user-approval`](../packages/ui/user-approval), [`workflow`](../packages/workflow/workflow) | | `internal/plugin` | - | `hmr`, `loader`, `modules`, `webserver` | | `internal/status` | - | [`agent`](../packages/core/agent) | | `locale/change` | `locale` (`emit`) | `locale`, `ui-models`, `ui-settings-general` | | `models/changed` | `runtime` (`emit`) | `ui-models` | -| `settings/changed` | `runtime` (`emit`) | `ui-models` | +| `settings/changed` | `runtime` (`emit`) | `ui-models`, `ui-settings-general` | | `slash/input-begin-command` | - | `ui-conversation` | | `slash/input-consume-token` | - | `ui-conversation` | | `slash/input-insert-reference` | - | `ui-conversation` | diff --git a/docs/module-graph.md b/docs/module-graph.md index 5827cf458d..602dff45c4 100644 --- a/docs/module-graph.md +++ b/docs/module-graph.md @@ -367,11 +367,13 @@ flowchart TD pkg_client_ui_models --> pkg_invariants pkg_client_ui_question --> pkg_client_locale pkg_client_ui_question --> pkg_invariants + pkg_client_ui_settings_general --> pkg_client_connection pkg_client_ui_settings_general --> pkg_client_locale pkg_client_ui_settings_general --> pkg_client_runtime pkg_client_ui_settings_general --> pkg_client_ui_primitives pkg_client_ui_settings_general --> pkg_client_ui_settings pkg_client_ui_settings_general --> pkg_client_ui_slots + pkg_client_ui_settings_general --> pkg_client_web_react pkg_client_ui_settings_general --> pkg_invariants pkg_client_ui_sidebar --> pkg_client_locale pkg_client_ui_sidebar --> pkg_client_runtime @@ -1067,7 +1069,7 @@ flowchart TD | [`web`](../packages/web/web) | `web` | [`invariants`](../packages/support/invariants), [`llm`](../packages/llm/llm) | | [`client-ui-models`](../packages/client/ui-models) | `client` | [`client-connection`](../packages/client/connection), [`client-runtime`](../packages/client/runtime), [`client-schema-form`](../packages/client/schema-form), [`client-ui-primitives`](../packages/client/ui-primitives), [`client-ui-slots`](../packages/client/ui-slots), [`client-web-react`](../packages/client/web-react), [`invariants`](../packages/support/invariants) | | [`client-ui-question`](../packages/client/ui-question) | `client` | [`client-locale`](../packages/client/locale), [`invariants`](../packages/support/invariants) | -| [`client-ui-settings-general`](../packages/client/ui-settings-general) | `client` | [`client-locale`](../packages/client/locale), [`client-runtime`](../packages/client/runtime), [`client-ui-primitives`](../packages/client/ui-primitives), [`client-ui-settings`](../packages/client/ui-settings), [`client-ui-slots`](../packages/client/ui-slots), [`invariants`](../packages/support/invariants) | +| [`client-ui-settings-general`](../packages/client/ui-settings-general) | `client` | [`client-connection`](../packages/client/connection), [`client-locale`](../packages/client/locale), [`client-runtime`](../packages/client/runtime), [`client-ui-primitives`](../packages/client/ui-primitives), [`client-ui-settings`](../packages/client/ui-settings), [`client-ui-slots`](../packages/client/ui-slots), [`client-web-react`](../packages/client/web-react), [`invariants`](../packages/support/invariants) | | [`client-ui-sidebar`](../packages/client/ui-sidebar) | `client` | [`client-locale`](../packages/client/locale), [`client-runtime`](../packages/client/runtime), [`client-ui-primitives`](../packages/client/ui-primitives), [`client-ui-slots`](../packages/client/ui-slots), [`invariants`](../packages/support/invariants) | | [`client-ui-slash`](../packages/client/ui-slash) | `client` | [`client-locale`](../packages/client/locale), [`client-runtime`](../packages/client/runtime), [`client-ui-primitives`](../packages/client/ui-primitives), [`client-ui-slots`](../packages/client/ui-slots), [`invariants`](../packages/support/invariants) | | [`client-ui-theme`](../packages/client/ui-theme) | `client` | [`client-locale`](../packages/client/locale), [`client-runtime`](../packages/client/runtime), [`client-ui-primitives`](../packages/client/ui-primitives), [`client-ui-slots`](../packages/client/ui-slots), [`invariants`](../packages/support/invariants) | diff --git a/packages/client/connection/src/index.ts b/packages/client/connection/src/index.ts index cedc7d86e7..ed4af2d21f 100644 --- a/packages/client/connection/src/index.ts +++ b/packages/client/connection/src/index.ts @@ -54,6 +54,7 @@ const PRIVILEGED_METHODS = new Set([ 'settings.describe', 'settings.update', 'settings.replace', + 'settings.mutate', 'credentials.describe', 'credentials.set', 'credentials.unset', diff --git a/packages/client/connection/tests/node-half.spec.ts b/packages/client/connection/tests/node-half.spec.ts index 6839d8b3ca..4910ba990c 100644 --- a/packages/client/connection/tests/node-half.spec.ts +++ b/packages/client/connection/tests/node-half.spec.ts @@ -107,7 +107,7 @@ describe('connection node half', () => { // passed), but each privileged method stays loopback-only and 403s. for (const method of [ 'host.pickDirectory', 'host.openPath', - 'settings.describe', 'settings.update', 'settings.replace', + 'settings.describe', 'settings.update', 'settings.replace', 'settings.mutate', 'credentials.describe', 'credentials.set', 'credentials.unset', ]) { const denied = fakeResponse() @@ -191,7 +191,7 @@ describe('connection node half over a real HTTP server', () => { // Reads are as privileged as writes: describe returns the exposed // configuration, and credentials.describe probes arbitrary env-var names. for (const method of [ - 'settings.describe', 'settings.update', 'settings.replace', + 'settings.describe', 'settings.update', 'settings.replace', 'settings.mutate', 'credentials.describe', 'credentials.set', 'credentials.unset', 'host.pickDirectory', 'host.openPath', ]) { diff --git a/packages/client/ui-models/README.i18n.yaml b/packages/client/ui-models/README.i18n.yaml index 0355080b11..3bc6c94ec4 100644 --- a/packages/client/ui-models/README.i18n.yaml +++ b/packages/client/ui-models/README.i18n.yaml @@ -2,5 +2,5 @@ # side as of the last confirmed-consistent state. Both languages carry equal authority; # after editing either side, bring the other along and re-record with: # pnpm run verify-translation-pairing --write packages/client/ui-models/README.md -README.md: aac437a13f6465196fcf1f8908b1d9ea2ccef401 -README.zh.md: 468537ac217a46395f2ec78174efa1f5d75a679d +README.md: 2f53024df95a79862d5461d3514987a6e8257f9d +README.zh.md: 7c95709933fa29a8fd6ed773696e9657d959f753 diff --git a/packages/client/ui-models/README.md b/packages/client/ui-models/README.md index aac437a13f..2f53024df9 100644 --- a/packages/client/ui-models/README.md +++ b/packages/client/ui-models/README.md @@ -2,11 +2,11 @@ English | [中文](README.zh.md) -Models settings plugin: the provider configuration page and official-DeepSeek first-run routing overlay. It joins three wire domains into one shared snapshot — `llm.providers` (the configurable-provider directory with each route's live/dormant state), `settings.describe` (serialized schemas, layered redacted values, secret slots), and `credentials.describe` (value-free configured/source/writable badges) — and renders provider rows with one editor card at a time. +Models settings plugin: the provider configuration page and official-DeepSeek conditional onboarding step. It joins three wire domains into one shared snapshot — `llm.providers` (the configurable-provider directory with each route's live/dormant state), `settings.describe` (serialized schemas, layered redacted values, secret slots), and `credentials.describe` (value-free configured/source/writable badges) — and renders provider rows with one editor card at a time. Rows are the *configured* providers (their profile resolves in the owning namespace); a whole-section provider whose key is not configured anywhere (the first-run DeepSeek posture) renders as its open setup card instead of a row, and the add flow is a card carrying the dormant-directory provider select — a bare-mounted `llm-pi-ai` offers its whole installed catalog before any route exists. The editor is a hand-written card per adapter family: the primary field is a single **API key** input — the page never asks for an environment-variable name; a typed key stores **write-only** through `credentials.set` under the profile's reference, deriving `_API_KEY` when the profile has none, and the pi-ai profile records that derivation as `apiKeyEnv`, so `settings.yaml` never carries a key value. The collapsed 自定义设置 fold carries the curated extras — `baseURL` for both families (the deepseek placeholder shows the public endpoint), plus `reasoningEffort` (deepseek) or `reasoning` (pi-ai); every other profile field stays owned by `settings.yaml`. A row is deletable only when the user layer alone carries it (removal restores the composition base). -The first-run overlay projects `deepseek-official` readiness from that same joined snapshot. A configured literal `apiKey` secret sidecar or configured credential reference suppresses the prompt, including a read-only launch-environment credential. A mounted adapter with a missing writable reference shows one action that opens Settings on the Models section, whose existing setup card exclusively owns key input and `credentials.set`; the overlay never holds a secret. An absent adapter is skipped because browser navigation cannot mount Cordis plugins, while an unusable settings or credential capability produces a deployment diagnostic with the same route to Models. +The DeepSeek step projects `deepseek-official` readiness from that same joined snapshot after earlier onboarding steps complete. A configured literal `apiKey` secret sidecar or configured credential reference completes the step without rendering, including a read-only launch-environment credential. A mounted adapter with a missing writable reference shows one action that opens Settings on the Models section, whose existing setup card exclusively owns key input and `credentials.set`; the step never holds a secret. An absent adapter is skipped because browser navigation cannot mount Cordis plugins, while an unusable settings or credential capability produces a deployment diagnostic with the same route to Models. Every edit lands as `settings.mutate` path ops against the stored section — a set per changed field, an unset per cleared one, and a single unset for a deleted row. The page only ever holds the REDACTED descriptor, so it names the fields it can see rather than rebuilding a section: a stored literal secret it never received is mentioned by no op and survives. Each write carries the `revision` the card opened at, so a concurrent write from another tab or an external `settings.yaml` edit is refused as `settings-conflict` and the card asks the user to reopen instead of replaying its stale snapshot. The page refetches on the pushed invalidations (`settings/changed`, `credentials/changed`, `models/changed`, and `connection/reset`) once it has loaded, so an external `settings.yaml` edit, a second tab, or a settings-born route converges without polling. diff --git a/packages/client/ui-models/README.zh.md b/packages/client/ui-models/README.zh.md index 468537ac21..7c95709933 100644 --- a/packages/client/ui-models/README.zh.md +++ b/packages/client/ui-models/README.zh.md @@ -2,11 +2,11 @@ [English](README.md) | 中文 -模型设置插件:提供方配置页和 DeepSeek 官方首次使用跳转浮层。它把三个协议领域汇聚为一个共享快照:`llm.providers`(可配置提供方目录,含每条路由的存活/休眠状态)、`settings.describe`(序列化 schema、分层脱敏值、secret 槽位)与 `credentials.describe`(不含值的 configured/source/writable 徽标);页面据此渲染提供方行,一次只展开一张编辑卡片。 +模型设置插件:提供方配置页和按条件显示的 DeepSeek 官方首次使用引导步骤。它把三个协议领域汇聚为一个共享快照:`llm.providers`(可配置提供方目录,含每条路由的存活/休眠状态)、`settings.describe`(序列化 schema、分层脱敏值、secret 槽位)与 `credentials.describe`(不含值的 configured/source/writable 徽标);页面据此渲染提供方行,一次只展开一张编辑卡片。 行是*已配置*的提供方(其 profile 在所属 namespace 中解析得出);密钥未在任何地方配置的整分节提供方(DeepSeek 的首次运行姿态)会渲染为其展开的设置卡片而非一行,「新增」流程则是一张承载休眠目录提供方选择框的卡片——裸挂载的 `llm-pi-ai` 在任何路由存在之前就能提供其完整的已安装 catalog。编辑器是每个适配器家族各一张的手写卡片:主字段是单独一个 **API 密钥**输入框——页面从不询问环境变量名;键入的密钥经 `credentials.set` 以**只写**方式存入 profile 的引用之下,profile 没有引用时便派生 `_API_KEY`,pi-ai profile 会把这次派生记录为 `apiKeyEnv`,因此 `settings.yaml` 从不携带密钥值。收起的「自定义设置」折叠区承载精选的额外字段——两个家族都有 `baseURL`(deepseek 的占位符显示公共端点),另加 `reasoningEffort`(deepseek)或 `reasoning`(pi-ai);其余每个 profile 字段仍归 `settings.yaml` 所有。只有当某行仅由用户层承载时它才可删除(删除会还原组合 base)。 -首次使用浮层从同一个联接快照得出 `deepseek-official` 的就绪状态。若 `apiKey` 字面量对应的 secret 槽位标记为已设置,或凭据引用已配置,浮层就不再显示,其中包括来自启动环境且只读的凭据。适配器已挂载、引用可写但尚未配置时,浮层只显示一个操作按钮,用于打开「设置」的 Models 分区;密钥输入和 `credentials.set` 仅由该分区已有的设置卡片负责,浮层绝不持有 secret。适配器缺失时直接跳过,因为浏览器导航无法挂载 Cordis 插件;设置或凭据能力不可用时则显示部署诊断,并提供同一个前往 Models 的入口。 +前序首次使用引导步骤完成后,DeepSeek 步骤会从同一个联接快照得出 `deepseek-official` 的就绪状态。若 `apiKey` 字面量对应的 secret 槽位标记为已设置,或凭据引用已配置,该步骤会直接完成而不渲染,其中包括来自启动环境且只读的凭据。适配器已挂载、引用可写但尚未配置时,该步骤只显示一个操作按钮,用于打开「设置」的 Models 分区;密钥输入和 `credentials.set` 仅由该分区已有的设置卡片负责,该步骤绝不持有 secret。适配器缺失时直接跳过,因为浏览器导航无法挂载 Cordis 插件;设置或凭据能力不可用时则显示部署诊断,并提供同一个前往 Models 的入口。 每一次编辑都以 `settings.mutate` 的路径 op 落到已存分节上——每个变更字段一条 set、每个清空字段一条 unset、删除整行则是单独一条 unset。页面自始至终只持有**脱敏后**的 descriptor,因此它点名自己看得见的字段,而不是重建分节:一个它从未收到过的已存字面机密不会被任何 op 提及,也就得以留存。每次写入都携带该卡片打开时的 `revision`,因此来自另一个标签页或对 `settings.yaml` 的外部编辑所产生的并发写入会以 `settings-conflict` 被拒绝,卡片会请用户重新打开,而不是把自己的陈旧快照重放上去。页面加载完成后会在推送的失效事件(`settings/changed`、`credentials/changed`、`models/changed` 与 `connection/reset`)上重拉,因此外部的 `settings.yaml` 编辑、第二个标签页或 settings 新生的路由都无需轮询即可收敛。 diff --git a/packages/client/ui-models/src/client/DeepSeekOnboardingDialog.tsx b/packages/client/ui-models/src/client/DeepSeekOnboardingDialog.tsx index 3d43bf2033..31ae571272 100644 --- a/packages/client/ui-models/src/client/DeepSeekOnboardingDialog.tsx +++ b/packages/client/ui-models/src/client/DeepSeekOnboardingDialog.tsx @@ -4,7 +4,7 @@ * routes the user to that page's single credential editor. */ -import { useEffect, useState } from 'react' +import { useEffect } from 'react' import type { ReactNode } from 'react' import type { PropsRuntime } from '@deepseek-ai/dsh-client-ui-slots' import { Button, Modal } from '@deepseek-ai/dsh-client-ui-primitives' @@ -64,26 +64,23 @@ function unavailableDiagnostic( * @returns the controlled modal or null when onboarding needs no intervention. */ export function DeepSeekOnboardingDialog(props: DeepSeekOnboardingDialogProps): ReactNode { - const { active, openSection, controller, useSnapshot, t } = props + const { complete, openSection, controller, useSnapshot, t } = props const state = useSnapshot(snapshot => snapshot) const readiness = deepSeekReadiness(state) - const [dismissed, setDismissed] = useState(false) useEffect(() => { - if (active && !dismissed && state.status === 'idle') void controller.load() - }, [active, controller, dismissed, state.status]) + if (state.status === 'idle') void controller.load() + }, [controller, state.status]) - const close = (): void => { - setDismissed(true) - } + useEffect(() => { + if (readiness.kind === 'adapter-absent' || readiness.kind === 'configured') complete() + }, [complete, readiness.kind]) const openModels = (): void => { - close() + complete() openSection('models') } - if (!active || dismissed) return null - let unavailableReason: UnavailableReason | undefined switch (readiness.kind) { case 'loading': @@ -108,7 +105,7 @@ export function DeepSeekOnboardingDialog(props: DeepSeekOnboardingDialogProps): return ( { throw new Error('unused standard hook') }) as never const props: DeepSeekOnboardingDialogProps = { - active: true, + stepId: 'deepseek-official', + complete, openSection, useSessions: unusedHook, useWorkspaces: unusedHook, @@ -102,7 +104,7 @@ function harness(options: { useSnapshot: bindSnapshotSelector(controller.store), t: key => en[key], } - return { controller, openSection, props, configure: () => { fileConfigured = true } } + return { controller, complete, openSection, props, configure: () => { fileConfigured = true } } } describe('DeepSeekOnboardingDialog', () => { @@ -122,8 +124,8 @@ describe('DeepSeekOnboardingDialog', () => { render() await screen.findByRole('dialog') fireEvent.click(screen.getByRole('button', { name: en.onboardingGoToSettings })) + expect(h.complete).toHaveBeenCalledOnce() expect(h.openSection).toHaveBeenCalledWith('models') - expect(screen.queryByRole('dialog', { name: en.onboardingTitle })).toBeNull() }) it('allows configure-later dismissal without opening settings', async () => { @@ -131,7 +133,7 @@ describe('DeepSeekOnboardingDialog', () => { render() await screen.findByRole('dialog') fireEvent.click(screen.getByRole('button', { name: en.onboardingLater })) - expect(screen.queryByRole('dialog')).toBeNull() + expect(h.complete).toHaveBeenCalledOnce() expect(h.openSection).not.toHaveBeenCalled() }) @@ -187,6 +189,7 @@ describe('DeepSeekOnboardingDialog', () => { const view = render() await act(async () => { await h.controller.load() }) expect(screen.queryByRole('dialog')).toBeNull() + await waitFor(() => { expect(h.complete).toHaveBeenCalledOnce() }) view.unmount() } }) @@ -198,14 +201,6 @@ describe('DeepSeekOnboardingDialog', () => { h.configure() await act(async () => { await h.controller.load() }) await waitFor(() => { expect(screen.queryByRole('dialog')).toBeNull() }) - }) - - it('stays hidden while the onboarding owner is inactive', async () => { - const h = harness() - const view = render() - await act(async () => { await h.controller.load() }) - expect(screen.queryByRole('dialog')).toBeNull() - view.rerender() - expect(await screen.findByRole('dialog', { name: en.onboardingTitle })).toBeTruthy() + expect(h.complete).toHaveBeenCalledOnce() }) }) diff --git a/packages/client/ui-settings-general/README.i18n.yaml b/packages/client/ui-settings-general/README.i18n.yaml index 9377fc73b8..b8fd2d4025 100644 --- a/packages/client/ui-settings-general/README.i18n.yaml +++ b/packages/client/ui-settings-general/README.i18n.yaml @@ -1,6 +1,6 @@ # Bilingual-pair consistency record (docs/i18n/README.md): the git blob hash of each # side as of the last confirmed-consistent state. Both languages carry equal authority; # after editing either side, bring the other along and re-record with: -# pnpm run verify-translation-pairing --write -README.md: c392d745021c0fc6a752cf71dd0506a435106c50 -README.zh.md: 83ab81e01eae435a74b50fa363a4de203c483002 +# pnpm run verify-translation-pairing --write packages/client/ui-settings-general/README.md +README.md: 3ae3f58bd00172ed9b547c01a354023c224f6a1c +README.zh.md: ffdaf0e4314daa947a4183e2b23b7b1650de7611 diff --git a/packages/client/ui-settings-general/README.md b/packages/client/ui-settings-general/README.md index c392d74502..3ae3f58bd0 100644 --- a/packages/client/ui-settings-general/README.md +++ b/packages/client/ui-settings-general/README.md @@ -2,7 +2,9 @@ English | [中文](README.zh.md) -Settings ownerless-copy plugin: registers everything on the Settings surface that belongs to no single feature — the shell's trigger/header/close chrome content, the General section (Permission/Tool Call skeleton rows + the `settings.general.item` slot declaration), and the `settings` dictionaries. Feature-owned rows (Language, Appearance) and sections (Models) stay with their feature packages. +Settings ownerless-copy and product-onboarding plugin: registers everything on the Settings surface that belongs to no single feature — the shell's trigger/header/close chrome content, the General section (Permission/Tool Call skeleton rows + the `settings.general.item` slot declaration), the `settings` dictionaries, and the first ordered welcome step. Feature-owned rows (Language, Appearance), sections (Models), and conditional onboarding steps stay with their feature packages. + +`src/onboarding-copy.ts` is the single editable owner of the complete Chinese and English notice plus `WELCOME_NOTICE_VERSION`. The Host half registers `ui-onboarding` in the user-settings seam; the browser compares `welcomeNoticeVersion` for exact equality and writes the current value only after Continue succeeds. The path mutation is idempotent across tabs and preserves sibling settings, while `host/settings-changed` makes an externally acknowledged notice advance without a reload. A different version deliberately presents the notice again. The welcome UI has no close, Escape, mask-click, or secondary path, and none of its copy or acknowledgement enters a Session log or model request. ## Model Experience diff --git a/packages/client/ui-settings-general/README.zh.md b/packages/client/ui-settings-general/README.zh.md index 83ab81e01e..ffdaf0e431 100644 --- a/packages/client/ui-settings-general/README.zh.md +++ b/packages/client/ui-settings-general/README.zh.md @@ -2,7 +2,9 @@ [English](README.md) | 中文 -设置界面文案插件:在设置界面注册所有不属于单一功能的内容,包括外壳的触发器、标题栏与关闭控件内容,「通用」分区(「权限」/「工具调用」骨架行和 `settings.general.item` slot 声明),以及 `settings` 字典。归具体功能所有的行(「语言」、「外观」)和分区(「模型」)仍由各自的功能包提供。 +设置界面无特定功能归属的文案与产品引导插件:在设置界面注册所有不属于单一功能的内容,包括外壳的触发器、标题栏与关闭控件内容,「通用」分区(「权限」/「工具调用」骨架行和 `settings.general.item` slot 声明)、`settings` 字典,以及第一个有序欢迎步骤。归具体功能所有的行(「语言」、「外观」)、分区(「模型」)和条件式首次使用引导步骤仍由各自的功能包提供。 + +`src/onboarding-copy.ts` 是完整中英文通知文案和 `WELCOME_NOTICE_VERSION` 的唯一可编辑来源。宿主端在 user-settings seam 中注册 `ui-onboarding`;浏览器比较 `welcomeNoticeVersion` 是否精确相等,仅在「继续」操作成功后写入当前值。该路径变更在不同标签页间幂等,并会保留同级设置;`host/settings-changed` 则让页面在通知被外部确认后,无需重新加载即可推进。版本不同时,系统会有意重新显示通知。欢迎界面没有关闭操作、Escape、点击遮罩或次要操作路径,其文案和确认状态均不会进入会话日志或模型请求。 ## 模型体验 diff --git a/packages/client/ui-settings-general/package.json b/packages/client/ui-settings-general/package.json index 798a7710f0..fa380cfc83 100644 --- a/packages/client/ui-settings-general/package.json +++ b/packages/client/ui-settings-general/package.json @@ -1,6 +1,6 @@ { "name": "@deepseek-ai/dsh-client-ui-settings-general", - "description": "Settings ownerless-copy plugin: the General section (skeleton rows + item slot), the shell trigger/header chrome content, and the settings dictionaries", + "description": "Settings ownerless-copy and product onboarding plugin: General, shell chrome, dictionaries, and the versioned welcome notice", "version": "0.0.1", "private": true, "type": "module", @@ -26,7 +26,8 @@ "inject": [ "@deepseek-ai/dsh-client-runtime", "@deepseek-ai/dsh-client-ui-settings", - "@deepseek-ai/dsh-client-locale" + "@deepseek-ai/dsh-client-locale", + "@deepseek-ai/dsh-client-connection" ], "platform": "web" }, @@ -35,22 +36,30 @@ "watch": "tsdown --watch" }, "license": "BSD-3-Clause", + "dependencies": { + "@deepseek-ai/dsh-settings": "workspace:^", + "schemastery": "^3.18.0" + }, "peerDependencies": { + "@deepseek-ai/dsh-client-connection": "^0.0.1", "@deepseek-ai/dsh-client-locale": "^0.0.1", "@deepseek-ai/dsh-client-runtime": "^0.0.1", "@deepseek-ai/dsh-client-ui-primitives": "^0.0.1", "@deepseek-ai/dsh-client-ui-settings": "^0.0.1", "@deepseek-ai/dsh-client-ui-slots": "^0.0.1", + "@deepseek-ai/dsh-client-web-react": "^0.0.1", "@deepseek-ai/dsh-invariants": "^0.0.1", "cordis": "^4.0.0-rc.7", "react": "^18.2.0" }, "devDependencies": { + "@deepseek-ai/dsh-client-connection": "workspace:^", "@deepseek-ai/dsh-client-locale": "workspace:^", "@deepseek-ai/dsh-client-runtime": "workspace:^", "@deepseek-ai/dsh-client-ui-primitives": "workspace:^", "@deepseek-ai/dsh-client-ui-settings": "workspace:^", "@deepseek-ai/dsh-client-ui-slots": "workspace:^", + "@deepseek-ai/dsh-client-web-react": "workspace:^", "@deepseek-ai/dsh-invariants": "workspace:^", "@types/react": "~18.3.1", "cordis": "^4.0.0-rc.7", diff --git a/packages/client/ui-settings-general/src/client/WelcomeNotice.module.css b/packages/client/ui-settings-general/src/client/WelcomeNotice.module.css new file mode 100644 index 0000000000..8ad90b5fe2 --- /dev/null +++ b/packages/client/ui-settings-general/src/client/WelcomeNotice.module.css @@ -0,0 +1,70 @@ +.overlay { + position: fixed; + inset: 0; + z-index: 1100; + display: flex; + align-items: center; + justify-content: center; + padding-top: 80px; + box-sizing: border-box; +} + +/* Mask */ +.mask { + position: absolute; + left: 0px; + right: 0px; + top: 80px; + bottom: 0px; + background: rgba(0, 0, 0, 0.24); + /* Mask-blur */ + backdrop-filter: blur(2px); +} + +.dialog { + position: relative; + z-index: 1; + width: min(640px, calc(100vw - 48px)); + max-height: calc(100vh - 128px); + padding: 32px; + box-sizing: border-box; + overflow-y: auto; + border-radius: 24px; + background: var(--dsw-alias-bg-layer-2); + box-shadow: var(--dsw-shadow-lv3); + color: var(--dsw-alias-label-primary); +} + +.title { + margin: 0; + font-size: 20px; + line-height: 30px; + font-weight: 600; +} + +.copy { + display: flex; + flex-direction: column; + gap: 14px; + margin-top: 18px; + font-size: 14px; + line-height: 24px; + color: var(--dsw-alias-label-secondary); +} + +.copy p, +.error { + margin: 0; +} + +.error { + margin-top: 14px; + font-size: 13px; + line-height: 20px; + color: var(--dsw-alias-state-error-primary); +} + +.primary { + width: 100%; + margin-top: 24px; +} diff --git a/packages/client/ui-settings-general/src/client/WelcomeNotice.tsx b/packages/client/ui-settings-general/src/client/WelcomeNotice.tsx new file mode 100644 index 0000000000..6255405f83 --- /dev/null +++ b/packages/client/ui-settings-general/src/client/WelcomeNotice.tsx @@ -0,0 +1,69 @@ +/** Product-wide, versioned first-run welcome step. */ + +import { useCallback, useEffect, useRef } from 'react' +import type { ReactNode } from 'react' +import type { PropsRuntime } from '@deepseek-ai/dsh-client-ui-slots' +import { Button } from '@deepseek-ai/dsh-client-ui-primitives' +import type { SnapshotSelectorHook } from '@deepseek-ai/dsh-client-web-react' +import type { WelcomeNoticeState, WelcomeNoticeStore } from './welcome-store.ts' +import css from './WelcomeNotice.module.css' + +/** Registrant-owned dependencies of {@link WelcomeNotice}. */ +export interface WelcomeNoticeInjected { + controller: WelcomeNoticeStore + useSnapshot: SnapshotSelectorHook + t: (key: string) => string +} + +/** Coordinator owner props plus the welcome step's injected face. */ +export type WelcomeNoticeProps = PropsRuntime<'settings.onboarding'> & WelcomeNoticeInjected + +/** Render the mandatory notice until its current version commits durably. */ +export function WelcomeNotice(props: WelcomeNoticeProps): ReactNode { + const { complete, controller, useSnapshot, t } = props + const state = useSnapshot(snapshot => snapshot) + const finished = useRef(false) + const finish = useCallback((): void => { + if (finished.current) return + finished.current = true + complete() + }, [complete]) + + useEffect(() => { + if (state.status === 'idle') void controller.load() + }, [controller, state.status]) + + useEffect(() => { + if (state.acknowledged) finish() + }, [finish, state.acknowledged]) + + if (state.status === 'idle' || state.status === 'loading' || state.acknowledged) return null + + const acknowledge = async (): Promise => { + if (await controller.acknowledge()) finish() + } + + return ( +
      + + ) +} diff --git a/packages/client/ui-settings-general/src/client/index.ts b/packages/client/ui-settings-general/src/client/index.ts index afb37d8b92..d2dd820ed9 100644 --- a/packages/client/ui-settings-general/src/client/index.ts +++ b/packages/client/ui-settings-general/src/client/index.ts @@ -8,13 +8,19 @@ */ import type { ClientContext } from '@deepseek-ai/dsh-client-runtime/client' import { deferRegistration } from '@deepseek-ai/dsh-client-ui-slots' +import type { ConnectionHandle } from '@deepseek-ai/dsh-client-connection/client' +import { bindSnapshotSelector } from '@deepseek-ai/dsh-client-web-react' // Type-only: pulls the shell's SlotMap merges (trigger/header/section/item). import type {} from '@deepseek-ai/dsh-client-ui-settings/client' import type { ChromeInjected } from './chrome.tsx' import { CloseLabel, HeaderContent, TriggerContent } from './chrome.tsx' import type { GeneralSectionInjected } from './GeneralSection.tsx' import { GeneralSection } from './GeneralSection.tsx' +import type { WelcomeNoticeInjected } from './WelcomeNotice.tsx' +import { WelcomeNotice } from './WelcomeNotice.tsx' +import { refreshWelcomeIfLoaded, WelcomeNoticeStore } from './welcome-store.ts' import { en, zh } from './locales.ts' +import { WELCOME_NOTICE_SETTINGS_NAMESPACE } from '../onboarding-copy.ts' export type { ChromeInjected, CloseLabelProps, HeaderContentProps, TriggerContentProps, @@ -22,6 +28,8 @@ export type { export type { GeneralSectionComponentProps, GeneralSectionInjected, } from './GeneralSection.tsx' +export type { WelcomeNoticeInjected, WelcomeNoticeProps } from './WelcomeNotice.tsx' +export type { WelcomeNoticeState } from './welcome-store.ts' /** Dictionary namespace owned by this plugin (shell chrome + General copy). */ const NS = 'settings' @@ -31,7 +39,7 @@ const NS = 'settings' * ui-settings' apply, whose activation order relative to this one is NOT * constrained; registration goes through declaration-aware deferral. */ -export const inject = ['slots', 'locale'] +export const inject = ['slots', 'locale', 'connection'] /** * Register the `settings` dictionaries, the chrome content, and the General @@ -48,8 +56,28 @@ export function apply(ctx: ClientContext): void { }, 'ui-settings-general: dictionaries') const t = ctx.locale.bind(NS) + const connection = ctx.get('connection') as ConnectionHandle + const welcomeController = new WelcomeNoticeStore(connection.api) + const useWelcomeSnapshot = bindSnapshotSelector(welcomeController.store) const chromeInjected = (): ChromeInjected => ({ t }) const generalInjected = (): GeneralSectionInjected => ({ t }) + const welcomeInjected = (): WelcomeNoticeInjected => ({ + controller: welcomeController, + useSnapshot: useWelcomeSnapshot, + t, + }) + + ctx.effect(() => { + const refresh = (ns?: string): void => { + if (ns !== undefined && ns !== WELCOME_NOTICE_SETTINGS_NAMESPACE) return + refreshWelcomeIfLoaded(welcomeController) + } + const disposers = [ + ctx.on('settings/changed', refresh), + ctx.on('connection/reset', () => { refresh() }), + ] + return () => { for (const dispose of disposers) dispose() } + }, 'ui-settings-general: welcome invalidations') // All four seats refresh on locale change: re-registration bumps each // slot's ledger version, which re-renders the outlets through their own @@ -70,11 +98,19 @@ export function apply(ctx: ClientContext): void { children: { 'settings.general.item': { kind: 'list', scope: 'root' } }, inject: generalInjected, }, GeneralSection)) + const welcome = deferRegistration(ctx.slots, 'settings.onboarding', WelcomeNotice, () => + ctx.slots.register({ + name: 'settings.onboarding', + id: 'welcome-notice', + order: -100, + inject: welcomeInjected, + }, WelcomeNotice)) const offLocale = ctx.on('locale/change', () => { trigger.refresh() header.refresh() close.refresh() general.refresh() + welcome.refresh() }) return () => { offLocale() @@ -82,6 +118,7 @@ export function apply(ctx: ClientContext): void { header.dispose() close.dispose() general.dispose() + welcome.dispose() } - }, 'ui-settings-general: chrome and section registrations') + }, 'ui-settings-general: chrome, section, and onboarding registrations') } diff --git a/packages/client/ui-settings-general/src/client/locales.ts b/packages/client/ui-settings-general/src/client/locales.ts index 6fc3295561..73c0daab58 100644 --- a/packages/client/ui-settings-general/src/client/locales.ts +++ b/packages/client/ui-settings-general/src/client/locales.ts @@ -6,6 +6,7 @@ * (Language, Appearance) ship their copy in their own packages. */ import type { LocaleDict } from '@deepseek-ai/dsh-client-locale/client' +import { WELCOME_NOTICE_COPY } from '../onboarding-copy.ts' const SHARED = { 'permission.value': 'Read only', @@ -25,6 +26,12 @@ export const zh: LocaleDict = { 'permission.title': '权限', 'permission.desc': '选择默认权限模式', 'toolcall.title': '工具调用', + 'welcome.paragraph.0': WELCOME_NOTICE_COPY.zh.paragraphs[0], + 'welcome.paragraph.1': WELCOME_NOTICE_COPY.zh.paragraphs[1], + 'welcome.paragraph.2': WELCOME_NOTICE_COPY.zh.paragraphs[2], + 'welcome.paragraph.3': WELCOME_NOTICE_COPY.zh.paragraphs[3], + 'welcome.continue': WELCOME_NOTICE_COPY.zh.continueLabel, + 'welcome.error': '暂时无法保存确认状态,请重试。', } /** English dictionary. */ @@ -37,4 +44,10 @@ export const en: LocaleDict = { 'permission.title': 'Permission', 'permission.desc': 'Choose default permission mode', 'toolcall.title': 'Tool Call', + 'welcome.paragraph.0': WELCOME_NOTICE_COPY.en.paragraphs[0], + 'welcome.paragraph.1': WELCOME_NOTICE_COPY.en.paragraphs[1], + 'welcome.paragraph.2': WELCOME_NOTICE_COPY.en.paragraphs[2], + 'welcome.paragraph.3': WELCOME_NOTICE_COPY.en.paragraphs[3], + 'welcome.continue': WELCOME_NOTICE_COPY.en.continueLabel, + 'welcome.error': 'The acknowledgement could not be saved. Please try again.', } diff --git a/packages/client/ui-settings-general/src/client/welcome-store.ts b/packages/client/ui-settings-general/src/client/welcome-store.ts new file mode 100644 index 0000000000..ad0e18305c --- /dev/null +++ b/packages/client/ui-settings-general/src/client/welcome-store.ts @@ -0,0 +1,108 @@ +/** Durable welcome-notice state over the Host settings document. */ + +import type { IApiClient, SettingsNamespaceView } from '@deepseek-ai/dsh-client-connection/client' +import type { SnapshotStore } from '@deepseek-ai/dsh-client-runtime/client' +import { createSnapshotStore } from '@deepseek-ai/dsh-client-runtime/client' +import { + WELCOME_NOTICE_ACK_FIELD, WELCOME_NOTICE_SETTINGS_NAMESPACE, WELCOME_NOTICE_VERSION, +} from '../onboarding-copy.ts' + +/** State rendered by the welcome step. */ +export interface WelcomeNoticeState { + status: 'idle' | 'loading' | 'ready' | 'saving' | 'error' + acknowledged: boolean + error: string | null +} + +function messageOf(error: unknown): string { + return error instanceof Error ? error.message : String(error) +} + +function acknowledgementOf(view: SettingsNamespaceView): string | undefined { + if (typeof view.value !== 'object' || view.value === null) return undefined + const value = (view.value as Record)[WELCOME_NOTICE_ACK_FIELD] + return typeof value === 'string' ? value : undefined +} + +/** Coordinates welcome acknowledgement reads and the sole durable write. */ +export class WelcomeNoticeStore { + /** uSES-safe state source shared by the registered welcome step. */ + readonly store: SnapshotStore = createSnapshotStore({ + status: 'idle', acknowledged: false, error: null, + }) + + private generation = 0 + + /** @param api - settings wire face used for durable reads and writes. */ + constructor(private readonly api: Pick) {} + + /** Load the current acknowledgement from the Host settings document. */ + async load(): Promise { + const generation = ++this.generation + this.store.update((state) => { state.status = 'loading'; state.error = null }) + try { + const response = await this.api.settings.describe({}) + if (!response.result.ok) throw new Error(response.result.error.message) + const view = response.result.value.namespaces.find( + candidate => candidate.ns === WELCOME_NOTICE_SETTINGS_NAMESPACE, + ) + if (view === undefined) throw new Error('welcome acknowledgement settings are unavailable') + if (generation !== this.generation) return + this.store.update((state) => { + state.status = 'ready' + state.acknowledged = acknowledgementOf(view) === WELCOME_NOTICE_VERSION + state.error = null + }) + } catch (error) { + if (generation !== this.generation) return + this.store.update((state) => { + state.status = 'error' + state.acknowledged = false + state.error = messageOf(error) + }) + } + } + + /** + * Persist this copy version. The path mutation is idempotent across tabs and + * preserves every sibling setting; failure leaves the step unacknowledged. + * @returns true only when the Host committed the acknowledgement. + */ + async acknowledge(): Promise { + const generation = ++this.generation + this.store.update((state) => { state.status = 'saving'; state.error = null }) + try { + const response = await this.api.settings.mutate({ + ns: WELCOME_NOTICE_SETTINGS_NAMESPACE, + ops: [{ op: 'set', path: [WELCOME_NOTICE_ACK_FIELD], value: WELCOME_NOTICE_VERSION }], + }) + if (!response.result.ok) throw new Error(response.result.error.message) + if (generation === this.generation) { + this.store.update((state) => { + state.status = 'ready' + state.acknowledged = true + state.error = null + }) + } + return true + } catch (error) { + if (generation === this.generation) { + this.store.update((state) => { + state.status = 'error' + state.acknowledged = false + state.error = messageOf(error) + }) + } + return false + } + } +} + +/** + * Refresh only after the welcome step has begun reading durable state. + * @param controller - welcome state owner whose current status decides whether to load. + */ +export function refreshWelcomeIfLoaded(controller: WelcomeNoticeStore): void { + if (controller.store.getSnapshot().status === 'idle') return + void controller.load() +} diff --git a/packages/client/ui-settings-general/src/index.ts b/packages/client/ui-settings-general/src/index.ts index 94b9bdf674..18518c2835 100644 --- a/packages/client/ui-settings-general/src/index.ts +++ b/packages/client/ui-settings-general/src/index.ts @@ -1,4 +1,31 @@ /** Host loader entry for the browser implementation exported from `./client`. */ -/** Host plugin body — no host-side behavior for the general settings plugin. */ -export function apply(): void {} +import type { Context } from 'cordis' +import z from 'schemastery' +import { settingsNamespace } from '@deepseek-ai/dsh-settings' +import { + WELCOME_NOTICE_ACK_FIELD, WELCOME_NOTICE_SETTINGS_NAMESPACE, +} from './onboarding-copy.ts' + +export { + WELCOME_NOTICE_ACK_FIELD, WELCOME_NOTICE_COPY, WELCOME_NOTICE_SETTINGS_NAMESPACE, + WELCOME_NOTICE_VERSION, +} from './onboarding-copy.ts' + +interface OnboardingSettings { + welcomeNoticeVersion?: string +} + +const OnboardingSettingsSchema: z = z.object({ + [WELCOME_NOTICE_ACK_FIELD]: z.string(), +}) + +/** Register the durable GUI-onboarding section when a settings provider exists. */ +export function apply(ctx: Context): void { + ctx.inject(['settings'], (settingsCtx) => { + settingsCtx.settings.register( + settingsNamespace(WELCOME_NOTICE_SETTINGS_NAMESPACE), + OnboardingSettingsSchema, + ) + }) +} diff --git a/packages/client/ui-settings-general/src/invariant.ts b/packages/client/ui-settings-general/src/invariant.ts index 29f762834d..d13ecc5cb8 100644 --- a/packages/client/ui-settings-general/src/invariant.ts +++ b/packages/client/ui-settings-general/src/invariant.ts @@ -15,10 +15,9 @@ export const name = 'client-ui-settings-general-invariant' export const inject = ['invariants'] /** - * No runtime invariant: a copy-owning registrant contributing chrome content - * and the General section into shell-declared slots — it emits no cordis - * events and owns no cross-plugin mutable relation; slot conflicts already - * fail loud in the slot core at load time. + * No runtime invariant: the settings seam validates and publishes the durable + * welcome section, while slot conflicts fail loud in the slot core; this + * package owns no additional event/data relationship between those systems. */ const install: InvariantInstaller = () => {} diff --git a/packages/client/ui-settings-general/src/onboarding-copy.ts b/packages/client/ui-settings-general/src/onboarding-copy.ts new file mode 100644 index 0000000000..04a075783e --- /dev/null +++ b/packages/client/ui-settings-general/src/onboarding-copy.ts @@ -0,0 +1,33 @@ +/** Durable settings namespace for product-wide GUI onboarding facts. */ +export const WELCOME_NOTICE_SETTINGS_NAMESPACE = 'ui-onboarding' + +/** Field storing the last welcome notice version the user acknowledged. */ +export const WELCOME_NOTICE_ACK_FIELD = 'welcomeNoticeVersion' + +/** + * Bump only when the notice changes materially and every user should see it + * again. The acknowledgement is compared for exact equality. + */ +export const WELCOME_NOTICE_VERSION = '2026-07-30.1' + +/** The complete editable welcome notice in both supported GUI locales. */ +export const WELCOME_NOTICE_COPY = { + zh: { + paragraphs: [ + '感谢您愿意拨冗试用 DeepSeek Harness。', + '目前的版本仍处于内部测试阶段,有些功能仍待完善,有些体验难免粗粝。', + '“如切如磋,如琢如磨。” 产品的成长,离不开一次次真实的碰撞与坦诚的反馈。您在真实使用中暴露的问题,也可能促使我们重新审视,甚至推翻已有的设计。', + '我们尤其希望听见那些失败、困惑与不顺手的时刻——如果它未能帮到您,甚至反而为工作平添了麻烦,请在企业微信群中留言,将使用感受告诉我们。每一条反馈,都会帮助我们把它打磨得更好。', + ], + continueLabel: '继续', + }, + en: { + paragraphs: [ + 'Thank you for taking the time to try DeepSeek Harness.', + 'This version is still in internal testing. Some features remain unfinished, and parts of the experience may feel rough.', + '“As one cuts and files, as one chisels and polishes.” A product grows through real encounters and candid feedback. Problems you uncover in real use may prompt us to reconsider—or even overturn—our existing designs.', + 'We especially want to hear about failures, confusion, and friction. If it did not help you, or even made your work harder, please leave a message in the company WeChat group and tell us about your experience. Every piece of feedback helps us refine it.', + ], + continueLabel: 'Continue', + }, +} as const diff --git a/packages/client/ui-settings-general/tests/apply.spec.ts b/packages/client/ui-settings-general/tests/apply.spec.ts index d01be576b7..9d03ac03b8 100644 --- a/packages/client/ui-settings-general/tests/apply.spec.ts +++ b/packages/client/ui-settings-general/tests/apply.spec.ts @@ -1,12 +1,15 @@ /** Ownerless-copy registrations: the four seats, the dictionaries, locale refresh, and HMR recovery. */ import { Context } from 'cordis' -import { describe, expect, it } from 'vitest' +import { describe, expect, it, vi } from 'vitest' import { SlotsService } from '@deepseek-ai/dsh-client-runtime/client' import { LocaleService } from '@deepseek-ai/dsh-client-locale/client' import { apply, inject } from '@deepseek-ai/dsh-client-ui-settings-general/client' import type { GeneralSectionInjected } from '@deepseek-ai/dsh-client-ui-settings-general/client' import { CloseLabel, HeaderContent, TriggerContent } from '../src/client/chrome.tsx' import { GeneralSection } from '../src/client/GeneralSection.tsx' +import { WelcomeNotice } from '../src/client/WelcomeNotice.tsx' +import type { WelcomeNoticeInjected } from '../src/client/WelcomeNotice.tsx' +import { WELCOME_NOTICE_SETTINGS_NAMESPACE } from '../src/onboarding-copy.ts' /** The four seats this plugin fills (slot name → expected component). */ const SEATS = [ @@ -14,6 +17,7 @@ const SEATS = [ ['settings.header', HeaderContent], ['settings.close', CloseLabel], ['settings.section', GeneralSection], + ['settings.onboarding', WelcomeNotice], ] as const async function bench() { @@ -21,7 +25,25 @@ async function bench() { await ctx.plugin(SlotsService).await() const locale = new LocaleService(ctx) ctx.provide('locale', locale) - return { ctx, slots: ctx.get('slots') as SlotsService, locale } + const settingsDescribe = vi.fn(() => Promise.resolve({ + rpcId: 'settings-general' as never, + result: { + ok: true as const, + value: { + writable: true, + namespaces: [{ + ns: WELCOME_NOTICE_SETTINGS_NAMESPACE, + schema: {}, + value: {}, + applies: 'live' as const, + secrets: [], + revision: 0, + }], + }, + }, + })) + ctx.provide('connection', { api: { settings: { describe: settingsDescribe } } } as never) + return { ctx, slots: ctx.get('slots') as SlotsService, locale, settingsDescribe } } /** Declare the shell's four child slots the way ui-settings' entry does. */ @@ -34,6 +56,7 @@ function declare(slots: SlotsService): () => void { 'settings.header': { kind: 'single', scope: 'root' }, 'settings.close': { kind: 'single', scope: 'root' }, 'settings.section': { kind: 'list', scope: 'root' }, + 'settings.onboarding': { kind: 'list', scope: 'root' }, }, } as never, () => null, @@ -46,7 +69,7 @@ function generalEntry(slots: SlotsService) { describe('ui-settings-general apply', () => { it('declares the services it uses', () => { - expect(inject).toEqual(['slots', 'locale']) + expect(inject).toEqual(['slots', 'locale', 'connection']) }) it('fills all four seats for declarations before or after apply', async () => { @@ -61,6 +84,8 @@ describe('ui-settings-general apply', () => { expect(before.slots.spec('settings.general.item')).toEqual({ kind: 'list', scope: 'root' }) const injected = (entry.inject as unknown as () => GeneralSectionInjected)() expect(injected.t('permission.title')).toBe('权限') + const welcome = before.slots.entries('settings.onboarding')[0]! + expect(welcome.options).toEqual({ id: 'welcome-notice', order: -100 }) // The chrome seats share one inject face: the settings-ns translate. const chrome = (before.slots.entries('settings.trigger')[0]!.inject as unknown as () => GeneralSectionInjected)() expect(chrome.t('trigger')).toBe('设置') @@ -116,6 +141,22 @@ describe('ui-settings-general apply', () => { b.locale.setLocale('zh') }) + it('refreshes loaded welcome state only for its settings namespace or a reconnect', async () => { + const b = await bench() + declare(b.slots) + await b.ctx.plugin({ inject: [...inject], apply }).await() + const entry = b.slots.entries('settings.onboarding')[0]! + const { controller } = (entry.inject as unknown as () => WelcomeNoticeInjected)() + await controller.load() + expect(b.settingsDescribe).toHaveBeenCalledOnce() + b.ctx.emit('settings/changed', 'unrelated') + expect(b.settingsDescribe).toHaveBeenCalledOnce() + b.ctx.emit('settings/changed', WELCOME_NOTICE_SETTINGS_NAMESPACE) + await vi.waitFor(() => { expect(b.settingsDescribe).toHaveBeenCalledTimes(2) }) + b.ctx.emit('connection/reset') + await vi.waitFor(() => { expect(b.settingsDescribe).toHaveBeenCalledTimes(3) }) + }) + it('re-registers after an HMR collapse of the declaring chain (stale disposers must not block)', async () => { const b = await bench() const redeclare = declare(b.slots) diff --git a/packages/client/ui-settings-general/tests/host.spec.ts b/packages/client/ui-settings-general/tests/host.spec.ts new file mode 100644 index 0000000000..6434bc833a --- /dev/null +++ b/packages/client/ui-settings-general/tests/host.spec.ts @@ -0,0 +1,29 @@ +import { Context } from 'cordis' +import { describe, expect, it } from 'vitest' +import { Settings, settingsNamespace, type SettingsNamespace } from '@deepseek-ai/dsh-settings' +import { apply } from '../src/index.ts' +import { WELCOME_NOTICE_SETTINGS_NAMESPACE } from '../src/onboarding-copy.ts' + +class MemorySettings extends Settings { + readonly writable = true + protected load(): Promise> { return Promise.resolve({}) } + protected persist(_ns: SettingsNamespace, _section: Record): Promise { + return Promise.resolve() + } +} + +describe('ui-settings-general host', () => { + it('registers and disposes the durable onboarding namespace with its fiber', async () => { + const ctx = new Context() + await ctx.plugin(MemorySettings).await() + const fiber = ctx.plugin({ apply }) + await fiber.await() + expect(ctx.settings.describe().map(row => row.ns)).toContain( + settingsNamespace(WELCOME_NOTICE_SETTINGS_NAMESPACE), + ) + await fiber.dispose() + expect(ctx.settings.describe().map(row => row.ns)).not.toContain( + settingsNamespace(WELCOME_NOTICE_SETTINGS_NAMESPACE), + ) + }) +}) diff --git a/packages/client/ui-settings-general/tests/invariant.spec.ts b/packages/client/ui-settings-general/tests/invariant.spec.ts index 7b0527c0ff..59863a5794 100644 --- a/packages/client/ui-settings-general/tests/invariant.spec.ts +++ b/packages/client/ui-settings-general/tests/invariant.spec.ts @@ -9,10 +9,4 @@ describe('invariant companion', () => { await ctx.plugin(InvariantService, { enabled: true }) await expect(ctx.plugin(GeneralInvariant).await()).resolves.toBeDefined() }) - - it('node-half apply is a no-op host placeholder', async () => { - const { apply } = await import('@deepseek-ai/dsh-client-ui-settings-general') - apply() - expect(true).toBe(true) // reaching here without throw is the contract - }) }) diff --git a/packages/client/ui-settings-general/tests/welcome-notice.spec.tsx b/packages/client/ui-settings-general/tests/welcome-notice.spec.tsx new file mode 100644 index 0000000000..5925cf048b --- /dev/null +++ b/packages/client/ui-settings-general/tests/welcome-notice.spec.tsx @@ -0,0 +1,101 @@ +// @vitest-environment jsdom +import { act, cleanup, fireEvent, render, screen } from '@testing-library/react' +import { afterEach, describe, expect, it, vi } from 'vitest' +import { bindSnapshotSelector } from '@deepseek-ai/dsh-client-web-react' +import { WelcomeNotice } from '../src/client/WelcomeNotice.tsx' +import type { WelcomeNoticeProps } from '../src/client/WelcomeNotice.tsx' +import { WelcomeNoticeStore } from '../src/client/welcome-store.ts' +import { zh } from '../src/client/locales.ts' +import { + WELCOME_NOTICE_ACK_FIELD, WELCOME_NOTICE_COPY, WELCOME_NOTICE_SETTINGS_NAMESPACE, + WELCOME_NOTICE_VERSION, +} from '../src/onboarding-copy.ts' + +afterEach(cleanup) + +function response(value: T) { + return { rpcId: 'welcome-rpc' as never, result: { ok: true as const, value } } +} + +function mount(version?: string, mutateImpl: () => Promise = () => Promise.resolve(response({}))) { + const mutate = vi.fn(mutateImpl) + const api = { + settings: { + describe: () => Promise.resolve(response({ + writable: true, + namespaces: [{ + ns: WELCOME_NOTICE_SETTINGS_NAMESPACE, + schema: {}, + value: version === undefined ? {} : { [WELCOME_NOTICE_ACK_FIELD]: version }, + applies: 'live' as const, + secrets: [], + revision: 0, + }], + })), + mutate, + }, + } + const controller = new WelcomeNoticeStore(api as never) + const complete = vi.fn() + const unusedHook = (() => { throw new Error('unused standard hook') }) as never + const props: WelcomeNoticeProps = { + stepId: 'welcome-notice', + complete, + openSection: vi.fn(), + useSessions: unusedHook, + useWorkspaces: unusedHook, + controller, + useSnapshot: bindSnapshotSelector(controller.store), + t: key => zh[key] ?? key, + } + return { ...render(), complete, controller, mutate } +} + +describe('WelcomeNotice', () => { + it('renders the owner copy with one primary action and no dismissal control', async () => { + const h = mount() + const dialog = await screen.findByRole('dialog', { name: WELCOME_NOTICE_COPY.zh.paragraphs[0] }) + for (const paragraph of WELCOME_NOTICE_COPY.zh.paragraphs) { + expect(screen.getByText(paragraph)).toBeTruthy() + } + const buttons = dialog.querySelectorAll('button') + expect(buttons).toHaveLength(1) + expect(screen.getByRole('button', { name: WELCOME_NOTICE_COPY.zh.continueLabel })).toBeTruthy() + fireEvent.keyDown(document, { key: 'Escape' }) + fireEvent.click(dialog.parentElement!.firstElementChild!) + expect(h.complete).not.toHaveBeenCalled() + expect(screen.getByRole('dialog')).toBeTruthy() + }) + + it('completes only after the acknowledgement write commits', async () => { + const h = mount() + await screen.findByRole('dialog') + fireEvent.click(screen.getByRole('button', { name: WELCOME_NOTICE_COPY.zh.continueLabel })) + await act(async () => { await Promise.resolve() }) + expect(h.mutate).toHaveBeenCalledOnce() + expect(h.complete).toHaveBeenCalledOnce() + }) + + it('skips itself when this exact version was already acknowledged', async () => { + const h = mount(WELCOME_NOTICE_VERSION) + await act(async () => { await h.controller.load() }) + expect(screen.queryByRole('dialog')).toBeNull() + expect(h.complete).toHaveBeenCalledOnce() + }) + + it('keeps the sole action disabled while saving and reports a refused write', async () => { + let resolveWrite!: (value: unknown) => void + const write = new Promise((resolve) => { resolveWrite = resolve }) + const h = mount(undefined, () => write) + await screen.findByRole('dialog') + const action = screen.getByRole('button', { name: WELCOME_NOTICE_COPY.zh.continueLabel }) + fireEvent.click(action) + expect(action.disabled).toBe(true) + resolveWrite({ + rpcId: 'welcome-refused' as never, + result: { ok: false, error: { code: 'settings-rejected', message: 'read only', details: { ns: WELCOME_NOTICE_SETTINGS_NAMESPACE } } }, + }) + expect((await screen.findByRole('alert')).textContent).toBe('暂时无法保存确认状态,请重试。') + expect(h.complete).not.toHaveBeenCalled() + }) +}) diff --git a/packages/client/ui-settings-general/tests/welcome-store.spec.ts b/packages/client/ui-settings-general/tests/welcome-store.spec.ts new file mode 100644 index 0000000000..28c7b0509c --- /dev/null +++ b/packages/client/ui-settings-general/tests/welcome-store.spec.ts @@ -0,0 +1,166 @@ +import { describe, expect, it, vi } from 'vitest' +import type { RpcResponse } from '@deepseek-ai/dsh-client-connection/client' +import { WelcomeNoticeStore } from '../src/client/welcome-store.ts' +import { refreshWelcomeIfLoaded } from '../src/client/welcome-store.ts' +import { + WELCOME_NOTICE_ACK_FIELD, WELCOME_NOTICE_SETTINGS_NAMESPACE, WELCOME_NOTICE_VERSION, +} from '../src/onboarding-copy.ts' + +let rpc = 0 +function ok(value: T): RpcResponse { + return { rpcId: `welcome-${rpc++}` as never, result: { ok: true, value } } +} + +function namespace(version?: string) { + return { + ns: WELCOME_NOTICE_SETTINGS_NAMESPACE, + schema: {}, + value: version === undefined ? {} : { [WELCOME_NOTICE_ACK_FIELD]: version }, + applies: 'live' as const, + secrets: [], + revision: 0, + } +} + +function deferred() { + let resolve!: (value: T) => void + let reject!: (reason: unknown) => void + const promise = new Promise((res, rej) => { resolve = res; reject = rej }) + return { promise, resolve, reject } +} + +describe('WelcomeNoticeStore', () => { + it('acknowledges only the exact current copy version', async () => { + for (const [version, acknowledged] of [ + [undefined, false], + ['older-copy', false], + [WELCOME_NOTICE_VERSION, true], + ] as const) { + const api = { + settings: { + describe: vi.fn(() => Promise.resolve(ok({ writable: true, namespaces: [namespace(version)] }))), + }, + } + const controller = new WelcomeNoticeStore(api as never) + await controller.load() + expect(controller.store.getSnapshot()).toMatchObject({ status: 'ready', acknowledged }) + } + }) + + it('persists the owner version through one idempotent path mutation', async () => { + const mutate = vi.fn(() => Promise.resolve(ok(namespace(WELCOME_NOTICE_VERSION)))) + const controller = new WelcomeNoticeStore({ settings: { mutate } } as never) + await expect(controller.acknowledge()).resolves.toBe(true) + expect(mutate).toHaveBeenCalledWith({ + ns: WELCOME_NOTICE_SETTINGS_NAMESPACE, + ops: [{ op: 'set', path: [WELCOME_NOTICE_ACK_FIELD], value: WELCOME_NOTICE_VERSION }], + }) + expect(controller.store.getSnapshot()).toMatchObject({ status: 'ready', acknowledged: true }) + }) + + it('keeps the notice pending when loading or persistence fails', async () => { + const load = new WelcomeNoticeStore({ + settings: { describe: () => Promise.reject(new Error('offline')) }, + } as never) + await load.load() + expect(load.store.getSnapshot()).toEqual({ status: 'error', acknowledged: false, error: 'offline' }) + + const save = new WelcomeNoticeStore({ + settings: { mutate: () => Promise.reject(new Error('disk full')) }, + } as never) + await expect(save.acknowledge()).resolves.toBe(false) + expect(save.store.getSnapshot()).toEqual({ status: 'error', acknowledged: false, error: 'disk full' }) + + const nonError = new WelcomeNoticeStore({ + // Durable/wire failures are unknown; exercise containment of a non-Error rejection. + // oxlint-disable-next-line typescript/prefer-promise-reject-errors + settings: { describe: () => Promise.reject('offline string') }, + } as never) + await nonError.load() + expect(nonError.store.getSnapshot().error).toBe('offline string') + }) + + it('reports business failures, missing namespaces, and malformed durable values', async () => { + for (const describe of [ + () => Promise.resolve({ + rpcId: 'failed' as never, + result: { ok: false as const, error: { code: 'internal' as const, message: 'denied', details: {} } }, + }), + () => Promise.resolve(ok({ writable: true, namespaces: [] })), + ]) { + const controller = new WelcomeNoticeStore({ settings: { describe } } as never) + await controller.load() + expect(controller.store.getSnapshot().status).toBe('error') + } + + for (const value of [null, 42, { [WELCOME_NOTICE_ACK_FIELD]: 42 }]) { + const controller = new WelcomeNoticeStore({ + settings: { describe: () => Promise.resolve(ok({ + writable: true, + namespaces: [{ ...namespace(), value }], + })) }, + } as never) + await controller.load() + expect(controller.store.getSnapshot()).toMatchObject({ status: 'ready', acknowledged: false }) + } + + const save = new WelcomeNoticeStore({ + settings: { mutate: () => Promise.resolve({ + rpcId: 'failed-save' as never, + result: { ok: false, error: { code: 'settings-rejected', message: 'denied', details: { ns: WELCOME_NOTICE_SETTINGS_NAMESPACE } } }, + }) }, + } as never) + await expect(save.acknowledge()).resolves.toBe(false) + expect(save.store.getSnapshot().error).toBe('denied') + }) + + it('lets the latest load win over stale success and failure', async () => { + const first = deferred>() + const describe = vi.fn() + .mockImplementationOnce(() => first.promise) + .mockImplementationOnce(() => Promise.resolve(ok({ writable: true, namespaces: [namespace()] }))) + const controller = new WelcomeNoticeStore({ settings: { describe } } as never) + const stale = controller.load() + await controller.load() + first.resolve(ok({ writable: true, namespaces: [namespace(WELCOME_NOTICE_VERSION)] })) + await stale + expect(controller.store.getSnapshot().acknowledged).toBe(false) + + const failed = deferred>() + describe + .mockImplementationOnce(() => failed.promise) + .mockImplementationOnce(() => Promise.resolve(ok({ writable: true, namespaces: [namespace(WELCOME_NOTICE_VERSION)] }))) + const staleFailure = controller.load() + await controller.load() + failed.reject('stale failure') + await staleFailure + expect(controller.store.getSnapshot()).toMatchObject({ status: 'ready', acknowledged: true, error: null }) + }) + + it('contains stale acknowledgement settlements and refreshes only a loaded store', async () => { + const write = deferred>() + const describe = vi.fn(() => Promise.resolve(ok({ writable: true, namespaces: [namespace()] }))) + const controller = new WelcomeNoticeStore({ + settings: { mutate: () => write.promise, describe }, + } as never) + refreshWelcomeIfLoaded(controller) + expect(describe).not.toHaveBeenCalled() + const staleWrite = controller.acknowledge() + await controller.load() + write.resolve(ok(namespace(WELCOME_NOTICE_VERSION))) + await expect(staleWrite).resolves.toBe(true) + expect(controller.store.getSnapshot().acknowledged).toBe(false) + refreshWelcomeIfLoaded(controller) + await vi.waitFor(() => { expect(describe).toHaveBeenCalledTimes(2) }) + + const failedWrite = deferred>() + const staleFailure = new WelcomeNoticeStore({ + settings: { mutate: () => failedWrite.promise, describe }, + } as never) + const pending = staleFailure.acknowledge() + await staleFailure.load() + failedWrite.reject('late failure') + await expect(pending).resolves.toBe(false) + expect(staleFailure.store.getSnapshot().status).toBe('ready') + }) +}) diff --git a/packages/client/ui-settings-general/tsconfig.json b/packages/client/ui-settings-general/tsconfig.json index 5ef01ba51c..5e37578f91 100644 --- a/packages/client/ui-settings-general/tsconfig.json +++ b/packages/client/ui-settings-general/tsconfig.json @@ -14,6 +14,9 @@ { "path": "../ui-slots" }, + { + "path": "../connection" + }, { "path": "../ui-primitives" }, @@ -23,9 +26,15 @@ { "path": "../ui-settings" }, + { + "path": "../web-react" + }, { "path": "../locale" }, + { + "path": "../../settings/settings" + }, { "path": "../../support/invariants" } diff --git a/packages/client/ui-settings/README.i18n.yaml b/packages/client/ui-settings/README.i18n.yaml index c09aed1d0a..41247a370b 100644 --- a/packages/client/ui-settings/README.i18n.yaml +++ b/packages/client/ui-settings/README.i18n.yaml @@ -2,5 +2,5 @@ # side as of the last confirmed-consistent state. Both languages carry equal authority; # after editing either side, bring the other along and re-record with: # pnpm run verify-translation-pairing --write packages/client/ui-settings/README.md -README.md: 9388e9dd3a984bfcebc85b6b1a35bcce4b9b116e -README.zh.md: 57c91ac5dd0bcc0a3e5e029359bf6c3a2be58ec7 +README.md: 02d8f0e5fdc169d3a45f59d7b42d873943df2b52 +README.zh.md: 465d57847588e9ccbccc9d9067099773de63c0d0 diff --git a/packages/client/ui-settings/README.md b/packages/client/ui-settings/README.md index 9388e9dd3a..02d8f0e5fd 100644 --- a/packages/client/ui-settings/README.md +++ b/packages/client/ui-settings/README.md @@ -2,9 +2,9 @@ English | [中文](README.zh.md) -Settings shell plugin: a pure composition face. It occupies `sidebar.settings` with the trigger chrome and modal settings panel, and declares the slots registrants fill: `settings.trigger` / `settings.header` / `settings.close` (chrome content), `settings.section` (one page per feature), and `settings.onboarding` (feature-owned overlays on the empty Hero). The shell ships no copy and reads no locale state — all text arrives from registrants (ui-settings-general owns chrome and General; features own their sections, rows, and onboarding overlays). +Settings shell plugin: a pure composition face. It occupies `sidebar.settings` with the trigger chrome and modal settings panel, and declares the slots registrants fill: `settings.trigger` / `settings.header` / `settings.close` (chrome content), `settings.section` (one page per feature), and `settings.onboarding` (ordered feature-owned steps on the empty Hero). The shell ships no copy and reads no locale state — all text arrives from registrants (ui-settings-general owns chrome, General, and the product welcome step; features own their sections, rows, and conditional onboarding steps). -The shell supplies onboarding registrants only two navigation facts: whether the session surface is the empty Hero and an `openSection(id)` callback that opens the panel on a registered section. Registrants own capability readiness, dismissal, copy, and mutations; the shell therefore does not become a second configuration fact source. +The shell projects the onboarding ledger into ascending order and mounts exactly one step at a time. The active registrant receives its id, `complete()`, and an `openSection(id)` callback; completing or skipping transfers ownership to the next entry. Registrants own durable completion, capability readiness, copy, and mutations, so two independently registered dialogs cannot stack and the shell does not become a second configuration fact source. ## Model Experience diff --git a/packages/client/ui-settings/README.zh.md b/packages/client/ui-settings/README.zh.md index 57c91ac5dd..465d578475 100644 --- a/packages/client/ui-settings/README.zh.md +++ b/packages/client/ui-settings/README.zh.md @@ -2,9 +2,9 @@ [English](README.md) | 中文 -设置外壳插件:一个纯组合表层。它以触发控件和模态设置面板占用 `sidebar.settings`,并声明由注册方填充的 slot:`settings.trigger`/`settings.header`/`settings.close`(界面框架内容)、`settings.section`(每项功能一页)和 `settings.onboarding`(由各功能持有、覆盖在空白 Hero 之上的浮层)。外壳不自带文案,也不读取 locale 状态:所有文本都来自注册方(ui-settings-general 拥有界面框架和「通用」分区;各功能拥有各自的分区、行和首次使用浮层)。 +设置外壳插件:一个纯组合表层。它以触发控件和模态设置面板占用 `sidebar.settings`,并声明由注册方填充的 slot:`settings.trigger`/`settings.header`/`settings.close`(界面框架内容)、`settings.section`(每项功能一页)和 `settings.onboarding`(由各功能持有、显示在空白 Hero 上的有序步骤)。外壳不自带文案,也不读取 locale 状态:所有文本都来自注册方(ui-settings-general 拥有界面框架、「通用」分区和产品欢迎步骤;各功能拥有各自的分区、行和条件式首次使用引导步骤)。 -外壳只向首次使用注册方提供两个导航事实:当前会话界面是否为空白 Hero,以及一个 `openSection(id)` 回调;后者会打开设置面板并切换到已注册的指定分区。能力就绪状态、浮层关闭、文案和变更操作均由注册方持有,因此外壳不会成为第二个配置事实来源。 +外壳将首次使用引导记录按升序投影,并且每次只挂载一个步骤。当前注册方会收到该条目的 id、`complete()` 和 `openSection(id)` 回调;完成或跳过当前步骤后,所有权转交给下一项。持久化完成状态、能力就绪状态、文案和变更操作均由注册方持有,因此两个独立注册的对话框无法堆叠,外壳也不会成为第二个配置事实来源。 ## 模型体验 diff --git a/packages/client/ui-settings/src/client/SettingsRoot.tsx b/packages/client/ui-settings/src/client/SettingsRoot.tsx index cfa3ac6cef..528a633810 100644 --- a/packages/client/ui-settings/src/client/SettingsRoot.tsx +++ b/packages/client/ui-settings/src/client/SettingsRoot.tsx @@ -6,8 +6,8 @@ * names resolve to that content (trigger: its own text; dialog: * aria-labelledby the title node; close: visually-hidden slot text). Modal * open state and the active section id are component-local viewing state; - * the onboarding slot receives the sessions-derived empty-Hero fact and a - * private callback that opens one registered section. + * the onboarding coordinator mounts exactly one ordered registrant while the + * sessions-derived empty-Hero fact is active. */ import { useCallback, useEffect, useId, useRef, useState } from 'react' import clsx from 'clsx' @@ -95,9 +95,10 @@ function SettingsPanel({ rows, renderSlot, activeId, onSelect, onClose }: PanelP * @returns the settings shell element tree. */ export function SettingsRoot(props: SettingsRootComponentProps) { - const { wide, useSections, useSessions, renderSlot } = props + const { wide, useSections, useOnboardingSteps, useSessions, renderSlot } = props const [open, setOpen] = useState(false) const [activeId, setActiveId] = useState(undefined) + const [completedOnboarding, setCompletedOnboarding] = useState>(() => new Set()) const close = useCallback(() => { setOpen(false) setActiveId(undefined) @@ -111,9 +112,25 @@ export function SettingsRoot(props: SettingsRootComponentProps) { // freshly localized text on locale change, and the trigger/header/close // seats re-render through their own outlets' subscriptions. const rows = useSections(s => s) + const onboardingSteps = useOnboardingSteps(s => s) const onboardingActive = useSessions(state => state.phase === 'ready' && (state.current === undefined || state.byId[state.current]?.blank === true)) + const onboardingStep = onboardingActive + ? onboardingSteps.find(step => !completedOnboarding.has(step.id)) + : undefined + + useEffect(() => { + if (onboardingActive) return + setCompletedOnboarding(new Set()) + }, [onboardingActive]) + + const completeOnboardingStep = useCallback((id: string) => { + setCompletedOnboarding((previous) => { + if (previous.has(id)) return previous + return new Set([...previous, id]) + }) + }, []) return ( <> @@ -135,7 +152,11 @@ export function SettingsRoot(props: SettingsRootComponentProps) { onClose={close} /> )} - {renderSlot('settings.onboarding', { active: onboardingActive, openSection })} + {onboardingStep !== undefined && renderSlot('settings.onboarding', { + stepId: onboardingStep.id, + complete: () => { completeOnboardingStep(onboardingStep.id) }, + openSection, + }, { only: onboardingStep.id })} ) } diff --git a/packages/client/ui-settings/src/client/contract/slots.ts b/packages/client/ui-settings/src/client/contract/slots.ts index 37847832bf..4d5e48d80f 100644 --- a/packages/client/ui-settings/src/client/contract/slots.ts +++ b/packages/client/ui-settings/src/client/contract/slots.ts @@ -48,10 +48,10 @@ declare module '@deepseek-ai/dsh-client-ui-slots' { */ 'settings.section': { kind: 'list'; scope: 'root'; owner: SettingsSectionOwnerProps } /** - * Root-scoped onboarding overlays contributed by settings features. The - * shell supplies whether the current navigation state is the empty Hero - * and a private callback that opens one settings section; registrants own - * readiness, copy, and dialog behavior. + * Root-scoped onboarding steps contributed by settings features. The + * shell mounts one ordered step at a time; the active registrant either + * completes itself or keeps ownership until the user completes its sole + * path. Registrants own readiness, copy, and dialog behavior. */ 'settings.onboarding': { kind: 'list'; scope: 'root'; owner: SettingsOnboardingOwnerProps } } @@ -79,10 +79,12 @@ export interface SettingsSectionOwnerProps { children?: never } -/** Owner share of a settings-backed onboarding overlay. */ +/** Owner share of the currently active settings-backed onboarding step. */ export interface SettingsOnboardingOwnerProps { - /** Whether the current UI is in its empty Hero/onboarding state. */ - active: boolean + /** Stable id of the step currently selected by the coordinator. */ + stepId: string + /** Complete or skip this step and transfer ownership to the next entry. */ + complete: () => void /** Open the settings panel directly on one registered section. */ openSection: (id: string) => void } @@ -94,6 +96,12 @@ export interface SettingsSectionRow { label: string } +/** One ordered onboarding step projected from a slot registration. */ +export interface SettingsOnboardingStep { + id: string + order: number +} + /** * Registrant-private injected share of the settings shell (assembled in * apply): the ledger's nav-row projection as a hooks-compartment source — @@ -103,6 +111,8 @@ export type SettingsRootInjected = { hooks: { /** settings.section ledger projected into ordered nav rows. */ sections: HostObservable + /** settings.onboarding ledger projected into coordinator order. */ + onboardingSteps: HostObservable } } diff --git a/packages/client/ui-settings/src/client/index.ts b/packages/client/ui-settings/src/client/index.ts index dad2f89e77..5660ef389c 100644 --- a/packages/client/ui-settings/src/client/index.ts +++ b/packages/client/ui-settings/src/client/index.ts @@ -9,12 +9,15 @@ */ import type { ClientContext } from '@deepseek-ai/dsh-client-runtime/client' import { deferRegistration } from '@deepseek-ai/dsh-client-ui-slots' -import type { SettingsRootInjected, SettingsSectionRow } from './contract/slots.ts' +import type { + SettingsOnboardingStep, SettingsRootInjected, SettingsSectionRow, +} from './contract/slots.ts' import { SettingsRoot } from './SettingsRoot.tsx' export type { SettingsHeaderOwnerProps, SettingsRootComponentProps, SettingsRootInjected, - SettingsOnboardingOwnerProps, SettingsSectionOwnerProps, SettingsSectionRow, SettingsTriggerOwnerProps, + SettingsOnboardingOwnerProps, SettingsOnboardingStep, SettingsSectionOwnerProps, + SettingsSectionRow, SettingsTriggerOwnerProps, } from './contract/slots.ts' /** @@ -35,6 +38,8 @@ export function apply(ctx: ClientContext): void { // getSnapshot returns the cached rows until the ledger version moves). let rowsVersion = -1 let rows: readonly SettingsSectionRow[] = [] + let onboardingVersion = -1 + let onboardingSteps: readonly SettingsOnboardingStep[] = [] const injected = (): SettingsRootInjected => ({ hooks: { sections: { @@ -55,6 +60,23 @@ export function apply(ctx: ClientContext): void { }, subscribe: listener => ctx.slots.subscribe('settings.section', listener), }, + onboardingSteps: { + getSnapshot: () => { + const version = ctx.slots.getVersion('settings.onboarding') + if (version !== onboardingVersion) { + onboardingVersion = version + onboardingSteps = ctx.slots.entries('settings.onboarding') + .map(e => ({ + /* v8 ignore next -- list-slot registration requires id */ + id: e.options.id ?? '', + order: e.options.order ?? 0, + })) + .sort((a, b) => a.order - b.order) + } + return onboardingSteps + }, + subscribe: listener => ctx.slots.subscribe('settings.onboarding', listener), + }, }, }) ctx.effect(() => { diff --git a/packages/client/ui-settings/tests/apply.spec.ts b/packages/client/ui-settings/tests/apply.spec.ts index de50c88d87..48b63bc0a0 100644 --- a/packages/client/ui-settings/tests/apply.spec.ts +++ b/packages/client/ui-settings/tests/apply.spec.ts @@ -83,6 +83,29 @@ describe('ui-settings apply', () => { off() }) + it('projects onboarding entries into stable coordinator order', async () => { + const b = await bench() + declare(b.slots) + await b.ctx.plugin({ inject: [...inject], apply }).await() + const { onboardingSteps } = injectedOf(b.slots).hooks + b.slots.register({ name: 'settings.onboarding', id: 'credential', order: 0 } as never, () => null) + b.slots.register({ name: 'settings.onboarding', id: 'welcome', order: -100 } as never, () => null) + b.slots.register({ name: 'settings.onboarding', id: 'default-order' } as never, () => null) + const steps = onboardingSteps.getSnapshot() + expect(steps).toEqual([ + { id: 'welcome', order: -100 }, + { id: 'credential', order: 0 }, + { id: 'default-order', order: 0 }, + ]) + expect(onboardingSteps.getSnapshot()).toBe(steps) + const listener = vi.fn() + const off = onboardingSteps.subscribe(listener) + b.slots.register({ name: 'settings.onboarding', id: 'later', order: 10 } as never, () => null) + await Promise.resolve() + expect(listener).toHaveBeenCalledOnce() + off() + }) + it('re-registers after an HMR collapse re-declares the slot (stale disposer must not block)', async () => { const b = await bench() const redeclare = declare(b.slots) diff --git a/packages/client/ui-settings/tests/settings-root.spec.tsx b/packages/client/ui-settings/tests/settings-root.spec.tsx index a7df311672..3d0d2e97a4 100644 --- a/packages/client/ui-settings/tests/settings-root.spec.tsx +++ b/packages/client/ui-settings/tests/settings-root.spec.tsx @@ -8,6 +8,7 @@ import { SettingsRoot } from '../src/client/SettingsRoot.tsx' afterEach(cleanup) type Row = { id: string; order: number; label: string } +type Step = { id: string; order: number } /** Slot-content stand-ins: the shell renders whatever the seats contribute. */ const SEAT_CONTENT: Record = { @@ -23,7 +24,11 @@ function mount({ { id: 'general', order: 0, label: 'General' }, { id: 'models', order: 10, label: 'Models' }, ], -}: { wide?: boolean; onboardingActive?: boolean; rows?: Row[] } = {}) { + steps = [ + { id: 'welcome', order: -100 }, + { id: 'credential', order: 0 }, + ], +}: { wide?: boolean; onboardingActive?: boolean; rows?: Row[]; steps?: Step[] } = {}) { // Mutable row source standing in for the bound useSections hook; bump() // plays a ledger change through the same observable contract. let current = rows @@ -46,6 +51,7 @@ function mount({ useSessions, useWorkspaces: unusedHook, wide, + useOnboardingSteps: select => select(steps), useSections: (select) => { const [, force] = useState(0) useEffect(() => { @@ -164,20 +170,30 @@ describe('SettingsPanel navigation', () => { expect(screen.queryByTestId('section-general')).toBeNull() }) - it('hands Hero readiness and a direct section opener to onboarding registrants', () => { + it('mounts onboarding steps in order and transfers ownership only on completion', () => { const { renderSlot } = mount() - const onboardingCall = renderSlot.mock.calls.find(call => call[0] === 'settings.onboarding') - expect(onboardingCall?.[1]).toMatchObject({ active: true }) + const first = renderSlot.mock.calls.find(call => call[0] === 'settings.onboarding') + expect(first?.[1]).toMatchObject({ stepId: 'welcome' }) + expect(first?.[2]).toEqual({ only: 'welcome' }) act(() => { - (onboardingCall?.[1] as { openSection: (id: string) => void }).openSection('models') + (first?.[1] as { complete: () => void }).complete() + ;(first?.[1] as { complete: () => void }).complete() + }) + const onboardingCalls = renderSlot.mock.calls.filter(call => call[0] === 'settings.onboarding') + const second = onboardingCalls.at(-1) + expect(second?.[1]).toMatchObject({ stepId: 'credential' }) + expect(second?.[2]).toEqual({ only: 'credential' }) + + act(() => { + (second?.[1] as { openSection: (id: string) => void }).openSection('models') }) expect(screen.getByRole('dialog')).toBeTruthy() expect(screen.getByTestId('section-models')).toBeTruthy() cleanup() - const active = mount({ onboardingActive: false }).renderSlot.mock.calls - .find(call => call[0] === 'settings.onboarding') - expect(active?.[1]).toMatchObject({ active: false }) + const inactive = mount({ onboardingActive: false }).renderSlot.mock.calls + .filter(call => call[0] === 'settings.onboarding') + expect(inactive).toHaveLength(0) }) it('falls back to the first row when the active entry unregisters', () => { diff --git a/packages/host/apiproxy/README.i18n.yaml b/packages/host/apiproxy/README.i18n.yaml index 990bb14305..7b97762c41 100644 --- a/packages/host/apiproxy/README.i18n.yaml +++ b/packages/host/apiproxy/README.i18n.yaml @@ -2,5 +2,5 @@ # side as of the last confirmed-consistent state. Both languages carry equal authority; # after editing either side, bring the other along and re-record with: # pnpm run verify-translation-pairing --write packages/host/apiproxy/README.md -README.md: 0abbeced0902471f7ff8ce9a73d188619ad2b64a -README.zh.md: 315ddb06791b8ce7723f8a5349b6cf576fe971de +README.md: bdf67f7d993df3e0ea7ccd7753c7d492d9d2d904 +README.zh.md: 7b758cfc888dc74ad136a2fc139b856705ee8168 diff --git a/packages/host/apiproxy/README.md b/packages/host/apiproxy/README.md index 0abbeced09..bdf67f7d99 100644 --- a/packages/host/apiproxy/README.md +++ b/packages/host/apiproxy/README.md @@ -26,7 +26,7 @@ Directory picking delegates to the composed `ctx.directoryPicker` backend ([the The `command.*` and `skill.*` domains expose the host command registry and skill catalog to clients. Every method addresses one session's agent by `sessionId` (a served session always has an Agent; `command.*` resumes cold sessions through the same path as `session.*`, while `skill.list` resolves the project root from the session header without touching the Agent registry). `skill.list` serves the browser's user-selected model-reference path, so it returns only skills that are both model-invocable and user-invocable; this domain has no direct skill-loading RPC. `command.execute` runs a slash-command line host-side with pure admission semantics: the response reports whether the line resolved to a handler plus the minted lifecycle `commandId` when it did (correlating the acknowledgment with the flow node), while the outcome rides the durably logged `command/run`/`command/done` lifecycle pair broadcast on the mux stream; the carrier's request signal cancels the running handler. `host/commands-changed` is the catalog invalidation frame: clients refetch `command.list` instead of diffing. -The `settings.*`, `credentials.*`, and `llm.*` domains are the configuration-page wire. The settings domain serves exactly the namespaces a registered configurable provider addresses (`ctx.llm.listConfigurableProviders()`): the seam is general, but this plane is the model-provider surface, so a namespace nothing in the directory names is neither described nor writable here and answers `settings-not-exposed` — the same answer an unregistered namespace gets, so no caller can enumerate the registry by probing. `settings.describe` returns each exposed namespace's serialized schemastery schema, redacted layered values (resolved/`base`/`user` — a field's presence in `user` marks it user-overridden), the `secrets` slot list, and the section's `revision`. `settings.update`/`settings.replace` write the user layer; `settings.mutate` applies path ops (`set`/`unset`) against the section as stored, which is the removal path for a client holding the redacted view — rebuilding a section from it and replacing wholesale would delete the secrets the wire never returned. Any write may carry `expectedRevision`; a stale one answers `settings-conflict` with both revisions rather than overwriting the writer that landed first, and every other seam refusal folds into `settings-rejected`. Secret-role values never ride any response in any layer; a secret crosses the wire in exactly one direction — inside an `update`/`mutate` payload or `credentials.set`. `credentials.describe` returns value-free views (`configured`/`source`/`writable`), and `credentials.set`/`credentials.unset` map a shadowed-reference refusal onto `credential-rejected`. `llm.providers` merges the configurable-provider directory with live routes (dormant entries carry `active: false`; undeclared live routes append with no settings address) and `llm.models` is the session-independent catalog. Three invalidation frames keep every surface converged without polling: `host/settings-changed {ns}` (`settings/document-updated` passthrough, so a raw change whose resolved value is unchanged still reaches clients), `host/credentials-changed {ref}` (reference names only, never values), and `host/models-changed` — fired both by `llm/adapters-updated` and by a change to an exposed provider namespace, whose settings carry that provider's catalog and endpoint. The browser carrier restricts the whole configuration plane, reads included (`settings.describe`/`update`/`replace`/`mutate`, `credentials.describe`/`set`/`unset`), to loopback same-origin requests — the `host.pickDirectory` privileged set. A composition without a settings or credential provider answers those domains with an actionable `internal` error naming the missing plugin. +The `settings.*`, `credentials.*`, and `llm.*` domains are the configuration-page wire. The settings domain serves a closed allowlist: namespaces addressed by registered configurable providers (`ctx.llm.listConfigurableProviders()`) plus product-owned `ui-onboarding`. The seam remains general, so any other namespace is neither described nor writable here and answers `settings-not-exposed` — the same answer an unregistered namespace gets, so no caller can enumerate the registry by probing. `settings.describe` returns each exposed namespace's serialized schemastery schema, redacted layered values (resolved/`base`/`user` — a field's presence in `user` marks it user-overridden), the `secrets` slot list, and the section's `revision`. `settings.update`/`settings.replace` write the user layer; `settings.mutate` applies path ops (`set`/`unset`) against the section as stored, which is the removal path for a client holding the redacted view — rebuilding a section from it and replacing wholesale would delete the secrets the wire never returned. Any write may carry `expectedRevision`; a stale one answers `settings-conflict` with both revisions rather than overwriting the writer that landed first, and every other seam refusal folds into `settings-rejected`. Secret-role values never ride any response in any layer; a secret crosses the wire in exactly one direction — inside an `update`/`mutate` payload or `credentials.set`. `credentials.describe` returns value-free views (`configured`/`source`/`writable`), and `credentials.set`/`credentials.unset` map a shadowed-reference refusal onto `credential-rejected`. `llm.providers` merges the configurable-provider directory with live routes (dormant entries carry `active: false`; undeclared live routes append with no settings address) and `llm.models` is the session-independent catalog. Three invalidation frames keep every surface converged without polling: `host/settings-changed {ns}` (`settings/document-updated` passthrough, so a raw change whose resolved value is unchanged still reaches clients), `host/credentials-changed {ref}` (reference names only, never values), and `host/models-changed` — fired both by `llm/adapters-updated` and by a change to a provider namespace, whose settings carry that provider's catalog and endpoint; `ui-onboarding` changes do not invalidate models. The browser carrier restricts the whole configuration plane, reads included (`settings.describe`/`update`/`replace`/`mutate`, `credentials.describe`/`set`/`unset`), to loopback same-origin requests — the `host.pickDirectory` privileged set. A composition without a settings or credential provider answers those domains with an actionable `internal` error naming the missing plugin. ## Carrier layer (`/client` + root) diff --git a/packages/host/apiproxy/README.zh.md b/packages/host/apiproxy/README.zh.md index 315ddb0679..7b758cfc88 100644 --- a/packages/host/apiproxy/README.zh.md +++ b/packages/host/apiproxy/README.zh.md @@ -26,7 +26,7 @@ Workspace 列表与 Session 列表是相互独立的重连基线。`workspace.cr `command.*` 与 `skill.*` 领域向客户端暴露宿主命令注册表和技能目录。每个方法都通过 `sessionId` 寻址一个会话的 Agent(被服务的会话必有 Agent;`command.*` 经由与 `session.*` 相同的路径恢复冷会话,而 `skill.list` 从会话头解析项目根目录,不触碰 Agent 注册表)。`skill.list` 服务于浏览器中由用户选择的模型引用路径,因此仅返回模型和用户均可调用的 skill;该领域没有直接加载 skill 的 RPC。`command.execute` 在宿主侧运行一条斜杠命令行,语义为纯准入:响应报告该行是否解析到处理器,并在解析到时回带铸造的生命周期 `commandId`(将本次确认与流节点关联);结局经由持久落账并在 mux 流广播的 `command/run`/`command/done` 生命周期事件对承载;载体的请求信号可取消正在运行的处理器。`host/commands-changed` 是目录失效帧:客户端重新拉取 `command.list` 而不是做差分。 -`settings.*`、`credentials.*` 与 `llm.*` 领域是配置页协议。settings 领域只服务于已注册可配置提供方所指向的那些 namespace(`ctx.llm.listConfigurableProviders()`):seam 本身是通用的,但这个面是模型提供方表层,因此目录中无人点名的 namespace 在这里既不会被描述也不可写入,只会得到 `settings-not-exposed`——未注册的 namespace 得到的是同一个答复,因此没有调用方能靠逐个探测把注册表枚举出来。`settings.describe` 为每个已暴露 namespace 提供其序列化 schemastery schema、脱敏后的分层值(resolved/`base`/`user`——字段出现在 `user` 中即标记其被用户覆盖)、`secrets` 槽位列表,以及该分节的 `revision`。`settings.update`/`settings.replace` 写入用户层;`settings.mutate` 则在已存分节上施加路径 op(`set`/`unset`),这是持有脱敏视图的客户端的删除路径——据此重建分节再整体替换,会删掉协议从未回传过的那些机密。任何写入都可携带 `expectedRevision`;过期的期望值会以 `settings-conflict` 连同两个 revision 作答,而不是覆盖先落地的那个写方,其余每种 seam 拒绝则折叠为 `settings-rejected`。secret 角色的值绝不在任何一层搭乘任何响应;secret 只沿一个方向跨越协议——在 `update`/`mutate` 载荷或 `credentials.set` 之内。`credentials.describe` 返回不含值的视图(`configured`/`source`/`writable`),`credentials.set`/`credentials.unset` 则把被遮蔽引用的拒绝映射为 `credential-rejected`。`llm.providers` 把可配置提供方目录与存活路由合并(休眠条目携带 `active: false`;未声明的存活路由追加在后,不带 settings 地址),`llm.models` 则是与会话无关的目录。三个失效帧让每个面无需轮询即保持收敛:`host/settings-changed {ns}`(`settings/document-updated` 透传,因此解析值未变的原始变更同样能到达客户端)、`host/credentials-changed {ref}`(只带引用名,绝不带值),以及 `host/models-changed`——它既由 `llm/adapters-updated` 触发,也由某个已暴露提供方 namespace 的变更触发,因为该提供方的设置正承载着它的目录与端点。浏览器载体把整个配置面(含读取:`settings.describe`/`update`/`replace`/`mutate` 与 `credentials.describe`/`set`/`unset`)限制为仅接受来自回环地址的同源请求——即 `host.pickDirectory` 所在的特权集合。未装 settings 或凭据 provider 的组合会以指名缺失插件、包含解决建议的 `internal` 错误应答这些领域。 +`settings.*`、`credentials.*` 与 `llm.*` 领域是配置页协议。settings 领域只服务于一个封闭的允许列表:已注册可配置提供方所指向的 namespace(`ctx.llm.listConfigurableProviders()`),以及产品持有的 `ui-onboarding`。seam 本身仍是通用的,因此其他 namespace 在这里既不会被描述也不可写入,只会得到 `settings-not-exposed`——未注册的 namespace 得到的是同一个答复,因此没有调用方能靠逐个探测把注册表枚举出来。`settings.describe` 为每个已暴露 namespace 提供其序列化 schemastery schema、脱敏后的分层值(resolved/`base`/`user`——字段出现在 `user` 中即标记其被用户覆盖)、`secrets` 槽位列表,以及该分节的 `revision`。`settings.update`/`settings.replace` 写入用户层;`settings.mutate` 则在已存分节上施加路径 op(`set`/`unset`),这是持有脱敏视图的客户端的删除路径——据此重建分节再整体替换,会删掉协议从未回传过的那些机密。任何写入都可携带 `expectedRevision`;过期的期望值会以 `settings-conflict` 连同两个 revision 作答,而不是覆盖先落地的那个写方,其余每种 seam 拒绝则折叠为 `settings-rejected`。secret 角色的值绝不在任何一层搭乘任何响应;secret 只沿一个方向跨越协议——在 `update`/`mutate` 载荷或 `credentials.set` 之内。`credentials.describe` 返回不含值的视图(`configured`/`source`/`writable`),`credentials.set`/`credentials.unset` 则把被遮蔽引用的拒绝映射为 `credential-rejected`。`llm.providers` 把可配置提供方目录与存活路由合并(休眠条目携带 `active: false`;未声明的存活路由追加在后,不带 settings 地址),`llm.models` 则是与会话无关的目录。三个失效帧让每个面无需轮询即保持收敛:`host/settings-changed {ns}`(`settings/document-updated` 透传,因此解析值未变的原始变更同样能到达客户端)、`host/credentials-changed {ref}`(只带引用名,绝不带值),以及 `host/models-changed`——它既由 `llm/adapters-updated` 触发,也由提供方 namespace 的变更触发,因为该提供方的设置正承载着它的目录与端点;`ui-onboarding` 的变更不会触发模型失效事件。浏览器载体把整个配置面(含读取:`settings.describe`/`update`/`replace`/`mutate` 与 `credentials.describe`/`set`/`unset`)限制为仅接受来自回环地址的同源请求——即 `host.pickDirectory` 所在的特权集合。未装 settings 或凭据 provider 的组合会以指名缺失插件、包含解决建议的 `internal` 错误应答这些领域。 ## 载体层(`/client` + 根路径) diff --git a/packages/host/apiproxy/src/api-proxy.ts b/packages/host/apiproxy/src/api-proxy.ts index 0990c5253c..364ec1c77d 100644 --- a/packages/host/apiproxy/src/api-proxy.ts +++ b/packages/host/apiproxy/src/api-proxy.ts @@ -69,6 +69,9 @@ const DEFAULT_MAX_MESSAGES = 50 /** Surface message event types (the pagination counting unit). */ const MESSAGE_TYPES = new Set(['user/message', 'assistant/message', 'steering/message']) +/** Product settings intentionally exposed beside model-provider namespaces. */ +const PRODUCT_SETTINGS_NAMESPACES = new Set(['ui-onboarding']) + /** * Message-boundary pagination: count maxMessages surface messages backwards from * the window tail; the cut is the starting seq of the oldest message group @@ -1014,24 +1017,26 @@ export function createApiProxy(ctx: Context, defaults: ApiProxyDefaults): ApiPro } } - /** - * The settings namespaces this proxy serves: exactly those a registered - * configurable provider addresses. The settings seam itself is general — - * any plugin may register a namespace for its own configuration — but the - * Web configuration plane is scoped to model providers, and that boundary - * has to be enforced here rather than assumed from the current plugin set. - * Without it, every future `settings.register()` would silently become - * remotely readable and writable configuration. - */ - function exposedNamespaces(): Set { + /** Settings namespaces whose values can change the model directory. */ + function providerSettingsNamespaces(): Set { return new Set(ctx.llm.listConfigurableProviders().map(entry => entry.settingsNs)) } - /** Refuse a namespace outside the model-provider boundary, naming why. */ + /** + * The settings namespaces this proxy serves: registered configurable + * providers plus a closed product-owned allowlist. The settings seam itself + * is general, so exposure stays explicit here; registering a future + * namespace never makes it remotely readable or writable by accident. + */ + function exposedNamespaces(): Set { + return new Set([...providerSettingsNamespaces(), ...PRODUCT_SETTINGS_NAMESPACES]) + } + + /** Refuse a namespace outside the explicit Web configuration boundary. */ function notExposed(request: RpcRequest, ns: string): RpcResponse { return err(request, { code: 'settings-not-exposed', - message: `settings namespace "${ns}" is not exposed to configuration clients; only a namespace a registered model provider addresses is`, + message: `settings namespace "${ns}" is not exposed to configuration clients`, details: { ns }, }) } @@ -1909,7 +1914,7 @@ export function createApiProxy(ctx: Context, defaults: ApiProxyDefaults): ApiPro // A provider's own settings carry its model catalog and endpoint, // so a change there invalidates the model list even when the route // set is untouched — `llm/adapters-updated` alone misses it. - if (exposedNamespaces().has(String(ns))) queue.push(frame({ type: 'host/models-changed' })) + if (providerSettingsNamespaces().has(String(ns))) queue.push(frame({ type: 'host/models-changed' })) }), ctx.on('credentials/updated', (ref) => { queue.push(frame({ type: 'host/credentials-changed', ref: String(ref) })) diff --git a/packages/host/apiproxy/tests/api-proxy-config.spec.ts b/packages/host/apiproxy/tests/api-proxy-config.spec.ts index a505f72018..bf077f4f0c 100644 --- a/packages/host/apiproxy/tests/api-proxy-config.spec.ts +++ b/packages/host/apiproxy/tests/api-proxy-config.spec.ts @@ -222,7 +222,7 @@ describe('settings domain', () => { expect(JSON.stringify(value)).not.toContain('user-secret') }) - it('serves only namespaces a registered model provider addresses', async () => { + it('keeps arbitrary plugin namespaces outside the explicit Web allowlist', async () => { // The settings seam is general: any plugin may register a namespace for // its own configuration. The Web configuration plane is not — it is the // model-provider surface, and a namespace nothing in the provider @@ -248,6 +248,21 @@ describe('settings domain', () => { expect(ctx.settings.describe().find(d => String(d.ns) === 'some-other-plugin')?.value).toEqual({}) }) + it('serves the product onboarding namespace without invalidating the model catalog', async () => { + const ctx = await harness() + ctx.settings.register(settingsNamespace('ui-onboarding'), z.object({ welcomeNoticeVersion: z.string() })) + const api = createApiProxy(ctx, DEFAULTS) + expect(expectOk(await api.settings.describe(request({}))).namespaces.map(view => view.ns)) + .toEqual(['ui-onboarding']) + const frames = await collectHost(api, ['host/settings-changed'], 1, async () => { + expectOk(await api.settings.mutate(request({ + ns: 'ui-onboarding', + ops: [{ op: 'set', path: ['welcomeNoticeVersion'], value: 'v1' }], + }))) + }) + expect(frames).toEqual([{ type: 'host/settings-changed', ns: 'ui-onboarding' }]) + }) + it('refuses even a model-provider namespace once its directory entry is gone', async () => { const ctx = await harness({ configurableProviders: false }) ctx.settings.register(NS, AdapterConfig) diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 6dd8389a6f..5b03fca2a5 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -1559,7 +1559,17 @@ importers: version: 18.3.1 packages/client/ui-settings-general: + dependencies: + '@deepseek-ai/dsh-settings': + specifier: workspace:^ + version: link:../../settings/settings + schemastery: + specifier: ^3.18.0 + version: 3.18.0 devDependencies: + '@deepseek-ai/dsh-client-connection': + specifier: workspace:^ + version: link:../connection '@deepseek-ai/dsh-client-locale': specifier: workspace:^ version: link:../locale @@ -1575,6 +1585,9 @@ importers: '@deepseek-ai/dsh-client-ui-slots': specifier: workspace:^ version: link:../ui-slots + '@deepseek-ai/dsh-client-web-react': + specifier: workspace:^ + version: link:../web-react '@deepseek-ai/dsh-invariants': specifier: workspace:^ version: link:../../support/invariants From 1ea5f0b124c51f17471278acf96bebbbe608d2a4 Mon Sep 17 00:00:00 2001 From: Chinesezjc Date: Thu, 30 Jul 2026 22:24:29 +0800 Subject: [PATCH 057/139] test(tui): cover diffContentLines empty-side arm MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The coverage lane flagged transcript.ts line 63 (diffContentLines' empty-text return) uncovered: the same-file diff test only fed newline-terminated sides. Add a third hunk removing a line with an empty added side (a full deletion), so the empty arm runs and the footer proves the empty side draws no `+ ` row (+2 -1 · 1 file). Raise the test's line budget so every hunk row stays visible. --- packages/ui/tui/tests/tui.spec.ts | 26 ++++++++++++++++++-------- 1 file changed, 18 insertions(+), 8 deletions(-) diff --git a/packages/ui/tui/tests/tui.spec.ts b/packages/ui/tui/tests/tui.spec.ts index 457b2c25ac..2354a6d51b 100644 --- a/packages/ui/tui/tests/tui.spec.ts +++ b/packages/ui/tui/tests/tui.spec.ts @@ -4320,16 +4320,20 @@ describe('tool cards and surface replay', () => { }, scatteredDiff: { name: 'scatteredDiff', description: '', parameters: {}, output: UNUSED_TOOL_OUTPUT, execute: async () => [], - // Two hunks in ONE file, each side ending in the terminator newline real - // write/edit content carries. The footer must read `+2 -0 · 1 file`: the - // trailing newline terminates its line rather than adding a phantom empty - // one, and the two hunks count as the single distinct path they touch. + // Three hunks in ONE file. The first two sides end in the terminator + // newline real write/edit content carries; the third removes a line and + // leaves an EMPTY added side (a full deletion), so `diffContentLines('')` + // returns zero lines. The footer must read `+2 -1 · 1 file`: each trailing + // newline terminates its line rather than adding a phantom empty one, the + // empty side contributes no `+ ` row, and the three hunks count as the + // single distinct path they touch. presentCall: () => ({ card: 'diff', title: 'Edit src/scatter.ts', diffs: [ { path: 'src/scatter.ts', oldText: null, newText: 'first\n' }, { path: 'src/scatter.ts', oldText: null, newText: 'second\n' }, + { path: 'src/scatter.ts', oldText: 'gone\n', newText: '' }, ], }), }, @@ -4638,7 +4642,10 @@ describe('tool cards and surface replay', () => { }) it('counts a same-file diff once and terminates its trailing newline', async () => { - const result = await setup({ tools }) + // A budget past the card's row count so every hunk row stays visible (the + // collapse arithmetic is covered elsewhere); this test is about the + // terminator rule and the distinct-path footer count. + const result = await setup({ tools, config: { maxToolOutputLines: 20 } }) appendUser(result.session, 'scatter edits in one file') appendAssistant(result.session, [ { type: 'text', text: 'Editing' }, @@ -4649,14 +4656,17 @@ describe('tool cards and surface replay', () => { }) await tick() const output = result.terminal.output - // Two hunks, one path: distinct-path count, same as the Web DiffBlock. + // Three hunks, one path: distinct-path count, same as the Web DiffBlock. expect(output).toContain('· 1 file') - expect(output).not.toContain('· 2 files') + expect(output).not.toContain('· 3 files') // The `first\n`/`second\n` sides each contribute exactly one added line — // the trailing newline terminates rather than adding a phantom empty `+ `. expect(output).toContain('+ first') expect(output).toContain('+ second') - expect(output).toContain('+2 -0') + // The third hunk removes `gone` and leaves an empty added side, which + // contributes no `+ ` row (diffContentLines('') is zero lines). + expect(output).toContain('- gone') + expect(output).toContain('+2 -1') await dispose(result) }) From c1d88ffb7b822a40ac6e5b3aa8fd3352c1f61c32 Mon Sep 17 00:00:00 2001 From: Chinesezjc Date: Thu, 30 Jul 2026 22:24:57 +0800 Subject: [PATCH 058/139] fix(client-web): pin keyed WebRow in boot smoke, show empty-search feedback - built-boot smoke asserts [data-variant=web][data-tool=web_search/fetch] (the keyed WebRow) instead of [data-web] (which WebBlock draws even on the GenericToolCard fallback, so a silent keyed-registration failure passed). - WebBlock renders an explicit empty-state note when a search returns no answer and no sources, instead of a blank
        ; the chat row does not surface the raw result content, so the backend's 'No results found.' was otherwise invisible. - README (ui-conversation, ui-primitives) and the frontend Agent Note record the unknown-web-kind null arm, the details-panel flattened body, and the empty-search copy; pairings re-recorded. --- ...6-07-30-web-result-card-frontend.i18n.yaml | 4 +- .../2026-07-30-web-result-card-frontend.md | 6 +-- .../2026-07-30-web-result-card-frontend.zh.md | 6 +-- apps/web/tests/built-boot.snapshot.ts | 11 ++-- .../client/ui-conversation/README.i18n.yaml | 4 +- packages/client/ui-conversation/README.md | 2 +- packages/client/ui-conversation/README.zh.md | 2 +- .../client/ui-primitives/README.i18n.yaml | 4 +- packages/client/ui-primitives/README.md | 4 +- packages/client/ui-primitives/README.zh.md | 4 +- .../ui-primitives/src/WebBlock.module.css | 5 ++ .../client/ui-primitives/src/WebBlock.tsx | 54 +++++++++++-------- .../ui-primitives/tests/web-block.spec.tsx | 19 +++++++ 13 files changed, 79 insertions(+), 46 deletions(-) diff --git a/.agents/notes/implemented/feature/2026-07-30-web-result-card-frontend.i18n.yaml b/.agents/notes/implemented/feature/2026-07-30-web-result-card-frontend.i18n.yaml index db354e75a3..dae8f18b4d 100644 --- a/.agents/notes/implemented/feature/2026-07-30-web-result-card-frontend.i18n.yaml +++ b/.agents/notes/implemented/feature/2026-07-30-web-result-card-frontend.i18n.yaml @@ -2,5 +2,5 @@ # side as of the last confirmed-consistent state. Both languages carry equal authority; # after editing either side, bring the other along and re-record with: # pnpm run verify-translation-pairing --write .agents/notes/implemented/feature/2026-07-30-web-result-card-frontend.md -2026-07-30-web-result-card-frontend.md: efead1f404879c526475a1b9f0b31f6c34978f07 -2026-07-30-web-result-card-frontend.zh.md: 2e76bf4c18f5032cd5fd9b15fe31d3c7b036b502 +2026-07-30-web-result-card-frontend.md: d6f4785e83335ca2dd5295516baf47c845ebf5bd +2026-07-30-web-result-card-frontend.zh.md: ed95cbe39f4f0bf77ba5da64d664705a0841863f diff --git a/.agents/notes/implemented/feature/2026-07-30-web-result-card-frontend.md b/.agents/notes/implemented/feature/2026-07-30-web-result-card-frontend.md index efead1f404..d6f4785e83 100644 --- a/.agents/notes/implemented/feature/2026-07-30-web-result-card-frontend.md +++ b/.agents/notes/implemented/feature/2026-07-30-web-result-card-frontend.md @@ -10,7 +10,7 @@ The `web_search` and `web_fetch` tools declare a `card: 'web'` result view ([web ## Decision -`WebBlock` is a `ui-primitives` component that renders a completed web retrieval, and every Web render site for a web call consumes the `web` render intent through it: the keyed chat tool rows (`web_search`/`web_fetch`), the `GenericToolCard` render-site fallback, and the details panel's Output section. `ui-conversation/src/client/contract/web-card-model.ts` is the single place that turns the snapshot's `resultView` into the component's props, mirroring `terminal-card-model.ts`, so no two sites disagree about what a web call shows. It returns null — the generic path — for a running call (the web card is result-only, since the tools keep a generic pending view), for a settled call whose result view is not a web card including a `card` value this client version does not know (which arrives over the wire and so cannot be trusted to be a compiled variant), and for a generic result view (a web tool's error path returns the generic card, whose text the generic path preserves). +`WebBlock` is a `ui-primitives` component that renders a completed web retrieval, and every Web render site for a web call consumes the `web` render intent through it: the keyed chat tool rows (`web_search`/`web_fetch`), the `GenericToolCard` render-site fallback, and the details panel's Output section. `ui-conversation/src/client/contract/web-card-model.ts` is the single place that turns the snapshot's `resultView` into the component's props, mirroring `terminal-card-model.ts`, so no two sites disagree about what a web call shows. It returns null — the generic path — for a running call (the web card is result-only, since the tools keep a generic pending view), for a settled call whose result view is not a web card including a `card` value this client version does not know (which arrives over the wire and so cannot be trusted to be a compiled variant), for a generic result view (a web tool's error path returns the generic card, whose text the generic path preserves), and for a web card whose `kind` this client version does not know (a newer host's value off the wire, which reading as a fetch would draw as an empty URL and `HTTP undefined`). One component draws both kinds, discriminated by `kind`. A `search` shows the answer as markdown above a citation list; each source is a safe external link labelled by its title, or its hostname when the provider gave none, with the snippet and publication date below it, and a `来源列表已截断` indicator when the tool capped the list. A `fetch` shows a compact summary: the linked final URL, its HTTP status, and a `内容已截断` indicator. One component rather than two because both are web retrieval rendered as one card family, which is exactly the reason the contract carries them under one `card` tag with a `kind` discriminant. @@ -18,7 +18,7 @@ One component draws both kinds, discriminated by `kind`. A `search` shows the an **Geometry mirrors CodeBlock/TerminalBlock** (12px radius, code-block surface, 16px vertical margin) so a web card reads as one family with them. A long source list caps at `maxSources` with a head/tail collapse using TerminalBlock's exact split arithmetic (`ceil(max/2)` head lines plus the remaining tail), so a long body's slices agree between the two cards. A source list is prose rather than column-aligned output, so it wraps normally instead of scrolling horizontally the way a terminal card's output does — that is the one deliberate divergence from TerminalBlock. -The card is **resident** under the summary row in the chat rows, capped at `CHAT_WEB_MAX_SOURCES` (8) — half the primitive's own default of 16, which the details panel keeps — the same summary-surface-versus-reading-surface split `CHAT_TERMINAL_MAX_LINES` draws for the terminal card, and the same resident posture `BashRow` uses. The keyed rows register one `WebRow` component under both `web_search` and `web_fetch`; the row discriminates on the tool name only to pick its icon (search vs. browse) and its title (`Search`/`Fetch`). A web-declaring tool without its own keyed row lands on `GenericToolCard`, which grows the same resident card. The details panel renders the card at the primitive's full source allowance. +The card is **resident** under the summary row in the chat rows, capped at `CHAT_WEB_MAX_SOURCES` (8) — half the primitive's own default of 16, which the details panel keeps — the same summary-surface-versus-reading-surface split `CHAT_TERMINAL_MAX_LINES` draws for the terminal card, and the same resident posture `BashRow` uses. The keyed rows register one `WebRow` component under both `web_search` and `web_fetch`; the row discriminates on the tool name only to pick its icon (search vs. browse) and its title (`Search`/`Fetch`). A web-declaring tool without its own keyed row lands on `GenericToolCard`, which grows the same resident card. The details panel renders the card at the primitive's full source allowance and, below it, the flattened model-visible result content: a `web_fetch` card carries only the URL and status, so its fetched body is readable only here. ## Consequences @@ -38,7 +38,7 @@ A separate later PR unifies the whole-row collapse/expand interaction and will f `packages/client/ui-primitives/tests/web-block.spec.tsx` pins the component per-file to the 100% gate: both kinds; the title-or-hostname-or-raw-URL label fallback; the safe-link attributes on both kinds (an http(s) URL becoming an external anchor with `target`/`rel`, a `javascript:`/`file:`/unparseable URL rendering as a plain span with no href); the snippet and date shown or omitted on present/empty/absent; the truncation indicator gated on the flag; and the source-list height cap with its head/tail slice and expand/collapse control including the default cap. -`packages/client/ui-conversation/tests/web-card.spec.tsx` mirrors `terminal-card.spec.tsx` at every wiring seam: `webCardModel`'s derivation projecting every source field, its truncation and absent-answer arms, the fetch derivation, and each null arm (running, null result view, generic result view, unknown card tag); the keyed `WebRow`'s resident card for both kinds capped tighter than the panel, its summary-row-alone running and failed arms; the `GenericToolCard` fallback growing the resident card for a web-declaring tool and keeping the plain row for a non-web call; the details panel's Output section for both kinds and its flattened fallback for a non-web result; and the keyed registration under both `web_search` and `web_fetch` with one component. That file sits on the coverage `exclude` list (`ui-conversation/src/*`), so a coverage run measures none of it. +`packages/client/ui-conversation/tests/web-card.spec.tsx` mirrors `terminal-card.spec.tsx` at every wiring seam: `webCardModel`'s derivation projecting every source field, its truncation and absent-answer arms, the fetch derivation, and each null arm (running, null result view, generic result view, unknown card tag, unknown web `kind`); the keyed `WebRow`'s resident card for both kinds capped tighter than the panel, its summary-row-alone running and failed arms; the `GenericToolCard` fallback growing the resident card for a web-declaring tool and keeping the plain row for a non-web call; the details panel's Output section for both kinds — including a `web_fetch`'s body flattened below its URL/status card — and its flattened fallback for a non-web result; and the keyed registration under both `web_search` and `web_fetch` with one component. That file sits on the coverage `exclude` list (`ui-conversation/src/*`), so a coverage run measures none of it. The fixture (`packages/client/connection/src/client/fixture.ts`) adds turns 66 (`web_search`) and 67 (`web_fetch`), authored inline because the client-side fixture cannot import the web tool: turn 66's result view carries an answer and three sources exercising the citation list (a titled source with a snippet and date, a source with no title so its hostname labels the link, and a source with a date but no snippet) with the capped indicator on; turn 67's carries the fetched URL and a 200 status. Both keep a generic pending call view and add the `web` card only at result time, matching the contract's result-only web shape, and are named after the real tools so they hit the keyed `WebRow`. They are ordered before the todo turn (renumbered to 68) for the same reason the terminal turn is: the standing plan retires at the next `turn/start`, so a turn appended after it would empty the dock's plan strip. This drives the built-boot snapshot and a live `?fixture` server. diff --git a/.agents/notes/implemented/feature/2026-07-30-web-result-card-frontend.zh.md b/.agents/notes/implemented/feature/2026-07-30-web-result-card-frontend.zh.md index 2e76bf4c18..ed95cbe39f 100644 --- a/.agents/notes/implemented/feature/2026-07-30-web-result-card-frontend.zh.md +++ b/.agents/notes/implemented/feature/2026-07-30-web-result-card-frontend.zh.md @@ -10,7 +10,7 @@ Status: implemented ## Decision -`WebBlock` 是一个 `ui-primitives` 组件,渲染一次已完成的 web 检索,web 调用的每个 Web 渲染点都通过它消费 `web` 渲染意图:键控的 chat 工具行(`web_search`/`web_fetch`)、`GenericToolCard` 渲染点兜底,以及详情面板的 Output 区。`ui-conversation/src/client/contract/web-card-model.ts` 是唯一把快照的 `resultView` 转成组件 props 的地方,镜像 `terminal-card-model.ts`,因此没有两个渲染点会对一次 web 调用的显示产生分歧。它返回 null —— 走通用路径 —— 对运行中的调用(web 卡片是 result-only 的,因为工具保留 generic pending 视图)、对 result view 不是 web 卡片的已结算调用(包括本客户端版本不认识的 `card` 值,它经 wire 抵达因而不能被信任为已编译的变体)、以及对 generic result view(web 工具的错误路径返回 generic 卡片,其文本由通用路径保留)。 +`WebBlock` 是一个 `ui-primitives` 组件,渲染一次已完成的 web 检索,web 调用的每个 Web 渲染点都通过它消费 `web` 渲染意图:键控的 chat 工具行(`web_search`/`web_fetch`)、`GenericToolCard` 渲染点兜底,以及详情面板的 Output 区。`ui-conversation/src/client/contract/web-card-model.ts` 是唯一把快照的 `resultView` 转成组件 props 的地方,镜像 `terminal-card-model.ts`,因此没有两个渲染点会对一次 web 调用的显示产生分歧。它返回 null —— 走通用路径 —— 对运行中的调用(web 卡片是 result-only 的,因为工具保留 generic pending 视图)、对 result view 不是 web 卡片的已结算调用(包括本客户端版本不认识的 `card` 值,它经 wire 抵达因而不能被信任为已编译的变体)、对 generic result view(web 工具的错误路径返回 generic 卡片,其文本由通用路径保留)、以及对本客户端版本不认识 `kind` 的 web 卡片(更新的 host 经 wire 发来的值,读作 fetch 会画出空 URL 和 `HTTP undefined`)。 一个组件绘制两种 kind,由 `kind` 判别。`search` 把 answer 作为 markdown 显示在引用列表上方;每个 source 是一个安全外链,以其标题为标签,provider 未给标题时以其主机名为标签,下方是 snippet 与发布日期,工具截断列表时显示 `来源列表已截断` 提示。`fetch` 显示一个紧凑摘要:带链接的最终 URL、其 HTTP 状态、以及 `内容已截断` 提示。用一个组件而非两个,因为两者都是渲染为同一卡片族的 web 检索 —— 这正是契约把它们放在一个 `card` 标签下、用 `kind` 判别的原因。 @@ -18,7 +18,7 @@ Status: implemented **几何镜像 CodeBlock/TerminalBlock**(12px 圆角、code-block 表面、16px 垂直外边距),使 web 卡片与它们读作一家。长 source 列表在 `maxSources` 处折叠,用 TerminalBlock 完全相同的分割算术做头/尾折叠(`ceil(max/2)` 头部行加剩余尾部),使长正文的切片在两张卡之间一致。source 列表是散文而非按列对齐的输出,所以它正常换行,而不像终端卡片的输出那样横向滚动 —— 这是与 TerminalBlock 唯一刻意的分歧。 -卡片在 chat 行中**常驻**于摘要行之下,上限 `CHAT_WEB_MAX_SOURCES`(8)—— 原语自身默认 16 的一半,面板保留 16 —— 与 `CHAT_TERMINAL_MAX_LINES` 为终端卡片所画的摘要面对阅读面的同一划分,以及 `BashRow` 所用的同一常驻姿态。键控行把一个 `WebRow` 组件注册在 `web_search` 与 `web_fetch` 两个键下;行仅根据工具名判别以选取其图标(search 对 browse)与标题(`Search`/`Fetch`)。没有自己键控行的 web 声明工具落到 `GenericToolCard`,它长出同一张常驻卡片。详情面板以原语的完整 source 额度渲染卡片。 +卡片在 chat 行中**常驻**于摘要行之下,上限 `CHAT_WEB_MAX_SOURCES`(8)—— 原语自身默认 16 的一半,面板保留 16 —— 与 `CHAT_TERMINAL_MAX_LINES` 为终端卡片所画的摘要面对阅读面的同一划分,以及 `BashRow` 所用的同一常驻姿态。键控行把一个 `WebRow` 组件注册在 `web_search` 与 `web_fetch` 两个键下;行仅根据工具名判别以选取其图标(search 对 browse)与标题(`Search`/`Fetch`)。没有自己键控行的 web 声明工具落到 `GenericToolCard`,它长出同一张常驻卡片。详情面板以原语的完整 source 额度渲染卡片,并在其下方渲染摊平的模型可见结果内容:`web_fetch` 卡片只携带 URL 与状态,因此其抓取正文只在此处可读。 ## Consequences @@ -38,7 +38,7 @@ Status: implemented `packages/client/ui-primitives/tests/web-block.spec.tsx` 把组件钉到 per-file 100% 门槛:两种 kind;标题-或-主机名-或-原始 URL 的标签回退;两种 kind 上的安全链接属性(http(s) URL 成为带 `target`/`rel` 的外链,`javascript:`/`file:`/无法解析的 URL 渲染为无 href 的纯 span);snippet 与日期在存在/为空/缺失时的显示或省略;由标志位控制的截断提示;以及 source 列表高度上限及其头/尾切片与展开/收起控件,含默认上限。 -`packages/client/ui-conversation/tests/web-card.spec.tsx` 在每个接线接缝镜像 `terminal-card.spec.tsx`:`webCardModel` 的派生投影每个 source 字段、其截断与缺失 answer 的支路、fetch 派生、以及每个 null 支路(运行中、null result view、generic result view、未知 card 标签);键控 `WebRow` 对两种 kind 的常驻卡片、比面板收得更紧、其仅摘要行的运行中与失败支路;`GenericToolCard` 兜底为 web 声明工具长出常驻卡片、并为非 web 调用保持纯行;详情面板 Output 区对两种 kind 及其对非 web 结果的摊平回退;以及在 `web_search` 与 `web_fetch` 两键下用一个组件的键控注册。该文件位于覆盖率 `exclude` 列表(`ui-conversation/src/*`),因此覆盖率运行不度量它。 +`packages/client/ui-conversation/tests/web-card.spec.tsx` 在每个接线接缝镜像 `terminal-card.spec.tsx`:`webCardModel` 的派生投影每个 source 字段、其截断与缺失 answer 的支路、fetch 派生、以及每个 null 支路(运行中、null result view、generic result view、未知 card 标签、未知 web `kind`);键控 `WebRow` 对两种 kind 的常驻卡片、比面板收得更紧、其仅摘要行的运行中与失败支路;`GenericToolCard` 兜底为 web 声明工具长出常驻卡片、并为非 web 调用保持纯行;详情面板 Output 区对两种 kind —— 含 `web_fetch` 正文摊平在其 URL/状态卡片下方 —— 及其对非 web 结果的摊平回退;以及在 `web_search` 与 `web_fetch` 两键下用一个组件的键控注册。该文件位于覆盖率 `exclude` 列表(`ui-conversation/src/*`),因此覆盖率运行不度量它。 fixture(`packages/client/connection/src/client/fixture.ts`)添加 turn 66(`web_search`)与 67(`web_fetch`),内联撰写,因为客户端 fixture 无法 import web 工具:turn 66 的 result view 携带一个 answer 与三个 source,演练引用列表(一个带 snippet 与日期的有标题 source、一个无标题因而以主机名标注链接的 source、一个有日期无 snippet 的 source)并开启截断提示;turn 67 携带抓取的 URL 与一个 200 状态。两者都保留 generic pending call view,仅在 result 时添加 `web` 卡片,匹配契约的 result-only web 形状,且以真实工具命名,使其命中键控 `WebRow`。它们被排在 todo turn(重编号为 68)之前,理由与终端 turn 相同:待定计划在下一个 `turn/start` 退休,所以排在其后的 turn 会清空 dock 的 plan strip。这驱动 built-boot snapshot 与一个实时 `?fixture` 服务。 diff --git a/apps/web/tests/built-boot.snapshot.ts b/apps/web/tests/built-boot.snapshot.ts index 8bf48fc761..e607ead421 100644 --- a/apps/web/tests/built-boot.snapshot.ts +++ b/apps/web/tests/built-boot.snapshot.ts @@ -111,12 +111,13 @@ it('boots the built plugin graph and renders a fixture session end to end', asyn // The web render intent reaches the assembled boot graph: the fixture's // web_search / web_fetch turns render their keyed WebRow cards, proving the // registration, wire projection, and card rendering survive the real bundle - // path (not just the per-package src benches). Without this the whole web - // card could silently fall back to the generic row and every new unit test - // would still pass. + // path (not just the per-package src benches). The selector pins the KEYED + // WebRow (its own `data-variant="web"` wrapper), not the `[data-web]` attribute + // WebBlock draws — the generic fallback renders the same WebBlock, so a silent + // keyed-registration failure would still satisfy a bare `[data-web]` check. await waitFor(() => { - expect(document.querySelector('[data-web="search"]')).not.toBeNull() - expect(document.querySelector('[data-web="fetch"]')).not.toBeNull() + expect(document.querySelector('[data-variant="web"][data-tool="web_search"]')).not.toBeNull() + expect(document.querySelector('[data-variant="web"][data-tool="web_fetch"]')).not.toBeNull() }, { timeout: 10_000 }) // Every bundle injected its plugin-owned style tag (the loader's CSS path). diff --git a/packages/client/ui-conversation/README.i18n.yaml b/packages/client/ui-conversation/README.i18n.yaml index 5c3353695a..1bdb6eac8e 100644 --- a/packages/client/ui-conversation/README.i18n.yaml +++ b/packages/client/ui-conversation/README.i18n.yaml @@ -2,5 +2,5 @@ # side as of the last confirmed-consistent state. Both languages carry equal authority; # after editing either side, bring the other along and re-record with: # pnpm run verify-translation-pairing --write packages/client/ui-conversation/README.md -README.md: 7b39702d8828b80b50d4bc37dbc9350a674b7fdf -README.zh.md: 7f3989e6446581f8264b6fa605dd975be8518ad7 +README.md: 84671fe067917f4aa38bccfaa413404652456fc2 +README.zh.md: 7aea71890bb725c7a87d9fb12804d9477f4eed7a diff --git a/packages/client/ui-conversation/README.md b/packages/client/ui-conversation/README.md index 7b39702d88..84671fe067 100644 --- a/packages/client/ui-conversation/README.md +++ b/packages/client/ui-conversation/README.md @@ -16,7 +16,7 @@ Generic tool rows classify the built-in bash, read, search, write, edit, and run A tool call declaring the `terminal` render intent renders its command output inline, at both conversation render sites, through ui-primitives' `TerminalBlock`. `contract/terminal-card-model.ts` is the single derivation from the snapshot's `callView`/`resultView` pair, so the sites cannot disagree about a command, its cwd, or its exit status; it yields null — the generic path — for any other card tag, including one this client version does not know. Both sites therefore also show the card's run-state dot, which is the same `StateDot` semantic a tool row's leading icon carries, so a row and its own card always agree about one command's state. A multi-line command gets one prompt row per line, with the dot marking the call once on the first row — the exit status is the whole call's, so a dot per line would claim a per-line outcome bash does not report. The keyed `BashRow` carries the card resident below its summary row; since tool rows are no longer details-panel click targets, the card's copy and expand controls are the row's only interactions. The render-site fallback row keeps the card behind its existing expand control. Rows cap at `CHAT_TERMINAL_MAX_LINES` (8) against the panel's 16, which is what keeps a summary surface bounded — the panel stays the single-call reading surface. Inline output is licensed per render intent — the terminal and web cards, each with its own bound; a generic tool's content remains panel-only ([decision](../../../.agents/notes/implemented/feature/2026-07-28-web-terminal-card.md)). -A tool call declaring the `web` render intent renders its web retrieval inline, at both conversation render sites, through ui-primitives' `WebBlock`. `contract/web-card-model.ts` is the single derivation from the snapshot's `resultView`, mirroring the terminal card, so the sites cannot disagree about what a web call shows; it yields null — the generic path — for a running call, a non-web result view, a generic result view, or a `card` tag this client version does not know. The keyed `WebRow` registers one component under both `web_search` and `web_fetch`, discriminating on the tool name only for its icon and title; a web-declaring tool without a keyed row lands on the `GenericToolCard` fallback, which grows the same resident card, and the details panel renders it at the primitive's full source allowance. Rows cap at `CHAT_WEB_MAX_SOURCES` (8) against the panel's 16, the same summary-versus-reading split the terminal card draws ([decision](../../../.agents/notes/implemented/feature/2026-07-30-web-result-card-frontend.md)). +A tool call declaring the `web` render intent renders its web retrieval inline, at both conversation render sites, through ui-primitives' `WebBlock`. `contract/web-card-model.ts` is the single derivation from the snapshot's `resultView`, mirroring the terminal card, so the sites cannot disagree about what a web call shows; it yields null — the generic path — for a running call, a non-web result view, a generic result view, a `card` tag this client version does not know, or a web card whose `kind` this client version does not know (a newer host's value, which the wire cannot be trusted to be `search` or `fetch`). The keyed `WebRow` registers one component under both `web_search` and `web_fetch`, discriminating on the tool name only for its icon and title; a web-declaring tool without a keyed row lands on the `GenericToolCard` fallback, which grows the same resident card, and the details panel renders it at the primitive's full source allowance and, below the card, the flattened model-visible result content — a fetch body is readable only there, since its card carries only the URL and status. Rows cap at `CHAT_WEB_MAX_SOURCES` (8) against the panel's 16, the same summary-versus-reading split the terminal card draws ([decision](../../../.agents/notes/implemented/feature/2026-07-30-web-result-card-frontend.md)). Tool rows are slots too — the standalone tool ring (`ToolViewRegistry`/`ctx.toolviews`/outlet) is retired. The chat entry declares the keyed `'conversation.chat.toolview'` hole (session scope; the key space is runtime-open); its render site dispatches per row via `entryKey: toolName` with `GenericToolCard` as the call-site `fallback`. The owner payload is the uniform `ToolRowOwnerProps` (`callId`/`toolName`/`block`/`openFile`) and `ToolRowProps` pre-composes it with the session standard kit. A registrant is a plain plugin: `ctx.slots.register({ name: 'conversation.chat.toolview', key: '', inject? }, Row)` with `inject: ['slots', 'conversation']` as the load-order seam (apply mounts ConversationService after the chat registration, so the service being present guarantees the slot is declared); session differentiation happens inside the component (`useSessions` reading `parentId` — the bash sample is the third-party-posture exemplar). Trajectory/waterfall toolview slots share this shape and land with their own render sites (RendersCheck rejects a declaration nobody renders). diff --git a/packages/client/ui-conversation/README.zh.md b/packages/client/ui-conversation/README.zh.md index 7f3989e644..7aea71890b 100644 --- a/packages/client/ui-conversation/README.zh.md +++ b/packages/client/ui-conversation/README.zh.md @@ -14,7 +14,7 @@ 声明 `terminal` 渲染意图的工具调用,会在两个对话渲染点上都通过 ui-primitives 的 `TerminalBlock` 内联渲染其命令输出。`contract/terminal-card-model.ts` 是从快照的 `callView`/`resultView` 对推导的唯一位置,因此两个渲染点不可能在命令、cwd 或退出状态上产生分歧;对任何其他 card 标签——包括当前客户端版本不认识的标签——它返回 null,落回通用路径。因此两个渲染点也都显示卡片的运行状态点,它与工具行行首图标承载同一套 `StateDot` 语义,所以一行与其自身的卡片对同一条命令的状态总是一致。多行命令的每一行各占一个提示行,状态点只在第一行为整次调用标记一次——退出状态属于整次调用,因此每行一枚就会声称一个 bash 并不报告的逐行结果。键控的 `BashRow` 把卡片常驻在摘要行下方;由于工具行已不再是详情面板的点击目标,卡片的复制与展开控件就是该行唯一的交互。渲染点兜底行则保持其既有的展开控件。行的上限是 `CHAT_TERMINAL_MAX_LINES`(8),面板为 16,正是这一点让摘要面保持有界——面板仍是单次调用的阅读面。内联输出按渲染意图开放——终端卡片与 web 卡片,各有自己的上限;通用工具的内容仍然只在面板中呈现([决策](../../../.agents/notes/implemented/feature/2026-07-28-web-terminal-card.md))。 -声明 `web` 渲染意图的工具调用,会在两个对话渲染点上都通过 ui-primitives 的 `WebBlock` 内联渲染其 web 检索。`contract/web-card-model.ts` 是从快照的 `resultView` 推导的唯一位置,镜像终端卡片,因此两个渲染点不可能对一次 web 调用的显示产生分歧;对运行中的调用、非 web 的 result view、generic result view,或本客户端版本不认识的 `card` 标签,它返回 null,落回通用路径。键控的 `WebRow` 把一个组件注册在 `web_search` 与 `web_fetch` 两个键下,仅根据工具名判别以选取图标与标题;没有自己键控行的 web 声明工具落到 `GenericToolCard` 兜底,它长出同一张常驻卡片,详情面板则以原语的完整 source 额度渲染它。行的上限是 `CHAT_WEB_MAX_SOURCES`(8),面板为 16,与终端卡片所画的摘要面对阅读面的同一划分([决策](../../../.agents/notes/implemented/feature/2026-07-30-web-result-card-frontend.md))。 +声明 `web` 渲染意图的工具调用,会在两个对话渲染点上都通过 ui-primitives 的 `WebBlock` 内联渲染其 web 检索。`contract/web-card-model.ts` 是从快照的 `resultView` 推导的唯一位置,镜像终端卡片,因此两个渲染点不可能对一次 web 调用的显示产生分歧;对运行中的调用、非 web 的 result view、generic result view、本客户端版本不认识的 `card` 标签,或本客户端版本不认识 `kind` 的 web 卡片(更新的 host 发来的值,wire 上不可信其为 `search` 或 `fetch`),它返回 null,落回通用路径。键控的 `WebRow` 把一个组件注册在 `web_search` 与 `web_fetch` 两个键下,仅根据工具名判别以选取图标与标题;没有自己键控行的 web 声明工具落到 `GenericToolCard` 兜底,它长出同一张常驻卡片,详情面板则以原语的完整 source 额度渲染它,并在卡片下方渲染摊平的模型可见结果内容——fetch 正文只在此处可读,因为其卡片只携带 URL 和状态。行的上限是 `CHAT_WEB_MAX_SOURCES`(8),面板为 16,与终端卡片所画的摘要面对阅读面的同一划分([决策](../../../.agents/notes/implemented/feature/2026-07-30-web-result-card-frontend.md))。 工具行同样是 slot:独立工具环(`ToolViewRegistry`/`ctx.toolviews`/outlet)已经退役。聊天配置项声明键控的 `'conversation.chat.toolview'` 空位(Session scope;key 空间在运行时开放);其渲染点逐行通过 `entryKey: toolName` 分发,并以 `GenericToolCard` 作为调用点 `fallback`。owner 载荷是统一的 `ToolRowOwnerProps`(`callId`/`toolName`/`block`/`openFile`),`ToolRowProps` 则预先将其与 Session 标准工具包组合。注册方只是普通插件:`ctx.slots.register({ name: 'conversation.chat.toolview', key: '', inject? }, Row)`,以 `inject: ['slots', 'conversation']` 作为加载顺序 seam(apply 在聊天注册后挂载 ConversationService,因此服务存在即可保证 slot 已声明);Session 区分在组件内部完成(`useSessions` 读取 `parentId`,bash 示例是第三方姿态的范例)。Trajectory/waterfall 工具视图 slot 共享此形状,并随各自的渲染点落地(RendersCheck 会拒绝没有任何渲染方的声明)。 diff --git a/packages/client/ui-primitives/README.i18n.yaml b/packages/client/ui-primitives/README.i18n.yaml index d7eae92129..a93e506412 100644 --- a/packages/client/ui-primitives/README.i18n.yaml +++ b/packages/client/ui-primitives/README.i18n.yaml @@ -2,5 +2,5 @@ # side as of the last confirmed-consistent state. Both languages carry equal authority; # after editing either side, bring the other along and re-record with: # pnpm run verify-translation-pairing --write packages/client/ui-primitives/README.md -README.md: 099da3ae3d4e2b45507fd18d279650ef0525f36a -README.zh.md: dc7fa5f78ea758cea75e86eefb0c06ebe92e61d2 +README.md: 4e1d85cd830fc720a3abf54b0700ea16789404ae +README.zh.md: 8b8771fa6ec714ba5c4a780135d98109f6c4d186 diff --git a/packages/client/ui-primitives/README.md b/packages/client/ui-primitives/README.md index 099da3ae3d..4e1d85cd83 100644 --- a/packages/client/ui-primitives/README.md +++ b/packages/client/ui-primitives/README.md @@ -14,7 +14,7 @@ Pure React atoms (zero cordis): StateDot, ic_ds_* icons, Button/Pill/Menu/Modal/ ## Web retrieval -`WebBlock` renders a completed web retrieval, one component for both kinds of the `web` render intent (discriminated by `kind`). A `search` shows an optional provider answer (through `MarkdownText`) above an ordered citation list: each source is a safe external link labelled by its title, or its hostname, falling back to the raw URL when the URL does not parse or has no hostname (a `file:`/`data:` URL) so a label is never blank; its snippet and publication date render below it. Only http(s) URLs become anchors (`target`/`rel` set) — the http(s) subset of the allowlist `MarkdownText` applies to untrusted links (it also permits `mailto:`, excluded here); any other URL renders as plain text. A long list caps at `maxSources` (default 16, the TerminalBlock split arithmetic) with a head/tail collapse; the collapsed tail keeps each source's original citation number via `
      1. `, and the expand control is a marker-less `
      2. ` so the `
          ` stays valid HTML. A `fetch` shows a compact summary: the linked final URL and its HTTP status. Both mark a capped retrieval. Rationale: [the web result card note](../../../.agents/notes/implemented/feature/2026-07-30-web-result-card-frontend.md). +`WebBlock` renders a completed web retrieval, one component for both kinds of the `web` render intent (discriminated by `kind`). A `search` shows an optional provider answer (through `MarkdownText`) above an ordered citation list: each source is a safe external link labelled by its title, or its hostname, falling back to the raw URL when the URL does not parse or has no hostname (a `file:`/`data:` URL) so a label is never blank; its snippet and publication date render below it. Only http(s) URLs become anchors (`target`/`rel` set) — the http(s) subset of the allowlist `MarkdownText` applies to untrusted links (it also permits `mailto:`, excluded here); any other URL renders as plain text. A long list caps at `maxSources` (default 16, the TerminalBlock split arithmetic) with a head/tail collapse; the collapsed tail keeps each source's original citation number via `
        1. `, and the expand control is a marker-less `
        2. ` so the `
            ` stays valid HTML. When a search legitimately returns no answer and no sources, the card shows an explicit empty-state note rather than a blank `
              ` (the chat row does not surface the raw result content). A `fetch` shows a compact summary: the linked final URL and its HTTP status. Both mark a capped retrieval. Rationale: [the web result card note](../../../.agents/notes/implemented/feature/2026-07-30-web-result-card-frontend.md). ## Model Experience @@ -29,5 +29,5 @@ None; this package neither assembles nor sends a provider request. - **Glyph-level icons are redrawn approximations** — the fish logo (and the sparkle held by ui-conversation) come from font glyphs whose vector geometry is not exportable from the local design data; hand-authored recreations stand in until an exact export path exists. - **Pill and Input have no design source** — both atoms are self-defined; the sidebar search field and view-tab strip that resemble them are consumer-owned compositions, not these atoms. - **StateDot `Active` variant is a hidden placeholder in the design** — not implemented; the four shipped states (done/warning/ongoing/error) are the complete P-I surface. -- **This package's user-facing copy is inline Chinese, not localized** — the atoms are zero-cordis and so cannot reach `ctx.locale`; `TerminalBlock`'s exit-code and signal pills, its copy and expand controls, `CodeBlock`'s copy control, and `WebBlock`'s source expand/collapse controls and its source-list and fetch truncation notes are all hardcoded. This matches the repo-wide state the locale package records (only the Settings surface is translated); extracting these into the `zh`/`en` dictionaries needs a localization channel for zero-cordis atoms and belongs to that repo-wide extraction. +- **This package's user-facing copy is inline Chinese, not localized** — the atoms are zero-cordis and so cannot reach `ctx.locale`; `TerminalBlock`'s exit-code and signal pills, its copy and expand controls, `CodeBlock`'s copy control, and `WebBlock`'s source expand/collapse controls, its source-list and fetch truncation notes, and its empty-search note are all hardcoded. This matches the repo-wide state the locale package records (only the Settings surface is translated); extracting these into the `zh`/`en` dictionaries needs a localization channel for zero-cordis atoms and belongs to that repo-wide extraction. - **`TerminalBlock` is not a terminal emulator** — it renders settled or still-running command output, not an interactive session: SGR color and attributes are honored, and so are the in-line cursor movements a progress line uses — carriage return, backspace, erase-in-line, tab stops and character width. Absolute cursor positioning, screen clearing, and alternate-screen sequences are stripped. Basic-16 magenta and cyan have no token equivalent and stay literal rgb. diff --git a/packages/client/ui-primitives/README.zh.md b/packages/client/ui-primitives/README.zh.md index dc7fa5f78e..8b8771fa6e 100644 --- a/packages/client/ui-primitives/README.zh.md +++ b/packages/client/ui-primitives/README.zh.md @@ -13,7 +13,7 @@ ## Web 检索 -`WebBlock` 渲染一次已完成的 web 检索,用一个组件绘制 `web` 渲染意图的两种 kind(由 `kind` 判别)。`search` 在有序引用列表上方显示可选的 provider answer(通过 `MarkdownText`):每个 source 是一个安全外链,以其标题为标签,或以其主机名为标签,当 URL 无法解析或没有主机名(`file:`/`data:` URL)时回退到原始 URL,因此标签绝不为空;其下渲染 snippet 与发布日期。只有 http(s) URL 会成为锚点(设置 `target`/`rel`)——这是 `MarkdownText` 对不受信任链接所用 allowlist 的 http(s) 子集(该 allowlist 还允许 `mailto:`,此处排除);任何其他 URL 渲染为纯文本。长列表在 `maxSources`(默认 16,即 TerminalBlock 的切分算术)处折叠为头部/尾部;折叠的尾部通过 `
            1. ` 保留每个 source 原始的引用编号,展开控件是无 marker 的 `
            2. `,使 `
                ` 保持为合法 HTML。`fetch` 显示一个紧凑摘要:带链接的最终 URL 及其 HTTP 状态。两者都会标记一次被截断的检索。原理:[Web result 卡片笔记](../../../.agents/notes/implemented/feature/2026-07-30-web-result-card-frontend.md)。 +`WebBlock` 渲染一次已完成的 web 检索,用一个组件绘制 `web` 渲染意图的两种 kind(由 `kind` 判别)。`search` 在有序引用列表上方显示可选的 provider answer(通过 `MarkdownText`):每个 source 是一个安全外链,以其标题为标签,或以其主机名为标签,当 URL 无法解析或没有主机名(`file:`/`data:` URL)时回退到原始 URL,因此标签绝不为空;其下渲染 snippet 与发布日期。只有 http(s) URL 会成为锚点(设置 `target`/`rel`)——这是 `MarkdownText` 对不受信任链接所用 allowlist 的 http(s) 子集(该 allowlist 还允许 `mailto:`,此处排除);任何其他 URL 渲染为纯文本。长列表在 `maxSources`(默认 16,即 TerminalBlock 的切分算术)处折叠为头部/尾部;折叠的尾部通过 `
              1. ` 保留每个 source 原始的引用编号,展开控件是无 marker 的 `
              2. `,使 `
                  ` 保持为合法 HTML。当一次 search 合法地返回无 answer 且无 source 时,卡片显示一个明确的空状态提示,而不是空的 `
                    `(chat 行不呈现原始 result content)。`fetch` 显示一个紧凑摘要:带链接的最终 URL 及其 HTTP 状态。两者都会标记一次被截断的检索。原理:[Web result 卡片笔记](../../../.agents/notes/implemented/feature/2026-07-30-web-result-card-frontend.md)。 ## 模型体验 @@ -28,5 +28,5 @@ - **字形级图标是重新绘制的近似版本**:鱼形标志(以及 ui-conversation 持有的闪光图标)来自字体字形,而本地设计数据无法导出其矢量几何;在获得精确导出路径前,使用手工重建版本代替。 - **Pill 与 Input 没有设计来源**:两个原子组件均自行定义;与其相似的侧边栏搜索字段和视图标签条由消费方组合,不是这些原子组件。 - **StateDot 的 `Active` 变体是设计中的隐藏占位符**:尚未实现;已交付的四种状态(done/warning/ongoing/error)构成完整的 P-I 表层。 -- **本包面向用户的文案是内联中文,未做本地化**:这些原子组件是 zero-cordis 的,因此拿不到 `ctx.locale`;`TerminalBlock` 的退出码与信号胶囊、它的复制与展开控件、`CodeBlock` 的复制控件,以及 `WebBlock` 的来源展开/收起控件与它的来源列表与 fetch 截断提示,全部硬编码。这与 locale 包记录的全仓现状一致(只有 Settings 表面做了翻译);把它们抽取进 `zh`/`en` 字典需要为 zero-cordis 原子组件提供一条本地化通道,属于那次全仓抽取的范围。 +- **本包面向用户的文案是内联中文,未做本地化**:这些原子组件是 zero-cordis 的,因此拿不到 `ctx.locale`;`TerminalBlock` 的退出码与信号胶囊、它的复制与展开控件、`CodeBlock` 的复制控件,以及 `WebBlock` 的来源展开/收起控件、它的来源列表与 fetch 截断提示、以及它的空搜索提示,全部硬编码。这与 locale 包记录的全仓现状一致(只有 Settings 表面做了翻译);把它们抽取进 `zh`/`en` 字典需要为 zero-cordis 原子组件提供一条本地化通道,属于那次全仓抽取的范围。 - **`TerminalBlock` 不是终端模拟器**:它渲染已结束或仍在运行的命令输出,而不是交互式会话:SGR 颜色与属性会被遵循,进度行所用的行内光标移动同样被遵循——回车、退格、行内擦除、制表位与字符宽度。绝对光标定位、清屏与备用屏幕序列会被剥离。基础 16 色中的洋红与青色没有对应 token,保持字面 rgb。 diff --git a/packages/client/ui-primitives/src/WebBlock.module.css b/packages/client/ui-primitives/src/WebBlock.module.css index 17383563bf..8aad5872ba 100644 --- a/packages/client/ui-primitives/src/WebBlock.module.css +++ b/packages/client/ui-primitives/src/WebBlock.module.css @@ -91,6 +91,11 @@ font: var(--dsw-font-xs-13); } +.empty { + color: var(--dsw-alias-label-secondary); + font: var(--dsw-font-xs-13); +} + /* The fetch card is a compact summary: the URL over a status/truncation row. */ .fetch { display: flex; diff --git a/packages/client/ui-primitives/src/WebBlock.tsx b/packages/client/ui-primitives/src/WebBlock.tsx index f0144bd601..804ff17dfa 100644 --- a/packages/client/ui-primitives/src/WebBlock.tsx +++ b/packages/client/ui-primitives/src/WebBlock.tsx @@ -174,34 +174,42 @@ function WebSearchBlock({ answer, sources, truncated, maxSources = DEFAULT_WEB_M const tailCount = maxSources - headCount const head = capped ? sources.slice(0, headCount) : sources const tail = capped ? sources.slice(sources.length - tailCount) : [] + // A provider may legitimately return no answer and no sources; the chat WebRow + // does not show the raw result content, so without this the user would see an + // empty card. Mirror the backend's `No results found.` render text. + const empty = (answer === undefined || answer === '') && sources.length === 0 return (
                    {answer !== undefined && answer !== '' && (
                    )} -
                      - {head.map((source, index) => )} - {hidden > 0 && ( -
                    1. - -
                    2. - )} - {tail.map((source, index) => ( - - ))} -
                    + {empty ? ( +
                    未找到结果
                    + ) : ( +
                      + {head.map((source, index) => )} + {hidden > 0 && ( +
                    1. + +
                    2. + )} + {tail.map((source, index) => ( + + ))} +
                    + )} {truncated &&
                    来源列表已截断
                    }
                    ) diff --git a/packages/client/ui-primitives/tests/web-block.spec.tsx b/packages/client/ui-primitives/tests/web-block.spec.tsx index b0778a636a..d681ce753b 100644 --- a/packages/client/ui-primitives/tests/web-block.spec.tsx +++ b/packages/client/ui-primitives/tests/web-block.spec.tsx @@ -36,6 +36,25 @@ describe('WebBlock search card', () => { expect(empty.container.querySelector('[class^="_answer_"]')).toBeNull() }) + it('shows the empty-state note when a search returns no answer and no sources', () => { + const view = render() + expect(view.getByText('未找到结果')).toBeTruthy() + // The empty note replaces the source list, not an empty
                      . + expect(view.container.querySelector('ol')).toBeNull() + }) + + it('shows the source list, not the empty note, when a source is present', () => { + const view = render() + expect(view.container.querySelector('ol')).toBeTruthy() + expect(view.queryByText('未找到结果')).toBeNull() + }) + + it('shows the source list when an empty source list still carries an answer', () => { + const view = render() + expect(view.getByText('Just an answer')).toBeTruthy() + expect(view.queryByText('未找到结果')).toBeNull() + }) + it('labels a source by its title, and by hostname when the title is absent', () => { const view = render( Date: Thu, 30 Jul 2026 22:26:14 +0800 Subject: [PATCH 059/139] fix(fs): correct Note pre-release link and restore read.ts decline coverage The Note's pre-release-stance link used the wrong depth and target (../../../CLAUDE.md); point it at ../../../../AGENTS.md with the section anchor so verify-md-links passes. The presentResult decline test's meta lacked the now-required offset, so it declined at meta narrowing instead of exercising the content-shape decline (read.ts:181-183); add offset back. --- .agents/notes/implemented/feature/2026-07-30-web-read-card.md | 2 +- .../notes/implemented/feature/2026-07-30-web-read-card.zh.md | 2 +- packages/fs/tool-fs/tests/tools.spec.ts | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/.agents/notes/implemented/feature/2026-07-30-web-read-card.md b/.agents/notes/implemented/feature/2026-07-30-web-read-card.md index 509fc86673..1fb3d61a11 100644 --- a/.agents/notes/implemented/feature/2026-07-30-web-read-card.md +++ b/.agents/notes/implemented/feature/2026-07-30-web-read-card.md @@ -16,7 +16,7 @@ Add a fourth `card` tag, `read`, to the [render-intent union](../architecture/20 The read tool projects the structured window through `output.presentationMeta`, the same persisted channel write/edit use for their applied-diff hunks ([canonical tool output contract](../architecture/2026-07-20-canonical-tool-output-contract.md)). `presentationMeta` runs once for a top-level surface call, returns `{ path, offset, lines, totalLines, lang? }` as JSON the session validates and stores on the result's `meta`, and `presentResult` narrows that meta back into the `ReadResultView` on both live and replay paths. `offset` (the 1-based first line the window requested) rides along because a byte cap below the first selected line yields an empty `lines` array with a positive `totalLines`; without the persisted `offset` a replayed card of such a window could not report where it starts or where a continuation resumes, and the last-line and re-parse fallbacks are both lossy. Without this channel the line array and total would be unreachable: the raw output object is not on the wire, and re-parsing the `N: text` text is lossy and fragile against the truncation footer. -`presentResult` returns `undefined` — the generic fallback — whenever the meta is absent or malformed (`readMetaFromMeta` narrows it defensively, so a replay of an older logged result never throws), whenever the result is an error, and whenever the single text block is not the read envelope. A pre-card logged result — a valid read envelope with no persisted `meta`, recorded before this card existed — takes that same `undefined` path deliberately: the client falls back to the raw `result.content`, so it shows the enveloped `//` text rather than the envelope-stripped generic card the old presenter returned. This is the accepted degradation under the [pre-release stance](../../../CLAUDE.md): reject the old on-disk format rather than add an envelope-stripping compatibility branch, since this PR re-records every published fixture and the session format promises no backward compatibility. On the success path `presentResult` carries `content` (the envelope-stripped text) alongside the structured fields, so a UI without the read capability, including the current TUI, renders the file text through the generic/default card arm exactly as before. The TUI's `renderBody` switch (`packages/ui/tui/src/components/transcript.ts`) is not `assertNever`-exhaustive: `terminal` and `diff` have arms and everything else falls through to the generic arm, which reads `view.content`. That default arm alone was not enough: `render()` sets `genericContent` — and with it the dim-Markdown `dimBody` treatment — on a separate gate that was `card === 'generic'` only, so a `read` card would have kept the text but lost its dim styling. The gate now admits `card: 'read'` too, taking `content` down the same dim-Markdown path, so a read renders in the TUI exactly as it did before the read card existed. Beyond that one gate the TUI needs no read-specific code. +`presentResult` returns `undefined` — the generic fallback — whenever the meta is absent or malformed (`readMetaFromMeta` narrows it defensively, so a replay of an older logged result never throws), whenever the result is an error, and whenever the single text block is not the read envelope. A pre-card logged result — a valid read envelope with no persisted `meta`, recorded before this card existed — takes that same `undefined` path deliberately: the client falls back to the raw `result.content`, so it shows the enveloped `//` text rather than the envelope-stripped generic card the old presenter returned. This is the accepted degradation under the [pre-release stance](../../../../AGENTS.md#pre-release-stance-foundation-over-blast-radius): reject the old on-disk format rather than add an envelope-stripping compatibility branch, since this PR re-records every published fixture and the session format promises no backward compatibility. On the success path `presentResult` carries `content` (the envelope-stripped text) alongside the structured fields, so a UI without the read capability, including the current TUI, renders the file text through the generic/default card arm exactly as before. The TUI's `renderBody` switch (`packages/ui/tui/src/components/transcript.ts`) is not `assertNever`-exhaustive: `terminal` and `diff` have arms and everything else falls through to the generic arm, which reads `view.content`. That default arm alone was not enough: `render()` sets `genericContent` — and with it the dim-Markdown `dimBody` treatment — on a separate gate that was `card === 'generic'` only, so a `read` card would have kept the text but lost its dim styling. The gate now admits `card: 'read'` too, taking `content` down the same dim-Markdown path, so a read renders in the TUI exactly as it did before the read card existed. Beyond that one gate the TUI needs no read-specific code. ### Language hint derivation diff --git a/.agents/notes/implemented/feature/2026-07-30-web-read-card.zh.md b/.agents/notes/implemented/feature/2026-07-30-web-read-card.zh.md index aec170fd21..946bcca95b 100644 --- a/.agents/notes/implemented/feature/2026-07-30-web-read-card.zh.md +++ b/.agents/notes/implemented/feature/2026-07-30-web-read-card.zh.md @@ -16,7 +16,7 @@ Status: implemented read 工具通过 `output.presentationMeta` 投影结构化窗口,这与 write/edit 用来投影其应用 diff hunk 的持久化通道相同([规范化工具输出契约](../architecture/2026-07-20-canonical-tool-output-contract.md))。`presentationMeta` 对一次顶层 surface 调用运行一次,返回 `{ path, offset, lines, totalLines, lang? }` 作为会话校验并存储在结果 `meta` 上的 JSON,`presentResult` 在 live 和回放路径上都把该 meta 收窄回 `ReadResultView`。`offset`(窗口请求的 1-based 起始行)一并携带,是因为当字节上限低于首个选中行时,窗口会返回空的 `lines` 数组而 `totalLines` 为正;没有持久化的 `offset`,这类窗口的回放 card 就无法报告它从哪行开始、或续读应从哪行继续,而末行推断与文本重解析两种兜底都有损。没有这个通道,行数组和总数就无法触及:原始输出对象不在线上,而重新解析 `N: text` 文本既有损又对截断脚注脆弱。 -`presentResult` 在以下情况返回 `undefined`——即 generic 回退:meta 缺失或畸形(`readMetaFromMeta` 防御性收窄它,因此回放旧的已记录结果永不抛错)、结果是错误、以及单个文本块不是 read 信封。本 card 出现之前记录的结果——信封合法但无持久化 `meta`——有意走同一条 `undefined` 路径:客户端回退到原始 `result.content`,因此显示带 `//` 信封的原文,而非旧展示器返回的剥信封 generic card。这是 [pre-release 立场](../../../CLAUDE.md)下接受的降级:拒绝旧的磁盘格式,而非加一个剥信封的兼容分支——本 PR 已重录全部已发布 fixtures,且 session 格式不承诺向后兼容。在成功路径上,`presentResult` 在结构化字段之外携带 `content`(剥信封后的文本),因此不具备 read 能力的 UI(包括当前的 TUI)通过 generic/default card 分支渲染文件文本,与之前完全一致。TUI 的 `renderBody` switch(`packages/ui/tui/src/components/transcript.ts`)不是 `assertNever` 穷尽的:`terminal` 和 `diff` 有分支,其余都落入 generic 分支,该分支读取 `view.content`。仅有该默认分支还不够:`render()` 在一个独立门控上设置 `genericContent`(连同 dim-Markdown 的 `dimBody` 处理),该门控原先只判 `card === 'generic'`,因此 `read` card 虽保留文本却会丢失 dim 样式。现在该门控也接纳 `card: 'read'`,让 `content` 走同一条 dim-Markdown 路径,因此 read 在 TUI 中的渲染与 read card 出现之前完全一致。除这一处门控外,TUI 无需 read 专属代码。 +`presentResult` 在以下情况返回 `undefined`——即 generic 回退:meta 缺失或畸形(`readMetaFromMeta` 防御性收窄它,因此回放旧的已记录结果永不抛错)、结果是错误、以及单个文本块不是 read 信封。本 card 出现之前记录的结果——信封合法但无持久化 `meta`——有意走同一条 `undefined` 路径:客户端回退到原始 `result.content`,因此显示带 `//` 信封的原文,而非旧展示器返回的剥信封 generic card。这是 [pre-release 立场](../../../../AGENTS.md#pre-release-stance-foundation-over-blast-radius)下接受的降级:拒绝旧的磁盘格式,而非加一个剥信封的兼容分支——本 PR 已重录全部已发布 fixtures,且 session 格式不承诺向后兼容。在成功路径上,`presentResult` 在结构化字段之外携带 `content`(剥信封后的文本),因此不具备 read 能力的 UI(包括当前的 TUI)通过 generic/default card 分支渲染文件文本,与之前完全一致。TUI 的 `renderBody` switch(`packages/ui/tui/src/components/transcript.ts`)不是 `assertNever` 穷尽的:`terminal` 和 `diff` 有分支,其余都落入 generic 分支,该分支读取 `view.content`。仅有该默认分支还不够:`render()` 在一个独立门控上设置 `genericContent`(连同 dim-Markdown 的 `dimBody` 处理),该门控原先只判 `card === 'generic'`,因此 `read` card 虽保留文本却会丢失 dim 样式。现在该门控也接纳 `card: 'read'`,让 `content` 走同一条 dim-Markdown 路径,因此 read 在 TUI 中的渲染与 read card 出现之前完全一致。除这一处门控外,TUI 无需 read 专属代码。 ### 语言提示推导 diff --git a/packages/fs/tool-fs/tests/tools.spec.ts b/packages/fs/tool-fs/tests/tools.spec.ts index 87177095ab..914a1bf7de 100644 --- a/packages/fs/tool-fs/tests/tools.spec.ts +++ b/packages/fs/tool-fs/tests/tools.spec.ts @@ -534,7 +534,7 @@ describe('tool-owned presentation (pure presentCall)', () => { it('read: completed presentation declines errors and non-single-text content', async () => { const envelope = '/tmp/a.txt\nfile\n\nbody\n' - const meta = { path: '/tmp/a.txt', lines: [{ number: 1, text: 'body' }], totalLines: 1 } + const meta = { path: '/tmp/a.txt', offset: 1, lines: [{ number: 1, text: 'body' }], totalLines: 1 } expect(await presentResult('read', { file_path: 'a.txt' }, { content: [{ type: 'text', text: envelope }], isError: true, From 111a4df38eb49f6ff1e6f0e3de25e2e3e51d2c6c Mon Sep 17 00:00:00 2001 From: Chinesezjc Date: Thu, 30 Jul 2026 22:26:31 +0800 Subject: [PATCH 060/139] docs(fs): re-record read-card Note i18n pairing after link fix --- .../implemented/feature/2026-07-30-web-read-card.i18n.yaml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/.agents/notes/implemented/feature/2026-07-30-web-read-card.i18n.yaml b/.agents/notes/implemented/feature/2026-07-30-web-read-card.i18n.yaml index e0d55b7496..abefa88679 100644 --- a/.agents/notes/implemented/feature/2026-07-30-web-read-card.i18n.yaml +++ b/.agents/notes/implemented/feature/2026-07-30-web-read-card.i18n.yaml @@ -2,5 +2,5 @@ # side as of the last confirmed-consistent state. Both languages carry equal authority; # after editing either side, bring the other along and re-record with: # pnpm run verify-translation-pairing --write .agents/notes/implemented/feature/2026-07-30-web-read-card.md -2026-07-30-web-read-card.md: 509fc866737be6f9f05a02aed02324f3a337e936 -2026-07-30-web-read-card.zh.md: aec170fd2180af58102d8079118339cdef55a4c4 +2026-07-30-web-read-card.md: 1fb3d61a113d26f6daf023fc791f3638055b5be0 +2026-07-30-web-read-card.zh.md: 946bcca95bcc9bb50beb1ef22e77e4a21728b538 From 1986de9ac14d8eb5ae5b0d8c79341d9faa3e2369 Mon Sep 17 00:00:00 2001 From: kingwl Date: Thu, 30 Jul 2026 22:42:25 +0800 Subject: [PATCH 061/139] fix(web): show plan status only while active --- ...input-machine-and-slash-pipeline.i18n.yaml | 4 +- ...25-web-input-machine-and-slash-pipeline.md | 3 +- ...web-input-machine-and-slash-pipeline.zh.md | 3 +- apps/web/tests/lifecycle-chrome.e2e.ts | 57 +++++++++- .../snapshots/code-mode-round/ui.expected.md | 1 - .../cordis-tool-round/ui.expected.md | 1 - .../snapshots/fresh-round-trip/ui.expected.md | 1 - .../lifecycle-chrome/hero.expected.md | 1 - .../lifecycle-chrome/plan-active.expected.md | 39 +++++++ .../lifecycle-chrome/reloaded.expected.md | 1 - .../live-interactions/cancel.expected.md | 1 - .../live-interactions/error-auth.expected.md | 1 - .../live-interactions/retry.expected.md | 1 - .../snapshots/message-actions/ui.expected.md | 1 - .../question-composer/answered.expected.md | 1 - .../queue-actions/editing.expected.md | 1 - .../snapshots/queue-actions/ui.expected.md | 1 - .../snapshots/seeded-history/ui.expected.md | 1 - .../snapshots/steering/settled.expected.md | 1 - packages/client/ui-plan/README.i18n.yaml | 4 +- packages/client/ui-plan/README.md | 4 +- packages/client/ui-plan/README.zh.md | 4 +- packages/client/ui-plan/package.json | 2 + .../src/client/PlanModeControl.module.css | 34 +++--- .../ui-plan/src/client/PlanModeControl.tsx | 53 +++++----- packages/client/ui-plan/src/client/index.ts | 24 ++--- .../ui-plan/tests/browser-plugin.spec.ts | 18 ++-- .../ui-plan/tests/plan-mode-control.spec.tsx | 100 +++++++----------- packages/client/ui-plan/tsconfig.json | 3 + pnpm-lock.yaml | 3 + 30 files changed, 212 insertions(+), 157 deletions(-) create mode 100644 apps/web/tests/snapshots/lifecycle-chrome/plan-active.expected.md diff --git a/.agents/notes/implemented/architecture/2026-07-25-web-input-machine-and-slash-pipeline.i18n.yaml b/.agents/notes/implemented/architecture/2026-07-25-web-input-machine-and-slash-pipeline.i18n.yaml index ea630a99f9..09ab4376b5 100644 --- a/.agents/notes/implemented/architecture/2026-07-25-web-input-machine-and-slash-pipeline.i18n.yaml +++ b/.agents/notes/implemented/architecture/2026-07-25-web-input-machine-and-slash-pipeline.i18n.yaml @@ -2,5 +2,5 @@ # side as of the last confirmed-consistent state. Both languages carry equal authority; # after editing either side, bring the other along and re-record with: # pnpm run verify-translation-pairing --write .agents/notes/implemented/architecture/2026-07-25-web-input-machine-and-slash-pipeline.md -2026-07-25-web-input-machine-and-slash-pipeline.md: 2793e9045fe5a3c82f52c65503dd4a8cdf6a0596 -2026-07-25-web-input-machine-and-slash-pipeline.zh.md: e3a35c4e55525fedd835eace973f114bd15da37b +2026-07-25-web-input-machine-and-slash-pipeline.md: c3deadb34d3a633525dde701c92bcc98c05e5d6e +2026-07-25-web-input-machine-and-slash-pipeline.zh.md: 7a6988423dcdffebb0a28735146439c8ade0a862 diff --git a/.agents/notes/implemented/architecture/2026-07-25-web-input-machine-and-slash-pipeline.md b/.agents/notes/implemented/architecture/2026-07-25-web-input-machine-and-slash-pipeline.md index 2793e9045f..c3deadb34d 100644 --- a/.agents/notes/implemented/architecture/2026-07-25-web-input-machine-and-slash-pipeline.md +++ b/.agents/notes/implemented/architecture/2026-07-25-web-input-machine-and-slash-pipeline.md @@ -101,7 +101,7 @@ skill/@subagent references skip the placeholder + occurrence identity chain — - `conversation.input.dock` — the stacked strip above the input (QueueDock's read-only queue list lands here), ordered by `order`. - `conversation.composer.dock` — the stats band on the composer's top edge. - `conversation.input.left` / `conversation.input.right` — the tool-row left and right regions. -- `conversation.input.plan` / `conversation.input.model` (single) — the tool row's two named control seats; the bar passes only `locked` (owner props), each stays empty until its owning plugin registers, no placeholder fallback. +- `conversation.input.plan` / `conversation.input.model` (single) — the tool row's two named control seats; the bar passes only `locked` (owner props), each stays empty until its owning plugin registers, no placeholder fallback. The plan seat stays empty while inactive because the shared Command source owns entry; an effective plan target renders the warn-state `Plan ×` status button, whose only action is `/plan off`. - `conversation.hero.workspace` (root scope) — the Workspace picker shared by the no-session and blank Hero; a pick reuses or creates the target blank session through `connectWorkspace`, moving the draft where necessary before switching current. ### Testing discipline @@ -122,6 +122,7 @@ The state machine's entire behavior is covered by pure-JS unit tests (event sequ | Space adjudication also claiming execute-kind commands | The misfire defense: after a space the whole line is an ordinary prompt; irreversible side effects keep explicit entry points only | | A generic tokenPattern decoration mechanism | Structured occurrence records replace pattern scanning | | A placeholder select resident in the tool row | Named seats stay empty until registration; a placeholder clashing with the real implementation is two sources of truth | +| An always-visible Plan on/off toggle | The shared Command source already owns entry; a second entry point turns a status seat into redundant mode chrome | | A second plus-menu component/controller, or an Add/File group above Command | It would duplicate async candidates, keyboard highlight, focus retention, and pick state; the plus control is only a source-filtered launcher for the existing MenuView, and this scope has no file capability | | All references through U+FFFC chips (the pre-Decision-21 line) | Plain text + derived decoration carries zero identity state; the literal text IS the model projection, sparing undo/clipboard any special cases; the chip chain is kept for scenarios needing indivisible atomicity | diff --git a/.agents/notes/implemented/architecture/2026-07-25-web-input-machine-and-slash-pipeline.zh.md b/.agents/notes/implemented/architecture/2026-07-25-web-input-machine-and-slash-pipeline.zh.md index e3a35c4e55..7a6988423d 100644 --- a/.agents/notes/implemented/architecture/2026-07-25-web-input-machine-and-slash-pipeline.zh.md +++ b/.agents/notes/implemented/architecture/2026-07-25-web-input-machine-and-slash-pipeline.zh.md @@ -101,7 +101,7 @@ skill/@subagent 引用不走占位符 + occurrence 身份链——pick 直接把 - `conversation.input.dock`——输入上方堆叠条(QueueDock 的队列只读列表落此),order 定序。 - `conversation.composer.dock`——composer 上沿统计带。 - `conversation.input.left` / `conversation.input.right`——工具行左右区。 -- `conversation.input.plan` / `conversation.input.model`(single)——工具行两具名控制位;bar 只传 `locked`(owner props),空到 owning 插件注册为止,无占位 fallback。 +- `conversation.input.plan` / `conversation.input.model`(single)——工具行两具名控制位;bar 只传 `locked`(owner props),空到 owning 插件注册为止,无占位 fallback。plan seat 未激活时保持为空,因为入口归共享 Command source 所有;有效 plan 目标会渲染 warn 状态的 `Plan ×` 状态按钮,其唯一动作是 `/plan off`。 - `conversation.hero.workspace`(root scope)——无 session / blank Hero 共用的 Workspace picker;pick 经 `connectWorkspace` 复用或创建目标 blank session,必要时搬运 draft 后切 current。 ### 测试纪律 @@ -122,6 +122,7 @@ skill/@subagent 引用不走占位符 + occurrence 身份链——pick 直接把 | 空格裁决也认领即执行型命令 | 误触发防线:空格后整行是普通 prompt;不可逆副作用只留显式入口 | | 通用 tokenPattern 装饰机制 | 结构化 occurrence 记录取代模式扫描 | | 占位 select 常驻工具行 | 具名坑位空到注册为止;占位件与真实现冲突时是双真相源 | +| 始终可见的 Plan 开/关切换 | 入口已归共享 Command source 所有;第二个入口会把状态 seat 变成冗余的 mode chrome | | 第二套加号菜单组件/controller,或在 Command 上方增加 Add/File 分组 | 这会重复异步候选、键盘高亮、焦点保留与 pick 状态;加号控件只是既有 MenuView 按 source 过滤的 launcher,且此 scope 没有文件能力 | | 引用一律走 U+FFFC chip(决策 21 前旧线) | 纯文本 + 派生装饰零身份状态;原文即模型投影,undo/剪贴板免特判;chip 链保留给需要不可分原子性的场景 | diff --git a/apps/web/tests/lifecycle-chrome.e2e.ts b/apps/web/tests/lifecycle-chrome.e2e.ts index 746cd37e36..97ffefccf7 100644 --- a/apps/web/tests/lifecycle-chrome.e2e.ts +++ b/apps/web/tests/lifecycle-chrome.e2e.ts @@ -26,6 +26,7 @@ const SNAPSHOT_DIR = fileURLToPath(new URL('./snapshots/lifecycle-chrome', impor const FIXTURE = join(SNAPSHOT_DIR, 'session.jsonl') const HERO_EXPECTED = join(SNAPSHOT_DIR, 'hero.expected.md') const COMMAND_MENU_EXPECTED = join(SNAPSHOT_DIR, 'command-menu.expected.md') +const PLAN_ACTIVE_EXPECTED = join(SNAPSHOT_DIR, 'plan-active.expected.md') // Post-reload golden: the same settled conversation rebuilt purely from // persistence + history — byte-equal rendering is exactly the recovery claim. const RELOADED_EXPECTED = join(SNAPSHOT_DIR, 'reloaded.expected.md') @@ -85,6 +86,60 @@ describe('web e2e: lifecycle & chrome (workspace flow / reload / dark mode)', () await expect.poll(() => menu.count()).toBe(0) }) + it.skipIf(MODE === 'record')('shows active Plan as the warn-state status action', async () => { + const activeScaffold = await launchWebScaffold() + const activePage = await newEnglishPage(browser) + const activeTripwire = watchConsole(activePage) + try { + await activePage.goto(activeScaffold.baseUrl, { waitUntil: 'load' }) + await activePage.waitForSelector('[class*="frame"]', { timeout: 30_000 }) + await connectFreshWorkspace(activePage) + const input = activePage.locator('textarea').first() + await activePage.getByRole('button', { name: 'Commands' }).click() + const menu = activePage.getByRole('listbox', { name: 'Trigger suggestions' }) + await menu.waitFor({ timeout: 10_000 }) + await menu.getByRole('option', { name: 'plan Enter or leave plan mode' }).click() + await expect.poll(() => input.inputValue()).toBe('/plan ') + await input.press('Enter') + const planButton = activePage.getByRole('button', { name: 'Plan mode on, press to turn off' }) + await planButton.waitFor({ timeout: 10_000 }) + const planSnapshot = await captureStableAria(activePage, '[class*="frame"]', activeScaffold.workspaceCwd) + await compareOrRefreshGolden(PLAN_ACTIVE_EXPECTED, planSnapshot, MODE) + const planStyle = await planButton.evaluate((element) => { + const probe = document.createElement('span') + probe.style.color = 'var(--dsw-alias-state-warn-label)' + probe.style.backgroundColor = 'var(--dsw-alias-state-warn-tertiary)' + document.body.append(probe) + const actual = getComputedStyle(element) + const reference = getComputedStyle(probe) + const result = { + color: actual.color, + backgroundColor: actual.backgroundColor, + borderRadius: actual.borderRadius, + fontSize: actual.fontSize, + referenceColor: reference.color, + referenceBackgroundColor: reference.backgroundColor, + } + probe.remove() + return result + }) + expect(planStyle.color).toBe(planStyle.referenceColor) + expect(planStyle.backgroundColor).toBe(planStyle.referenceBackgroundColor) + expect(planStyle.borderRadius).toBe('999px') + expect(planStyle.fontSize).toBe('13px') + await planButton.click() + await expect.poll(() => planButton.count()).toBe(0) + expect(activeTripwire.pageErrors).toEqual([]) + expect(activeTripwire.warnings).toEqual([]) + } catch (error) { + await saveFailureShot(activePage, 'web-e2e-plan-active').catch(() => undefined) + throw error + } finally { + await activePage.close() + await activeScaffold.close() + } + }) + it('sends the first prompt from the empty-state hero (all modes)', async () => { onTestFailed(() => saveFailureShot(page, 'web-e2e-lifecycle-send')) if (MODE !== 'record') { @@ -182,7 +237,7 @@ describe('web e2e: lifecycle & chrome (workspace flow / reload / dark mode)', () it.skipIf(MODE === 'record')('keeps the fixture inventory closed', async () => { expect(tripwire.warnings).toEqual([]) await assertFixtureInventory(SNAPSHOT_DIR, [ - 'session.jsonl', 'command-menu.expected.md', 'hero.expected.md', 'reloaded.expected.md', + 'session.jsonl', 'command-menu.expected.md', 'hero.expected.md', 'plan-active.expected.md', 'reloaded.expected.md', ]) }) }) diff --git a/apps/web/tests/snapshots/code-mode-round/ui.expected.md b/apps/web/tests/snapshots/code-mode-round/ui.expected.md index 31476daefd..7b957e5899 100644 --- a/apps/web/tests/snapshots/code-mode-round/ui.expected.md +++ b/apps/web/tests/snapshots/code-mode-round/ui.expected.md @@ -36,7 +36,6 @@ - button "Commands": - img - 'button "Access mode, current: Danger Full Access"': Danger Full Access -- button "Plan mode off, press to turn on": Plan off - button "Select model, current DeepSeek-V4-Flash": - text: DeepSeek-V4-Flash - img diff --git a/apps/web/tests/snapshots/cordis-tool-round/ui.expected.md b/apps/web/tests/snapshots/cordis-tool-round/ui.expected.md index 4425921fdf..5abf911c83 100644 --- a/apps/web/tests/snapshots/cordis-tool-round/ui.expected.md +++ b/apps/web/tests/snapshots/cordis-tool-round/ui.expected.md @@ -50,7 +50,6 @@ - button "Commands": - img - 'button "Access mode, current: Danger Full Access"': Danger Full Access -- button "Plan mode off, press to turn on": Plan off - button "Select model, current DeepSeek-V4-Flash": - text: DeepSeek-V4-Flash - img diff --git a/apps/web/tests/snapshots/fresh-round-trip/ui.expected.md b/apps/web/tests/snapshots/fresh-round-trip/ui.expected.md index 64c62f85d6..ec99a493f3 100644 --- a/apps/web/tests/snapshots/fresh-round-trip/ui.expected.md +++ b/apps/web/tests/snapshots/fresh-round-trip/ui.expected.md @@ -33,7 +33,6 @@ - button "Commands": - img - 'button "Access mode, current: Danger Full Access"': Danger Full Access -- button "Plan mode off, press to turn on": Plan off - button "Select model, current DeepSeek-V4-Flash": - text: DeepSeek-V4-Flash - img diff --git a/apps/web/tests/snapshots/lifecycle-chrome/hero.expected.md b/apps/web/tests/snapshots/lifecycle-chrome/hero.expected.md index 783964ed31..bed9df014c 100644 --- a/apps/web/tests/snapshots/lifecycle-chrome/hero.expected.md +++ b/apps/web/tests/snapshots/lifecycle-chrome/hero.expected.md @@ -29,7 +29,6 @@ - button "Commands": - img - 'button "Access mode, current: Danger Full Access"': Danger Full Access -- button "Plan mode off, press to turn on": Plan off - button "Select model, current DeepSeek-V4-Flash": - text: DeepSeek-V4-Flash - img diff --git a/apps/web/tests/snapshots/lifecycle-chrome/plan-active.expected.md b/apps/web/tests/snapshots/lifecycle-chrome/plan-active.expected.md new file mode 100644 index 0000000000..8bb1351e0f --- /dev/null +++ b/apps/web/tests/snapshots/lifecycle-chrome/plan-active.expected.md @@ -0,0 +1,39 @@ +- button "New session" +- button "Collapse sidebar": + - img +- button "New session": + - img + - text: New Session +- text: Workspaces +- button "Group by": + - img +- button "Create workspace": + - img +- button "Search sessions": + - img +- textbox "Search name, keywords..." +- tree "Sessions": + - treeitem "workspace 1 session" [expanded]: + - img + - text: workspace 1 session + - treeitem "New Session now" [selected] +- button "Settings": + - img + - text: Settings +- text: Let's start building +- button "Choose workspace": + - img + - text: workspace + - img +- textbox "Describe what you want to build" +- button "Commands": + - img +- 'button "Access mode, current: Danger Full Access"': Danger Full Access +- button "Plan mode on, press to turn off": Plan +- button "Select model, current deepseek-v4-flash": + - text: deepseek-v4-flash + - img +- button "Send message" [disabled] +- text: 详情 +- button "关闭详情" +- text: 点击消息流中的工具行查看详情 diff --git a/apps/web/tests/snapshots/lifecycle-chrome/reloaded.expected.md b/apps/web/tests/snapshots/lifecycle-chrome/reloaded.expected.md index 81f1ab608b..b323b67a30 100644 --- a/apps/web/tests/snapshots/lifecycle-chrome/reloaded.expected.md +++ b/apps/web/tests/snapshots/lifecycle-chrome/reloaded.expected.md @@ -25,7 +25,6 @@ - button "Commands": - img - 'button "Access mode, current: Danger Full Access"': Danger Full Access -- button "Plan mode off, press to turn on": Plan off - button "Select model, current DeepSeek-V4-Flash": - text: DeepSeek-V4-Flash - img diff --git a/apps/web/tests/snapshots/live-interactions/cancel.expected.md b/apps/web/tests/snapshots/live-interactions/cancel.expected.md index f65b090a16..2b14062211 100644 --- a/apps/web/tests/snapshots/live-interactions/cancel.expected.md +++ b/apps/web/tests/snapshots/live-interactions/cancel.expected.md @@ -22,7 +22,6 @@ - button "Commands": - img - 'button "Access mode, current: Danger Full Access"': Danger Full Access -- button "Plan mode off, press to turn on": Plan off - button "Select model, current DeepSeek-V4-Flash": - text: DeepSeek-V4-Flash - img diff --git a/apps/web/tests/snapshots/live-interactions/error-auth.expected.md b/apps/web/tests/snapshots/live-interactions/error-auth.expected.md index 0d013f819d..364cf54ddb 100644 --- a/apps/web/tests/snapshots/live-interactions/error-auth.expected.md +++ b/apps/web/tests/snapshots/live-interactions/error-auth.expected.md @@ -15,7 +15,6 @@ - button "Commands": - img - 'button "Access mode, current: Danger Full Access"': Danger Full Access -- button "Plan mode off, press to turn on": Plan off - button "Select model, current DeepSeek-V4-Flash": - text: DeepSeek-V4-Flash - img diff --git a/apps/web/tests/snapshots/live-interactions/retry.expected.md b/apps/web/tests/snapshots/live-interactions/retry.expected.md index 11bb665e71..c008fc4dba 100644 --- a/apps/web/tests/snapshots/live-interactions/retry.expected.md +++ b/apps/web/tests/snapshots/live-interactions/retry.expected.md @@ -25,7 +25,6 @@ - button "Commands": - img - 'button "Access mode, current: Danger Full Access"': Danger Full Access -- button "Plan mode off, press to turn on": Plan off - button "Select model, current DeepSeek-V4-Flash": - text: DeepSeek-V4-Flash - img diff --git a/apps/web/tests/snapshots/message-actions/ui.expected.md b/apps/web/tests/snapshots/message-actions/ui.expected.md index b15a665c45..369f03c6f1 100644 --- a/apps/web/tests/snapshots/message-actions/ui.expected.md +++ b/apps/web/tests/snapshots/message-actions/ui.expected.md @@ -36,7 +36,6 @@ - button "Commands": - img - 'button "Access mode, current: Danger Full Access"': Danger Full Access -- button "Plan mode off, press to turn on": Plan off - button "Select model, current deepseek-v4-flash": - text: deepseek-v4-flash - img diff --git a/apps/web/tests/snapshots/question-composer/answered.expected.md b/apps/web/tests/snapshots/question-composer/answered.expected.md index db0c2cfd3a..ec9a074e72 100644 --- a/apps/web/tests/snapshots/question-composer/answered.expected.md +++ b/apps/web/tests/snapshots/question-composer/answered.expected.md @@ -33,7 +33,6 @@ - button "Commands": - img - 'button "Access mode, current: Danger Full Access"': Danger Full Access -- button "Plan mode off, press to turn on": Plan off - button "Select model, current DeepSeek-V4-Flash": - text: DeepSeek-V4-Flash - img diff --git a/apps/web/tests/snapshots/queue-actions/editing.expected.md b/apps/web/tests/snapshots/queue-actions/editing.expected.md index 7e67544f04..0f890e271f 100644 --- a/apps/web/tests/snapshots/queue-actions/editing.expected.md +++ b/apps/web/tests/snapshots/queue-actions/editing.expected.md @@ -29,7 +29,6 @@ - button "Commands": - img - 'button "Access mode, current: Danger Full Access"': Danger Full Access -- button "Plan mode off, press to turn on": Plan off - button "Select model, current DeepSeek-V4-Flash": - text: DeepSeek-V4-Flash - img diff --git a/apps/web/tests/snapshots/queue-actions/ui.expected.md b/apps/web/tests/snapshots/queue-actions/ui.expected.md index 48c288909c..81144381cf 100644 --- a/apps/web/tests/snapshots/queue-actions/ui.expected.md +++ b/apps/web/tests/snapshots/queue-actions/ui.expected.md @@ -23,7 +23,6 @@ - button "Commands": - img - 'button "Access mode, current: Danger Full Access"': Danger Full Access -- button "Plan mode off, press to turn on": Plan off - button "Select model, current DeepSeek-V4-Flash": - text: DeepSeek-V4-Flash - img diff --git a/apps/web/tests/snapshots/seeded-history/ui.expected.md b/apps/web/tests/snapshots/seeded-history/ui.expected.md index c520dafae9..8b6a393664 100644 --- a/apps/web/tests/snapshots/seeded-history/ui.expected.md +++ b/apps/web/tests/snapshots/seeded-history/ui.expected.md @@ -39,7 +39,6 @@ - button "Commands": - img - 'button "Access mode, current: Danger Full Access"': Danger Full Access -- button "Plan mode off, press to turn on": Plan off - button "Select model, current deepseek-v4-flash": - text: deepseek-v4-flash - img diff --git a/apps/web/tests/snapshots/steering/settled.expected.md b/apps/web/tests/snapshots/steering/settled.expected.md index 1172d3ca5d..193f19ef05 100644 --- a/apps/web/tests/snapshots/steering/settled.expected.md +++ b/apps/web/tests/snapshots/steering/settled.expected.md @@ -33,7 +33,6 @@ - button "Commands": - img - 'button "Access mode, current: Danger Full Access"': Danger Full Access -- button "Plan mode off, press to turn on": Plan off - button "Select model, current DeepSeek-V4-Flash": - text: DeepSeek-V4-Flash - img diff --git a/packages/client/ui-plan/README.i18n.yaml b/packages/client/ui-plan/README.i18n.yaml index 199210a863..c1abb744cc 100644 --- a/packages/client/ui-plan/README.i18n.yaml +++ b/packages/client/ui-plan/README.i18n.yaml @@ -2,5 +2,5 @@ # side as of the last confirmed-consistent state. Both languages carry equal authority; # after editing either side, bring the other along and re-record with: # pnpm run verify-translation-pairing --write packages/client/ui-plan/README.md -README.md: 1d22c057b439ff337bf9daadcdba96dd4cca4540 -README.zh.md: 183b8ef7776b60c1f0afa630e04627a474d40391 +README.md: 2f83dd738e11ada5b24a55d1eec97e154ffd2aea +README.zh.md: a026390191179f6492a55ee931a3406d8e1953e8 diff --git a/packages/client/ui-plan/README.md b/packages/client/ui-plan/README.md index 1d22c057b4..2f83dd738e 100644 --- a/packages/client/ui-plan/README.md +++ b/packages/client/ui-plan/README.md @@ -4,7 +4,7 @@ English | [中文](README.zh.md) Plan-mode status chip, a pure browser surface plugin. The browser half occupies the conversation-declared `conversation.input.plan` single seat (to the right of the access-mode control); the node half is an empty apply (the roster row). Plan behavior itself — the `/plan` command, the boundary-or-idle-committed `plan/mode` state, the `plan` projection unit, and the policy section — is owned by [`@deepseek-ai/dsh-plan-mode`](../../plan/plan-mode/README.md), composed independently on the host roster. -Plan mode is entered through the `/plan` command only; there is no UI control that turns it on. While the host-computed `plan` projection's effective target is plan mode (`pending ? !active : active` — a folded host value, not client optimism, so an arriving frame corrects the chip either way), the seat renders a read-only "Plan" chip whose hover × executes `/plan off` through `command.execute`; otherwise the seat stays empty — a host without plan-mode (or a Draft with no session) shows nothing. While plan mode is the effective target, the composer textarea's placeholder switches to the plan-task hint — "describe your task to generate plan", localized through ui-conversation's `command.hint` locale namespace and shared verbatim with the claimed `/plan` command hint (rendered by the composer from the same projection; owner-supplied placeholders win). +Plan mode is entered through the `/plan` command path: users can choose Plan from the composer's `+` Command menu or type `/plan`, while this package renders no inactive plan control. While the host-computed `plan` projection's effective target is plan mode (`pending ? !active : active` — a folded host value, not client optimism, so an arriving frame corrects the chip either way), the seat renders the warn-colored "Plan ×" status button, which executes `/plan off` through `command.execute`; otherwise the seat stays empty — a host without plan-mode (or a Draft with no session) shows nothing. While plan mode is the effective target, the composer textarea's placeholder switches to the plan-task hint — "describe your task to generate plan", localized through ui-conversation's `command.hint` locale namespace and shared verbatim with the claimed `/plan` command hint (rendered by the composer from the same projection; owner-supplied placeholders win). The chip carries the accessible description "Plan mode on, press to turn off". Admission failures (`matched: false`, business errors, transport faults) surface as an inline error and the chip stays until the projection confirms the exit. @@ -22,4 +22,4 @@ Entering or leaving plan mode changes the active `plan:policy` system-prompt sec - **Plan mode is guidance, not an execution sandbox** — deployments that require enforced read-only planning must compose the independent sandbox and approval policies. - **The chip belongs to the default composer** — a pending whole-composer interaction such as plan review temporarily replaces the InputBar and its chip. -- **No UI entry point** — plan mode is entered by typing `/plan`; a session with the capability but inactive mode shows no affordance in the tool row. +- **No inactive plan control** — entry uses the shared Command source; a session with the capability but inactive mode shows no plan affordance in the tool row. diff --git a/packages/client/ui-plan/README.zh.md b/packages/client/ui-plan/README.zh.md index 183b8ef777..a026390191 100644 --- a/packages/client/ui-plan/README.zh.md +++ b/packages/client/ui-plan/README.zh.md @@ -4,7 +4,7 @@ Plan mode 状态徽章,纯浏览器 surface 插件。浏览器侧占据会话声明的 `conversation.input.plan` 单座(位于 access 模式控件右侧);node 侧是空 apply(roster 行)。plan 行为本身——`/plan` 命令、边界或空闲即时提交的 `plan/mode` 状态、`plan` 投影单元与 policy 段——归 [`@deepseek-ai/dsh-plan-mode`](../../plan/plan-mode/README.md) 所有,由 host roster 独立组合。 -plan mode 只经 `/plan` 命令进入;UI 上没有打开它的控件。当 host 计算的 `plan` 投影有效目标为 plan mode 时(`pending ? !active : active`——折叠的 host 值而非客户端乐观态,帧到达即自动纠正),座位渲染一个只读 "Plan" chip,hover 出现的 × 经 `command.execute` 执行 `/plan off`;否则座位保持为空——未组合 plan-mode 的 host(或尚无会话的 Draft)不显示任何内容。plan mode 为有效目标期间,composer 文本框的 placeholder 切换为 plan 任务提示——"describe your task to generate plan"(中文「描述你的任务以生成计划」),经 ui-conversation 的 `command.hint` locale 命名空间本地化,并与已认领 `/plan` 命令的提示逐字共用同一份文案(由 composer 从同一投影渲染;owner 提供的 placeholder 优先)。 +plan mode 经 `/plan` 命令路径进入:用户可以从 composer 的 `+` Command 菜单选择 Plan,也可以输入 `/plan`,而本包(package)不渲染未激活态 plan 控件。当 host 计算的 `plan` 投影有效目标为 plan mode 时(`pending ? !active : active`——折叠的 host 值而非客户端乐观态,帧到达即自动纠正),座位渲染 warn 色的 "Plan ×" 状态按钮,该按钮经 `command.execute` 执行 `/plan off`;否则座位保持为空——未组合 plan-mode 的 host(或尚无会话的 Draft)不显示任何内容。plan mode 为有效目标期间,composer 文本框的 placeholder 切换为 plan 任务提示——"describe your task to generate plan"(中文「描述你的任务以生成计划」),经 ui-conversation 的 `command.hint` locale 命名空间本地化,并与已认领 `/plan` 命令的提示逐字共用同一份文案(由 composer 从同一投影渲染;owner 提供的 placeholder 优先)。 chip 携带无障碍描述 "Plan mode on, press to turn off"。准入失败(`matched: false`、业务错误、传输故障)以内联错误呈现,chip 保持显示直至投影确认退出。 @@ -22,4 +22,4 @@ chip 携带无障碍描述 "Plan mode on, press to turn off"。准入失败(`m - **Plan mode 是引导而非执行沙箱**——需要强制只读规划的部署必须组合独立的沙箱与审批策略。 - **chip 属于默认编辑器**——待处理的整编辑器交互(如 plan 评审)会临时取代 InputBar 及其 chip。 -- **无 UI 进入点**——plan mode 靠敲 `/plan` 进入;有能力但未激活的会话在工具行不显示任何入口。 +- **无未激活态 plan 控件**——入口使用共享 Command source;有能力但 mode 未激活的会话在工具行不显示 plan 入口。 diff --git a/packages/client/ui-plan/package.json b/packages/client/ui-plan/package.json index a2aec47985..d7524cbc7d 100644 --- a/packages/client/ui-plan/package.json +++ b/packages/client/ui-plan/package.json @@ -38,6 +38,7 @@ "@deepseek-ai/dsh-client-connection": "^0.0.1", "@deepseek-ai/dsh-client-runtime": "^0.0.1", "@deepseek-ai/dsh-client-ui-conversation": "^0.0.1", + "@deepseek-ai/dsh-client-ui-primitives": "^0.0.1", "@deepseek-ai/dsh-client-ui-slots": "^0.0.1", "@deepseek-ai/dsh-invariants": "^0.0.1", "@deepseek-ai/dsh-plan-mode": "^0.0.1", @@ -48,6 +49,7 @@ "@deepseek-ai/dsh-client-connection": "workspace:^", "@deepseek-ai/dsh-client-runtime": "workspace:^", "@deepseek-ai/dsh-client-ui-conversation": "workspace:^", + "@deepseek-ai/dsh-client-ui-primitives": "workspace:^", "@deepseek-ai/dsh-client-ui-slots": "workspace:^", "@deepseek-ai/dsh-client-web-react": "workspace:^", "@deepseek-ai/dsh-invariants": "workspace:^", diff --git a/packages/client/ui-plan/src/client/PlanModeControl.module.css b/packages/client/ui-plan/src/client/PlanModeControl.module.css index f79e9073db..46e893aee8 100644 --- a/packages/client/ui-plan/src/client/PlanModeControl.module.css +++ b/packages/client/ui-plan/src/client/PlanModeControl.module.css @@ -1,5 +1,4 @@ -/* Plan-mode toggle chip: quiet while off; the pressed state takes the - business accent pair (same token pairing as the trajectory user badge). */ +/* Active plan status follows Figma's warn-state pill. */ .wrap { display: inline-flex; @@ -10,30 +9,25 @@ .chip { display: inline-flex; align-items: center; - padding: 4px 8px; + gap: 4px; + min-width: 34px; + padding: 2px 8px; border: none; - border-radius: 8px; - background: transparent; - color: var(--dsw-alias-label-secondary); - font-size: 14px; + border-radius: 999px; + background: var(--dsw-alias-state-warn-tertiary); + color: var(--dsw-alias-state-warn-label); + font-size: 13px; + font-weight: 500; line-height: 20px; cursor: pointer; } .chip:hover:not(:disabled) { - background: var(--dsw-alias-interactive-bg-hover); -} - -/* Hovering keeps the pressed accent: the higher-specificity hover rule above - would otherwise swap it back to the neutral hover wash. */ -.chip[aria-pressed='true'], -.chip[aria-pressed='true']:hover:not(:disabled) { - color: var(--dsw-alias-state-business-primary); - background: var(--dsw-alias-state-business-tertiary); + color: var(--dsw-alias-state-warn-primary); } .chip:focus-visible { - outline: 2px solid var(--dsw-alias-label-secondary); + outline: 2px solid var(--dsw-alias-state-warn-label); outline-offset: 2px; } @@ -42,6 +36,12 @@ cursor: default; } +.close { + display: inline-flex; + align-items: center; + color: currentColor; +} + .error { color: var(--dsw-alias-state-error-primary); font-size: 12px; diff --git a/packages/client/ui-plan/src/client/PlanModeControl.tsx b/packages/client/ui-plan/src/client/PlanModeControl.tsx index 961d7435ef..a6fc74f77b 100644 --- a/packages/client/ui-plan/src/client/PlanModeControl.tsx +++ b/packages/client/ui-plan/src/client/PlanModeControl.tsx @@ -1,5 +1,6 @@ import { useEffect, useRef, useState } from 'react' import type { InjectFace, PropsRuntime } from '@deepseek-ai/dsh-client-ui-slots' +import { IconCloseFill14 } from '@deepseek-ai/dsh-client-ui-primitives' // Type-only: pulls the ui-conversation SlotMap merge (the input.plan seat and // its {locked} owner share). import type {} from '@deepseek-ai/dsh-client-ui-conversation/client' @@ -11,16 +12,14 @@ export type PlanChipProps = PropsRuntime<'conversation.input.plan'> & InjectFace /** - * Plan-mode toggle over the host-computed `plan` projection. The chip renders - * whenever the capability is present and reflects the effective target as its - * pressed state (`pending ? !active : active` — a folded host value, not - * client optimism, so an arriving frame corrects it). Clicking executes - * /plan or /plan off toward the opposite target. + * Plan-mode status over the host-computed `plan` projection. The chip renders + * only while the effective target is plan mode (`pending ? !active : active` + * — a folded host value, not client optimism) and executes /plan off. */ -export function PlanChip({ useProjection, locked, setPlanMode }: PlanChipProps) { +export function PlanChip({ useProjection, locked, exitPlanMode }: PlanChipProps) { const plan = useProjection('plan') - const [busy, setBusy] = useState(false) - const [error, setError] = useState<{ text: string; detail: string } | null>(null) + const [leaving, setLeaving] = useState(false) + const [error, setError] = useState(null) const aliveRef = useRef(true) useEffect(() => { @@ -30,25 +29,21 @@ export function PlanChip({ useProjection, locked, setPlanMode }: PlanChipProps) } }, []) - // Absent capability (no plan-mode host plugin / no session yet): no seat - // content — without the capability there is nothing to toggle. if (plan === undefined) return null const target = plan.pending ? !plan.active : plan.active + if (!target) return null - const toggle = (): void => { - // No busy/locked guard: both disable the button, so no click arrives. - const on = !target - const failText = on ? '进入 plan mode 失败' : '退出 plan mode 失败' - setBusy(true) + const off = (): void => { + setLeaving(true) setError(null) - void setPlanMode(on).then((failure) => { + void exitPlanMode().then((failure) => { if (!aliveRef.current) return - setBusy(false) - setError(failure === null ? null : { text: failText, detail: failure }) + setLeaving(false) + setError(failure) }, (reason: unknown) => { if (!aliveRef.current) return - setBusy(false) - setError({ text: failText, detail: reason instanceof Error ? reason.message : String(reason) }) + setLeaving(false) + setError(reason instanceof Error ? reason.message : String(reason)) }) } @@ -57,17 +52,17 @@ export function PlanChip({ useProjection, locked, setPlanMode }: PlanChipProps) - {error !== null && {error.text}} + {error !== null && 退出 plan mode 失败} ) } diff --git a/packages/client/ui-plan/src/client/index.ts b/packages/client/ui-plan/src/client/index.ts index 77779efb02..d85e508922 100644 --- a/packages/client/ui-plan/src/client/index.ts +++ b/packages/client/ui-plan/src/client/index.ts @@ -1,11 +1,11 @@ /** * Plan control plugin, browser half: occupies the composer's named - * `conversation.input.plan` seat with a plan-mode toggle chip. While the - * `plan` projection is present the chip renders in both states and executes - * /plan or /plan off through `command.execute` toward the opposite target; - * an absent projection (no capability) leaves the seat empty. Reads ride the - * generic projection pair through the standard-kit `useProjection` (an absent - * key is capability absence); zero client-side plan state. + * `conversation.input.plan` seat with an active-state status chip. Plan mode + * is entered through the command source; while the projection's effective + * target is plan mode the chip renders and executes /plan off through + * `command.execute`, otherwise the seat stays empty. Reads ride the generic + * projection pair through the standard-kit `useProjection`; zero client-side + * plan state. */ import type { ConnectionHandle } from '@deepseek-ai/dsh-client-connection/client' import type { ClientContext, SessionId } from '@deepseek-ai/dsh-client-runtime/client' @@ -18,11 +18,10 @@ import { PlanChip } from './PlanModeControl.tsx' /** Injected business face of the composer plan seat. */ export interface PlanChipInjected { /** - * Switch plan mode by executing /plan (on) or /plan off. - * @param on - desired target: true enters plan mode, false leaves it. + * Leave plan mode by executing /plan off. * @returns null on admitted execution; a user-visible failure line otherwise. */ - setPlanMode: (on: boolean) => Promise + exitPlanMode: () => Promise } /** @@ -39,12 +38,11 @@ export function apply(ctx: ClientContext): void { ctx.effect(() => ctx.slots.register({ name: 'conversation.input.plan', inject: (sessionId: SessionId): PlanChipInjected => ({ - setPlanMode: async (on) => { - const line = on ? '/plan' : '/plan off' + exitPlanMode: async () => { const connection = ctx.get('connection') as ConnectionHandle - const { result } = await connection.api.commands.execute({ sessionId, line }) + const { result } = await connection.api.commands.execute({ sessionId, line: '/plan off' }) if (!result.ok) return `${result.error.message}(${result.error.code})` - if (!result.value.matched) return `未知命令:${line}` + if (!result.value.matched) return '未知命令:/plan off' return null }, }), diff --git a/packages/client/ui-plan/tests/browser-plugin.spec.ts b/packages/client/ui-plan/tests/browser-plugin.spec.ts index 1051d52777..aa0bf35b55 100644 --- a/packages/client/ui-plan/tests/browser-plugin.spec.ts +++ b/packages/client/ui-plan/tests/browser-plugin.spec.ts @@ -1,9 +1,9 @@ /** * ui-plan browser half on a real SlotsService: the plugin occupies the - * conversation-declared `conversation.input.plan` single seat with the plan - * toggle chip; the injected face executes /plan or /plan off by direction and - * folds admission outcomes into null (admitted) or a user-visible failure - * line; teardown empties the seat (HMR safety). + * conversation-declared `conversation.input.plan` single seat with the active + * plan status chip; the injected face executes /plan off and folds admission + * outcomes into null (admitted) or a user-visible failure line; teardown + * empties the seat (HMR safety). */ import { Context } from 'cordis' import { describe, expect, it, vi } from 'vitest' @@ -49,7 +49,7 @@ describe('ui-plan browser apply', () => { .rejects.toThrow(/slot "conversation.input.plan" is not declared/) }) - it('registers the chip, executes /plan by direction, and unregisters on teardown', async () => { + it('registers the chip, executes /plan off, and unregisters on teardown', async () => { const b = await bench() const fiber = b.ctx.plugin({ inject: [...inject], apply }) await fiber.await() @@ -57,22 +57,20 @@ describe('ui-plan browser apply', () => { expect(entry.component).toBe(PlanChip) const injected = (entry.inject as unknown as (id: SessionId) => PlanChipInjected)(SID) - await expect(injected.setPlanMode(false)).resolves.toBeNull() + await expect(injected.exitPlanMode()).resolves.toBeNull() expect(b.execute).toHaveBeenLastCalledWith({ sessionId: SID, line: '/plan off' }) - await expect(injected.setPlanMode(true)).resolves.toBeNull() - expect(b.execute).toHaveBeenLastCalledWith({ sessionId: SID, line: '/plan' }) // Business failure folds to the composer-visible line. b.execute.mockResolvedValueOnce({ result: { ok: false as const, error: { code: 'session-not-found', message: 'gone', details: {} } }, } as never) - await expect(injected.setPlanMode(false)).resolves.toBe('gone(session-not-found)') + await expect(injected.exitPlanMode()).resolves.toBe('gone(session-not-found)') // Unmatched admission (plan-mode not composed host-side) is also a failure line. b.execute.mockResolvedValueOnce({ result: { ok: true as const, value: { matched: false as const } }, } as never) - await expect(injected.setPlanMode(true)).resolves.toBe('未知命令:/plan') + await expect(injected.exitPlanMode()).resolves.toBe('未知命令:/plan off') await fiber.dispose() expect(b.slots.entries('conversation.input.plan')).toHaveLength(0) diff --git a/packages/client/ui-plan/tests/plan-mode-control.spec.tsx b/packages/client/ui-plan/tests/plan-mode-control.spec.tsx index 63f6bd7a6e..2489b53be0 100644 --- a/packages/client/ui-plan/tests/plan-mode-control.spec.tsx +++ b/packages/client/ui-plan/tests/plan-mode-control.spec.tsx @@ -1,11 +1,9 @@ // @vitest-environment jsdom /** * PlanChip over the `plan` projection: nothing renders while the capability - * is absent; with the capability present the chip renders in both states with - * aria-pressed following the effective target (pending folds — /plan shows - * pressed immediately, /plan off unpressed immediately); clicking executes - * the command toward the opposite target and surfaces direction-specific - * failures while the projection still owns the displayed state. + * is absent or the effective target is the default mode; while plan mode is + * the target, the chip executes /plan off and remains visible through failures + * until the projection confirms the exit. */ import { afterEach, describe, expect, it, vi } from 'vitest' import { cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react' @@ -18,98 +16,74 @@ afterEach(cleanup) function setup( plan: PlanProjection | undefined, - setPlanMode = vi.fn((_on: boolean) => Promise.resolve(null)), + exitPlanMode = vi.fn(() => Promise.resolve(null)), locked = false, ) { const store = createSnapshotStore<{ value: PlanProjection | undefined }>({ value: plan }) const useProjection = (_key: string, selector?: (v: unknown) => unknown) => bindSnapshotSelector(store)(s => (selector ?? (v => v))(s.value)) - const props = { useProjection, locked, setPlanMode } as unknown as PlanChipProps + const props = { useProjection, locked, exitPlanMode } as unknown as PlanChipProps const view = render() - return { store, setPlanMode, view } + return { store, exitPlanMode, view } } -const onChip = () => screen.getByRole('button', { name: 'Plan mode on, press to turn off' }) -const offChip = () => screen.getByRole('button', { name: 'Plan mode off, press to turn on' }) +const chip = () => screen.getByRole('button', { name: 'Plan mode on, press to turn off' }) describe('PlanChip', () => { - it('renders nothing while the capability is absent', () => { + it('renders nothing for an absent capability or a default-mode target', () => { const absent = setup(undefined) expect(absent.view.container.innerHTML).toBe('') + cleanup() + const inactive = setup({ active: false, pending: false }) + expect(inactive.view.container.innerHTML).toBe('') + cleanup() + const leaving = setup({ active: true, pending: true }) + expect(leaving.view.container.innerHTML).toBe('') }) - it('reflects the effective target as the pressed state, folding pending', () => { - setup({ active: false, pending: false }) - expect(offChip().getAttribute('aria-pressed')).toBe('false') - cleanup() + it('renders the Plan status for active and pending-entry targets', () => { setup({ active: true, pending: false }) - expect(onChip().getAttribute('aria-pressed')).toBe('true') + expect(chip().textContent).toBe('Plan') cleanup() - // /plan just ran (command/run folded, plan/mode not yet): target is plan. setup({ active: false, pending: true }) - expect(onChip().getAttribute('aria-pressed')).toBe('true') - cleanup() - // Active with a pending exit: the target is default — already unpressed. - setup({ active: true, pending: true }) - expect(offChip().getAttribute('aria-pressed')).toBe('false') + expect(chip().textContent).toBe('Plan') }) - it('unpressed chip executes /plan (on) once and follows the projection up', async () => { + it('executes /plan off once and follows the projection down', async () => { let resolve!: (value: string | null) => void - const setPlanMode = vi.fn((_on: boolean) => new Promise((done) => { resolve = done })) - const { store } = setup({ active: false, pending: false }, setPlanMode) - fireEvent.click(offChip()) - expect(setPlanMode).toHaveBeenCalledTimes(1) - expect(setPlanMode).toHaveBeenLastCalledWith(true) - // Busy while its own call is in flight. - fireEvent.click(offChip()) - expect(setPlanMode).toHaveBeenCalledTimes(1) + const exitPlanMode = vi.fn(() => new Promise((done) => { resolve = done })) + const { store } = setup({ active: true, pending: false }, exitPlanMode) + fireEvent.click(chip()) + expect(exitPlanMode).toHaveBeenCalledTimes(1) + fireEvent.click(chip()) + expect(exitPlanMode).toHaveBeenCalledTimes(1) resolve(null) - // The command's run record folds: target flips, the chip presses. - store.set({ value: { active: false, pending: true } }) - await waitFor(() => { - expect(onChip().getAttribute('aria-pressed')).toBe('true') - }) - }) - - it('pressed chip executes /plan off and follows the projection down', async () => { - const setPlanMode = vi.fn((_on: boolean) => Promise.resolve(null)) - const { store } = setup({ active: true, pending: false }, setPlanMode) - fireEvent.click(onChip()) - expect(setPlanMode).toHaveBeenLastCalledWith(false) store.set({ value: { active: true, pending: true } }) await waitFor(() => { - expect(offChip().getAttribute('aria-pressed')).toBe('false') + expect(screen.queryByRole('button', { name: 'Plan mode on, press to turn off' })).toBeNull() }) }) it('disables under the locked owner prop', () => { setup({ active: true, pending: false }, vi.fn(), true) - expect((onChip() as HTMLButtonElement).disabled).toBe(true) + expect((chip() as HTMLButtonElement).disabled).toBe(true) }) - it('surfaces direction-specific admission and transport failures while staying visible', async () => { - const exitFailing = vi.fn() + it('surfaces admission and transport failures while staying visible', async () => { + const exitPlanMode = vi.fn() .mockResolvedValueOnce('host said no') .mockRejectedValueOnce(new Error('network down')) .mockRejectedValueOnce('socket closed') - setup({ active: true, pending: false }, exitFailing) - fireEvent.click(onChip()) + setup({ active: true, pending: false }, exitPlanMode) + fireEvent.click(chip()) expect((await screen.findByText('退出 plan mode 失败')).getAttribute('title')).toBe('host said no') - expect(onChip()).toBeTruthy() + expect(chip()).toBeTruthy() - fireEvent.click(onChip()) + fireEvent.click(chip()) expect(await screen.findByTitle('network down')).toBeTruthy() - fireEvent.click(onChip()) + fireEvent.click(chip()) expect(await screen.findByTitle('socket closed')).toBeTruthy() - cleanup() - - const enterFailing = vi.fn().mockResolvedValueOnce('agent busy') - setup({ active: false, pending: false }, enterFailing) - fireEvent.click(offChip()) - expect((await screen.findByText('进入 plan mode 失败')).getAttribute('title')).toBe('agent busy') - expect(offChip()).toBeTruthy() }) it('ignores in-flight fulfillment and rejection after unmount', () => { @@ -118,14 +92,14 @@ describe('PlanChip', () => { { active: true, pending: false }, vi.fn(() => new Promise((done) => { resolve = done })), ) - fireEvent.click(onChip()) + fireEvent.click(chip()) successful.view.unmount() expect(() => { resolve(null) }).not.toThrow() let reject!: (reason: unknown) => void - const setPlanMode = vi.fn(() => new Promise((_done, fail) => { reject = fail })) - const { view } = setup({ active: true, pending: false }, setPlanMode) - fireEvent.click(onChip()) + const exitPlanMode = vi.fn(() => new Promise((_done, fail) => { reject = fail })) + const { view } = setup({ active: true, pending: false }, exitPlanMode) + fireEvent.click(chip()) view.unmount() expect(() => { reject(new Error('late')) }).not.toThrow() }) diff --git a/packages/client/ui-plan/tsconfig.json b/packages/client/ui-plan/tsconfig.json index 4ab13662f2..23ce289533 100644 --- a/packages/client/ui-plan/tsconfig.json +++ b/packages/client/ui-plan/tsconfig.json @@ -20,6 +20,9 @@ { "path": "../ui-conversation" }, + { + "path": "../ui-primitives" + }, { "path": "../ui-slots" }, diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index a014fa2333..58fc06888f 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -1367,6 +1367,9 @@ importers: '@deepseek-ai/dsh-client-ui-conversation': specifier: workspace:^ version: link:../ui-conversation + '@deepseek-ai/dsh-client-ui-primitives': + specifier: workspace:^ + version: link:../ui-primitives '@deepseek-ai/dsh-client-ui-slots': specifier: workspace:^ version: link:../ui-slots From 04f8b30db151462e9f21ecee9176c30cbfb70d36 Mon Sep 17 00:00:00 2001 From: NI0317 Date: Thu, 30 Jul 2026 22:58:52 +0800 Subject: [PATCH 062/139] fix(web): make the welcome notice scan-first --- ...versioned-gui-welcome-onboarding.i18n.yaml | 4 +- ...-07-30-versioned-gui-welcome-onboarding.md | 2 +- ...-30-versioned-gui-welcome-onboarding.zh.md | 2 +- .../tests/onboarding-deepseek-config.e2e.ts | 4 +- .../welcome.expected.md | 12 ++- .../src/client/WelcomeNotice.module.css | 96 ++++++++++++++++--- .../src/client/WelcomeNotice.tsx | 32 ++++--- .../ui-settings-general/src/client/locales.ts | 20 ++-- .../src/onboarding-copy.ts | 26 ++--- .../tests/welcome-notice.spec.tsx | 14 ++- 10 files changed, 150 insertions(+), 62 deletions(-) diff --git a/.agents/notes/implemented/feature/2026-07-30-versioned-gui-welcome-onboarding.i18n.yaml b/.agents/notes/implemented/feature/2026-07-30-versioned-gui-welcome-onboarding.i18n.yaml index 24bdee3b68..db1397809e 100644 --- a/.agents/notes/implemented/feature/2026-07-30-versioned-gui-welcome-onboarding.i18n.yaml +++ b/.agents/notes/implemented/feature/2026-07-30-versioned-gui-welcome-onboarding.i18n.yaml @@ -2,5 +2,5 @@ # side as of the last confirmed-consistent state. Both languages carry equal authority; # after editing either side, bring the other along and re-record with: # pnpm run verify-translation-pairing --write .agents/notes/implemented/feature/2026-07-30-versioned-gui-welcome-onboarding.md -2026-07-30-versioned-gui-welcome-onboarding.md: 405c6fe833d995123cd15e5694cd5ef75a0cd03d -2026-07-30-versioned-gui-welcome-onboarding.zh.md: ea83aa958866ab3dcca749f362d43e4b29408e02 +2026-07-30-versioned-gui-welcome-onboarding.md: 06ac9fbe5c10db872c7ea3989ff2e14f756965a0 +2026-07-30-versioned-gui-welcome-onboarding.zh.md: e2d726368e6282e4f6043c225b665c1945228f2d diff --git a/.agents/notes/implemented/feature/2026-07-30-versioned-gui-welcome-onboarding.md b/.agents/notes/implemented/feature/2026-07-30-versioned-gui-welcome-onboarding.md index 405c6fe833..06ac9fbe5c 100644 --- a/.agents/notes/implemented/feature/2026-07-30-versioned-gui-welcome-onboarding.md +++ b/.agents/notes/implemented/feature/2026-07-30-versioned-gui-welcome-onboarding.md @@ -18,7 +18,7 @@ The GUI's credential onboarding begins with a DeepSeek-specific readiness check, **Concurrent views converge without stale replacement.** The acknowledgement write omits `expectedRevision` deliberately: every tab writes the same version to one path, so the operation is idempotent and preserves sibling fields instead of rebuilding the section. `settings/document-updated` becomes `host/settings-changed`; an already mounted tab refetches and advances when another tab or an external editor commits the current version. The API proxy exposes this one product namespace through a closed allowlist beside configurable-provider namespaces, without treating its changes as model-catalog invalidations. -**The welcome modal has one completion path.** It renders no close icon or secondary action, installs no Escape handler, and assigns no click handler to the mask. Its mask starts below the 80 px top chrome and preserves `position:absolute`, zero left/right/bottom offsets, `rgba(0, 0, 0, 0.24)`, and `backdrop-filter: blur(2px)`. Continue is the sole button and receives initial focus. +**The welcome modal is scan-first and has one completion path.** Its hierarchy is a declaration title, one status sentence, one emphasized feedback callout, one consequence sentence, and a restrained quotation; the notice version changes whenever that authored copy changes materially. It renders no close icon or secondary action, installs no Escape handler, and assigns no click handler to the mask. Its mask starts below the 80 px top chrome and preserves `position:absolute`, zero left/right/bottom offsets, `rgba(0, 0, 0, 0.24)`, and `backdrop-filter: blur(2px)`. Continue is the sole button and receives initial focus. ## Alternatives considered diff --git a/.agents/notes/implemented/feature/2026-07-30-versioned-gui-welcome-onboarding.zh.md b/.agents/notes/implemented/feature/2026-07-30-versioned-gui-welcome-onboarding.zh.md index ea83aa9588..e2d726368e 100644 --- a/.agents/notes/implemented/feature/2026-07-30-versioned-gui-welcome-onboarding.zh.md +++ b/.agents/notes/implemented/feature/2026-07-30-versioned-gui-welcome-onboarding.zh.md @@ -18,7 +18,7 @@ GUI 的凭据引导从 DeepSeek 专用的就绪状态检查开始,但内部测 **并发视图无需陈旧的整体替换即可收敛。** 确认写入有意省略 `expectedRevision`:每个标签页都向同一路径写入相同版本,因此该操作是幂等的,并会保留同级字段,而不是重建整个分节。`settings/document-updated` 会转为 `host/settings-changed`;另一个标签页或外部编辑器提交当前版本后,已挂载的标签页会重新拉取状态并推进。API 网关在可配置提供方 namespace 之外,通过封闭的允许列表暴露这一个产品 namespace,同时不会把它的变更视为模型目录失效事件。 -**欢迎模态窗口只有一条完成路径。** 界面不渲染关闭图标或次要操作,不安装 Escape 处理器,也不为遮罩添加点击处理器。遮罩从顶部 80 px 的界面框架下方开始,并保留 `position:absolute`、left/right/bottom 偏移量为零、`rgba(0, 0, 0, 0.24)` 和 `backdrop-filter: blur(2px)`。「继续」是唯一按钮,并会获得初始焦点。 +**欢迎模态窗口以便于扫读为先,且只有一条完成路径。** 其信息层级依次为声明标题、一句状态说明、一则重点突出的反馈提示、一句影响说明和一则克制的引语;只要这份文案发生实质变化,就同步提升通知版本。界面不渲染关闭图标或次要操作,不安装 Escape 处理器,也不为遮罩添加点击处理器。遮罩从顶部 80 px 的界面框架下方开始,并保留 `position:absolute`、left/right/bottom 偏移量为零、`rgba(0, 0, 0, 0.24)` 和 `backdrop-filter: blur(2px)`。「继续」是唯一按钮,并会获得初始焦点。 ## 曾考虑的替代方案 diff --git a/apps/web/tests/onboarding-deepseek-config.e2e.ts b/apps/web/tests/onboarding-deepseek-config.e2e.ts index f372910a61..8731bf10e0 100644 --- a/apps/web/tests/onboarding-deepseek-config.e2e.ts +++ b/apps/web/tests/onboarding-deepseek-config.e2e.ts @@ -48,7 +48,7 @@ describe.skipIf(MODE === 'record')('web e2e: first-run DeepSeek credential setup it('stores a key write-only and observes configured state without restarting', async () => { onTestFailed(() => saveFailureShot(page, 'web-e2e-onboarding-deepseek-config')) - const welcome = page.getByRole('dialog', { name: WELCOME_NOTICE_COPY.zh.paragraphs[0] }) + const welcome = page.getByRole('dialog', { name: WELCOME_NOTICE_COPY.zh.title }) await welcome.waitFor({ timeout: 15_000 }) const welcomeAria = await captureStableAria(page, '[role="dialog"]', scaffold.workspaceCwd) await compareOrRefreshGolden(WELCOME_EXPECTED, welcomeAria, MODE) @@ -132,7 +132,7 @@ describe.skipIf(MODE === 'record')('web e2e: first-run DeepSeek credential setup await page.reload({ waitUntil: 'load' }) acknowledgeReloadConnectionLoss(tripwire, secondReloadWarnings) await page.waitForSelector('[class*="frame"]', { timeout: 15_000 }) - expect(await page.getByRole('dialog', { name: WELCOME_NOTICE_COPY.zh.paragraphs[0] }).count()).toBe(0) + expect(await page.getByRole('dialog', { name: WELCOME_NOTICE_COPY.zh.title }).count()).toBe(0) expect(await page.getByRole('dialog', { name: '添加一个 API Key 开始使用' }).count()).toBe(0) // A different stored copy version represents an intentional version bump: diff --git a/apps/web/tests/snapshots/onboarding-deepseek-config/welcome.expected.md b/apps/web/tests/snapshots/onboarding-deepseek-config/welcome.expected.md index 370737df6b..d0fcb2b68d 100644 --- a/apps/web/tests/snapshots/onboarding-deepseek-config/welcome.expected.md +++ b/apps/web/tests/snapshots/onboarding-deepseek-config/welcome.expected.md @@ -1,6 +1,8 @@ -- dialog "感谢您愿意拨冗试用 DeepSeek Harness。": - - heading "感谢您愿意拨冗试用 DeepSeek Harness。" [level=2] - - paragraph: 目前的版本仍处于内部测试阶段,有些功能仍待完善,有些体验难免粗粝。 - - paragraph: “如切如磋,如琢如磨。” 产品的成长,离不开一次次真实的碰撞与坦诚的反馈。您在真实使用中暴露的问题,也可能促使我们重新审视,甚至推翻已有的设计。 - - paragraph: 我们尤其希望听见那些失败、困惑与不顺手的时刻——如果它未能帮到您,甚至反而为工作平添了麻烦,请在企业微信群中留言,将使用感受告诉我们。每一条反馈,都会帮助我们把它打磨得更好。 +- dialog "内测声明": + - heading "内测声明" [level=2] + - paragraph: 感谢您试用 DeepSeek Harness。目前仍处于内部测试阶段,部分功能与体验还在持续打磨。 + - strong: 我们最想听见:失败、困惑和不顺手 + - paragraph: 如果它没帮到您,甚至给工作添了麻烦,请在企业微信群告诉我们。 + - paragraph: 真实使用中的每一个问题,都可能促使我们重新审视,甚至推翻已有设计。 + - paragraph: “如切如磋,如琢如磨。” - button "继续" diff --git a/packages/client/ui-settings-general/src/client/WelcomeNotice.module.css b/packages/client/ui-settings-general/src/client/WelcomeNotice.module.css index 8ad90b5fe2..805f411918 100644 --- a/packages/client/ui-settings-general/src/client/WelcomeNotice.module.css +++ b/packages/client/ui-settings-general/src/client/WelcomeNotice.module.css @@ -24,7 +24,7 @@ .dialog { position: relative; z-index: 1; - width: min(640px, calc(100vw - 48px)); + width: min(600px, calc(100vw - 48px)); max-height: calc(100vh - 128px); padding: 32px; box-sizing: border-box; @@ -40,21 +40,65 @@ font-size: 20px; line-height: 30px; font-weight: 600; + letter-spacing: -0.01em; } -.copy { - display: flex; - flex-direction: column; - gap: 14px; - margin-top: 18px; - font-size: 14px; - line-height: 24px; +.lead, +.closing, +.quote, +.feedback p, +.error { + margin: 0; +} + +.lead { + margin-top: 12px; + font-size: 16px; + line-height: 25px; color: var(--dsw-alias-label-secondary); } -.copy p, -.error { - margin: 0; +.feedback { + margin-top: 20px; + padding: 16px 18px; + border-radius: 14px; + border: 1px solid var(--dsw-alias-border-l1); + background: var(--dsw-alias-bg-module-platform); + font-size: 15px; + line-height: 24px; +} + +.feedback strong { + display: block; + margin-bottom: 4px; + font-weight: 600; +} + +.feedback p, +.closing { + color: var(--dsw-alias-label-secondary); +} + +.closing { + margin-top: 16px; + font-size: 15px; + line-height: 24px; +} + +.quote { + font-size: 14px; + line-height: 22px; + color: var(--dsw-alias-label-secondary); +} + +.footer { + display: flex; + align-items: center; + justify-content: space-between; + gap: 24px; + margin-top: 24px; + padding-top: 20px; + border-top: 1px solid var(--dsw-alias-border-l1); } .error { @@ -65,6 +109,32 @@ } .primary { - width: 100%; - margin-top: 24px; + min-width: 104px; + transition: transform 140ms cubic-bezier(0.23, 1, 0.32, 1); +} + +.primary:active:not(:disabled) { + transform: scale(0.97); +} + +@media (prefers-reduced-motion: reduce) { + .primary { + transition: none; + } +} + +@media (max-width: 560px) { + .dialog { + padding: 24px; + } + + .footer { + align-items: stretch; + flex-direction: column; + gap: 14px; + } + + .primary { + width: 100%; + } } diff --git a/packages/client/ui-settings-general/src/client/WelcomeNotice.tsx b/packages/client/ui-settings-general/src/client/WelcomeNotice.tsx index 6255405f83..ebdab519a4 100644 --- a/packages/client/ui-settings-general/src/client/WelcomeNotice.tsx +++ b/packages/client/ui-settings-general/src/client/WelcomeNotice.tsx @@ -47,22 +47,26 @@ export function WelcomeNotice(props: WelcomeNoticeProps): ReactNode {
                      ) diff --git a/packages/client/ui-settings-general/src/client/locales.ts b/packages/client/ui-settings-general/src/client/locales.ts index 73c0daab58..f2486faea2 100644 --- a/packages/client/ui-settings-general/src/client/locales.ts +++ b/packages/client/ui-settings-general/src/client/locales.ts @@ -26,10 +26,12 @@ export const zh: LocaleDict = { 'permission.title': '权限', 'permission.desc': '选择默认权限模式', 'toolcall.title': '工具调用', - 'welcome.paragraph.0': WELCOME_NOTICE_COPY.zh.paragraphs[0], - 'welcome.paragraph.1': WELCOME_NOTICE_COPY.zh.paragraphs[1], - 'welcome.paragraph.2': WELCOME_NOTICE_COPY.zh.paragraphs[2], - 'welcome.paragraph.3': WELCOME_NOTICE_COPY.zh.paragraphs[3], + 'welcome.title': WELCOME_NOTICE_COPY.zh.title, + 'welcome.lead': WELCOME_NOTICE_COPY.zh.lead, + 'welcome.feedbackTitle': WELCOME_NOTICE_COPY.zh.feedbackTitle, + 'welcome.feedbackBody': WELCOME_NOTICE_COPY.zh.feedbackBody, + 'welcome.closing': WELCOME_NOTICE_COPY.zh.closing, + 'welcome.quote': WELCOME_NOTICE_COPY.zh.quote, 'welcome.continue': WELCOME_NOTICE_COPY.zh.continueLabel, 'welcome.error': '暂时无法保存确认状态,请重试。', } @@ -44,10 +46,12 @@ export const en: LocaleDict = { 'permission.title': 'Permission', 'permission.desc': 'Choose default permission mode', 'toolcall.title': 'Tool Call', - 'welcome.paragraph.0': WELCOME_NOTICE_COPY.en.paragraphs[0], - 'welcome.paragraph.1': WELCOME_NOTICE_COPY.en.paragraphs[1], - 'welcome.paragraph.2': WELCOME_NOTICE_COPY.en.paragraphs[2], - 'welcome.paragraph.3': WELCOME_NOTICE_COPY.en.paragraphs[3], + 'welcome.title': WELCOME_NOTICE_COPY.en.title, + 'welcome.lead': WELCOME_NOTICE_COPY.en.lead, + 'welcome.feedbackTitle': WELCOME_NOTICE_COPY.en.feedbackTitle, + 'welcome.feedbackBody': WELCOME_NOTICE_COPY.en.feedbackBody, + 'welcome.closing': WELCOME_NOTICE_COPY.en.closing, + 'welcome.quote': WELCOME_NOTICE_COPY.en.quote, 'welcome.continue': WELCOME_NOTICE_COPY.en.continueLabel, 'welcome.error': 'The acknowledgement could not be saved. Please try again.', } diff --git a/packages/client/ui-settings-general/src/onboarding-copy.ts b/packages/client/ui-settings-general/src/onboarding-copy.ts index 04a075783e..805a9d35d0 100644 --- a/packages/client/ui-settings-general/src/onboarding-copy.ts +++ b/packages/client/ui-settings-general/src/onboarding-copy.ts @@ -8,26 +8,26 @@ export const WELCOME_NOTICE_ACK_FIELD = 'welcomeNoticeVersion' * Bump only when the notice changes materially and every user should see it * again. The acknowledgement is compared for exact equality. */ -export const WELCOME_NOTICE_VERSION = '2026-07-30.1' +export const WELCOME_NOTICE_VERSION = '2026-07-30.2' /** The complete editable welcome notice in both supported GUI locales. */ export const WELCOME_NOTICE_COPY = { zh: { - paragraphs: [ - '感谢您愿意拨冗试用 DeepSeek Harness。', - '目前的版本仍处于内部测试阶段,有些功能仍待完善,有些体验难免粗粝。', - '“如切如磋,如琢如磨。” 产品的成长,离不开一次次真实的碰撞与坦诚的反馈。您在真实使用中暴露的问题,也可能促使我们重新审视,甚至推翻已有的设计。', - '我们尤其希望听见那些失败、困惑与不顺手的时刻——如果它未能帮到您,甚至反而为工作平添了麻烦,请在企业微信群中留言,将使用感受告诉我们。每一条反馈,都会帮助我们把它打磨得更好。', - ], + title: '内测声明', + lead: '感谢您试用 DeepSeek Harness。目前仍处于内部测试阶段,部分功能与体验还在持续打磨。', + feedbackTitle: '我们最想听见:失败、困惑和不顺手', + feedbackBody: '如果它没帮到您,甚至给工作添了麻烦,请在企业微信群告诉我们。', + closing: '真实使用中的每一个问题,都可能促使我们重新审视,甚至推翻已有设计。', + quote: '“如切如磋,如琢如磨。”', continueLabel: '继续', }, en: { - paragraphs: [ - 'Thank you for taking the time to try DeepSeek Harness.', - 'This version is still in internal testing. Some features remain unfinished, and parts of the experience may feel rough.', - '“As one cuts and files, as one chisels and polishes.” A product grows through real encounters and candid feedback. Problems you uncover in real use may prompt us to reconsider—or even overturn—our existing designs.', - 'We especially want to hear about failures, confusion, and friction. If it did not help you, or even made your work harder, please leave a message in the company WeChat group and tell us about your experience. Every piece of feedback helps us refine it.', - ], + title: 'Internal Testing Notice', + lead: 'Thank you for trying DeepSeek Harness. This version is still in internal testing, and some features and experiences remain under refinement.', + feedbackTitle: 'What we most want to hear: failures, confusion, and friction', + feedbackBody: 'If it did not help—or even made your work harder—please tell us in the company WeChat group.', + closing: 'Every problem found in real use may prompt us to reconsider, or even overturn, an existing design.', + quote: '“As one cuts and files, as one chisels and polishes.”', continueLabel: 'Continue', }, } as const diff --git a/packages/client/ui-settings-general/tests/welcome-notice.spec.tsx b/packages/client/ui-settings-general/tests/welcome-notice.spec.tsx index 5925cf048b..d414146e47 100644 --- a/packages/client/ui-settings-general/tests/welcome-notice.spec.tsx +++ b/packages/client/ui-settings-general/tests/welcome-notice.spec.tsx @@ -54,10 +54,18 @@ function mount(version?: string, mutateImpl: () => Promise = () => Prom describe('WelcomeNotice', () => { it('renders the owner copy with one primary action and no dismissal control', async () => { const h = mount() - const dialog = await screen.findByRole('dialog', { name: WELCOME_NOTICE_COPY.zh.paragraphs[0] }) - for (const paragraph of WELCOME_NOTICE_COPY.zh.paragraphs) { - expect(screen.getByText(paragraph)).toBeTruthy() + const dialog = await screen.findByRole('dialog', { name: WELCOME_NOTICE_COPY.zh.title }) + for (const text of [ + WELCOME_NOTICE_COPY.zh.title, + WELCOME_NOTICE_COPY.zh.lead, + WELCOME_NOTICE_COPY.zh.feedbackTitle, + WELCOME_NOTICE_COPY.zh.feedbackBody, + WELCOME_NOTICE_COPY.zh.closing, + WELCOME_NOTICE_COPY.zh.quote, + ]) { + expect(screen.getByText(text)).toBeTruthy() } + expect(dialog.textContent?.match(/感谢您试用 DeepSeek Harness/g) ?? []).toHaveLength(1) const buttons = dialog.querySelectorAll('button') expect(buttons).toHaveLength(1) expect(screen.getByRole('button', { name: WELCOME_NOTICE_COPY.zh.continueLabel })).toBeTruthy() From f9a40d555f2667b35b165a639bf2621a3524560b Mon Sep 17 00:00:00 2001 From: Chinesezjc Date: Thu, 30 Jul 2026 22:59:34 +0800 Subject: [PATCH 063/139] docs: record ui-conversation README pairing hash after master merge --- packages/client/ui-conversation/README.i18n.yaml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/packages/client/ui-conversation/README.i18n.yaml b/packages/client/ui-conversation/README.i18n.yaml index 0f0529e337..96db5f7c1a 100644 --- a/packages/client/ui-conversation/README.i18n.yaml +++ b/packages/client/ui-conversation/README.i18n.yaml @@ -2,5 +2,5 @@ # side as of the last confirmed-consistent state. Both languages carry equal authority; # after editing either side, bring the other along and re-record with: # pnpm run verify-translation-pairing --write packages/client/ui-conversation/README.md -README.md: e3625f40a1f6b0d4097cbef51818c250c88cd0e8 -README.zh.md: a1c10c085d30dd5241823492d666f3c0b58d7942 +README.md: fa4a19c6e97e423dc01bc037c7784b30c5d4c0e6 +README.zh.md: e09e1c85d7f8ac48b5d86ee9b81d3ba3f6da268e From d2521a7e6107e12090a69e5e8938ed5ee80560fe Mon Sep 17 00:00:00 2001 From: ZiyaZhang <199893125+ZiyaZhang@users.noreply.github.com> Date: Thu, 30 Jul 2026 08:09:59 -0700 Subject: [PATCH 064/139] test(web): refresh queue collapse access golden --- apps/web/tests/snapshots/queue-actions/collapsed.expected.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/apps/web/tests/snapshots/queue-actions/collapsed.expected.md b/apps/web/tests/snapshots/queue-actions/collapsed.expected.md index cdbf6fc64b..81394b8468 100644 --- a/apps/web/tests/snapshots/queue-actions/collapsed.expected.md +++ b/apps/web/tests/snapshots/queue-actions/collapsed.expected.md @@ -16,7 +16,7 @@ - textbox "Message the agent" - button "Add attachment": - img -- 'button "Access mode, current: Danger Full Access"': Danger Full Access +- 'button "Access mode, current: Full access"': Full access - button "Plan mode off, press to turn on": Plan off - button "Select model, current DeepSeek-V4-Flash": - text: DeepSeek-V4-Flash From 6991650fce41ffe0c74fb0c1b45a8e0f7492c65e Mon Sep 17 00:00:00 2001 From: Chinesezjc Date: Thu, 30 Jul 2026 23:53:11 +0800 Subject: [PATCH 065/139] fix(config): map dsh-host-directory-picker-auto to workspace source web.cordis.yml references @deepseek-ai/dsh-host-directory-picker-auto but tsconfig.base.json had no paths entry for it, so the tsx source launch fell back to built lib/ and verify-cordis-config failed. Add the mapping alongside its -browse/-native siblings. --- tsconfig.base.json | 2 ++ 1 file changed, 2 insertions(+) diff --git a/tsconfig.base.json b/tsconfig.base.json index f5f5c0a3ba..9bdaa91652 100644 --- a/tsconfig.base.json +++ b/tsconfig.base.json @@ -125,6 +125,8 @@ "@deepseek-ai/dsh-host-directory-picker-browse/*": ["./packages/host/directory-picker-browse/src/*"], "@deepseek-ai/dsh-host-directory-picker-native": ["./packages/host/directory-picker-native/src"], "@deepseek-ai/dsh-host-directory-picker-native/*": ["./packages/host/directory-picker-native/src/*"], + "@deepseek-ai/dsh-host-directory-picker-auto": ["./packages/host/directory-picker-auto/src"], + "@deepseek-ai/dsh-host-directory-picker-auto/*": ["./packages/host/directory-picker-auto/src/*"], "@deepseek-ai/dsh-host-apiproxy/client": ["./packages/host/apiproxy/src/fetch/client.ts"], "@deepseek-ai/dsh-host-apiproxy/*": ["./packages/host/apiproxy/src/*"], "@deepseek-ai/dsh-host-webserver": ["./packages/host/webserver/src"], From 2c8da83fc820ad41501c5533a4b1a6c292f2bbdc Mon Sep 17 00:00:00 2001 From: ZiyaZhang <199893125+ZiyaZhang@users.noreply.github.com> Date: Thu, 30 Jul 2026 09:27:49 -0700 Subject: [PATCH 066/139] test(web): refresh plan review access golden --- apps/web/tests/snapshots/plan-review/approved.expected.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/apps/web/tests/snapshots/plan-review/approved.expected.md b/apps/web/tests/snapshots/plan-review/approved.expected.md index aca0bc31bb..70fc4c5d0e 100644 --- a/apps/web/tests/snapshots/plan-review/approved.expected.md +++ b/apps/web/tests/snapshots/plan-review/approved.expected.md @@ -42,7 +42,7 @@ - textbox "Message the agent" - button "Add attachment": - img -- 'button "Access mode, current: Danger Full Access"': Danger Full Access +- 'button "Access mode, current: Full access"': Full access - button "Plan mode off, press to turn on": Plan off - button "Select model, current DeepSeek-V4-Flash": - text: DeepSeek-V4-Flash From 75a0366a526021f6e4e3164eaf5ebe030248952b Mon Sep 17 00:00:00 2001 From: NI0317 Date: Fri, 31 Jul 2026 00:28:17 +0800 Subject: [PATCH 067/139] feat(web): present onboarding as a continuous page --- ...versioned-gui-welcome-onboarding.i18n.yaml | 4 +- ...-07-30-versioned-gui-welcome-onboarding.md | 2 +- ...-30-versioned-gui-welcome-onboarding.zh.md | 2 +- .../tests/onboarding-deepseek-config.e2e.ts | 28 +-- .../missing.expected.md | 6 +- .../welcome.expected.md | 14 +- .../DeepSeekOnboardingDialog.module.css | 136 +++++++++++- .../src/client/DeepSeekOnboardingDialog.tsx | 53 +++-- .../tests/onboarding-dialog.spec.tsx | 22 +- .../ui-settings-general/README.i18n.yaml | 4 +- packages/client/ui-settings-general/README.md | 2 +- .../client/ui-settings-general/README.zh.md | 2 +- .../src/client/WelcomeNotice.module.css | 194 ++++++++++-------- .../src/client/WelcomeNotice.tsx | 66 +++--- .../ui-settings-general/src/client/locales.ts | 20 +- .../src/onboarding-copy.ts | 26 ++- .../tests/welcome-notice.spec.tsx | 28 +-- packages/client/ui-settings/README.i18n.yaml | 4 +- packages/client/ui-settings/README.md | 4 +- packages/client/ui-settings/README.zh.md | 4 +- packages/client/ui-settings/package.json | 9 +- .../src/client/SettingsRoot.module.css | 30 +++ .../ui-settings/src/client/SettingsRoot.tsx | 26 ++- .../ui-settings/tests/settings-root.spec.tsx | 11 + pnpm-lock.yaml | 6 + 25 files changed, 475 insertions(+), 228 deletions(-) diff --git a/.agents/notes/implemented/feature/2026-07-30-versioned-gui-welcome-onboarding.i18n.yaml b/.agents/notes/implemented/feature/2026-07-30-versioned-gui-welcome-onboarding.i18n.yaml index db1397809e..cdf0c3a817 100644 --- a/.agents/notes/implemented/feature/2026-07-30-versioned-gui-welcome-onboarding.i18n.yaml +++ b/.agents/notes/implemented/feature/2026-07-30-versioned-gui-welcome-onboarding.i18n.yaml @@ -2,5 +2,5 @@ # side as of the last confirmed-consistent state. Both languages carry equal authority; # after editing either side, bring the other along and re-record with: # pnpm run verify-translation-pairing --write .agents/notes/implemented/feature/2026-07-30-versioned-gui-welcome-onboarding.md -2026-07-30-versioned-gui-welcome-onboarding.md: 06ac9fbe5c10db872c7ea3989ff2e14f756965a0 -2026-07-30-versioned-gui-welcome-onboarding.zh.md: e2d726368e6282e4f6043c225b665c1945228f2d +2026-07-30-versioned-gui-welcome-onboarding.md: 0705469e02ddb9068722ae5d500c151f077c83fd +2026-07-30-versioned-gui-welcome-onboarding.zh.md: bdd21d635f824b8c4a4813e6bff7798b34ec9677 diff --git a/.agents/notes/implemented/feature/2026-07-30-versioned-gui-welcome-onboarding.md b/.agents/notes/implemented/feature/2026-07-30-versioned-gui-welcome-onboarding.md index 06ac9fbe5c..0705469e02 100644 --- a/.agents/notes/implemented/feature/2026-07-30-versioned-gui-welcome-onboarding.md +++ b/.agents/notes/implemented/feature/2026-07-30-versioned-gui-welcome-onboarding.md @@ -18,7 +18,7 @@ The GUI's credential onboarding begins with a DeepSeek-specific readiness check, **Concurrent views converge without stale replacement.** The acknowledgement write omits `expectedRevision` deliberately: every tab writes the same version to one path, so the operation is idempotent and preserves sibling fields instead of rebuilding the section. `settings/document-updated` becomes `host/settings-changed`; an already mounted tab refetches and advances when another tab or an external editor commits the current version. The API proxy exposes this one product namespace through a closed allowlist beside configurable-provider namespaces, without treating its changes as model-catalog invalidations. -**The welcome modal is scan-first and has one completion path.** Its hierarchy is a declaration title, one status sentence, one emphasized feedback callout, one consequence sentence, and a restrained quotation; the notice version changes whenever that authored copy changes materially. It renders no close icon or secondary action, installs no Escape handler, and assigns no click handler to the mask. Its mask starts below the 80 px top chrome and preserves `position:absolute`, zero left/right/bottom offsets, `rgba(0, 0, 0, 0.24)`, and `backdrop-filter: blur(2px)`. Continue is the sole button and receives initial focus. +**Onboarding temporarily owns the viewport as one continuous stage.** A solid product surface replaces the complete application view through a body-level portal and marks the underlying app root inert; the exact required mask remains mounted behind that surface with `position:absolute`, zero left/right/bottom offsets, `top:80px`, `rgba(0, 0, 0, 0.24)`, and `backdrop-filter: blur(2px)`. Welcome and conditional credential setup render as successive pages in this stage instead of independent modals. Both pages reuse the Web UI's black `BrandWordmark`. The welcome page preserves the four authored paragraphs verbatim under the `内测声明` title; every paragraph uses one 16/28 body scale, and only the requested action clause inside the final paragraph receives a subtle 500 weight. A short staggered opacity/vertical entrance supplies pacing without blocking interaction and disappears under reduced motion. The title receives initial focus, Continue is the sole button, and no close, Escape, or mask-click path exists. ## Alternatives considered diff --git a/.agents/notes/implemented/feature/2026-07-30-versioned-gui-welcome-onboarding.zh.md b/.agents/notes/implemented/feature/2026-07-30-versioned-gui-welcome-onboarding.zh.md index e2d726368e..bdd21d635f 100644 --- a/.agents/notes/implemented/feature/2026-07-30-versioned-gui-welcome-onboarding.zh.md +++ b/.agents/notes/implemented/feature/2026-07-30-versioned-gui-welcome-onboarding.zh.md @@ -18,7 +18,7 @@ GUI 的凭据引导从 DeepSeek 专用的就绪状态检查开始,但内部测 **并发视图无需陈旧的整体替换即可收敛。** 确认写入有意省略 `expectedRevision`:每个标签页都向同一路径写入相同版本,因此该操作是幂等的,并会保留同级字段,而不是重建整个分节。`settings/document-updated` 会转为 `host/settings-changed`;另一个标签页或外部编辑器提交当前版本后,已挂载的标签页会重新拉取状态并推进。API 网关在可配置提供方 namespace 之外,通过封闭的允许列表暴露这一个产品 namespace,同时不会把它的变更视为模型目录失效事件。 -**欢迎模态窗口以便于扫读为先,且只有一条完成路径。** 其信息层级依次为声明标题、一句状态说明、一则重点突出的反馈提示、一句影响说明和一则克制的引语;只要这份文案发生实质变化,就同步提升通知版本。界面不渲染关闭图标或次要操作,不安装 Escape 处理器,也不为遮罩添加点击处理器。遮罩从顶部 80 px 的界面框架下方开始,并保留 `position:absolute`、left/right/bottom 偏移量为零、`rgba(0, 0, 0, 0.24)` 和 `backdrop-filter: blur(2px)`。「继续」是唯一按钮,并会获得初始焦点。 +**引导流程会暂时接管视口,形成一个连续阶段。** 纯色产品界面通过挂载到 `body` 的 portal 取代完整的应用视图,并将底层应用根节点标记为 inert;严格符合要求的遮罩仍挂载在该界面后方,并保留 `position:absolute`、left/right/bottom 偏移量为零、`top:80px`、`rgba(0, 0, 0, 0.24)` 和 `backdrop-filter: blur(2px)`。欢迎页和按条件显示的凭据设置页在这一阶段中依次呈现,而不是各自作为独立的模态窗口。两个页面都复用 Web UI 的黑色 `BrandWordmark`。欢迎页在 `内测声明` 标题下逐字保留既定的四段文案;所有段落统一采用 16/28 的正文字号与行高,只有最后一段中指定的行动语句使用较为克制的 500 字重。短暂的错落式透明度与纵向位移动画营造出舒缓节奏,但不会阻碍交互,并会在用户启用减少动态效果时禁用。初始焦点落在标题上,「继续」是唯一按钮,且不存在关闭、Escape 或点击遮罩的退出路径。 ## 曾考虑的替代方案 diff --git a/apps/web/tests/onboarding-deepseek-config.e2e.ts b/apps/web/tests/onboarding-deepseek-config.e2e.ts index 8731bf10e0..f7a91e8d3e 100644 --- a/apps/web/tests/onboarding-deepseek-config.e2e.ts +++ b/apps/web/tests/onboarding-deepseek-config.e2e.ts @@ -48,14 +48,17 @@ describe.skipIf(MODE === 'record')('web e2e: first-run DeepSeek credential setup it('stores a key write-only and observes configured state without restarting', async () => { onTestFailed(() => saveFailureShot(page, 'web-e2e-onboarding-deepseek-config')) - const welcome = page.getByRole('dialog', { name: WELCOME_NOTICE_COPY.zh.title }) + const welcome = page.getByRole('region', { name: WELCOME_NOTICE_COPY.zh.title }) await welcome.waitFor({ timeout: 15_000 }) - const welcomeAria = await captureStableAria(page, '[role="dialog"]', scaffold.workspaceCwd) + expect(await page.locator('#root').evaluate(root => (root as HTMLElement).inert)).toBe(true) + const welcomeAria = await captureStableAria(page, '[role="region"]', scaffold.workspaceCwd) await compareOrRefreshGolden(WELCOME_EXPECTED, welcomeAria, MODE) expect(await welcome.getByRole('button').allTextContents()).toEqual([WELCOME_NOTICE_COPY.zh.continueLabel]) expect(await welcome.locator('button').count()).toBe(1) - const maskStyles = await welcome.locator('xpath=..').locator(':scope > div').first().evaluate((mask) => { + const mask = page.locator('[class*="onboardingMask"]') + expect(await mask.count()).toBe(1) + const maskStyles = await mask.evaluate((mask) => { const style = getComputedStyle(mask) const rect = mask.getBoundingClientRect() return { @@ -89,16 +92,17 @@ describe.skipIf(MODE === 'record')('web e2e: first-run DeepSeek credential setup await welcome.getByRole('button', { name: WELCOME_NOTICE_COPY.zh.continueLabel }).click() await welcome.waitFor({ state: 'detached', timeout: 15_000 }) - const dialog = page.getByRole('dialog', { name: '添加一个 API Key 开始使用' }) - await dialog.waitFor({ timeout: 15_000 }) - expect(await dialog.getByRole('textbox').count()).toBe(0) - const initial = await captureStableAria(page, '[role="dialog"]', scaffold.workspaceCwd) + const credentialStep = page.getByRole('region', { name: '添加一个 API Key 开始使用' }) + await credentialStep.waitFor({ timeout: 15_000 }) + expect(await credentialStep.getByRole('textbox').count()).toBe(0) + const initial = await captureStableAria(page, '[role="region"]', scaffold.workspaceCwd) await compareOrRefreshGolden(MISSING_EXPECTED, initial, MODE) - await dialog.getByRole('button', { name: '前往配置' }).click() - await dialog.waitFor({ state: 'detached', timeout: 15_000 }) + await credentialStep.getByRole('button', { name: '前往配置' }).click() + await credentialStep.waitFor({ state: 'detached', timeout: 15_000 }) const settings = page.getByRole('dialog', { name: '设置' }) await settings.waitFor({ timeout: 10_000 }) + expect(await page.locator('#root').evaluate(root => (root as HTMLElement).inert)).toBe(false) const keyInput = settings.getByLabel('API 密钥', { exact: true }) await keyInput.waitFor({ timeout: 10_000 }) @@ -132,8 +136,8 @@ describe.skipIf(MODE === 'record')('web e2e: first-run DeepSeek credential setup await page.reload({ waitUntil: 'load' }) acknowledgeReloadConnectionLoss(tripwire, secondReloadWarnings) await page.waitForSelector('[class*="frame"]', { timeout: 15_000 }) - expect(await page.getByRole('dialog', { name: WELCOME_NOTICE_COPY.zh.title }).count()).toBe(0) - expect(await page.getByRole('dialog', { name: '添加一个 API Key 开始使用' }).count()).toBe(0) + expect(await page.getByRole('region', { name: WELCOME_NOTICE_COPY.zh.title }).count()).toBe(0) + expect(await page.getByRole('region', { name: '添加一个 API Key 开始使用' }).count()).toBe(0) // A different stored copy version represents an intentional version bump: // the welcome step returns even though the credential is already ready. @@ -146,7 +150,7 @@ describe.skipIf(MODE === 'record')('web e2e: first-run DeepSeek credential setup await welcome.waitFor({ timeout: 15_000 }) await welcome.getByRole('button', { name: WELCOME_NOTICE_COPY.zh.continueLabel }).click() await welcome.waitFor({ state: 'detached', timeout: 15_000 }) - expect(await page.getByRole('dialog', { name: '添加一个 API Key 开始使用' }).count()).toBe(0) + expect(await page.getByRole('region', { name: '添加一个 API Key 开始使用' }).count()).toBe(0) expect((await page.content()).includes(secret)).toBe(false) expect((await page.locator('body').ariaSnapshot()).includes(secret)).toBe(false) diff --git a/apps/web/tests/snapshots/onboarding-deepseek-config/missing.expected.md b/apps/web/tests/snapshots/onboarding-deepseek-config/missing.expected.md index 102b6a7fab..89f3e009f5 100644 --- a/apps/web/tests/snapshots/onboarding-deepseek-config/missing.expected.md +++ b/apps/web/tests/snapshots/onboarding-deepseek-config/missing.expected.md @@ -1,6 +1,6 @@ -- dialog "添加一个 API Key 开始使用": +- region "添加一个 API Key 开始使用": - heading "添加一个 API Key 开始使用" [level=2] - - button "稍后配置": - - img - paragraph: 配置 DeepSeek 官方模型,即可开始使用。 + - text: DeepSeek deepseek-official + - button "稍后配置" - button "前往配置" diff --git a/apps/web/tests/snapshots/onboarding-deepseek-config/welcome.expected.md b/apps/web/tests/snapshots/onboarding-deepseek-config/welcome.expected.md index d0fcb2b68d..1fe30502c1 100644 --- a/apps/web/tests/snapshots/onboarding-deepseek-config/welcome.expected.md +++ b/apps/web/tests/snapshots/onboarding-deepseek-config/welcome.expected.md @@ -1,8 +1,10 @@ -- dialog "内测声明": +- region "内测声明": - heading "内测声明" [level=2] - - paragraph: 感谢您试用 DeepSeek Harness。目前仍处于内部测试阶段,部分功能与体验还在持续打磨。 - - strong: 我们最想听见:失败、困惑和不顺手 - - paragraph: 如果它没帮到您,甚至给工作添了麻烦,请在企业微信群告诉我们。 - - paragraph: 真实使用中的每一个问题,都可能促使我们重新审视,甚至推翻已有设计。 - - paragraph: “如切如磋,如琢如磨。” + - paragraph: 感谢您愿意拨冗试用 DeepSeek Harness。 + - paragraph: 目前的版本仍处于内部测试阶段,有些功能仍待完善,有些体验难免粗粝。 + - blockquote: “如切如磋,如琢如磨。” 产品的成长,离不开一次次真实的碰撞与坦诚的反馈。您在真实使用中暴露的问题,也可能促使我们重新审视,甚至推翻已有的设计。 + - paragraph: + - text: 我们尤其希望听见那些失败、困惑与不顺手的时刻—— + - strong: 如果它未能帮到您,甚至反而为工作平添了麻烦,请在企业微信群中留言 + - text: ,将使用感受告诉我们。每一条反馈,都会帮助我们把它打磨得更好。 - button "继续" diff --git a/packages/client/ui-models/src/client/DeepSeekOnboardingDialog.module.css b/packages/client/ui-models/src/client/DeepSeekOnboardingDialog.module.css index 6823556903..6d8b77f8ab 100644 --- a/packages/client/ui-models/src/client/DeepSeekOnboardingDialog.module.css +++ b/packages/client/ui-models/src/client/DeepSeekOnboardingDialog.module.css @@ -1,14 +1,136 @@ -.dialog { - width: min(420px, 100%); +.page { + position: relative; + z-index: 1; + width: min(640px, calc(100vw - 64px)); + max-height: 100vh; + padding: clamp(64px, 9vh, 108px) 0 40px; + box-sizing: border-box; + overflow-y: auto; + color: var(--dsw-alias-label-primary); } -.diagnostic { +.brand { + display: flex; + align-items: center; + margin-bottom: 42px; + color: var(--dsw-alias-label-primary); +} + +.title { + max-width: 620px; margin: 0; - font-size: 13px; - line-height: 20px; + font-size: clamp(30px, 4vw, 42px); + line-height: 1.15; + font-weight: 600; + letter-spacing: -0.035em; + outline: none; +} + +.description, +.diagnostic { + max-width: 600px; + margin: 22px 0 0; + font-size: 17px; + line-height: 29px; color: var(--dsw-alias-label-secondary); } -.primary { - width: 100%; +.provider { + display: flex; + align-items: center; + justify-content: space-between; + max-width: 600px; + margin-top: 36px; + padding: 18px 20px; + border: 1px solid var(--dsw-alias-border-l2); + border-radius: 16px; + background: var(--dsw-alias-bg-module-platform); +} + +.providerName { + font-size: 16px; + line-height: 24px; + font-weight: 600; +} + +.providerRoute { + font-size: 13px; + line-height: 20px; + color: var(--dsw-alias-label-tertiary); +} + +.actions { + display: flex; + align-items: center; + gap: 12px; + margin-top: 40px; +} + +.primary { + min-width: 132px; +} + +.brand, +.title, +.description, +.diagnostic, +.provider, +.actions { + animation: credential-enter 280ms cubic-bezier(0.23, 1, 0.32, 1) both; +} + +.title { animation-delay: 40ms; } +.description, +.diagnostic { animation-delay: 80ms; } +.provider { animation-delay: 120ms; } +.actions { animation-delay: 160ms; } + +@keyframes credential-enter { + from { + opacity: 0; + transform: translateY(8px); + } + + to { + opacity: 1; + transform: translateY(0); + } +} + +@media (prefers-reduced-motion: reduce) { + .brand, + .title, + .description, + .diagnostic, + .provider, + .actions { + animation: none; + } +} + +@media (max-width: 560px) { + .page { + width: calc(100vw - 40px); + padding-top: 48px; + } + + .brand { + margin-bottom: 30px; + } + + .description, + .diagnostic { + font-size: 16px; + line-height: 27px; + } + + .actions { + align-items: stretch; + flex-direction: column-reverse; + } + + .primary, + .later { + width: 100%; + } } diff --git a/packages/client/ui-models/src/client/DeepSeekOnboardingDialog.tsx b/packages/client/ui-models/src/client/DeepSeekOnboardingDialog.tsx index 31ae571272..54055d4bf0 100644 --- a/packages/client/ui-models/src/client/DeepSeekOnboardingDialog.tsx +++ b/packages/client/ui-models/src/client/DeepSeekOnboardingDialog.tsx @@ -1,13 +1,13 @@ /** - * Official-DeepSeek first-run dialog. Readiness comes from the same + * Official-DeepSeek first-run step. Readiness comes from the same * provider/settings/credential join as the Models page; the prompt only * routes the user to that page's single credential editor. */ -import { useEffect } from 'react' +import { useEffect, useRef } from 'react' import type { ReactNode } from 'react' import type { PropsRuntime } from '@deepseek-ai/dsh-client-ui-slots' -import { Button, Modal } from '@deepseek-ai/dsh-client-ui-primitives' +import { BrandWordmark, Button } from '@deepseek-ai/dsh-client-ui-primitives' import type { SnapshotSelectorHook } from '@deepseek-ai/dsh-client-web-react' import type { DeepSeekReadiness, ModelsSettingsState, ModelsSettingsStore } from './store.ts' import { deepSeekReadiness } from './store.ts' @@ -61,12 +61,13 @@ function unavailableDiagnostic( * Prompt a first-run user to open Models while the official adapter exists * and its effective credential is not configured. * @param props - settings-shell owner state and Models feature dependencies. - * @returns the controlled modal or null when onboarding needs no intervention. + * @returns the onboarding page or null when onboarding needs no intervention. */ export function DeepSeekOnboardingDialog(props: DeepSeekOnboardingDialogProps): ReactNode { const { complete, openSection, controller, useSnapshot, t } = props const state = useSnapshot(snapshot => snapshot) const readiness = deepSeekReadiness(state) + const titleRef = useRef(null) useEffect(() => { if (state.status === 'idle') void controller.load() @@ -81,6 +82,12 @@ export function DeepSeekOnboardingDialog(props: DeepSeekOnboardingDialogProps): openSection('models') } + useEffect(() => { + if (readiness.kind === 'credential-missing' || readiness.kind === 'unavailable') { + titleRef.current?.focus() + } + }, [readiness.kind]) + let unavailableReason: UnavailableReason | undefined switch (readiness.kind) { case 'loading': @@ -102,26 +109,38 @@ export function DeepSeekOnboardingDialog(props: DeepSeekOnboardingDialogProps): ? undefined : unavailableDiagnostic(unavailableReason, t) + const title = unavailable ? t('onboardingUnavailableTitle') : t('onboardingTitle') + return ( - + +

                      + {title} +

                      + {unavailable + ?

                      {diagnostic}

                      + :

                      {t('onboardingDescription')}

                      } +
                      + DeepSeek + deepseek-official +
                      +
                      + - )} - > - {diagnostic === undefined ? undefined :

                      {diagnostic}

                      } - +
                      + ) } diff --git a/packages/client/ui-models/tests/onboarding-dialog.spec.tsx b/packages/client/ui-models/tests/onboarding-dialog.spec.tsx index 035faf31d0..731fa2406d 100644 --- a/packages/client/ui-models/tests/onboarding-dialog.spec.tsx +++ b/packages/client/ui-models/tests/onboarding-dialog.spec.tsx @@ -111,18 +111,18 @@ describe('DeepSeekOnboardingDialog', () => { it('loads on first entry and presents one accessible route to Models', async () => { const h = harness() render() - expect(await screen.findByRole('dialog', { name: en.onboardingTitle })).toBeTruthy() + expect(await screen.findByRole('region', { name: en.onboardingTitle })).toBeTruthy() expect(screen.getByText(en.onboardingDescription)).toBeTruthy() const action = screen.getByRole('button', { name: en.onboardingGoToSettings }) expect(action).toBeTruthy() - expect(document.activeElement).toBe(action) + expect(document.activeElement).toBe(screen.getByRole('heading', { name: en.onboardingTitle })) expect(screen.queryByRole('textbox')).toBeNull() }) it('opens the Models section and dismisses the prompt', async () => { const h = harness() render() - await screen.findByRole('dialog') + await screen.findByRole('region') fireEvent.click(screen.getByRole('button', { name: en.onboardingGoToSettings })) expect(h.complete).toHaveBeenCalledOnce() expect(h.openSection).toHaveBeenCalledWith('models') @@ -131,7 +131,7 @@ describe('DeepSeekOnboardingDialog', () => { it('allows configure-later dismissal without opening settings', async () => { const h = harness() render() - await screen.findByRole('dialog') + await screen.findByRole('region') fireEvent.click(screen.getByRole('button', { name: en.onboardingLater })) expect(h.complete).toHaveBeenCalledOnce() expect(h.openSection).not.toHaveBeenCalled() @@ -140,7 +140,7 @@ describe('DeepSeekOnboardingDialog', () => { it('routes an unavailable credential deployment to Models with a diagnostic', async () => { const h = harness({ describeFailure: 'credentials service is absent' }) render() - await screen.findByRole('dialog', { name: en.onboardingUnavailableTitle }) + await screen.findByRole('region', { name: en.onboardingUnavailableTitle }) expect(screen.getByText(en.onboardingCredentialsUnavailable)).toBeTruthy() fireEvent.click(screen.getByRole('button', { name: en.onboardingGoToSettings })) expect(h.openSection).toHaveBeenCalledWith('models') @@ -152,7 +152,7 @@ describe('DeepSeekOnboardingDialog', () => { harness({ settingsWritable: false }), ]) { const view = render() - await screen.findByRole('dialog', { name: en.onboardingUnavailableTitle }) + await screen.findByRole('region', { name: en.onboardingUnavailableTitle }) expect(screen.getByText(en.onboardingReadOnly)).toBeTruthy() view.unmount() } @@ -161,7 +161,7 @@ describe('DeepSeekOnboardingDialog', () => { it('distinguishes an initial transport failure from deployment misconfiguration', async () => { const h = harness({ providersRejectOnce: true }) render() - await screen.findByRole('dialog', { name: en.onboardingUnavailableTitle }) + await screen.findByRole('region', { name: en.onboardingUnavailableTitle }) expect(screen.getByText(en.onboardingLoadFailed)).toBeTruthy() fireEvent.click(screen.getByRole('button', { name: en.onboardingGoToSettings })) expect(h.openSection).toHaveBeenCalledWith('models') @@ -174,7 +174,7 @@ describe('DeepSeekOnboardingDialog', () => { harness({ apiKeyEnv: null }), ]) { const view = render() - await screen.findByRole('dialog', { name: en.onboardingUnavailableTitle }) + await screen.findByRole('region', { name: en.onboardingUnavailableTitle }) expect(screen.getByText(en.onboardingConfigurationUnavailable)).toBeTruthy() view.unmount() } @@ -188,7 +188,7 @@ describe('DeepSeekOnboardingDialog', () => { ]) { const view = render() await act(async () => { await h.controller.load() }) - expect(screen.queryByRole('dialog')).toBeNull() + expect(screen.queryByRole('region')).toBeNull() await waitFor(() => { expect(h.complete).toHaveBeenCalledOnce() }) view.unmount() } @@ -197,10 +197,10 @@ describe('DeepSeekOnboardingDialog', () => { it('closes when an external credential invalidation refreshes the shared join', async () => { const h = harness() render() - await screen.findByRole('dialog') + await screen.findByRole('region') h.configure() await act(async () => { await h.controller.load() }) - await waitFor(() => { expect(screen.queryByRole('dialog')).toBeNull() }) + await waitFor(() => { expect(screen.queryByRole('region')).toBeNull() }) expect(h.complete).toHaveBeenCalledOnce() }) }) diff --git a/packages/client/ui-settings-general/README.i18n.yaml b/packages/client/ui-settings-general/README.i18n.yaml index b8fd2d4025..73bae23ebd 100644 --- a/packages/client/ui-settings-general/README.i18n.yaml +++ b/packages/client/ui-settings-general/README.i18n.yaml @@ -2,5 +2,5 @@ # side as of the last confirmed-consistent state. Both languages carry equal authority; # after editing either side, bring the other along and re-record with: # pnpm run verify-translation-pairing --write packages/client/ui-settings-general/README.md -README.md: 3ae3f58bd00172ed9b547c01a354023c224f6a1c -README.zh.md: ffdaf0e4314daa947a4183e2b23b7b1650de7611 +README.md: 0ec2e14bc4f483a23607de7f33ca4c35687c7c4f +README.zh.md: 9ce7136ce9a0bf384bd2b6419d52cd0da5c7dc83 diff --git a/packages/client/ui-settings-general/README.md b/packages/client/ui-settings-general/README.md index 3ae3f58bd0..0ec2e14bc4 100644 --- a/packages/client/ui-settings-general/README.md +++ b/packages/client/ui-settings-general/README.md @@ -4,7 +4,7 @@ English | [中文](README.zh.md) Settings ownerless-copy and product-onboarding plugin: registers everything on the Settings surface that belongs to no single feature — the shell's trigger/header/close chrome content, the General section (Permission/Tool Call skeleton rows + the `settings.general.item` slot declaration), the `settings` dictionaries, and the first ordered welcome step. Feature-owned rows (Language, Appearance), sections (Models), and conditional onboarding steps stay with their feature packages. -`src/onboarding-copy.ts` is the single editable owner of the complete Chinese and English notice plus `WELCOME_NOTICE_VERSION`. The Host half registers `ui-onboarding` in the user-settings seam; the browser compares `welcomeNoticeVersion` for exact equality and writes the current value only after Continue succeeds. The path mutation is idempotent across tabs and preserves sibling settings, while `host/settings-changed` makes an externally acknowledged notice advance without a reload. A different version deliberately presents the notice again. The welcome UI has no close, Escape, mask-click, or secondary path, and none of its copy or acknowledgement enters a Session log or model request. +`src/onboarding-copy.ts` is the single editable owner of the complete Chinese and English notice plus `WELCOME_NOTICE_VERSION`. The Host half registers `ui-onboarding` in the user-settings seam; the browser compares `welcomeNoticeVersion` for exact equality and writes the current value only after Continue succeeds. The path mutation is idempotent across tabs and preserves sibling settings, while `host/settings-changed` makes an externally acknowledged notice advance without a reload. A different version deliberately presents the notice again. The welcome page preserves every authored paragraph, gives the requested clause in the final paragraph the sole emphasis, initially focuses the title, and has no close, Escape, mask-click, or secondary path. None of its copy or acknowledgement enters a Session log or model request. ## Model Experience diff --git a/packages/client/ui-settings-general/README.zh.md b/packages/client/ui-settings-general/README.zh.md index ffdaf0e431..9ce7136ce9 100644 --- a/packages/client/ui-settings-general/README.zh.md +++ b/packages/client/ui-settings-general/README.zh.md @@ -4,7 +4,7 @@ 设置界面无特定功能归属的文案与产品引导插件:在设置界面注册所有不属于单一功能的内容,包括外壳的触发器、标题栏与关闭控件内容,「通用」分区(「权限」/「工具调用」骨架行和 `settings.general.item` slot 声明)、`settings` 字典,以及第一个有序欢迎步骤。归具体功能所有的行(「语言」、「外观」)、分区(「模型」)和条件式首次使用引导步骤仍由各自的功能包提供。 -`src/onboarding-copy.ts` 是完整中英文通知文案和 `WELCOME_NOTICE_VERSION` 的唯一可编辑来源。宿主端在 user-settings seam 中注册 `ui-onboarding`;浏览器比较 `welcomeNoticeVersion` 是否精确相等,仅在「继续」操作成功后写入当前值。该路径变更在不同标签页间幂等,并会保留同级设置;`host/settings-changed` 则让页面在通知被外部确认后,无需重新加载即可推进。版本不同时,系统会有意重新显示通知。欢迎界面没有关闭操作、Escape、点击遮罩或次要操作路径,其文案和确认状态均不会进入会话日志或模型请求。 +`src/onboarding-copy.ts` 是完整中英文通知文案和 `WELCOME_NOTICE_VERSION` 的唯一可编辑来源。宿主端在 user-settings seam 中注册 `ui-onboarding`;浏览器比较 `welcomeNoticeVersion` 是否精确相等,仅在「继续」操作成功后写入当前值。该路径变更在不同标签页间幂等,并会保留同级设置;`host/settings-changed` 则让页面在通知被外部确认后,无需重新加载即可推进。版本不同时,系统会有意重新显示通知。欢迎页保留原文的每个段落,仅强调最后一段中指定的句段,初始焦点落在标题上,并且没有关闭操作、Escape、点击遮罩或次要操作路径。其文案和确认状态均不会进入会话日志或模型请求。 ## 模型体验 diff --git a/packages/client/ui-settings-general/src/client/WelcomeNotice.module.css b/packages/client/ui-settings-general/src/client/WelcomeNotice.module.css index 805f411918..843606605e 100644 --- a/packages/client/ui-settings-general/src/client/WelcomeNotice.module.css +++ b/packages/client/ui-settings-general/src/client/WelcomeNotice.module.css @@ -1,137 +1,161 @@ -.overlay { - position: fixed; - inset: 0; - z-index: 1100; - display: flex; - align-items: center; - justify-content: center; - padding-top: 80px; - box-sizing: border-box; -} - -/* Mask */ -.mask { - position: absolute; - left: 0px; - right: 0px; - top: 80px; - bottom: 0px; - background: rgba(0, 0, 0, 0.24); - /* Mask-blur */ - backdrop-filter: blur(2px); -} - -.dialog { +.page { position: relative; z-index: 1; - width: min(600px, calc(100vw - 48px)); - max-height: calc(100vh - 128px); - padding: 32px; + width: min(640px, calc(100vw - 64px)); + max-height: 100vh; + padding: clamp(64px, 9vh, 104px) 0 40px; box-sizing: border-box; overflow-y: auto; - border-radius: 24px; - background: var(--dsw-alias-bg-layer-2); - box-shadow: var(--dsw-shadow-lv3); + color: var(--dsw-alias-label-primary); + --welcome-ease-out: cubic-bezier(0.23, 1, 0.32, 1); +} + +.brand { + display: flex; + align-items: center; + margin-bottom: 42px; color: var(--dsw-alias-label-primary); } .title { margin: 0; - font-size: 20px; - line-height: 30px; + font-size: 28px; + line-height: 36px; font-weight: 600; - letter-spacing: -0.01em; + letter-spacing: -0.02em; + outline: none; } -.lead, -.closing, -.quote, -.feedback p, +.opening, +.status, +.reflection, +.feedback, .error { margin: 0; } -.lead { - margin-top: 12px; - font-size: 16px; - line-height: 25px; - color: var(--dsw-alias-label-secondary); +.opening { + margin-top: 30px; +} + +.status { + margin-top: 18px; +} + +.reflection { + margin-top: 36px; + padding: 0; } .feedback { - margin-top: 20px; - padding: 16px 18px; - border-radius: 14px; - border: 1px solid var(--dsw-alias-border-l1); - background: var(--dsw-alias-bg-module-platform); - font-size: 15px; - line-height: 24px; + margin-top: 30px; +} + +.opening, +.status, +.reflection, +.feedback { + font-size: 16px; + line-height: 28px; + color: var(--dsw-alias-label-secondary); } .feedback strong { - display: block; - margin-bottom: 4px; - font-weight: 600; -} - -.feedback p, -.closing { - color: var(--dsw-alias-label-secondary); -} - -.closing { - margin-top: 16px; - font-size: 15px; - line-height: 24px; -} - -.quote { - font-size: 14px; - line-height: 22px; - color: var(--dsw-alias-label-secondary); + color: inherit; + font-weight: 500; } .footer { display: flex; - align-items: center; - justify-content: space-between; - gap: 24px; - margin-top: 24px; - padding-top: 20px; - border-top: 1px solid var(--dsw-alias-border-l1); + justify-content: flex-end; + margin-top: 32px; } .error { - margin-top: 14px; - font-size: 13px; - line-height: 20px; + margin-top: 20px; + font-size: 14px; + line-height: 22px; color: var(--dsw-alias-state-error-primary); } .primary { - min-width: 104px; - transition: transform 140ms cubic-bezier(0.23, 1, 0.32, 1); + min-width: 120px; + transition: transform 140ms var(--welcome-ease-out); } .primary:active:not(:disabled) { transform: scale(0.97); } +.brand, +.title, +.opening, +.status, +.reflection, +.feedback, +.footer { + animation: welcome-enter 280ms var(--welcome-ease-out) both; +} + +.title { animation-delay: 40ms; } +.opening { animation-delay: 80ms; } +.status { animation-delay: 120ms; } +.reflection { animation-delay: 160ms; } +.feedback { animation-delay: 200ms; } +.footer { animation-delay: 240ms; } + +@keyframes welcome-enter { + from { + opacity: 0; + transform: translateY(8px); + } + + to { + opacity: 1; + transform: translateY(0); + } +} + @media (prefers-reduced-motion: reduce) { + .brand, + .title, + .opening, + .status, + .reflection, + .feedback, + .footer { + animation: none; + } + .primary { transition: none; } } @media (max-width: 560px) { - .dialog { - padding: 24px; + .page { + width: calc(100vw - 40px); + padding-top: 38px; + } + + .brand { + margin-bottom: 30px; + } + + .opening { + margin-top: 24px; + } + + .reflection { + margin-top: 28px; + } + + .feedback { + margin-top: 28px; } .footer { - align-items: stretch; - flex-direction: column; - gap: 14px; + margin-top: 30px; } .primary { diff --git a/packages/client/ui-settings-general/src/client/WelcomeNotice.tsx b/packages/client/ui-settings-general/src/client/WelcomeNotice.tsx index ebdab519a4..f1e14d6815 100644 --- a/packages/client/ui-settings-general/src/client/WelcomeNotice.tsx +++ b/packages/client/ui-settings-general/src/client/WelcomeNotice.tsx @@ -3,11 +3,24 @@ import { useCallback, useEffect, useRef } from 'react' import type { ReactNode } from 'react' import type { PropsRuntime } from '@deepseek-ai/dsh-client-ui-slots' -import { Button } from '@deepseek-ai/dsh-client-ui-primitives' +import { BrandWordmark, Button } from '@deepseek-ai/dsh-client-ui-primitives' import type { SnapshotSelectorHook } from '@deepseek-ai/dsh-client-web-react' import type { WelcomeNoticeState, WelcomeNoticeStore } from './welcome-store.ts' import css from './WelcomeNotice.module.css' +function emphasizedFeedback(paragraph: string, emphasis: string): ReactNode { + const index = paragraph.indexOf(emphasis) + /* v8 ignore next -- both locale values derive from one owner object that contains the emphasis */ + if (index < 0) return paragraph + return ( + <> + {paragraph.slice(0, index)} + {emphasis} + {paragraph.slice(index + emphasis.length)} + + ) +} + /** Registrant-owned dependencies of {@link WelcomeNotice}. */ export interface WelcomeNoticeInjected { controller: WelcomeNoticeStore @@ -23,6 +36,7 @@ export function WelcomeNotice(props: WelcomeNoticeProps): ReactNode { const { complete, controller, useSnapshot, t } = props const state = useSnapshot(snapshot => snapshot) const finished = useRef(false) + const titleRef = useRef(null) const finish = useCallback((): void => { if (finished.current) return finished.current = true @@ -37,6 +51,10 @@ export function WelcomeNotice(props: WelcomeNoticeProps): ReactNode { if (state.acknowledged) finish() }, [finish, state.acknowledged]) + useEffect(() => { + if (state.status === 'ready' && !state.acknowledged) titleRef.current?.focus() + }, [state.acknowledged, state.status]) + if (state.status === 'idle' || state.status === 'loading' || state.acknowledged) return null const acknowledge = async (): Promise => { @@ -44,30 +62,26 @@ export function WelcomeNotice(props: WelcomeNoticeProps): ReactNode { } return ( -
                      - +
                      + +

                      {t('welcome.title')}

                      +

                      {t('welcome.paragraph.0')}

                      +

                      {t('welcome.paragraph.1')}

                      +
                      {t('welcome.paragraph.2')}
                      +

                      + {emphasizedFeedback(t('welcome.paragraph.3'), t('welcome.feedbackEmphasis'))} +

                      + {state.error === null ? null :

                      {t('welcome.error')}

                      } +
                      + +
                      +
                      ) } diff --git a/packages/client/ui-settings-general/src/client/locales.ts b/packages/client/ui-settings-general/src/client/locales.ts index f2486faea2..c3432cfe72 100644 --- a/packages/client/ui-settings-general/src/client/locales.ts +++ b/packages/client/ui-settings-general/src/client/locales.ts @@ -27,11 +27,11 @@ export const zh: LocaleDict = { 'permission.desc': '选择默认权限模式', 'toolcall.title': '工具调用', 'welcome.title': WELCOME_NOTICE_COPY.zh.title, - 'welcome.lead': WELCOME_NOTICE_COPY.zh.lead, - 'welcome.feedbackTitle': WELCOME_NOTICE_COPY.zh.feedbackTitle, - 'welcome.feedbackBody': WELCOME_NOTICE_COPY.zh.feedbackBody, - 'welcome.closing': WELCOME_NOTICE_COPY.zh.closing, - 'welcome.quote': WELCOME_NOTICE_COPY.zh.quote, + 'welcome.paragraph.0': WELCOME_NOTICE_COPY.zh.paragraphs[0], + 'welcome.paragraph.1': WELCOME_NOTICE_COPY.zh.paragraphs[1], + 'welcome.paragraph.2': WELCOME_NOTICE_COPY.zh.paragraphs[2], + 'welcome.paragraph.3': WELCOME_NOTICE_COPY.zh.paragraphs[3], + 'welcome.feedbackEmphasis': WELCOME_NOTICE_COPY.zh.feedbackEmphasis, 'welcome.continue': WELCOME_NOTICE_COPY.zh.continueLabel, 'welcome.error': '暂时无法保存确认状态,请重试。', } @@ -47,11 +47,11 @@ export const en: LocaleDict = { 'permission.desc': 'Choose default permission mode', 'toolcall.title': 'Tool Call', 'welcome.title': WELCOME_NOTICE_COPY.en.title, - 'welcome.lead': WELCOME_NOTICE_COPY.en.lead, - 'welcome.feedbackTitle': WELCOME_NOTICE_COPY.en.feedbackTitle, - 'welcome.feedbackBody': WELCOME_NOTICE_COPY.en.feedbackBody, - 'welcome.closing': WELCOME_NOTICE_COPY.en.closing, - 'welcome.quote': WELCOME_NOTICE_COPY.en.quote, + 'welcome.paragraph.0': WELCOME_NOTICE_COPY.en.paragraphs[0], + 'welcome.paragraph.1': WELCOME_NOTICE_COPY.en.paragraphs[1], + 'welcome.paragraph.2': WELCOME_NOTICE_COPY.en.paragraphs[2], + 'welcome.paragraph.3': WELCOME_NOTICE_COPY.en.paragraphs[3], + 'welcome.feedbackEmphasis': WELCOME_NOTICE_COPY.en.feedbackEmphasis, 'welcome.continue': WELCOME_NOTICE_COPY.en.continueLabel, 'welcome.error': 'The acknowledgement could not be saved. Please try again.', } diff --git a/packages/client/ui-settings-general/src/onboarding-copy.ts b/packages/client/ui-settings-general/src/onboarding-copy.ts index 805a9d35d0..21e27114d4 100644 --- a/packages/client/ui-settings-general/src/onboarding-copy.ts +++ b/packages/client/ui-settings-general/src/onboarding-copy.ts @@ -8,26 +8,30 @@ export const WELCOME_NOTICE_ACK_FIELD = 'welcomeNoticeVersion' * Bump only when the notice changes materially and every user should see it * again. The acknowledgement is compared for exact equality. */ -export const WELCOME_NOTICE_VERSION = '2026-07-30.2' +export const WELCOME_NOTICE_VERSION = '2026-07-30.3' /** The complete editable welcome notice in both supported GUI locales. */ export const WELCOME_NOTICE_COPY = { zh: { title: '内测声明', - lead: '感谢您试用 DeepSeek Harness。目前仍处于内部测试阶段,部分功能与体验还在持续打磨。', - feedbackTitle: '我们最想听见:失败、困惑和不顺手', - feedbackBody: '如果它没帮到您,甚至给工作添了麻烦,请在企业微信群告诉我们。', - closing: '真实使用中的每一个问题,都可能促使我们重新审视,甚至推翻已有设计。', - quote: '“如切如磋,如琢如磨。”', + paragraphs: [ + '感谢您愿意拨冗试用 DeepSeek Harness。', + '目前的版本仍处于内部测试阶段,有些功能仍待完善,有些体验难免粗粝。', + '“如切如磋,如琢如磨。” 产品的成长,离不开一次次真实的碰撞与坦诚的反馈。您在真实使用中暴露的问题,也可能促使我们重新审视,甚至推翻已有的设计。', + '我们尤其希望听见那些失败、困惑与不顺手的时刻——如果它未能帮到您,甚至反而为工作平添了麻烦,请在企业微信群中留言,将使用感受告诉我们。每一条反馈,都会帮助我们把它打磨得更好。', + ], + feedbackEmphasis: '如果它未能帮到您,甚至反而为工作平添了麻烦,请在企业微信群中留言', continueLabel: '继续', }, en: { title: 'Internal Testing Notice', - lead: 'Thank you for trying DeepSeek Harness. This version is still in internal testing, and some features and experiences remain under refinement.', - feedbackTitle: 'What we most want to hear: failures, confusion, and friction', - feedbackBody: 'If it did not help—or even made your work harder—please tell us in the company WeChat group.', - closing: 'Every problem found in real use may prompt us to reconsider, or even overturn, an existing design.', - quote: '“As one cuts and files, as one chisels and polishes.”', + paragraphs: [ + 'Thank you for taking the time to try DeepSeek Harness.', + 'This version is still in internal testing. Some features remain unfinished, and parts of the experience may feel rough.', + '“As one cuts and files, as one chisels and polishes.” A product grows through real encounters and candid feedback. Problems you uncover in real use may prompt us to reconsider—or even overturn—our existing designs.', + 'We especially want to hear about failures, confusion, and friction. If it did not help you, or even made your work harder, please leave a message in the company WeChat group and tell us about your experience. Every piece of feedback helps us refine it.', + ], + feedbackEmphasis: 'If it did not help you, or even made your work harder, please leave a message in the company WeChat group', continueLabel: 'Continue', }, } as const diff --git a/packages/client/ui-settings-general/tests/welcome-notice.spec.tsx b/packages/client/ui-settings-general/tests/welcome-notice.spec.tsx index d414146e47..767f35ef33 100644 --- a/packages/client/ui-settings-general/tests/welcome-notice.spec.tsx +++ b/packages/client/ui-settings-general/tests/welcome-notice.spec.tsx @@ -54,30 +54,22 @@ function mount(version?: string, mutateImpl: () => Promise = () => Prom describe('WelcomeNotice', () => { it('renders the owner copy with one primary action and no dismissal control', async () => { const h = mount() - const dialog = await screen.findByRole('dialog', { name: WELCOME_NOTICE_COPY.zh.title }) - for (const text of [ - WELCOME_NOTICE_COPY.zh.title, - WELCOME_NOTICE_COPY.zh.lead, - WELCOME_NOTICE_COPY.zh.feedbackTitle, - WELCOME_NOTICE_COPY.zh.feedbackBody, - WELCOME_NOTICE_COPY.zh.closing, - WELCOME_NOTICE_COPY.zh.quote, - ]) { - expect(screen.getByText(text)).toBeTruthy() - } - expect(dialog.textContent?.match(/感谢您试用 DeepSeek Harness/g) ?? []).toHaveLength(1) - const buttons = dialog.querySelectorAll('button') + const page = await screen.findByRole('region', { name: WELCOME_NOTICE_COPY.zh.title }) + expect(screen.getByText(WELCOME_NOTICE_COPY.zh.title)).toBeTruthy() + for (const text of WELCOME_NOTICE_COPY.zh.paragraphs) expect(page.textContent).toContain(text) + expect(page.textContent?.match(/感谢您愿意拨冗试用 DeepSeek Harness/g) ?? []).toHaveLength(1) + const buttons = page.querySelectorAll('button') expect(buttons).toHaveLength(1) expect(screen.getByRole('button', { name: WELCOME_NOTICE_COPY.zh.continueLabel })).toBeTruthy() + expect(document.activeElement).toBe(screen.getByRole('heading', { name: WELCOME_NOTICE_COPY.zh.title })) fireEvent.keyDown(document, { key: 'Escape' }) - fireEvent.click(dialog.parentElement!.firstElementChild!) expect(h.complete).not.toHaveBeenCalled() - expect(screen.getByRole('dialog')).toBeTruthy() + expect(screen.getByRole('region')).toBeTruthy() }) it('completes only after the acknowledgement write commits', async () => { const h = mount() - await screen.findByRole('dialog') + await screen.findByRole('region') fireEvent.click(screen.getByRole('button', { name: WELCOME_NOTICE_COPY.zh.continueLabel })) await act(async () => { await Promise.resolve() }) expect(h.mutate).toHaveBeenCalledOnce() @@ -87,7 +79,7 @@ describe('WelcomeNotice', () => { it('skips itself when this exact version was already acknowledged', async () => { const h = mount(WELCOME_NOTICE_VERSION) await act(async () => { await h.controller.load() }) - expect(screen.queryByRole('dialog')).toBeNull() + expect(screen.queryByRole('region')).toBeNull() expect(h.complete).toHaveBeenCalledOnce() }) @@ -95,7 +87,7 @@ describe('WelcomeNotice', () => { let resolveWrite!: (value: unknown) => void const write = new Promise((resolve) => { resolveWrite = resolve }) const h = mount(undefined, () => write) - await screen.findByRole('dialog') + await screen.findByRole('region') const action = screen.getByRole('button', { name: WELCOME_NOTICE_COPY.zh.continueLabel }) fireEvent.click(action) expect(action.disabled).toBe(true) diff --git a/packages/client/ui-settings/README.i18n.yaml b/packages/client/ui-settings/README.i18n.yaml index 41247a370b..b02b945303 100644 --- a/packages/client/ui-settings/README.i18n.yaml +++ b/packages/client/ui-settings/README.i18n.yaml @@ -2,5 +2,5 @@ # side as of the last confirmed-consistent state. Both languages carry equal authority; # after editing either side, bring the other along and re-record with: # pnpm run verify-translation-pairing --write packages/client/ui-settings/README.md -README.md: 02d8f0e5fdc169d3a45f59d7b42d873943df2b52 -README.zh.md: 465d57847588e9ccbccc9d9067099773de63c0d0 +README.md: 6d784e906b937e912b56b2e85bfa32866d8cb9b8 +README.zh.md: 3c627c185db3d1d80915f19df56a8fe7257fa828 diff --git a/packages/client/ui-settings/README.md b/packages/client/ui-settings/README.md index 02d8f0e5fd..6d784e906b 100644 --- a/packages/client/ui-settings/README.md +++ b/packages/client/ui-settings/README.md @@ -2,9 +2,9 @@ English | [中文](README.zh.md) -Settings shell plugin: a pure composition face. It occupies `sidebar.settings` with the trigger chrome and modal settings panel, and declares the slots registrants fill: `settings.trigger` / `settings.header` / `settings.close` (chrome content), `settings.section` (one page per feature), and `settings.onboarding` (ordered feature-owned steps on the empty Hero). The shell ships no copy and reads no locale state — all text arrives from registrants (ui-settings-general owns chrome, General, and the product welcome step; features own their sections, rows, and conditional onboarding steps). +Settings shell plugin: a pure composition face. It occupies `sidebar.settings` with the trigger chrome and modal settings panel, and declares the slots registrants fill: `settings.trigger` / `settings.header` / `settings.close` (chrome content), `settings.section` (one page per feature), and `settings.onboarding` (ordered feature-owned pages in a full-viewport stage). The shell ships no copy and reads no locale state — all text arrives from registrants (ui-settings-general owns chrome, General, and the product notice; features own their sections, rows, and conditional onboarding pages). -The shell projects the onboarding ledger into ascending order and mounts exactly one step at a time. The active registrant receives its id, `complete()`, and an `openSection(id)` callback; completing or skipping transfers ownership to the next entry. Registrants own durable completion, capability readiness, copy, and mutations, so two independently registered dialogs cannot stack and the shell does not become a second configuration fact source. +The shell projects the onboarding ledger into ascending order and mounts exactly one page at a time in a body-level stage while marking the underlying app root inert. The active registrant receives its id, `complete()`, and an `openSection(id)` callback; completing or skipping transfers ownership to the next entry. Registrants own durable completion, capability readiness, copy, and mutations, so independently registered flows cannot stack and the shell does not become a second configuration fact source. ## Model Experience diff --git a/packages/client/ui-settings/README.zh.md b/packages/client/ui-settings/README.zh.md index 465d578475..3c627c185d 100644 --- a/packages/client/ui-settings/README.zh.md +++ b/packages/client/ui-settings/README.zh.md @@ -2,9 +2,9 @@ [English](README.md) | 中文 -设置外壳插件:一个纯组合表层。它以触发控件和模态设置面板占用 `sidebar.settings`,并声明由注册方填充的 slot:`settings.trigger`/`settings.header`/`settings.close`(界面框架内容)、`settings.section`(每项功能一页)和 `settings.onboarding`(由各功能持有、显示在空白 Hero 上的有序步骤)。外壳不自带文案,也不读取 locale 状态:所有文本都来自注册方(ui-settings-general 拥有界面框架、「通用」分区和产品欢迎步骤;各功能拥有各自的分区、行和条件式首次使用引导步骤)。 +设置外壳插件:一个纯组合表层。它以触发控件和模态设置面板占用 `sidebar.settings`,并声明由注册方填充的 slot:`settings.trigger`/`settings.header`/`settings.close`(界面框架内容)、`settings.section`(每项功能一页)和 `settings.onboarding`(由各功能持有、显示在全视口展示层中的有序页面)。外壳不自带文案,也不读取 locale 状态:所有文本都来自注册方(ui-settings-general 拥有界面框架、「通用」分区和产品声明;各功能拥有各自的分区、行和条件式首次使用引导页面)。 -外壳将首次使用引导记录按升序投影,并且每次只挂载一个步骤。当前注册方会收到该条目的 id、`complete()` 和 `openSection(id)` 回调;完成或跳过当前步骤后,所有权转交给下一项。持久化完成状态、能力就绪状态、文案和变更操作均由注册方持有,因此两个独立注册的对话框无法堆叠,外壳也不会成为第二个配置事实来源。 +外壳将首次使用引导记录按升序投影,在 body 层级的展示层中每次只挂载一个页面,同时将下层应用根节点标记为 `inert`。当前注册方会收到该条目的 id、`complete()` 和 `openSection(id)` 回调;完成或跳过当前页面后,所有权转交给下一项。持久化完成状态、能力就绪状态、文案和变更操作均由注册方持有,因此独立注册的流程无法堆叠,外壳也不会成为第二个配置事实来源。 ## 模型体验 diff --git a/packages/client/ui-settings/package.json b/packages/client/ui-settings/package.json index 8c65eee5b2..fa8bf78b9f 100644 --- a/packages/client/ui-settings/package.json +++ b/packages/client/ui-settings/package.json @@ -1,6 +1,6 @@ { "name": "@deepseek-ai/dsh-client-ui-settings", - "description": "Settings shell plugin: sidebar trigger, modal panel, feature sections, and root-scoped onboarding overlays", + "description": "Settings shell plugin: sidebar trigger, modal panel, feature sections, and an ordered full-page onboarding stage", "version": "0.0.1", "private": true, "type": "module", @@ -43,7 +43,8 @@ "@deepseek-ai/dsh-client-ui-slots": "^0.0.1", "@deepseek-ai/dsh-invariants": "^0.0.1", "cordis": "^4.0.0-rc.7", - "react": "^18.2.0" + "react": "^18.2.0", + "react-dom": "^18.2.0" }, "devDependencies": { "@deepseek-ai/dsh-client-runtime": "workspace:^", @@ -51,9 +52,11 @@ "@deepseek-ai/dsh-client-ui-sidebar": "workspace:^", "@deepseek-ai/dsh-client-ui-slots": "workspace:^", "@deepseek-ai/dsh-invariants": "workspace:^", + "@types/react-dom": "~18.3.0", "@types/react": "~18.3.1", "cordis": "^4.0.0-rc.7", - "react": "^18.2.0" + "react": "^18.2.0", + "react-dom": "^18.2.0" }, "files": [ "lib/index.js", diff --git a/packages/client/ui-settings/src/client/SettingsRoot.module.css b/packages/client/ui-settings/src/client/SettingsRoot.module.css index 04eaf14d2b..817ab38d9a 100644 --- a/packages/client/ui-settings/src/client/SettingsRoot.module.css +++ b/packages/client/ui-settings/src/client/SettingsRoot.module.css @@ -209,3 +209,33 @@ clip: rect(0 0 0 0); white-space: nowrap; } + +/* First-run stage: keep the product top bar visible, then let onboarding own + the complete workspace instead of presenting another settings modal. */ +.onboardingOverlay { + position: fixed; + inset: 0; + z-index: 1100; +} + +/* Mask */ +.onboardingMask { + position: absolute; + left: 0px; + right: 0px; + top: 80px; + bottom: 0px; + background: rgba(0, 0, 0, 0.24); + /* Mask-blur */ + backdrop-filter: blur(2px); +} + +.onboardingStage { + position: absolute; + z-index: 1; + inset: 0; + display: flex; + justify-content: center; + overflow: hidden; + background: var(--dsw-alias-bg-layer-1); +} diff --git a/packages/client/ui-settings/src/client/SettingsRoot.tsx b/packages/client/ui-settings/src/client/SettingsRoot.tsx index 528a633810..3eefbd4ef1 100644 --- a/packages/client/ui-settings/src/client/SettingsRoot.tsx +++ b/packages/client/ui-settings/src/client/SettingsRoot.tsx @@ -10,6 +10,7 @@ * sessions-derived empty-Hero fact is active. */ import { useCallback, useEffect, useId, useRef, useState } from 'react' +import { createPortal } from 'react-dom' import clsx from 'clsx' import { IconCloseOutline16, IconDataOutline16, IconSettingsOutline16 } from '@deepseek-ai/dsh-client-ui-primitives' import type { SettingsRootComponentProps, SettingsSectionRow } from './contract/slots.ts' @@ -132,6 +133,14 @@ export function SettingsRoot(props: SettingsRootComponentProps) { }) }, []) + useEffect(() => { + if (onboardingStep === undefined) return + const appRoot = document.getElementById('root') + if (appRoot === null) return + appRoot.inert = true + return () => { appRoot.inert = false } + }, [onboardingStep]) + return ( <> @@ -276,6 +296,29 @@ function Loaded({ injected }: { injected: ModelsSectionInjected }): ReactNode { )}
                      + + + + + )} + />
                      ) } diff --git a/packages/client/ui-models/src/client/locales.ts b/packages/client/ui-models/src/client/locales.ts index 48431ddacf..5cc6782dca 100644 --- a/packages/client/ui-models/src/client/locales.ts +++ b/packages/client/ui-models/src/client/locales.ts @@ -9,8 +9,13 @@ export const en = { dormant: 'Inactive', edit: 'Edit', remove: 'Delete', + deleteTitle: 'Delete model provider?', + deleteDescription: 'Deleting this model provider removes its configuration. You will not be able to use its models until you add the provider again.', + deleteConfirm: 'Delete provider', + deleting: 'Deleting provider…', add: 'Add provider', provider: 'Provider', + close: 'Close', cancel: 'Cancel', apply: 'Apply', applying: 'Applying…', @@ -46,8 +51,13 @@ export const zh: typeof en = { dormant: '未启用', edit: '编辑', remove: '删除', + deleteTitle: '删除模型提供方?', + deleteDescription: '删除此模型提供方会移除其配置。在重新添加前,你将无法继续使用其模型。', + deleteConfirm: '删除提供方', + deleting: '正在删除提供方…', add: '添加提供方', provider: '提供方', + close: '关闭', cancel: '取消', apply: '保存', applying: '保存中…', diff --git a/packages/client/ui-models/tests/apply.spec.ts b/packages/client/ui-models/tests/apply.spec.ts index eb34b162a0..6c64a93058 100644 --- a/packages/client/ui-models/tests/apply.spec.ts +++ b/packages/client/ui-models/tests/apply.spec.ts @@ -48,6 +48,7 @@ describe('ui-models apply', () => { expect(resolveSlotLabel(entry.options.label)).toBe('模型') const injected = (entry.inject as unknown as () => import('../src/client/ModelsSection.tsx').ModelsSectionInjected)() expect(injected.t('nav')).toBe('模型') + expect(injected.t('deleteTitle')).toBe('删除模型提供方?') expect(typeof injected.controller.load).toBe('function') expect(typeof injected.useSnapshot).toBe('function') expect(injected.api).toBeDefined() @@ -73,8 +74,11 @@ describe('ui-models apply', () => { await b.ctx.plugin({ inject: [...inject], apply }).await() b.locale.setLocale('en') expect(resolveSlotLabel(b.slots.entries('settings.section')[0]!.options.label)).toBe('Models') + const injected = b.slots.entries('settings.section')[0]!.inject as unknown as () => import('../src/client/ModelsSection.tsx').ModelsSectionInjected + expect(injected().t('deleteTitle')).toBe('Delete model provider?') b.locale.setLocale('zh') expect(resolveSlotLabel(b.slots.entries('settings.section')[0]!.options.label)).toBe('模型') + expect(injected().t('deleteTitle')).toBe('删除模型提供方?') }) it('locale change while the slot is undeclared stays a no-op', async () => { diff --git a/packages/client/ui-models/tests/components.spec.tsx b/packages/client/ui-models/tests/components.spec.tsx index a4f3734fbd..47aec0dd5e 100644 --- a/packages/client/ui-models/tests/components.spec.tsx +++ b/packages/client/ui-models/tests/components.spec.tsx @@ -1,6 +1,6 @@ // @vitest-environment jsdom /** Section, setup-card, and hand-written editor behavior over a scripted wire face. */ -import { cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react' +import { act, cleanup, fireEvent, render, screen, waitFor, within } from '@testing-library/react' import { afterEach, describe, expect, it, vi } from 'vitest' import Schema from 'schemastery' import { bindSnapshotSelector } from '@deepseek-ai/dsh-client-web-react' @@ -471,10 +471,28 @@ describe('ModelsSection', () => { await waitFor(() => { expect(set).toHaveBeenCalledTimes(1) }) }) - it('removes a user-added provider by unsetting its path', async () => { + it('requires confirmation before removing a user-added provider', async () => { const { replace, mutate } = await mountSection() fireEvent.click(screen.getAllByText(en.remove)[0] as HTMLElement) + const dialog = screen.getByRole('dialog', { name: en.deleteTitle }) + expect(dialog.textContent).toContain(en.deleteDescription) + expect(document.activeElement).toBe(within(dialog).getByRole('button', { name: en.cancel })) + expect(mutate).not.toHaveBeenCalled() + fireEvent.click(within(dialog).getByRole('button', { name: en.cancel })) + expect(screen.queryByRole('dialog', { name: en.deleteTitle })).toBeNull() + expect(mutate).not.toHaveBeenCalled() + + fireEvent.click(screen.getAllByText(en.remove)[0] as HTMLElement) + fireEvent.click(within(screen.getByRole('dialog', { name: en.deleteTitle })) + .getByRole('button', { name: en.close })) + expect(screen.queryByRole('dialog', { name: en.deleteTitle })).toBeNull() + expect(mutate).not.toHaveBeenCalled() + + fireEvent.click(screen.getAllByText(en.remove)[0] as HTMLElement) + fireEvent.click(within(screen.getByRole('dialog', { name: en.deleteTitle })) + .getByRole('button', { name: en.deleteConfirm })) await waitFor(() => { expect(mutate).toHaveBeenCalledTimes(1) }) + expect(screen.queryByRole('dialog', { name: en.deleteTitle })).toBeNull() expect(replace).not.toHaveBeenCalled() expect(mutate.mock.calls[0]?.[0]).toEqual({ ns: 'llm-pi-ai', @@ -482,6 +500,28 @@ describe('ModelsSection', () => { }) }) + it('blocks duplicate deletion while the confirmed removal is pending', async () => { + let resolveRemoval!: (response: RpcResponse) => void + const mutate = vi.fn(() => new Promise>((resolve) => { + resolveRemoval = resolve + })) + await mountSection({ mutate }) + fireEvent.click(screen.getAllByText(en.remove)[0] as HTMLElement) + const dialog = screen.getByRole('dialog', { name: en.deleteTitle }) + const confirm = within(dialog).getByRole('button', { name: en.deleteConfirm }) + fireEvent.click(confirm) + fireEvent.click(confirm) + expect(mutate).toHaveBeenCalledOnce() + expect(confirm.disabled).toBe(true) + expect(within(dialog).getByRole('button', { name: en.cancel }).disabled).toBe(true) + expect(within(dialog).getByRole('button', { name: en.deleting })).toBe(confirm) + fireEvent.click(within(dialog).getByRole('button', { name: en.close })) + expect(screen.getByRole('dialog', { name: en.deleteTitle })).toBe(dialog) + expect(mutate).toHaveBeenCalledOnce() + await act(async () => { resolveRemoval(ok(wireNamespaces()[2]!)) }) + await waitFor(() => { expect(screen.queryByRole('dialog', { name: en.deleteTitle })).toBeNull() }) + }) + it('renders the load failure with a retry control', async () => { const face = scriptedFace() face.face.llm.providers = vi.fn(() => Promise.resolve(fail('directory down', 'internal'))) as never @@ -589,6 +629,8 @@ describe('ModelsSection', () => { // would appear — rather than the row silently staying put. await mountSection({ mutate: vi.fn(() => Promise.reject(new Error('the host refused'))) }) fireEvent.click(screen.getAllByText(en.remove)[0] as HTMLElement) + fireEvent.click(within(screen.getByRole('dialog', { name: en.deleteTitle })) + .getByRole('button', { name: en.deleteConfirm })) await screen.findByText(`${en.loadFailed}: the host refused`) }) diff --git a/packages/client/ui-models/tests/styles.spec.ts b/packages/client/ui-models/tests/styles.spec.ts new file mode 100644 index 0000000000..478046454b --- /dev/null +++ b/packages/client/ui-models/tests/styles.spec.ts @@ -0,0 +1,13 @@ +import { readFileSync } from 'node:fs' +import { fileURLToPath } from 'node:url' +import { describe, expect, it } from 'vitest' + +const css = readFileSync(fileURLToPath(new URL('../src/client/ModelsSection.module.css', import.meta.url)), 'utf8') + +describe('ModelsSection theme styles', () => { + it('uses the shared theme tokens without light-only fallbacks', () => { + expect(css).not.toMatch(/var\(--(?:surface|text-|border|accent-strong)/) + expect(css).toContain('background: var(--dsw-alias-bg-layer-3)') + expect(css).toContain('color: var(--dsw-alias-label-primary)') + }) +}) From 45627bd93bc472579a2aa1f9874281b37baa6e70 Mon Sep 17 00:00:00 2001 From: ZiyaZhang <199893125+ZiyaZhang@users.noreply.github.com> Date: Thu, 30 Jul 2026 20:17:04 -0700 Subject: [PATCH 096/139] fix(ci): tolerate initializing Lefthook lock --- scripts/install-lefthook.mjs | 73 +++++++++++++++++++++++++++++--- scripts/install-lefthook.spec.ts | 16 +++++++ 2 files changed, 84 insertions(+), 5 deletions(-) diff --git a/scripts/install-lefthook.mjs b/scripts/install-lefthook.mjs index f94fb3bf11..ba4695f4d4 100644 --- a/scripts/install-lefthook.mjs +++ b/scripts/install-lefthook.mjs @@ -1,6 +1,17 @@ #!/usr/bin/env node import { randomUUID } from 'node:crypto' -import { existsSync, lstatSync, mkdirSync, readdirSync, readFileSync, unlinkSync, writeFileSync } from 'node:fs' +import { + closeSync, + existsSync, + fstatSync, + lstatSync, + mkdirSync, + openSync, + readdirSync, + readFileSync, + unlinkSync, + writeFileSync, +} from 'node:fs' import { spawnSync } from 'node:child_process' import { dirname, isAbsolute, join, resolve } from 'node:path' @@ -11,6 +22,7 @@ const OWNERSHIP_MARKER_VERSION = 1 const OWNERSHIP_MARKER_OWNER = 'deepseek-harness worktree-local lefthook hooks' const INSTALL_LOCK = 'dsh-lefthook-install.lock' const INSTALL_LOCK_TIMEOUT_MS = 30_000 +const INSTALL_LOCK_INITIALIZATION_TIMEOUT_MS = 1_000 const INSTALL_LOCK_POLL_MS = 50 const ALLOW_HOOKS_PATH_OVERRIDE = 'DSH_LEFTHOOK_ALLOW_HOOKS_PATH_OVERRIDE' const REPOSITORY_EXTENSION_PATTERN = '^extensions\\.' @@ -303,6 +315,11 @@ function parseInstallLock(record) { return Number.isSafeInteger(owner) ? owner : undefined } +function installLockRecordMayBeIncomplete(record) { + // Exclusive creation exposes the inode before its owner record is fully written. + return record === '' || (!record.endsWith('\n') && /^[1-9]\d*(?: [0-9a-f-]*)?$/i.test(record)) +} + function lockOwnerIsAlive(owner) { try { process.kill(owner, 0) @@ -351,11 +368,29 @@ async function acquireInstallLock(commonDirectory) { const lockPath = join(commonDirectory, INSTALL_LOCK) const deadline = Date.now() + INSTALL_LOCK_TIMEOUT_MS const ownedRecord = `${String(process.pid)} ${randomUUID()}\n` + let initializingLock while (true) { try { - writeFileSync(lockPath, ownedRecord, { flag: 'wx', mode: 0o600 }) - const ownedStat = installLockStat(lockPath) - if (ownedStat === undefined || !ownedStat.isFile() || ownedStat.isSymbolicLink()) { + const lockHandle = openSync(lockPath, 'wx', 0o600) + let ownedStat + try { + ownedStat = fstatSync(lockHandle) + const writeDelay = Number(process.env.DSH_TEST_LEFTHOOK_LOCK_WRITE_DELAY_MS ?? 0) + if (writeDelay > 0) { + await new Promise(resolveWait => setTimeout(resolveWait, writeDelay)) + } + writeFileSync(lockHandle, ownedRecord) + } finally { + closeSync(lockHandle) + } + const publishedStat = installLockStat(lockPath) + if ( + publishedStat === undefined + || !publishedStat.isFile() + || publishedStat.isSymbolicLink() + || publishedStat.dev !== ownedStat.dev + || publishedStat.ino !== ownedStat.ino + ) { throw lockOwnershipChangedError(lockPath) } return () => releaseInstallLock(lockPath, ownedRecord, ownedStat) @@ -368,8 +403,36 @@ async function acquireInstallLock(commonDirectory) { } const existingRecord = readInstallLock(lockPath) if (existingRecord === undefined) continue + const verifiedStat = installLockStat(lockPath) + if (verifiedStat === undefined) continue + if (!verifiedStat.isFile() || verifiedStat.isSymbolicLink()) { + throw manualLockRecoveryError(lockPath, 'invalid') + } + if (verifiedStat.dev !== existingStat.dev || verifiedStat.ino !== existingStat.ino) continue const owner = parseInstallLock(existingRecord) - if (owner === undefined) throw manualLockRecoveryError(lockPath, 'invalid') + if (owner === undefined) { + if (!installLockRecordMayBeIncomplete(existingRecord)) { + throw manualLockRecoveryError(lockPath, 'invalid') + } + const now = Date.now() + if ( + initializingLock === undefined + || initializingLock.dev !== existingStat.dev + || initializingLock.ino !== existingStat.ino + ) { + initializingLock = { + deadline: now + INSTALL_LOCK_INITIALIZATION_TIMEOUT_MS, + dev: existingStat.dev, + ino: existingStat.ino, + } + } + if (now >= initializingLock.deadline) { + throw manualLockRecoveryError(lockPath, 'invalid') + } + await new Promise(resolveWait => setTimeout(resolveWait, INSTALL_LOCK_POLL_MS)) + continue + } + initializingLock = undefined if (!lockOwnerIsAlive(owner)) throw manualLockRecoveryError(lockPath, 'stale') if (Date.now() >= deadline) { throw new Error(`timed out waiting for Lefthook installer lock ${lockPath}`) diff --git a/scripts/install-lefthook.spec.ts b/scripts/install-lefthook.spec.ts index e38a958410..d76c16bba5 100644 --- a/scripts/install-lefthook.spec.ts +++ b/scripts/install-lefthook.spec.ts @@ -307,6 +307,22 @@ describe('worktree-local Lefthook installer', () => { expect(existsSync(join(hooksPath(fixture, fixture.main), '.fake-lefthook-running'))).toBe(false) }, 15_000) + it('waits for a concurrent installer to finish publishing its lock record', async () => { + const fixture = createFixture() + const lockPath = installLockPath(fixture) + const publishing = runInstaller(fixture, fixture.main, { + DSH_TEST_LEFTHOOK_LOCK_WRITE_DELAY_MS: '200', + }) + await waitForPath(lockPath) + expect(readFileSync(lockPath, 'utf8')).toBe('') + + const waiting = runInstaller(fixture, fixture.linked) + const results = await Promise.all([publishing, waiting]) + + for (const result of results) expect(result.status, result.stderr).toBe(0) + expect(existsSync(lockPath)).toBe(false) + }) + it('repairs its owned absolute hook path after the checkout moves', async () => { const fixture = createFixture() const oldRoot = fixture.main From e9cbfa153afd8e664b331b8fabe2fddf945cc455 Mon Sep 17 00:00:00 2001 From: NI0317 Date: Fri, 31 Jul 2026 11:18:49 +0800 Subject: [PATCH 097/139] docs: address README review --- .../2026-07-22-product-first-root-readme.i18n.yaml | 4 ++-- .../process/2026-07-22-product-first-root-readme.md | 2 +- .../process/2026-07-22-product-first-root-readme.zh.md | 2 +- README.i18n.yaml | 4 ++-- README.md | 10 +++++----- README.zh.md | 8 ++++---- .../request-response.expected.json | 4 ++-- 7 files changed, 17 insertions(+), 17 deletions(-) diff --git a/.agents/notes/implemented/process/2026-07-22-product-first-root-readme.i18n.yaml b/.agents/notes/implemented/process/2026-07-22-product-first-root-readme.i18n.yaml index b38df9878c..70c5ce5a90 100644 --- a/.agents/notes/implemented/process/2026-07-22-product-first-root-readme.i18n.yaml +++ b/.agents/notes/implemented/process/2026-07-22-product-first-root-readme.i18n.yaml @@ -2,5 +2,5 @@ # side as of the last confirmed-consistent state. Both languages carry equal authority; # after editing either side, bring the other along and re-record with: # pnpm run verify-translation-pairing --write .agents/notes/implemented/process/2026-07-22-product-first-root-readme.md -2026-07-22-product-first-root-readme.md: 34bee8210615f4c9b4a2a9389e6edd962850fdc5 -2026-07-22-product-first-root-readme.zh.md: be0c6189f5feef9b923f0081e224a7e042aef001 +2026-07-22-product-first-root-readme.md: 32542a45019d64ed1826d4eb21e68c67c3c3d52e +2026-07-22-product-first-root-readme.zh.md: 1c4d5fa53854bfcade9742da1fb74d9636909f84 diff --git a/.agents/notes/implemented/process/2026-07-22-product-first-root-readme.md b/.agents/notes/implemented/process/2026-07-22-product-first-root-readme.md index 34bee82106..32542a4501 100644 --- a/.agents/notes/implemented/process/2026-07-22-product-first-root-readme.md +++ b/.agents/notes/implemented/process/2026-07-22-product-first-root-readme.md @@ -14,7 +14,7 @@ The root README preserves its existing structure, order, and wording wherever th A note before installation thanks internal testers, states that features and experience remain unfinished, and asks for direct reports of failures, confusion, and friction through the WeCom group. The existing development-stage statement identifies DeepSeek Harness as being in internal testing. -The user-surface section adds the ACP automation server and Python/JSON-RPC SDK beside the existing Web, TUI, and headless entries. The installed TUI remains the single `dsh` command after real PTY validation; the Web instructions build the default active checkout once and then run `dsh web`, matching a production build and HTTP smoke. The capability paragraph keeps its compact inventory style while adding the shipped PTY, LSP, web, goal, planning, task, sandbox, approval, session-query, and telemetry families and stating that compositions select subsets. One adjacent bullet records the authoritative-session-log rule because persistence, replay, queries, telemetry, and interfaces depend on it. +The user-surface section adds the ACP automation server and Python/JSON-RPC SDK beside the existing Web, TUI, and headless entries. The installed TUI remains the single `dsh` command; the Web instructions build the active checkout before running `dsh web`, and custom or reused checkout paths stay explicit. These launch paths must remain executable through a real PTY and a production build/HTTP smoke, respectively. The capability paragraph keeps its compact inventory style while adding the shipped PTY, LSP, web, goal, planning, task, sandbox, approval, settings, credentials, session-query, and telemetry families and stating that compositions select subsets. One adjacent bullet records the authoritative-session-log rule because persistence, replay, queries, telemetry, and interfaces depend on it. Detailed package and service inventories remain at their owning documentation. The English and Chinese README sides share the same technical structure, while their community sections continue to point to the primary channel for each language audience. The documentation website keeps its separate user-guide landing page. diff --git a/.agents/notes/implemented/process/2026-07-22-product-first-root-readme.zh.md b/.agents/notes/implemented/process/2026-07-22-product-first-root-readme.zh.md index be0c6189f5..1c4d5fa538 100644 --- a/.agents/notes/implemented/process/2026-07-22-product-first-root-readme.zh.md +++ b/.agents/notes/implemented/process/2026-07-22-product-first-root-readme.zh.md @@ -14,7 +14,7 @@ Status: implemented 安装说明之前的一则文字感谢内测用户,说明功能和体验仍待完善,并邀请大家通过企业微信群直接反馈失败、困惑和不顺手之处。既有的开发阶段声明明确说明 DeepSeek Harness 处于内测阶段。 -用户入口章节在已有的 Web、TUI 和 Headless 入口旁补充 ACP(Agent Client Protocol)自动化服务器和 Python/JSON-RPC SDK。经真实 PTY 验证,安装后的 TUI 仍只需执行一条 `dsh` 命令;Web 说明要求先构建一次默认活动检出,然后运行 `dsh web`,该路径已经过生产构建与 HTTP 冒烟验证。能力段落沿用简洁清单的写法,补充已经交付的 PTY、LSP、Web、目标、规划、任务、沙箱、审批、会话查询和遥测等能力类别,并说明不同组合只选用其中一部分。相邻的一条列表项说明权威会话日志规则,因为持久化、回放、查询、遥测和各类接口都依赖它。 +用户入口章节在已有的 Web、TUI 和 Headless 入口旁补充 ACP(Agent Client Protocol)自动化服务器和 Python/JSON-RPC SDK。安装后的 TUI 仍只需执行一条 `dsh` 命令;Web 说明要求先构建当前检出,再运行 `dsh web`,并明确处理自定义或复用的检出路径。这两条启动路径必须分别能在真实 PTY 与生产构建/HTTP 冒烟中原样执行。能力段落沿用简洁清单的写法,补充已经交付的 PTY、LSP、Web、目标、规划、任务、沙箱、审批、设置、凭据、会话查询和遥测等能力类别,并说明不同组合只选用其中一部分。相邻的一条列表项说明权威会话日志规则,因为持久化、回放、查询、遥测和各类接口都依赖它。 包(package)与服务的完整清单仍由各自的归属文档维护。中英文 README 采用相同的技术结构,但社区章节仍分别指向各自语言受众的主要交流渠道。文档网站继续使用独立的用户指南首页。 diff --git a/README.i18n.yaml b/README.i18n.yaml index 1575c6d5d3..66400262db 100644 --- a/README.i18n.yaml +++ b/README.i18n.yaml @@ -2,5 +2,5 @@ # side as of the last confirmed-consistent state. Both languages carry equal authority; # after editing either side, bring the other along and re-record with: # pnpm run verify-translation-pairing --write README.md -README.md: c89a7bad2b06a1d9aeaf74b9450c6362f8fbeb6b -README.zh.md: 85156ca3f6b40801da0f773601301f8cfe3d9c65 +README.md: baf5d79b157ae845cc837261452853afd48dbe46 +README.zh.md: 57d7bcf44cda36b37ae233754dbfba4ead2204fd diff --git a/README.md b/README.md index c89a7bad2b..baf5d79b15 100644 --- a/README.md +++ b/README.md @@ -14,7 +14,7 @@ This version is still in internal testing. Some features remain unfinished, and “As one cuts and files, as one carves and polishes.” Products grow through repeated encounters with real use and candid feedback. The problems you uncover in practice may lead us to re-examine, or even discard, existing designs. -We especially want to hear about moments of failure, confusion, or friction. If DeepSeek Harness does not help—or instead makes your work harder—please leave a message in our WeCom group and tell us about your experience. Every report will help us refine it. +We especially want to hear about moments of failure, confusion, or friction. If DeepSeek Harness does not help—or instead makes your work harder—please leave a message in our WeCom group and tell us about your experience. Every report will help us refine it. ## Install @@ -39,7 +39,7 @@ For the recommended local interface, build the active checkout after installatio dsh web ``` -The build path above is the installer's default; see [`scripts/install.sh`](scripts/install.sh) for alternate locations. The Web UI is served at `http://127.0.0.1:3080` by default. +The full build produces the library and client bundles plus the frontend dist. The path above is the installer's default. If you set `DSH_SOURCE` or `DSH_CURRENT`, or reused an existing checkout, replace `~/.dsh/source/current` with that checkout path; see [`scripts/install.sh`](scripts/install.sh) for details. The Web UI is served at `http://127.0.0.1:3080` by default. ### TUI @@ -59,17 +59,17 @@ dsh -p "summarize this workspace" ### Automation and SDKs -From a source checkout, start the ACP automation server: +From a source checkout with `DEEPSEEK_API_KEY` in the environment or its root `.env`, start the ACP automation server: ```sh pnpm run demo:acp ``` -The [Python SDK](python/README.md) drives a bundled JSON-RPC runtime. The [examples](examples/README.md) cover the runnable TUI, headless, ACP, JSON-RPC, Code Mode, and self-referential compositions. +The [Python SDK](python/README.md) drives a bundled JSON-RPC runtime. The [examples](examples/README.md) cover the runnable headless, ACP, JSON-RPC, Code Mode, and self-referential compositions. ## Why DeepSeek Harness -Built-in capabilities cover file reading, editing, and search; shell and persistent PTY execution; reusable skills; task tracking, goals, plans, todos, and background tasks; subagents and workflows; sandboxing and approvals; persistent, resumable, forkable, and queryable sessions; LSP and web access; context compaction; and telemetry. Each composition selects the subset appropriate to its surface. The TUI also includes Plan Mode. +Built-in capabilities cover file reading, editing, and search; shell and persistent PTY execution; reusable skills; task tracking, goals, plans, todos, and background tasks; subagents and workflows; sandboxing and approvals; settings and credentials; persistent, resumable, forkable, and queryable sessions; LSP and web access; context compaction; and telemetry. Each composition selects the subset appropriate to its surface. The TUI and Web UI both include Plan Mode. - **Everything is a plugin.** Models, tools, policies, storage, context management, and interfaces are composable [Cordis plugins](docs/user/develop/basic/index.md), so deployments can extend or replace behavior without forking the agent loop. See the [architecture](docs/architecture.md) for the underlying design. - **Runs are reconstructable.** Anything visible to the model is logged in the authoritative session stream; persistence, resume/fork/query, replay, telemetry, and UIs derive from the same events. See the [session-log architecture](docs/architecture.md#session-log). diff --git a/README.zh.md b/README.zh.md index 85156ca3f6..57d7bcf44c 100644 --- a/README.zh.md +++ b/README.zh.md @@ -39,7 +39,7 @@ curl -fsSL https://raw.githubusercontent.com/deepseek-harness/deepseek-harness/m dsh web ``` -上述构建路径使用安装器的默认安装位置;如需使用其他位置,请参阅 [`scripts/install.sh`](scripts/install.sh)。Web UI 默认通过 `http://127.0.0.1:3080` 提供服务。 +完整构建会生成库与客户端 bundle,以及前端 dist。上述路径是安装器的默认位置。如果你设置过 `DSH_SOURCE` 或 `DSH_CURRENT`,或者复用了已有检出,请把 `~/.dsh/source/current` 换成该检出路径;详情见 [`scripts/install.sh`](scripts/install.sh)。Web UI 默认通过 `http://127.0.0.1:3080` 提供服务。 ### TUI @@ -59,17 +59,17 @@ dsh -p "summarize this workspace" ### 自动化与 SDK -从源码检出中启动 ACP(Agent Client Protocol)自动化服务器: +在源码检出中通过环境变量或根目录 `.env` 设置 `DEEPSEEK_API_KEY`,然后启动 ACP(Agent Client Protocol)自动化服务器: ```sh pnpm run demo:acp ``` -[Python SDK](python/README.md) 驱动随附的 JSON-RPC 运行时。[示例](examples/README.md)涵盖可运行的 TUI、headless、ACP、JSON-RPC、Code Mode 和自指组合。 +[Python SDK](python/README.md) 驱动随附的 JSON-RPC 运行时。[示例](examples/README.md)涵盖可运行的 headless、ACP、JSON-RPC、Code Mode 和自指组合。 ## 为什么选择 DeepSeek Harness -内置功能涵盖文件读取、编辑与搜索、shell 和持久 PTY 执行、可复用 skill(技能)、任务跟踪、目标、计划、待办事项与后台任务、subagent 与工作流、沙箱与审批、可持久化、恢复、fork 与查询的会话、LSP 与 Web 访问、上下文压缩(context compaction),以及遥测。每个组合只选用适合其使用方式的能力子集。TUI 还包含 Plan Mode。 +内置功能涵盖文件读取、编辑与搜索、shell 和持久 PTY 执行、可复用 skill(技能)、任务跟踪、目标、计划、待办事项与后台任务、subagent 与工作流、沙箱与审批、设置与凭据、可持久化、恢复、fork 与查询的会话、LSP 与 Web 访问、上下文压缩(context compaction),以及遥测。每个组合只选用适合其使用方式的能力子集。TUI 与 Web UI 均包含 Plan Mode。 - **一切皆插件。** 模型、工具、策略、存储、上下文管理和界面均可组合为 [Cordis 插件](docs/user/develop/basic/index.md),部署方无需 fork agent loop(智能体循环)即可扩展或替换行为。底层设计见[架构文档](docs/architecture.md)。 - **运行可重建。** 凡是模型可见的内容,都会记录在权威会话流中;持久化、恢复/fork/查询、回放、遥测和 UI 均从同一组事件派生。参见[会话日志架构](docs/architecture.md#session-log)。 diff --git a/scripts/snapshots/translation-prompt-v4/request-response.expected.json b/scripts/snapshots/translation-prompt-v4/request-response.expected.json index fc61f9d6bc..1cc80d9286 100644 --- a/scripts/snapshots/translation-prompt-v4/request-response.expected.json +++ b/scripts/snapshots/translation-prompt-v4/request-response.expected.json @@ -8,11 +8,11 @@ }, { "role": "user", - "content": "# DeepSeek Harness\n\nEnglish | [中文](README.zh.md)\n\nDeepSeek Harness (`dsh`) is an open-source coding agent built on the DeepSeek Harness SDK.\n\nIt uses an architecture where **everything is a plugin**.\n\n## Internal testing notice\n\nThank you for making time to try DeepSeek Harness.\n\nThis version is still in internal testing. Some features remain unfinished, and parts of the experience may feel rough.\n\n“As one cuts and files, as one carves and polishes.” Products grow through repeated encounters with real use and candid feedback. The problems you uncover in practice may lead us to re-examine, or even discard, existing designs.\n\nWe especially want to hear about moments of failure, confusion, or friction. If DeepSeek Harness does not help—or instead makes your work harder—please leave a message in our WeCom group and tell us about your experience. Every report will help us refine it.\n\n## Install\n\nInstall `dsh` with one command:\n\n```sh\ncurl -fsSL https://raw.githubusercontent.com/deepseek-harness/deepseek-harness/master/scripts/install.sh | sh\n```\n\nThe installer requires `git` and Node `^22.19 || >=24`, offers to install `pnpm` when it is missing, and prompts for a DeepSeek API key.\n\nThe installer keeps every checkout under `~/.dsh/source`: the master clone at `~/.dsh/source/master` and each install's staging checkout as a git worktree `~/.dsh/source/staging-`. The stable symlink `~/.dsh/source/current` points at the active staging worktree, and `dsh` in `~/.local/bin` links to `current/bin/dsh`, so an upgrade repoints one symlink and the `dsh` on PATH never moves. Re-running the command adds a fresh staging worktree from an updated master and repoints `current` at it. See [`scripts/install.sh`](scripts/install.sh) for alternate install locations and other options.\n\n## Use DeepSeek Harness\n\n### Web UI\n\nFor the recommended local interface, build the active checkout after installation and after each update, then start the Web UI:\n\n```sh\n(cd ~/.dsh/source/current && pnpm run build)\ndsh web\n```\n\nThe build path above is the installer's default; see [`scripts/install.sh`](scripts/install.sh) for alternate locations. The Web UI is served at `http://127.0.0.1:3080` by default.\n\n### TUI\n\nStart the full-screen terminal interface:\n\n```sh\ndsh\n```\n\n### Headless\n\nRun one task, print the final answer, and exit:\n\n```sh\ndsh -p \"summarize this workspace\"\n```\n\n### Automation and SDKs\n\nFrom a source checkout, start the ACP automation server:\n\n```sh\npnpm run demo:acp\n```\n\nThe [Python SDK](python/README.md) drives a bundled JSON-RPC runtime. The [examples](examples/README.md) cover the runnable TUI, headless, ACP, JSON-RPC, Code Mode, and self-referential compositions.\n\n## Why DeepSeek Harness\n\nBuilt-in capabilities cover file reading, editing, and search; shell and persistent PTY execution; reusable skills; task tracking, goals, plans, todos, and background tasks; subagents and workflows; sandboxing and approvals; persistent, resumable, forkable, and queryable sessions; LSP and web access; context compaction; and telemetry. Each composition selects the subset appropriate to its surface. The TUI also includes Plan Mode.\n\n- **Everything is a plugin.** Models, tools, policies, storage, context management, and interfaces are composable [Cordis plugins](docs/user/develop/basic/index.md), so deployments can extend or replace behavior without forking the agent loop. See the [architecture](docs/architecture.md) for the underlying design.\n- **Runs are reconstructable.** Anything visible to the model is logged in the authoritative session stream; persistence, resume/fork/query, replay, telemetry, and UIs derive from the same events. See the [session-log architecture](docs/architecture.md#session-log).\n- **Code Mode (opt-in).** It exposes a `run_code` tool and a generated TypeScript SDK; only program output re-enters model context. See [Code Mode](packages/core/tools/README.md#code-mode).\n- **Self-referential Cordis tools are opt-in.** They let the agent inspect its live runtime and mount or unmount plugins while it runs. See the [Cordis tools](packages/cordis/tool-cordis/README.md).\n\n## Community\n\nFollow DeepSeek Harness on Twitter for project updates.\n\n## Development\n\n```sh\npnpm install\npnpm run test:coverage\n```\n\nStart with the [development guide](docs/development.md) and read the [architecture](docs/architecture.md) before changing packages.\n\nFor agents, follow [AGENTS.md](AGENTS.md).\n\nDeepSeek Harness is currently in internal testing.\n\n## License\n\n[BSD 3-Clause](LICENSE)\n" + "content": "# DeepSeek Harness\n\nEnglish | [中文](README.zh.md)\n\nDeepSeek Harness (`dsh`) is an open-source coding agent built on the DeepSeek Harness SDK.\n\nIt uses an architecture where **everything is a plugin**.\n\n## Internal testing notice\n\nThank you for making time to try DeepSeek Harness.\n\nThis version is still in internal testing. Some features remain unfinished, and parts of the experience may feel rough.\n\n“As one cuts and files, as one carves and polishes.” Products grow through repeated encounters with real use and candid feedback. The problems you uncover in practice may lead us to re-examine, or even discard, existing designs.\n\nWe especially want to hear about moments of failure, confusion, or friction. If DeepSeek Harness does not help—or instead makes your work harder—please leave a message in our WeCom group and tell us about your experience. Every report will help us refine it.\n\n## Install\n\nInstall `dsh` with one command:\n\n```sh\ncurl -fsSL https://raw.githubusercontent.com/deepseek-harness/deepseek-harness/master/scripts/install.sh | sh\n```\n\nThe installer requires `git` and Node `^22.19 || >=24`, offers to install `pnpm` when it is missing, and prompts for a DeepSeek API key.\n\nThe installer keeps every checkout under `~/.dsh/source`: the master clone at `~/.dsh/source/master` and each install's staging checkout as a git worktree `~/.dsh/source/staging-`. The stable symlink `~/.dsh/source/current` points at the active staging worktree, and `dsh` in `~/.local/bin` links to `current/bin/dsh`, so an upgrade repoints one symlink and the `dsh` on PATH never moves. Re-running the command adds a fresh staging worktree from an updated master and repoints `current` at it. See [`scripts/install.sh`](scripts/install.sh) for alternate install locations and other options.\n\n## Use DeepSeek Harness\n\n### Web UI\n\nFor the recommended local interface, build the active checkout after installation and after each update, then start the Web UI:\n\n```sh\n(cd ~/.dsh/source/current && pnpm run build)\ndsh web\n```\n\nThe full build produces the library and client bundles plus the frontend dist. The path above is the installer's default. If you set `DSH_SOURCE` or `DSH_CURRENT`, or reused an existing checkout, replace `~/.dsh/source/current` with that checkout path; see [`scripts/install.sh`](scripts/install.sh) for details. The Web UI is served at `http://127.0.0.1:3080` by default.\n\n### TUI\n\nStart the full-screen terminal interface:\n\n```sh\ndsh\n```\n\n### Headless\n\nRun one task, print the final answer, and exit:\n\n```sh\ndsh -p \"summarize this workspace\"\n```\n\n### Automation and SDKs\n\nFrom a source checkout with `DEEPSEEK_API_KEY` in the environment or its root `.env`, start the ACP automation server:\n\n```sh\npnpm run demo:acp\n```\n\nThe [Python SDK](python/README.md) drives a bundled JSON-RPC runtime. The [examples](examples/README.md) cover the runnable headless, ACP, JSON-RPC, Code Mode, and self-referential compositions.\n\n## Why DeepSeek Harness\n\nBuilt-in capabilities cover file reading, editing, and search; shell and persistent PTY execution; reusable skills; task tracking, goals, plans, todos, and background tasks; subagents and workflows; sandboxing and approvals; settings and credentials; persistent, resumable, forkable, and queryable sessions; LSP and web access; context compaction; and telemetry. Each composition selects the subset appropriate to its surface. The TUI and Web UI both include Plan Mode.\n\n- **Everything is a plugin.** Models, tools, policies, storage, context management, and interfaces are composable [Cordis plugins](docs/user/develop/basic/index.md), so deployments can extend or replace behavior without forking the agent loop. See the [architecture](docs/architecture.md) for the underlying design.\n- **Runs are reconstructable.** Anything visible to the model is logged in the authoritative session stream; persistence, resume/fork/query, replay, telemetry, and UIs derive from the same events. See the [session-log architecture](docs/architecture.md#session-log).\n- **Code Mode (opt-in).** It exposes a `run_code` tool and a generated TypeScript SDK; only program output re-enters model context. See [Code Mode](packages/core/tools/README.md#code-mode).\n- **Self-referential Cordis tools are opt-in.** They let the agent inspect its live runtime and mount or unmount plugins while it runs. See the [Cordis tools](packages/cordis/tool-cordis/README.md).\n\n## Community\n\nFollow DeepSeek Harness on Twitter for project updates.\n\n## Development\n\n```sh\npnpm install\npnpm run test:coverage\n```\n\nStart with the [development guide](docs/development.md) and read the [architecture](docs/architecture.md) before changing packages.\n\nFor agents, follow [AGENTS.md](AGENTS.md).\n\nDeepSeek Harness is currently in internal testing.\n\n## License\n\n[BSD 3-Clause](LICENSE)\n" }, { "role": "assistant", - "content": "# DeepSeek Harness\n\n[English](README.md) | 中文\n\nDeepSeek Harness(`dsh`)是一款基于 DeepSeek Harness SDK 构建的开源 coding agent(编程智能体)。\n\n它采用了**一切皆插件**的架构。\n\n## 内测声明\n\n感谢您愿意拨冗试用 DeepSeek Harness。\n\n目前的版本仍处于内部测试阶段,有些功能仍待完善,有些体验难免粗粝。\n\n“如切如磋,如琢如磨。”产品的成长,离不开一次次真实的碰撞与坦诚的反馈。您在真实使用中暴露的问题,也可能促使我们重新审视,甚至推翻已有的设计。\n\n我们尤其希望听见那些失败、困惑与不顺手的时刻——如果它未能帮到您,甚至反而为工作平添了麻烦,请在企业微信群中留言,将使用感受告诉我们。每一条反馈,都会帮助我们把它打磨得更好。\n\n## 安装\n\n使用一条命令安装 `dsh`:\n\n```sh\ncurl -fsSL https://raw.githubusercontent.com/deepseek-harness/deepseek-harness/master/scripts/install.sh | sh\n```\n\n安装器要求系统已安装 `git` 和 Node `^22.19 || >=24`,缺少 `pnpm` 时可代为安装,并会提示输入 DeepSeek API 密钥。\n\n安装器会把所有检出都放在 `~/.dsh/source` 下:master 克隆位于 `~/.dsh/source/master`,每次安装的 staging 检出是一个 git worktree `~/.dsh/source/staging-<时间戳>`。稳定符号链接 `~/.dsh/source/current` 指向当前生效的 staging worktree,`~/.local/bin` 中的 `dsh` 链接到 `current/bin/dsh`,因此升级只需重指一个符号链接,PATH 上的 `dsh` 从不移动。再次运行该命令会基于更新后的 master 新增一个 staging worktree,并把 `current` 重指到它。其他安装位置和选项见 [`scripts/install.sh`](scripts/install.sh)。\n\n## 使用 DeepSeek Harness\n\n### Web UI\n\n推荐在本地使用 Web UI。安装完成后以及每次更新后,请先构建当前生效的检出,再启动 Web UI:\n\n```sh\n(cd ~/.dsh/source/current && pnpm run build)\ndsh web\n```\n\n上述构建路径使用安装器的默认安装位置;如需使用其他位置,请参阅 [`scripts/install.sh`](scripts/install.sh)。Web UI 默认通过 `http://127.0.0.1:3080` 提供服务。\n\n### TUI\n\n启动全屏终端界面:\n\n```sh\ndsh\n```\n\n### Headless\n\n运行一项任务,打印最终答案后退出:\n\n```sh\ndsh -p \"summarize this workspace\"\n```\n\n### 自动化与 SDK\n\n从源码检出中启动 ACP(Agent Client Protocol)自动化服务器:\n\n```sh\npnpm run demo:acp\n```\n\n[Python SDK](python/README.md) 驱动随附的 JSON-RPC 运行时。[示例](examples/README.md)涵盖可运行的 TUI、headless、ACP、JSON-RPC、Code Mode 和自指组合。\n\n## 为什么选择 DeepSeek Harness\n\n内置功能涵盖文件读取、编辑与搜索、shell 和持久 PTY 执行、可复用 skill(技能)、任务跟踪、目标、计划、待办事项与后台任务、subagent 与工作流、沙箱与审批、可持久化、恢复、fork 与查询的会话、LSP 与 Web 访问、上下文压缩(context compaction),以及遥测。每个组合只选用适合其使用方式的能力子集。TUI 还包含 Plan Mode。\n\n- **一切皆插件。** 模型、工具、策略、存储、上下文管理和界面均可组合为 [Cordis 插件](docs/user/develop/basic/index.md),部署方无需 fork agent loop(智能体循环)即可扩展或替换行为。底层设计见[架构文档](docs/architecture.md)。\n- **运行可重建。** 凡是模型可见的内容,都会记录在权威会话流中;持久化、恢复/fork/查询、回放、遥测和 UI 均从同一组事件派生。参见[会话日志架构](docs/architecture.md#session-log)。\n- **Code Mode(需显式启用)。** 它会提供 `run_code` 工具和生成的 TypeScript SDK,只有程序输出会重新进入模型上下文。参见 [Code Mode](packages/core/tools/README.md#code-mode)。\n- **自指 Cordis 工具需显式启用。** 这些工具可让 agent 检查自身的实时运行时,并在运行中挂载或卸载插件。参见 [Cordis 工具](packages/cordis/tool-cordis/README.md)。\n\n## 社区\n\n扫描二维码,或打开 DeepSeek Harness 微信社区申请页面 申请加入。\n\n

                      \n \"DeepSeek\n

                      \n\n## 开发\n\n```sh\npnpm install\npnpm run test:coverage\n```\n\n请先阅读[开发指南](docs/development.md);修改包之前,请阅读[架构文档](docs/architecture.md)。\n\n面向 agent:遵循 [AGENTS.md](AGENTS.md)。\n\nDeepSeek Harness 目前处于内测阶段。\n\n## 许可证\n\n[BSD 3-Clause](LICENSE)\n" + "content": "# DeepSeek Harness\n\n[English](README.md) | 中文\n\nDeepSeek Harness(`dsh`)是一款基于 DeepSeek Harness SDK 构建的开源 coding agent(编程智能体)。\n\n它采用了**一切皆插件**的架构。\n\n## 内测声明\n\n感谢您愿意拨冗试用 DeepSeek Harness。\n\n目前的版本仍处于内部测试阶段,有些功能仍待完善,有些体验难免粗粝。\n\n“如切如磋,如琢如磨。”产品的成长,离不开一次次真实的碰撞与坦诚的反馈。您在真实使用中暴露的问题,也可能促使我们重新审视,甚至推翻已有的设计。\n\n我们尤其希望听见那些失败、困惑与不顺手的时刻——如果它未能帮到您,甚至反而为工作平添了麻烦,请在企业微信群中留言,将使用感受告诉我们。每一条反馈,都会帮助我们把它打磨得更好。\n\n## 安装\n\n使用一条命令安装 `dsh`:\n\n```sh\ncurl -fsSL https://raw.githubusercontent.com/deepseek-harness/deepseek-harness/master/scripts/install.sh | sh\n```\n\n安装器要求系统已安装 `git` 和 Node `^22.19 || >=24`,缺少 `pnpm` 时可代为安装,并会提示输入 DeepSeek API 密钥。\n\n安装器会把所有检出都放在 `~/.dsh/source` 下:master 克隆位于 `~/.dsh/source/master`,每次安装的 staging 检出是一个 git worktree `~/.dsh/source/staging-<时间戳>`。稳定符号链接 `~/.dsh/source/current` 指向当前生效的 staging worktree,`~/.local/bin` 中的 `dsh` 链接到 `current/bin/dsh`,因此升级只需重指一个符号链接,PATH 上的 `dsh` 从不移动。再次运行该命令会基于更新后的 master 新增一个 staging worktree,并把 `current` 重指到它。其他安装位置和选项见 [`scripts/install.sh`](scripts/install.sh)。\n\n## 使用 DeepSeek Harness\n\n### Web UI\n\n推荐在本地使用 Web UI。安装完成后以及每次更新后,请先构建当前生效的检出,再启动 Web UI:\n\n```sh\n(cd ~/.dsh/source/current && pnpm run build)\ndsh web\n```\n\n完整构建会生成库与客户端 bundle,以及前端 dist。上述路径是安装器的默认位置。如果你设置过 `DSH_SOURCE` 或 `DSH_CURRENT`,或者复用了已有检出,请把 `~/.dsh/source/current` 换成该检出路径;详情见 [`scripts/install.sh`](scripts/install.sh)。Web UI 默认通过 `http://127.0.0.1:3080` 提供服务。\n\n### TUI\n\n启动全屏终端界面:\n\n```sh\ndsh\n```\n\n### Headless\n\n运行一项任务,打印最终答案后退出:\n\n```sh\ndsh -p \"summarize this workspace\"\n```\n\n### 自动化与 SDK\n\n在源码检出中通过环境变量或根目录 `.env` 设置 `DEEPSEEK_API_KEY`,然后启动 ACP(Agent Client Protocol)自动化服务器:\n\n```sh\npnpm run demo:acp\n```\n\n[Python SDK](python/README.md) 驱动随附的 JSON-RPC 运行时。[示例](examples/README.md)涵盖可运行的 headless、ACP、JSON-RPC、Code Mode 和自指组合。\n\n## 为什么选择 DeepSeek Harness\n\n内置功能涵盖文件读取、编辑与搜索、shell 和持久 PTY 执行、可复用 skill(技能)、任务跟踪、目标、计划、待办事项与后台任务、subagent 与工作流、沙箱与审批、设置与凭据、可持久化、恢复、fork 与查询的会话、LSP 与 Web 访问、上下文压缩(context compaction),以及遥测。每个组合只选用适合其使用方式的能力子集。TUI 与 Web UI 均包含 Plan Mode。\n\n- **一切皆插件。** 模型、工具、策略、存储、上下文管理和界面均可组合为 [Cordis 插件](docs/user/develop/basic/index.md),部署方无需 fork agent loop(智能体循环)即可扩展或替换行为。底层设计见[架构文档](docs/architecture.md)。\n- **运行可重建。** 凡是模型可见的内容,都会记录在权威会话流中;持久化、恢复/fork/查询、回放、遥测和 UI 均从同一组事件派生。参见[会话日志架构](docs/architecture.md#session-log)。\n- **Code Mode(需显式启用)。** 它会提供 `run_code` 工具和生成的 TypeScript SDK,只有程序输出会重新进入模型上下文。参见 [Code Mode](packages/core/tools/README.md#code-mode)。\n- **自指 Cordis 工具需显式启用。** 这些工具可让 agent 检查自身的实时运行时,并在运行中挂载或卸载插件。参见 [Cordis 工具](packages/cordis/tool-cordis/README.md)。\n\n## 社区\n\n扫描二维码,或打开 DeepSeek Harness 微信社区申请页面 申请加入。\n\n

                      \n \"DeepSeek\n

                      \n\n## 开发\n\n```sh\npnpm install\npnpm run test:coverage\n```\n\n请先阅读[开发指南](docs/development.md);修改包之前,请阅读[架构文档](docs/architecture.md)。\n\n面向 agent:遵循 [AGENTS.md](AGENTS.md)。\n\nDeepSeek Harness 目前处于内测阶段。\n\n## 许可证\n\n[BSD 3-Clause](LICENSE)\n" }, { "role": "user", From c955c9adb1f12e0045b6fe33a266facc71380c41 Mon Sep 17 00:00:00 2001 From: NI0317 Date: Fri, 31 Jul 2026 11:27:01 +0800 Subject: [PATCH 098/139] fix(web): align the credential onboarding page --- .../missing.expected.md | 1 - .../DeepSeekOnboardingDialog.module.css | 67 ++++++------------- .../src/client/DeepSeekOnboardingDialog.tsx | 4 -- 3 files changed, 19 insertions(+), 53 deletions(-) diff --git a/apps/web/tests/snapshots/onboarding-deepseek-config/missing.expected.md b/apps/web/tests/snapshots/onboarding-deepseek-config/missing.expected.md index 89f3e009f5..ed37b0fe4d 100644 --- a/apps/web/tests/snapshots/onboarding-deepseek-config/missing.expected.md +++ b/apps/web/tests/snapshots/onboarding-deepseek-config/missing.expected.md @@ -1,6 +1,5 @@ - region "添加一个 API Key 开始使用": - heading "添加一个 API Key 开始使用" [level=2] - paragraph: 配置 DeepSeek 官方模型,即可开始使用。 - - text: DeepSeek deepseek-official - button "稍后配置" - button "前往配置" diff --git a/packages/client/ui-models/src/client/DeepSeekOnboardingDialog.module.css b/packages/client/ui-models/src/client/DeepSeekOnboardingDialog.module.css index 4d72cc076b..031d92b198 100644 --- a/packages/client/ui-models/src/client/DeepSeekOnboardingDialog.module.css +++ b/packages/client/ui-models/src/client/DeepSeekOnboardingDialog.module.css @@ -1,68 +1,45 @@ .page { position: relative; z-index: 1; - width: min(640px, calc(100vw - 64px)); - max-height: 100vh; - padding: clamp(64px, 9vh, 108px) 0 40px; + display: flex; + flex-direction: column; + justify-content: center; + width: min(560px, calc(100vw - 64px)); + min-height: 100vh; + padding: 40px 0; box-sizing: border-box; - overflow-y: auto; color: var(--dsw-alias-label-primary); } .brand { display: flex; align-items: center; - margin-bottom: 42px; + margin-bottom: 36px; color: var(--dsw-alias-label-primary); } .title { - max-width: 620px; margin: 0; - font-size: clamp(30px, 4vw, 42px); - line-height: 1.15; + font-size: 32px; + line-height: 40px; font-weight: 600; - letter-spacing: -0.035em; + letter-spacing: -0.02em; outline: none; } .description { - max-width: 600px; - margin: 22px 0 0; - font-size: 17px; - line-height: 29px; - color: var(--dsw-alias-label-secondary); -} - -.provider { - display: flex; - align-items: center; - justify-content: space-between; - max-width: 600px; - margin-top: 36px; - padding: 18px 20px; - border: 1px solid var(--dsw-alias-border-l2); - border-radius: 16px; - background: var(--dsw-alias-bg-module-platform); -} - -.providerName { + margin: 16px 0 0; font-size: 16px; - line-height: 24px; - font-weight: 600; -} - -.providerRoute { - font-size: 13px; - line-height: 20px; - color: var(--dsw-alias-label-tertiary); + line-height: 28px; + color: var(--dsw-alias-label-secondary); } .actions { display: flex; align-items: center; + justify-content: flex-end; gap: 12px; - margin-top: 40px; + margin-top: 36px; } .primary { @@ -72,15 +49,13 @@ .brand, .title, .description, -.provider, .actions { animation: credential-enter 280ms cubic-bezier(0.23, 1, 0.32, 1) both; } .title { animation-delay: 40ms; } .description { animation-delay: 80ms; } -.provider { animation-delay: 120ms; } -.actions { animation-delay: 160ms; } +.actions { animation-delay: 120ms; } @keyframes credential-enter { from { @@ -98,7 +73,6 @@ .brand, .title, .description, - .provider, .actions { animation: none; } @@ -107,21 +81,18 @@ @media (max-width: 560px) { .page { width: calc(100vw - 40px); - padding-top: 48px; + justify-content: flex-start; + padding-top: 64px; } .brand { margin-bottom: 30px; } - .description { - font-size: 16px; - line-height: 27px; - } - .actions { align-items: stretch; flex-direction: column-reverse; + margin-top: 32px; } .primary, diff --git a/packages/client/ui-models/src/client/DeepSeekOnboardingDialog.tsx b/packages/client/ui-models/src/client/DeepSeekOnboardingDialog.tsx index 9ffcd24947..7ee67484bc 100644 --- a/packages/client/ui-models/src/client/DeepSeekOnboardingDialog.tsx +++ b/packages/client/ui-models/src/client/DeepSeekOnboardingDialog.tsx @@ -91,10 +91,6 @@ export function DeepSeekOnboardingDialog(props: DeepSeekOnboardingDialogProps): {t('onboardingTitle')}

                      {t('onboardingDescription')}

                      -
                      - DeepSeek - deepseek-official -