('[role="treeitem"]')
+ if (group === null) throw new Error('fixture Workspace group missing')
+ if (group.getAttribute('aria-expanded') === 'false') {
+ fireEvent.click(within(group).getByText('fixture'))
+ await waitFor(() => {
+ expect(within(tree).getByText('4 sessions').closest('[role="treeitem"]')?.getAttribute('aria-expanded')).toBe('true')
+ })
+ }
+ const session = await within(tree).findByText('Fixture 历史会话')
+ fireEvent.click(session)
+ await waitFor(() => {
+ expect(document.querySelector('[data-variant="code"]')).not.toBeNull()
+ }, { timeout: 10_000 })
+}
+
+it('renders the fixture run_code turn: code parent row, nested sub-rows, error state', async () => {
+ boot()
+ await openFixtureSession()
+
+ const codeRoot = document.querySelector('[data-variant="code"]')
+ if (codeRoot === null) throw new Error('code-variant row missing')
+ const nest = codeRoot.closest('[class*="callRow"]')?.querySelector('[data-subcalls]')
+ if (nest === undefined || nest === null) throw new Error('sub-call nest missing under the code row')
+
+ expect({
+ parentRow: visibleText(codeRoot),
+ // The three sub-rows in dispatch order: bash rides the sample plugin's
+ // keyed registration (the same one a native top-level bash row uses),
+ // both reads ride GenericToolCard.
+ bashSample: nest.querySelector('[data-sample="bash-global"]') !== null,
+ subRows: [...nest.querySelectorAll(':scope > *')].map(visibleText),
+ errorSubRow: nest.querySelector('[data-state="error"]') !== null,
+ }).toMatchInlineSnapshot(`
+ {
+ "bashSample": true,
+ "errorSubRow": true,
+ "parentRow": "CodeRead the notes files and summarize",
+ "subRows": [
+ "$List notes",
+ "Readnotes/demo.txt",
+ "Readnotes/missing.txt",
+ ],
+ }
+ `)
+})
+
+it('expands the code row into the program body and resolves a sub-row through the details panel', async () => {
+ boot()
+ await openFixtureSession()
+
+ // Expand: the leading control reveals the program (shiki-tokenized: the
+ // text splits into styled spans inside one tree).
+ const codeRoot = document.querySelector('[data-variant="code"]')
+ if (codeRoot === null) throw new Error('code-variant row missing')
+ const toggle = codeRoot.querySelector('button[aria-expanded]')
+ if (toggle === null) throw new Error('code row expand control missing')
+ fireEvent.click(toggle)
+ await waitFor(() => {
+ // Scope to THIS row: the markdown fixture turn also renders shiki pres.
+ const pre = codeRoot.querySelector('pre.shiki')
+ if (pre === null || !(pre.textContent ?? '').includes('const listing = await tools.bash')) {
+ throw new Error('highlighted program body missing under the code row')
+ }
+ })
+
+ // Sub-row click → details panel resolves the sub-callId with FULL output.
+ const nest = document.querySelector('[data-subcalls]')
+ if (nest === null) throw new Error('sub-call nest missing')
+ const bashRow = nest.querySelector('[data-sample="bash-global"]')
+ if (bashRow === null) throw new Error('bash sample sub-row missing')
+ fireEvent.click(bashRow)
+ const details = await screen.findByText('Input')
+ const panel = details.closest('[class*="root"]')
+ if (panel === null) throw new Error('details panel missing')
+ expect({
+ title: visibleText(within(panel as HTMLElement).getByText('bash')),
+ inputEchoesArgs: visibleText(panel).includes('ls notes'),
+ outputComplete: visibleText(panel).includes('demo.txt new-demo.txt')
+ || visibleText(panel).includes('demo.txt\nnew-demo.txt')
+ || (panel.textContent ?? '').includes('demo.txt\nnew-demo.txt'),
+ }).toMatchInlineSnapshot(`
+ {
+ "inputEchoesArgs": true,
+ "outputComplete": true,
+ "title": "bash",
+ }
+ `)
+})
+
+it('trajectory and waterfall surface the run_code sub-calls with real timing', async () => {
+ boot()
+ await openFixtureSession()
+
+ // Switch to the trajectory tab (same slot ring the chat view registers in).
+ fireEvent.click(await screen.findByRole('tab', { name: 'Trajectory' }))
+ await waitFor(() => {
+ expect(document.querySelector('[data-kind="subtool"]')).not.toBeNull()
+ }, { timeout: 10_000 })
+ const subCells = [...document.querySelectorAll('[data-kind="subtool"]')]
+ expect({
+ // Three Sub cells nested under the run_code Tool cell, in dispatch order,
+ // each with a real +N.Ns own-duration off the start/settle pair (the
+ // fixture spaces every event 800ms apart — never the em dash).
+ subCells: subCells.map(cell => visibleText(cell)),
+ }).toMatchInlineSnapshot(`
+ {
+ "subCells": [
+ "#53Subbash · {"command":"ls notes","description":"List notes"}+0.8s",
+ "#54Subread · {"path":"notes/demo.txt"}+0.8s",
+ "#55Subread · {"path":"notes/missing.txt"}+0.8s",
+ ],
+ }
+ `)
+
+ // Waterfall: each sub-call draws a measured lane scaled into the parent
+ // turn's dispatch window.
+ fireEvent.click(screen.getByRole('tab', { name: 'Waterfall' }))
+ await waitFor(() => {
+ expect(document.querySelector('[data-subspan]')).not.toBeNull()
+ }, { timeout: 10_000 })
+ const lanes = [...document.querySelectorAll('[data-subspan]')]
+ expect({
+ lanes: lanes.map(lane => ({
+ label: visibleText(lane.querySelector('[class*="subTag"]') ?? lane),
+ title: lane.querySelector('[data-timing]')?.getAttribute('title'),
+ timing: lane.querySelector('[data-timing]')?.getAttribute('data-timing'),
+ })),
+ }).toMatchInlineSnapshot(`
+ {
+ "lanes": [
+ {
+ "label": "bash",
+ "timing": "measured",
+ "title": "bash · 0.80s",
+ },
+ {
+ "label": "read",
+ "timing": "measured",
+ "title": "read · 0.80s",
+ },
+ {
+ "label": "read",
+ "timing": "measured",
+ "title": "read · 0.80s",
+ },
+ ],
+ }
+ `)
+})
diff --git a/apps/web/tests/code-mode-round.e2e.ts b/apps/web/tests/code-mode-round.e2e.ts
new file mode 100644
index 0000000000..32c51a2a2a
--- /dev/null
+++ b/apps/web/tests/code-mode-round.e2e.ts
@@ -0,0 +1,146 @@
+// Web e2e scenario: a Code Mode round trip. The scaffold boots the SAME
+// shipped tree with the tools row patched to mode: code (the run_code-only
+// wire), a real chromium sends a prompt engineered to elicit one run_code
+// program with several sub-calls, and the UI must render the code-variant
+// parent row with its always-visible nested sub-rows — each sub-row the same
+// component a native call renders through — plus details-panel resolution for
+// a clicked sub-row. Drive steps wait only on generic completion
+// (whenTurnSettled); assertion steps run in replay/refresh only.
+// Record: DSH_SNAPSHOT=record rewrites session.jsonl, then a keyless
+// DSH_SNAPSHOT=refresh regenerates ui.expected.md.
+import { readFile } from 'node:fs/promises'
+import { fileURLToPath } from 'node:url'
+import type { Browser, Page } from 'playwright'
+import { chromium } from 'playwright'
+import { afterAll, beforeAll, describe, expect, it, onTestFailed } from 'vitest'
+import type { SessionEvent } from '@deepseek-ai/dsh-session'
+import {
+ captureStableAria, compareOrRefreshGolden, fixtureUserPrompts,
+ launchWebScaffold, recordFixture, watchConsole, webSnapshotMode, type WebScaffold,
+} from './scaffold.ts'
+import { connectFreshWorkspace, saveFailureShot } from './support.ts'
+
+const FIXTURE = fileURLToPath(new URL('./snapshots/code-mode-round/session.jsonl', import.meta.url))
+const UI_EXPECTED = fileURLToPath(new URL('./snapshots/code-mode-round/ui.expected.md', import.meta.url))
+const MODE = webSnapshotMode()
+
+// The scenario's one drive prompt: elicits one program with a bash sub-call
+// and a failing read the program tolerates — the sub-row set the assertions
+// (and the PR gif) need. Never asserted against model prose.
+const PROMPT = 'Using ONE run_code program: run bash `echo CODE_ROUND_OK`, then read the file missing.txt '
+ + 'catching its error in the program. Return an object with both outcomes. Then reply DONE and stop.'
+
+describe('web e2e: Code Mode round renders nested sub-calls', () => {
+ let scaffold: WebScaffold
+ let browser: Browser
+ let page: Page
+ let tripwire: ReturnType
+ const sessionEvents: SessionEvent[] = []
+
+ beforeAll(async () => {
+ scaffold = await launchWebScaffold({
+ toolsMode: 'code',
+ ...(MODE === 'record' ? {} : { replayFixture: FIXTURE, paceMs: 15 }),
+ })
+ scaffold.ctx.on('session/event', (_session, event: SessionEvent) => { sessionEvents.push(event) })
+ browser = await chromium.launch()
+ 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 })
+ // Fresh world: connect a Workspace so the composer scenarios start live.
+ await connectFreshWorkspace(page)
+ }, 120_000)
+
+ afterAll(async () => {
+ await browser?.close()
+ await scaffold?.close()
+ })
+
+ it('drives the recorded prompt to a settled turn (all modes)', async () => {
+ onTestFailed(() => saveFailureShot(page, 'web-e2e-code-mode-drive'))
+ if (MODE !== 'record') {
+ // Drift guard: the committed fixture must carry exactly the drive prompt.
+ expect(fixtureUserPrompts(await readFile(FIXTURE, 'utf8'))).toEqual([PROMPT])
+ }
+ const input = page.locator('textarea').first()
+ await input.waitFor({ timeout: 10_000 })
+ const settled = scaffold.whenTurnSettled()
+ await input.fill(PROMPT)
+ await input.press('Enter')
+ const sessionId = await settled
+ if (MODE === 'record') {
+ await recordFixture(scaffold, sessionId, FIXTURE)
+ }
+ }, 200_000)
+
+ it.skipIf(MODE === 'record')('the durable log carries run_code with full-content sub-dispatches', () => {
+ // Wire discipline: code mode collapsed the call surface to run_code.
+ const calls = sessionEvents.filter(event => event.type === 'tool/call')
+ expect(calls.length).toBeGreaterThanOrEqual(1)
+ expect(new Set(calls.map(call => (call.data as { name: string }).name))).toEqual(new Set(['run_code']))
+ // Sub-dispatches logged with the complete tool/result vocabulary.
+ const dispatches = sessionEvents.filter(event => (event.type as string) === 'tool/code-dispatch')
+ expect(dispatches.length).toBeGreaterThanOrEqual(2)
+ for (const dispatch of dispatches) {
+ const data = dispatch.data as unknown as {
+ parentCallId: string
+ subCallId: string
+ name: string
+ isError: boolean
+ content: { type: string }[]
+ }
+ expect(data.subCallId.startsWith(`${data.parentCallId}:code:`)).toBe(true)
+ expect(Array.isArray(data.content)).toBe(true)
+ expect(typeof data.isError).toBe('boolean')
+ }
+ const bash = dispatches.find(dispatch => (dispatch.data as { name: string }).name === 'bash')
+ expect(bash).toBeDefined()
+ const bashContent = (bash!.data as { content: { type: string; text?: string }[] }).content
+ expect(bashContent.filter(block => block.type === 'text').map(block => block.text).join('')).toContain('CODE_ROUND_OK')
+ })
+
+ it.skipIf(MODE === 'record')('renders the code parent row with always-visible nested sub-rows', async () => {
+ onTestFailed(() => saveFailureShot(page, 'web-e2e-code-mode-rows'))
+ await expect.poll(() => page.getByText('DONE', { exact: true }).count(), { timeout: 15_000 }).toBeGreaterThanOrEqual(1)
+ // The parent run_code row wears the code variant with the model-authored
+ // description as its summary (the PR1 presentCall contract).
+ const codeRow = page.locator('[data-variant="code"]').first()
+ await codeRow.waitFor({ timeout: 10_000 })
+ // Nested rows are visible WITHOUT any expand interaction, inside the
+ // sub-call nest, each rendered by the same components as native rows:
+ // the bash sub-call landed in the bash sample registration.
+ const nest = page.locator('[data-subcalls]').first()
+ await nest.waitFor({ timeout: 10_000 })
+ expect(await nest.locator('[data-sample="bash-global"]').count()).toBeGreaterThanOrEqual(1)
+ // The failing read sub-call wears the same error state a native failed
+ // row wears (the recorded program tolerates a read of missing.txt).
+ expect(await nest.locator('[data-state="error"]').count()).toBeGreaterThanOrEqual(1)
+ }, 60_000)
+
+ it.skipIf(MODE === 'record')('a sub-row click opens the details panel on the sub-call material', async () => {
+ onTestFailed(() => saveFailureShot(page, 'web-e2e-code-mode-details'))
+ const nest = page.locator('[data-subcalls]').first()
+ await nest.locator('[data-sample="bash-global"]').first().click()
+ // The details column opens (width > 0) and shows the sub-call's complete
+ // output — the full-content log contract, no truncation marker anywhere.
+ await page.waitForFunction(() => {
+ const frame = document.querySelector('[class*="frame"]')
+ if (frame === null) return false
+ return Number(getComputedStyle(frame).gridTemplateColumns.split(' ').pop()!.replace('px', '')) > 0
+ }, undefined, { timeout: 10_000 })
+ await expect.poll(() => page.getByText('CODE_ROUND_OK', { exact: false }).count(), { timeout: 5_000 })
+ .toBeGreaterThanOrEqual(1)
+ })
+
+ it.skipIf(MODE === 'record')('matches the conversation aria golden with stable anchors', async () => {
+ onTestFailed(() => saveFailureShot(page, 'web-e2e-code-mode-aria'))
+ const snapshot = await captureStableAria(page, '[class*="centerCol"]', scaffold.workspaceCwd)
+ await compareOrRefreshGolden(UI_EXPECTED, snapshot, MODE)
+ })
+
+ it.skipIf(MODE === 'record')('stayed clean: no page errors, no reconnect churn', () => {
+ expect(tripwire.pageErrors).toEqual([])
+ expect(tripwire.warnings).toEqual([])
+ })
+})
diff --git a/apps/web/tests/lifecycle-chrome.e2e.ts b/apps/web/tests/lifecycle-chrome.e2e.ts
new file mode 100644
index 0000000000..4b54242495
--- /dev/null
+++ b/apps/web/tests/lifecycle-chrome.e2e.ts
@@ -0,0 +1,165 @@
+// Web e2e scenarios: lifecycle & chrome — the workspace-aware first-send
+// flow over the real wire, reload recovery, and the dark-mode token cascade.
+// One tiny recorded turn (text-only) drives the whole spec: the empty-state
+// hero materializes a real Workspace + Session on first send (the jsdom
+// workspace-flow suite pins the object-layer state machine over the fixture
+// client; THIS spec pins the same flow through HTTP RPC + SSE + the host
+// gateway), reload replays everything from the log (zero further model
+// calls), and the theme scenario proves the shipped dark palette actually
+// cascades: attribute -> alias token flip -> painted surface change. Per the
+// lane's scope ruling there is no theme/layout golden (aria is color-blind);
+// the hero's waiting state gets the one golden here.
+import { readFile } from 'node:fs/promises'
+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 type { SessionEvent } from '@deepseek-ai/dsh-session'
+import {
+ acknowledgeReloadConnectionLoss, assertFixtureInventory, captureStableAria, compareOrRefreshGolden, fixtureUserPrompts,
+ launchWebScaffold, recordFixture, watchConsole, webSnapshotMode, type WebScaffold,
+} from './scaffold.ts'
+import { connectFreshWorkspace, saveFailureShot } from './support.ts'
+
+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')
+// 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')
+const MODE = webSnapshotMode()
+
+const PROMPT = 'Reply with the single word LIGHTHOUSE and stop.'
+
+describe('web e2e: lifecycle & chrome (workspace flow / reload / dark mode)', () => {
+ let scaffold: WebScaffold
+ let browser: Browser
+ let page: Page
+ let tripwire: ReturnType
+ const sessionEvents: SessionEvent[] = []
+
+ beforeAll(async () => {
+ scaffold = await launchWebScaffold(MODE === 'record' ? {} : { replayFixture: FIXTURE, paceMs: 15 })
+ scaffold.ctx.on('session/event', (_session, event: SessionEvent) => { sessionEvents.push(event) })
+ browser = await chromium.launch()
+ 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 })
+ // Fresh world: connect a Workspace so the composer scenarios start live.
+ await connectFreshWorkspace(page)
+ }, 120_000)
+
+ afterAll(async () => {
+ await browser?.close()
+ await scaffold?.close()
+ })
+
+ it('sends the first prompt from the empty-state hero (all modes)', async () => {
+ onTestFailed(() => saveFailureShot(page, 'web-e2e-lifecycle-send'))
+ if (MODE !== 'record') {
+ expect(fixtureUserPrompts(await readFile(FIXTURE, 'utf8'))).toEqual([PROMPT])
+ }
+ // The blank frame renders the hero, not the resident composer: the
+ // headline plus the guidance placeholder are the empty state's anchors.
+ await expect.poll(() => page.getByText("Let's start building", { exact: false }).count(), { timeout: 15_000 }).toBe(1)
+ const input = page.locator('textarea').first()
+ await input.waitFor({ timeout: 10_000 })
+ if (MODE !== 'record') {
+ // Golden of the hero's stable waiting state (captured before any send;
+ // the conversation-region goldens belong to the other scenarios).
+ const snapshot = await captureStableAria(page, '[class*="frame"]', scaffold.workspaceCwd)
+ await compareOrRefreshGolden(HERO_EXPECTED, snapshot, MODE)
+ }
+ const settled = scaffold.whenTurnSettled()
+ await input.fill(PROMPT)
+ await input.press('Enter')
+ const sessionId = await settled
+ if (MODE === 'record') {
+ await recordFixture(scaffold, sessionId, FIXTURE)
+ }
+ }, 200_000)
+
+ it.skipIf(MODE === 'record')('materialized a real Workspace and Session over the wire', async () => {
+ onTestFailed(() => saveFailureShot(page, 'web-e2e-lifecycle-materialize'))
+ // Browser: the sidebar tree now carries the auto-created workspace group
+ // with its one session, and the opened session is the selected row.
+ await expect.poll(() => page.getByText('1 session', { exact: true }).count(), { timeout: 15_000 }).toBeGreaterThanOrEqual(1)
+ await expect.poll(() => page.locator('[role="treeitem"][aria-selected="true"]').count(), { timeout: 10_000 }).toBe(1)
+ await expect.poll(() => page.getByText('LIGHTHOUSE', { exact: true }).count(), { timeout: 15_000 }).toBeGreaterThanOrEqual(1)
+ // Host: the session's durable header cwd is the workspace flow's
+ // create-by-name target (/workspace, the composer's
+ // default draft name) — the proof the send went through workspace
+ // materialization rather than a bare default-cwd session.
+ const cwds = scaffold.ctx.sessions.list().map(session => session.header.cwd)
+ expect(cwds).toEqual([join(scaffold.workspaceCwd, 'workspace')])
+ const turnEnds = sessionEvents.filter(e => e.type === 'turn/end')
+ expect(turnEnds).toHaveLength(1)
+ expect((turnEnds[0] as SessionEvent & { data: { reason: { kind: string } } }).data.reason.kind).toBe('completed')
+ }, 60_000)
+
+ it.skipIf(MODE === 'record')('recovers the whole surface across a reload from the log alone', async () => {
+ onTestFailed(() => saveFailureShot(page, 'web-e2e-lifecycle-reload'))
+ // Fold a layout preference into the same reload: collapse the sidebar
+ // (persisted under dsh.layout.panels) before reloading.
+ await page.getByRole('button', { name: 'Collapse sidebar' }).click()
+ await expect.poll(() => page.getByRole('button', { name: 'Open sidebar' }).count(), { timeout: 10_000 }).toBe(1)
+ const warningStart = tripwire.warnings.length
+ await page.reload({ waitUntil: 'load' })
+ await page.waitForSelector('[class*="frame"]', { timeout: 30_000 })
+ acknowledgeReloadConnectionLoss(tripwire, warningStart)
+ // Layout persisted: the sidebar comes back collapsed.
+ await expect.poll(() => page.getByRole('button', { name: 'Open sidebar' }).count(), { timeout: 10_000 }).toBe(1)
+ // Selection persisted (dsh.sessions.current) and history replayed: the
+ // recorded turn re-renders from session.history with zero model calls —
+ // the replay cursor was fully consumed before the reload, so any stray
+ // request would fail the scenario loudly at close().
+ await expect.poll(() => page.getByText('LIGHTHOUSE', { exact: true }).count(), { timeout: 15_000 }).toBeGreaterThanOrEqual(1)
+ // Expand back and confirm the tree still lists the materialized session.
+ await page.getByRole('button', { name: 'Open sidebar' }).click()
+ await expect.poll(() => page.locator('[role="treeitem"][aria-selected="true"]').count(), { timeout: 10_000 }).toBe(1)
+ // Golden of the recovered conversation region: rebuilt from the log, it
+ // must render the same settled transcript the live turn produced.
+ const snapshot = await captureStableAria(page, '[class*="centerCol"]', scaffold.workspaceCwd)
+ await compareOrRefreshGolden(RELOADED_EXPECTED, snapshot, MODE)
+ expect(tripwire.pageErrors).toEqual([])
+ }, 90_000)
+
+ it.skipIf(MODE === 'record')('cascades the dark theme from the body attribute to painted surfaces', async () => {
+ onTestFailed(() => saveFailureShot(page, 'web-e2e-lifecycle-dark'))
+ // This scenario pins the ThemeService's DOM contract seam directly (the
+ // body[data-ds-dark-theme] attribute -> stylesheet cascade); the REAL
+ // user gesture above it (Settings -> Appearance cubes) is owned by
+ // settings-chrome.e2e.ts. Driving the attribute here keeps the cascade
+ // pinned independently of the settings surface's own lifecycle.
+ const sample = async (): Promise<{ token: string; sidebarBg: string; bodyBg: string }> =>
+ await page.evaluate(() => {
+ const sidebar = document.querySelector('[class*="sidebar"], [class*="rail"]') ?? document.body
+ return {
+ token: getComputedStyle(document.body).getPropertyValue('--dsw-alias-bg-base').trim(),
+ sidebarBg: getComputedStyle(sidebar).backgroundColor,
+ bodyBg: getComputedStyle(document.body).backgroundColor,
+ }
+ })
+ const light = await sample()
+ await page.evaluate(() => { document.body.setAttribute('data-ds-dark-theme', '') })
+ const dark = await sample()
+ // The alias token itself must flip — the cascade's root fact.
+ expect(dark.token).not.toBe(light.token)
+ // And a real painted surface must consume it (not just variables in a
+ // void): at least one of the sampled backgrounds repaints.
+ expect(dark.sidebarBg !== light.sidebarBg || dark.bodyBg !== light.bodyBg).toBe(true)
+ // Removing the attribute restores the light values exactly (the palettes
+ // live in one stylesheet; activation is attribute-only by design).
+ await page.evaluate(() => { document.body.removeAttribute('data-ds-dark-theme') })
+ const restored = await sample()
+ expect(restored).toEqual(light)
+ expect(tripwire.pageErrors).toEqual([])
+ }, 60_000)
+
+ 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'])
+ })
+})
diff --git a/apps/web/tests/live-interactions.e2e.ts b/apps/web/tests/live-interactions.e2e.ts
new file mode 100644
index 0000000000..692210b352
--- /dev/null
+++ b/apps/web/tests/live-interactions.e2e.ts
@@ -0,0 +1,211 @@
+// Web e2e scenarios: live-turn interactions — cancellation, error surfacing,
+// and transient-retry recovery, all through the real composition and wire.
+// The model seam is dsh-llm-replay with override sidecars: `hang` (+ a
+// readyFile marker) makes mid-stream cancel deterministic by construction,
+// `throw` entries express provider failures by stable code, and `{ patches }`
+// augmentation injects a transient throw before the recorded success so
+// llm-retry's recovery is proven end-to-end in the browser. Sidecar CONTENT
+// is authored here (single-sourced against the fixture via deriveReplayScript
+// — no committed copy of recorded chunks); the file is a per-run artifact in
+// the temp workspace. One recorded base fixture serves all three scenarios.
+import { mkdtemp, readFile, rm, writeFile } from 'node:fs/promises'
+import { existsSync } from 'node:fs'
+import { tmpdir } from 'node:os'
+import { fileURLToPath } from 'node:url'
+import { join } from 'node:path'
+import type { Browser, Page } from 'playwright'
+import { chromium } from 'playwright'
+import { afterEach, describe, expect, it, onTestFailed } from 'vitest'
+import { deriveReplayScript, parseSessionLog } from '@deepseek-ai/dsh-llm-replay'
+import type { ReplayOverrideDoc } from '@deepseek-ai/dsh-llm-replay'
+import type { SessionEvent } from '@deepseek-ai/dsh-session'
+import {
+ assertFixtureInventory, captureStableAria, compareOrRefreshGolden, fixtureUserPrompts,
+ launchWebScaffold, recordFixture, watchConsole, webSnapshotMode, type WebScaffold,
+} from './scaffold.ts'
+import { connectFreshWorkspace, saveFailureShot } from './support.ts'
+
+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.
+const CANCEL_EXPECTED = join(SNAPSHOT_DIR, 'cancel.expected.md')
+const ERROR_EXPECTED = join(SNAPSHOT_DIR, 'error-auth.expected.md')
+const RETRY_EXPECTED = join(SNAPSHOT_DIR, 'retry.expected.md')
+const MODE = webSnapshotMode()
+
+// The recorded base: one text-only turn whose derived script the sidecars
+// patch. Kept deliberately tool-free so the derived script is exactly one
+// model call.
+const PROMPT = 'Reply with a one-sentence description of event sourcing, then stop.'
+
+/** turn/end reasons observed, in order. */
+function turnEndReasons(events: SessionEvent[]): string[] {
+ return events
+ .filter(e => e.type === 'turn/end')
+ .map(e => (e as SessionEvent & { data: { reason: { kind: string } } }).data.reason.kind)
+}
+
+describe('web e2e: live-turn interactions (cancel / error / retry)', () => {
+ let scaffold: WebScaffold | undefined
+ let browser: Browser | undefined
+ let page: Page
+ let tripwire: ReturnType
+ let sessionEvents: SessionEvent[]
+ let sidecarDir: string | undefined
+
+ afterEach(async () => {
+ // scaffold.close() failures MUST fail the scenario: assertConsumed() is
+ // the fixture-drift tripwire and cleanup problems are real defects. Run
+ // every teardown step regardless, then rethrow what failed.
+ const failures: unknown[] = []
+ await browser?.close().catch((error: unknown) => failures.push(error))
+ browser = undefined
+ const closing = scaffold
+ scaffold = undefined
+ await closing?.close().catch((error: unknown) => failures.push(error))
+ if (sidecarDir !== undefined) await rm(sidecarDir, { recursive: true, force: true }).catch((error: unknown) => failures.push(error))
+ sidecarDir = undefined
+ if (failures.length === 1) throw failures[0]
+ if (failures.length > 1) throw new AggregateError(failures, 'live-interactions teardown failed')
+ })
+
+ /** Boot scaffold + page with an optional override doc materialized per run. */
+ async function launch(buildOverride?: (sidecarHome: string) => ReplayOverrideDoc): Promise {
+ sessionEvents = []
+ let overridePath: string | undefined
+ if (buildOverride !== undefined) {
+ // The sidecar CONTENT is authored in this spec; the file is a per-run
+ // artifact minted in a spec-owned temp dir. It must exist BEFORE the
+ // scaffold boots — installLlmReplay resolves the script at install.
+ sidecarDir = await mkdtemp(join(tmpdir(), 'dsh-web-e2e-sidecar-'))
+ overridePath = join(sidecarDir, 'replay.override.json')
+ await writeFile(overridePath, JSON.stringify(buildOverride(sidecarDir)))
+ }
+ scaffold = await launchWebScaffold({
+ replayFixture: FIXTURE,
+ ...(overridePath === undefined ? {} : { replayOverride: overridePath }),
+ })
+ scaffold.ctx.on('session/event', (_session, event: SessionEvent) => { sessionEvents.push(event) })
+ browser = await chromium.launch()
+ 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 })
+ // Fresh world: connect a Workspace so the composer scenarios start live.
+ await connectFreshWorkspace(page)
+ }
+
+ /**
+ * Type the recorded prompt and send, with the settled barrier pre-armed.
+ * Returned WRAPPED ({ settled }) — a bare returned promise would be
+ * flattened by the caller's await, blocking on turn/end before the caller
+ * can act mid-turn (the cancel scenario's whole point).
+ */
+ async function sendPrompt(timeoutMs?: number): Promise<{ settled: ReturnType }> {
+ const input = page.locator('textarea').first()
+ await input.waitFor({ timeout: 10_000 })
+ const settled = scaffold!.whenTurnSettled(timeoutMs)
+ await input.fill(PROMPT)
+ await input.press('Enter')
+ return { settled }
+ }
+
+ it.skipIf(MODE !== 'record')('records the base fixture live through the composer', async () => {
+ await launch()
+ onTestFailed(() => saveFailureShot(page, 'web-e2e-interactions-record'))
+ const { settled } = await sendPrompt(180_000)
+ const sessionId = await settled
+ await recordFixture(scaffold!, sessionId, FIXTURE)
+ }, 200_000)
+
+ it.skipIf(MODE === 'record')('cancels a hung stream deterministically via the readyFile marker', async () => {
+ expect(fixtureUserPrompts(await readFile(FIXTURE, 'utf8'))).toEqual([PROMPT])
+ let marker = ''
+ await launch((sidecarHome) => {
+ marker = join(sidecarHome, '.hang-ready')
+ return { patches: [{ at: 0, entry: { kind: 'hang', readyFile: marker } }] }
+ })
+ onTestFailed(() => saveFailureShot(page, 'web-e2e-cancel'))
+ const { settled } = await sendPrompt()
+ // 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 page.getByRole('button', { name: 'Stop generating' }).click()
+ await settled
+ expect(turnEndReasons(sessionEvents).at(-1)).toBe('aborted')
+ // Composer recovered; no streaming node lingers. The host settled first
+ // (awaited above), but the abort frame reaches the browser over SSE — the
+ // frozen-partial swap is eventually consistent, so poll rather than count.
+ await expect.poll(() => page.locator('textarea').first().isEnabled(), { timeout: 10_000 }).toBe(true)
+ await expect.poll(() => page.locator('[data-streaming="true"]').count(), { timeout: 10_000 }).toBe(0)
+ // Golden of the aborted end-state: the prompt bubble plus the frozen
+ // partial ('partial' is the hang entry's replayed prefix) and no more.
+ const snapshot = await captureStableAria(page, '[class*="centerCol"]', scaffold!.workspaceCwd)
+ await compareOrRefreshGolden(CANCEL_EXPECTED, snapshot, MODE)
+ expect(tripwire.pageErrors).toEqual([])
+ expect(tripwire.warnings).toEqual([])
+ }, 120_000)
+
+ it.skipIf(MODE === 'record')('surfaces a non-retryable AUTH failure without retrying', async () => {
+ await launch(() => ({
+ patches: [{ at: 0, entry: { kind: 'throw', chunks: [], message: 'invalid api key', code: 'AUTH' } }],
+ }))
+ onTestFailed(() => saveFailureShot(page, 'web-e2e-error-auth'))
+ const { settled } = await sendPrompt()
+ await settled
+ expect(turnEndReasons(sessionEvents).at(-1)).toBe('error')
+ // AUTH is outside llm-retry's retryable set: no retry record.
+ expect(sessionEvents.filter(e => e.type === 'llm/retry').length).toBe(0)
+ // Product gap found by this lane, pinned as-is: the client consumes no
+ // agent/error frames and a pre-chunk failure freezes no partial, so THIS
+ // failure renders no error copy anywhere — the user sees the send simply
+ // stop. FIXME(web-error-surface): assert visible error text here once the
+ // web UI grows an error rendering; until then the pinned contract is
+ // "no crash, composer recovers, turn logged as error".
+ await expect.poll(() => page.locator('textarea').first().isEnabled(), { timeout: 10_000 }).toBe(true)
+ expect(await page.locator('[data-streaming="true"]').count()).toBe(0)
+ // Golden of the same gap: the prompt bubble alone, no error copy in the
+ // tree — the diff that changes when web-error-surface lands.
+ const snapshot = await captureStableAria(page, '[class*="centerCol"]', scaffold!.workspaceCwd)
+ await compareOrRefreshGolden(ERROR_EXPECTED, snapshot, MODE)
+ expect(tripwire.pageErrors).toEqual([])
+ expect(tripwire.warnings).toEqual([])
+ }, 120_000)
+
+ it.skipIf(MODE === 'record')('recovers a transient SERVER failure through llm-retry and completes', async () => {
+ const derived = deriveReplayScript(parseSessionLog(await readFile(FIXTURE, 'utf8')))
+ expect(derived).toHaveLength(1)
+ await launch(() => ({
+ patches: [
+ { at: 0, entry: { kind: 'throw', chunks: [], message: 'upstream 503', code: 'SERVER' } },
+ // Append the fixture's own success as the retry attempt — single-
+ // sourced from the recording, never copied into a committed sidecar.
+ { at: 1, entry: derived[0]! },
+ ],
+ }))
+ onTestFailed(() => saveFailureShot(page, 'web-e2e-retry'))
+ // llm-retry backs off ~500ms before the second attempt.
+ const { settled } = await sendPrompt(60_000)
+ await settled
+ expect(turnEndReasons(sessionEvents).at(-1)).toBe('completed')
+ // The durable retry record proves the second attempt (request/header logs
+ // only on change, so attempt count is invisible there).
+ expect(sessionEvents.filter(e => e.type === 'llm/retry').length).toBeGreaterThanOrEqual(1)
+ await expect.poll(() => page.getByText('event sourcing', { exact: false }).count(), { timeout: 10_000 }).toBeGreaterThan(0)
+ // Golden of the recovered end-state: indistinguishable from a clean
+ // completion — retries are deliberately invisible in the transcript.
+ const snapshot = await captureStableAria(page, '[class*="centerCol"]', scaffold!.workspaceCwd)
+ await compareOrRefreshGolden(RETRY_EXPECTED, snapshot, MODE)
+ expect(tripwire.pageErrors).toEqual([])
+ expect(tripwire.warnings).toEqual([])
+ }, 120_000)
+
+ 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',
+ ])
+ })
+})
diff --git a/apps/web/tests/navigation-panes.e2e.ts b/apps/web/tests/navigation-panes.e2e.ts
new file mode 100644
index 0000000000..bbae7363df
--- /dev/null
+++ b/apps/web/tests/navigation-panes.e2e.ts
@@ -0,0 +1,190 @@
+// Web e2e scenarios: navigation & panes — the view tabs (Trajectory /
+// Waterfall), the details column, and sidebar search, all over ONE rich
+// two-turn seeded fixture rendered purely from the log (the seeded-history
+// pattern: zero model calls in replay, so every surface here is the client
+// fold + host history RPC, not replay binding). The seed is recorded live
+// under the standard discipline: turn 1 produces a bash call plus two
+// parallel reads in one assistant message (tool-call density for the
+// trajectory/waterfall lanes and a details-capable bash row), turn 2 a
+// markdown-rich reply (a second turn so the waterfall has two lanes).
+import { mkdir, readFile, writeFile } from 'node:fs/promises'
+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 { parseSessionLog } from '@deepseek-ai/dsh-llm-replay'
+import type { SessionEvent } from '@deepseek-ai/dsh-session'
+import {
+ assertFixtureInventory, captureStableAria, compareOrRefreshGolden, fixtureUserPrompts,
+ launchWebScaffold, recordFixture, seedSession, watchConsole, webSnapshotMode, type WebScaffold,
+} from './scaffold.ts'
+import { saveFailureShot } from './support.ts'
+
+const SNAPSHOT_DIR = fileURLToPath(new URL('./snapshots/navigation-panes', import.meta.url))
+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 MODE = webSnapshotMode()
+const SEED_ID = 'navigation-panes-web-e2e'
+
+// Turn 1 leads with a distinctive word: the session-title fallback takes the
+// first words of the first message, so the sidebar-search scenario has a
+// known-matching query ('navscenario') without depending on a live title call.
+const PROMPT_TURN1 = 'NavScenario: first run bash to print exactly NAVIGATION_OK, then read nav-a.md and nav-b.md using two read calls in ONE assistant message, then reply with the single word FIRST_DONE and stop.'
+const PROMPT_TURN2 = 'Reply in markdown with: a level-2 heading "Navigation Summary", a bulleted list of exactly two items, and a fenced code block containing echo WATERFALL. Then stop.'
+
+describe('web e2e: navigation & panes over a rich seeded session', () => {
+ let scaffold: WebScaffold
+ let browser: Browser
+ let page: Page
+ let tripwire: ReturnType
+
+ beforeAll(async () => {
+ scaffold = await launchWebScaffold({})
+ // The workspace-aware flow runs sessions in /workspace;
+ // the read targets must live in that session cwd (pre-creation is safe:
+ // create-by-name adopts an existing directory).
+ const sessionCwd = join(scaffold.workspaceCwd, 'workspace')
+ await mkdir(sessionCwd, { recursive: true })
+ await writeFile(join(sessionCwd, 'nav-a.md'), '# alpha nav\n')
+ await writeFile(join(sessionCwd, 'nav-b.md'), '# beta nav\n')
+ if (MODE !== 'record') {
+ const raw = await readFile(SEED, 'utf8')
+ expect(fixtureUserPrompts(raw), 'seed fixture must carry exactly the two drive prompts')
+ .toEqual([PROMPT_TURN1, PROMPT_TURN2])
+ await seedSession(scaffold, raw, SEED_ID)
+ }
+ browser = await chromium.launch()
+ 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 })
+ }, 120_000)
+
+ afterAll(async () => {
+ await browser?.close()
+ await scaffold?.close()
+ })
+
+ it.skipIf(MODE !== 'record')('records the two-turn seed live through the composer', async () => {
+ onTestFailed(() => saveFailureShot(page, 'web-e2e-navigation-record'))
+ const input = page.locator('textarea').first()
+ await input.waitFor({ timeout: 10_000 })
+ let sessionId: Awaited> | undefined
+ for (const prompt of [PROMPT_TURN1, PROMPT_TURN2]) {
+ const settled = scaffold.whenTurnSettled()
+ // Turn 2 types into the same composer once turn 1 unlocks it.
+ await expect.poll(() => input.isEnabled(), { timeout: 15_000 }).toBe(true)
+ await input.fill(prompt)
+ await input.press('Enter')
+ sessionId = await settled
+ }
+ await recordFixture(scaffold, sessionId!, SEED)
+ // Fixture honesty: the recording must carry the shape the replay
+ // scenarios assert on — three calls in turn 1 and two closed turns.
+ const recorded = parseSessionLog(await readFile(SEED, 'utf8'))
+ expect(recorded.filter(e => e.type === 'turn/end')).toHaveLength(2)
+ const calls = recorded.filter((e): e is SessionEvent & { data: { name: string } } => e.type === 'tool/call')
+ 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()
+ 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 expect.poll(() => search.inputValue(), { timeout: 5_000 }).toBe('')
+ await expect.poll(() => page.locator('[role="treeitem"]').count(), { timeout: 10_000 }).toBeGreaterThanOrEqual(1)
+ }, 60_000)
+
+ it.skipIf(MODE === 'record')('renders the trajectory tab with turn sections and step cells', async () => {
+ onTestFailed(() => saveFailureShot(page, 'web-e2e-navigation-trajectory'))
+ await page.getByRole('tab', { name: 'Trajectory' }).click()
+ // Two sticky turn sections; turn 1's step group summarizes its tool mix
+ // (bash + the two parallel reads collapse to 'bash read×2').
+ await expect.poll(() => page.getByText('Turn 1', { exact: true }).count(), { timeout: 15_000 }).toBe(1)
+ await expect.poll(() => page.getByText('Turn 2', { exact: true }).count(), { timeout: 10_000 }).toBe(1)
+ await expect.poll(() => page.getByText('bash read×2', { exact: false }).count(), { timeout: 10_000 }).toBe(1)
+ const snapshot = (await captureStableAria(page, '[class*="viewArea"]', scaffold.workspaceCwd))
+ .split(SEED_ID).join('{{seededId}}')
+ await compareOrRefreshGolden(TRAJECTORY_EXPECTED, snapshot, MODE)
+ }, 60_000)
+
+ it.skipIf(MODE === 'record')('renders the waterfall tab with span stats and one lane per span', async () => {
+ onTestFailed(() => saveFailureShot(page, 'web-e2e-navigation-waterfall'))
+ await page.getByRole('tab', { name: 'Waterfall' }).click()
+ // The stats header rides the waterfall body. The span fold counts THREE
+ // spans for this two-turn log: only assistant/steering nodes carry a turn
+ // number, so the first user message lands in a turn-0 prologue span (a
+ // P-I placeholder shape — pinned as-is; real spans are deferred to
+ // P-III per the view's deviation ledger). Calls: bash + two reads.
+ await expect.poll(() => page.getByText(/3 turns · \d+ steps · 3 tool calls/).count(), { timeout: 15_000 }).toBe(1)
+ // One lane per span, tagged by turn number, prologue included.
+ for (const tag of ['turn 0', 'turn 1', 'turn 2']) {
+ await expect.poll(() => page.getByText(tag, { exact: true }).count(), { timeout: 10_000 }).toBe(1)
+ }
+ const snapshot = (await captureStableAria(page, '[class*="viewArea"]', scaffold.workspaceCwd))
+ .split(SEED_ID).join('{{seededId}}')
+ await compareOrRefreshGolden(WATERFALL_EXPECTED, snapshot, MODE)
+ }, 60_000)
+
+ it.skipIf(MODE === 'record')('opens the details column from the bash row and closes it', async () => {
+ onTestFailed(() => saveFailureShot(page, 'web-e2e-navigation-details'))
+ await page.getByRole('tab', { name: 'Chat' }).click()
+ // The bash toolview row routes its click to openDetails (read rows are
+ // expand-in-place instead — the seeded-history scenario owns that fold).
+ const bashRow = page.locator('[data-sample="bash-global"]').first()
+ await bashRow.waitFor({ timeout: 15_000 })
+ // Open/closed is the frame's collapsed attribute: the column collapses to
+ // width 0 but its subtree deliberately never unmounts (hidden, not
+ // absent), so element presence/visibility cannot express the state.
+ const frame = page.locator('[data-details-collapsed], [class*="frame"]').first()
+ expect(await frame.getAttribute('data-details-collapsed')).not.toBeNull()
+ await bashRow.click()
+ await expect.poll(() => frame.getAttribute('data-details-collapsed'), { timeout: 10_000 }).toBeNull()
+ // The open panel shows the selected call's name, arguments, and durable
+ // result (NAVIGATION_OK appears in the chat row too, hence >= 2 total).
+ await expect.poll(() => page.getByText('NAVIGATION_OK', { exact: false }).count(), { timeout: 10_000 }).toBeGreaterThanOrEqual(2)
+ // Golden of the open panel: tool name header, Input args, Output result.
+ const snapshot = (await captureStableAria(page, '[class*="detailsCol"]', scaffold.workspaceCwd))
+ .split(SEED_ID).join('{{seededId}}')
+ await compareOrRefreshGolden(DETAILS_EXPECTED, snapshot, MODE)
+ await page.getByRole('button', { name: '关闭详情' }).click()
+ await expect.poll(() => frame.getAttribute('data-details-collapsed'), { timeout: 10_000 }).not.toBeNull()
+ }, 60_000)
+
+ it.skipIf(MODE === 'record')('issued zero model calls and stayed clean', async () => {
+ expect(tripwire.pageErrors).toEqual([])
+ expect(tripwire.warnings).toEqual([])
+ await assertFixtureInventory(SNAPSHOT_DIR, [
+ 'seed.jsonl', 'trajectory.expected.md', 'waterfall.expected.md', 'details-open.expected.md',
+ ])
+ })
+})
diff --git a/apps/web/tests/question-composer.e2e.ts b/apps/web/tests/question-composer.e2e.ts
new file mode 100644
index 0000000000..46f6af7b86
--- /dev/null
+++ b/apps/web/tests/question-composer.e2e.ts
@@ -0,0 +1,109 @@
+// Web e2e scenario: the resident question composer. The shipped composition
+// already exposes ask_user_question (the ui-question row's node half mounts
+// the tool), so a recorded turn where the model asks blocks mid-turn on the
+// real userInteraction seam: the composer renders in the browser, the test
+// answers through it, and the turn completes with the answer in the log.
+// Replay is fully deterministic — the question content arrives from replayed
+// chunks, the composer wait is real, and the answer click is the test's own
+// gesture (the ONE place a drive step legitimately reacts to model content:
+// the turn cannot complete without it, in record and replay alike).
+import { readFile } from 'node:fs/promises'
+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 type { SessionEvent } from '@deepseek-ai/dsh-session'
+import {
+ assertFixtureInventory, captureStableAria, compareOrRefreshGolden, fixtureUserPrompts,
+ launchWebScaffold, recordFixture, watchConsole, webSnapshotMode, type WebScaffold,
+} from './scaffold.ts'
+import { connectFreshWorkspace, saveFailureShot } from './support.ts'
+
+const SNAPSHOT_DIR = fileURLToPath(new URL('./snapshots/question-composer', import.meta.url))
+const FIXTURE = join(SNAPSHOT_DIR, 'session.jsonl')
+const UI_EXPECTED = join(SNAPSHOT_DIR, 'ui.expected.md')
+// Second golden: the answered transcript — the question resolved into its
+// tool round trip and the final reply, the state the waiting golden cannot see.
+const ANSWERED_EXPECTED = join(SNAPSHOT_DIR, 'answered.expected.md')
+const MODE = webSnapshotMode()
+
+const PROMPT = 'Use the ask_user_question tool to ask me exactly one question with id "color", question "Which color do you prefer?", header "Pick one", and options labeled "Blue" and "Green". After I answer, reply with the single word DONE and stop.'
+
+describe('web e2e: resident question composer round trip', () => {
+ let scaffold: WebScaffold
+ let browser: Browser
+ let page: Page
+ let tripwire: ReturnType
+ const sessionEvents: SessionEvent[] = []
+
+ beforeAll(async () => {
+ scaffold = await launchWebScaffold(MODE === 'record' ? {} : { replayFixture: FIXTURE, paceMs: 15 })
+ scaffold.ctx.on('session/event', (_session, event: SessionEvent) => { sessionEvents.push(event) })
+ browser = await chromium.launch()
+ 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 })
+ // Fresh world: connect a Workspace so the composer scenarios start live.
+ await connectFreshWorkspace(page)
+ }, 120_000)
+
+ afterAll(async () => {
+ await browser?.close()
+ await scaffold?.close()
+ })
+
+ it('asks through the composer, answers, and completes with the answer logged', async () => {
+ onTestFailed(() => saveFailureShot(page, 'web-e2e-question'))
+ if (MODE !== 'record') {
+ expect(fixtureUserPrompts(await readFile(FIXTURE, 'utf8'))).toEqual([PROMPT])
+ }
+ const input = page.locator('textarea').first()
+ await input.waitFor({ timeout: 10_000 })
+ const settled = scaffold.whenTurnSettled(MODE === 'record' ? 180_000 : 30_000)
+ await input.fill(PROMPT)
+ await input.press('Enter')
+
+ // The composer takes over the input area while the tool blocks. Its
+ // presence is a STABLE waiting state (not a transient): it stays until
+ // answered, so a plain waitFor is race-free.
+ const composer = page.locator('[data-question-key]')
+ await composer.waitFor({ timeout: MODE === 'record' ? 120_000 : 30_000 })
+ await expect.poll(() => composer.getByText('Which color do you prefer?').count(), { timeout: 10_000 }).toBeGreaterThan(0)
+
+ if (MODE !== 'record') {
+ // This golden owns the stable question surface; the answered-state
+ // golden below owns the resulting transcript.
+ const snapshot = await captureStableAria(page, '[data-question-key]', scaffold.workspaceCwd)
+ await compareOrRefreshGolden(UI_EXPECTED, snapshot, MODE)
+ }
+
+ await composer.getByRole('radio', { name: 'Blue' }).click()
+ // Submit: Enter on the focused option (the composer's documented submit).
+ await composer.getByRole('radio', { name: 'Blue' }).press('Enter')
+
+ const sessionId = await settled
+ if (MODE === 'record') {
+ await recordFixture(scaffold, sessionId, FIXTURE)
+ return
+ }
+ // World state: the tool result carries the chosen answer, and DONE lands.
+ const results = sessionEvents.filter(e => e.type === 'tool/result')
+ expect(JSON.stringify(results.at(-1))).toContain('Blue')
+ await expect.poll(() => page.getByText('DONE', { exact: true }).count(), { timeout: 15_000 }).toBeGreaterThanOrEqual(1)
+ // Composer gone; regular input restored.
+ expect(await page.locator('[data-question-key]').count()).toBe(0)
+ await expect.poll(() => page.locator('textarea').first().isEnabled(), { timeout: 10_000 }).toBe(true)
+ // Golden of the answered transcript: the ask_user_question round trip
+ // rendered as history (question tool row + DONE), composer takeover gone.
+ const snapshot = await captureStableAria(page, '[class*="centerCol"]', scaffold.workspaceCwd)
+ await compareOrRefreshGolden(ANSWERED_EXPECTED, snapshot, MODE)
+ expect(tripwire.pageErrors).toEqual([])
+ expect(tripwire.warnings).toEqual([])
+ }, 200_000)
+
+ it.skipIf(MODE === 'record')('keeps the fixture inventory closed', async () => {
+ await assertFixtureInventory(SNAPSHOT_DIR, ['session.jsonl', 'ui.expected.md', 'answered.expected.md'])
+ })
+})
diff --git a/apps/web/tests/replay-round-trip.e2e.ts b/apps/web/tests/replay-round-trip.e2e.ts
new file mode 100644
index 0000000000..10f374c920
--- /dev/null
+++ b/apps/web/tests/replay-round-trip.e2e.ts
@@ -0,0 +1,131 @@
+// Web e2e scenario: fresh round trip. A real chromium types a prompt into the
+// real composer; the wire, apiproxy, agent loop, and the REAL bash tool (echo
+// in the temp workspace) all run; the model seam is dsh-llm-replay (keyless)
+// or the live adapter (record). Drive steps run in every mode and wait only
+// on generic completion (whenTurnSettled — never model-content selectors, so
+// record cannot hang on a live model answering differently); assertion steps
+// run in replay/refresh only. Settled states only — streaming incrementality
+// is asserted from the persisted assistant/chunk events, not transient DOM.
+// Record: DSH_SNAPSHOT=record rewrites session.jsonl, then a keyless
+// DSH_SNAPSHOT=refresh regenerates ui.expected.md.
+import { readFile } from 'node:fs/promises'
+import { fileURLToPath } from 'node:url'
+import type { Browser, Page } from 'playwright'
+import { chromium } from 'playwright'
+import { afterAll, beforeAll, describe, expect, it, onTestFailed } from 'vitest'
+import type { SessionEvent } from '@deepseek-ai/dsh-session'
+import {
+ assertFixtureInventory, captureStableAria, compareOrRefreshGolden, fixtureUserPrompts,
+ launchWebScaffold, recordFixture, watchConsole, webSnapshotMode, type WebScaffold,
+} from './scaffold.ts'
+import { connectFreshWorkspace, saveFailureShot } from './support.ts'
+
+const SNAPSHOT_DIR = fileURLToPath(new URL('./snapshots/fresh-round-trip', import.meta.url))
+const FIXTURE = fileURLToPath(new URL('./snapshots/fresh-round-trip/session.jsonl', import.meta.url))
+const UI_EXPECTED = fileURLToPath(new URL('./snapshots/fresh-round-trip/ui.expected.md', import.meta.url))
+const MODE = webSnapshotMode()
+
+// The scenario's one drive prompt. Record sends it; replay asserts the
+// committed fixture recorded exactly it, so drive script and fixture cannot
+// drift apart.
+const PROMPT = 'Use the bash tool to run exactly: echo WEB_E2E_OK. Then reply with the single word DONE and stop.'
+
+describe('web e2e: fresh round trip through the real assembly', () => {
+ let scaffold: WebScaffold
+ let browser: Browser
+ let page: Page
+ let tripwire: ReturnType
+ const sessionEvents: SessionEvent[] = []
+
+ beforeAll(async () => {
+ scaffold = await launchWebScaffold({
+ ...(MODE === 'record' ? {} : { replayFixture: FIXTURE, paceMs: 15 }),
+ })
+ scaffold.ctx.on('session/event', (_session, event: SessionEvent) => { sessionEvents.push(event) })
+ browser = await chromium.launch()
+ 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 })
+ // Fresh world: connect a Workspace so the composer scenarios start live.
+ await connectFreshWorkspace(page)
+ }, 120_000)
+
+ afterAll(async () => {
+ await browser?.close()
+ await scaffold?.close()
+ })
+
+ it('drives the recorded prompt to a settled turn (all modes)', async () => {
+ onTestFailed(() => saveFailureShot(page, 'web-e2e-round-trip'))
+ if (MODE !== 'record') {
+ // Drift guard: the committed fixture must carry exactly the drive prompt.
+ expect(fixtureUserPrompts(await readFile(FIXTURE, 'utf8'))).toEqual([PROMPT])
+ }
+ const input = page.locator('textarea').first()
+ await input.waitFor({ timeout: 10_000 })
+ // Arm the host-side settled barrier BEFORE the send click.
+ const settled = scaffold.whenTurnSettled()
+ await input.fill(PROMPT)
+ await input.press('Enter')
+ const sessionId = await settled
+ if (MODE === 'record') {
+ await recordFixture(scaffold, sessionId, FIXTURE)
+ }
+ }, 200_000)
+
+ it.skipIf(MODE === 'record')('rendered the settled turn: markdown, tool row, composer restore', async () => {
+ onTestFailed(() => saveFailureShot(page, 'web-e2e-round-trip-settled'))
+ // Browser settled-poll after host completion (host strictly precedes render).
+ await page.locator('[data-streaming="true"]').waitFor({ state: 'detached', timeout: 15_000 }).catch(() => {
+ // Chunks may coalesce into one commit; a never-mounted streaming node is
+ // legal — the chunk-event assertions below carry incrementality.
+ })
+ await expect.poll(() => page.getByText('DONE', { exact: true }).count(), { timeout: 15_000 }).toBeGreaterThanOrEqual(1)
+ // World state, not self-report: the real bash executor returned the exact
+ // command output, and the turn closed cleanly.
+ const bashCall = sessionEvents.find(event => event.type === 'tool/call' && event.data.name === 'bash')
+ if (bashCall?.type !== 'tool/call') throw new Error('the replayed turn did not call the bash tool')
+ const bashResult = sessionEvents.find(event =>
+ event.type === 'tool/result' && event.data.callId === bashCall.data.callId)
+ if (bashResult?.type !== 'tool/result') throw new Error('the bash tool call produced no durable result')
+ expect(bashResult.data.isError).toBe(false)
+ expect(bashResult.data.content.filter(block => block.type === 'text').map(block => block.text).join(''))
+ .toBe('WEB_E2E_OK\n')
+ const turnEnds = sessionEvents.filter(e => e.type === 'turn/end')
+ expect(turnEnds.length).toBe(1)
+ expect((turnEnds[0] as SessionEvent & { data: { reason: { kind: string } } }).data.reason.kind).toBe('completed')
+ // The persisted chunk events are the authoritative incrementality proof.
+ expect(sessionEvents.filter(e => e.type === 'assistant/chunk').length).toBeGreaterThan(10)
+ }, 60_000)
+
+ it.skipIf(MODE === 'record')('matches the conversation aria golden with stable anchors', async () => {
+ onTestFailed(() => saveFailureShot(page, 'web-e2e-round-trip-aria'))
+ // Anchor assertions survive a semantics-preserving component rewrite even
+ // while the whole-region golden churns.
+ await expect(page.getByRole('textbox').first().isVisible()).resolves.toBe(true)
+ expect(await page.getByText('WEB_E2E_OK', { exact: false }).count()).toBeGreaterThanOrEqual(1)
+ const snapshot = await captureStableAria(page, '[class*="centerCol"]', scaffold.workspaceCwd)
+ await compareOrRefreshGolden(UI_EXPECTED, snapshot, MODE)
+ })
+
+ it.skipIf(MODE === 'record')('expands and collapses the reasoning fold from its click target', async () => {
+ onTestFailed(() => saveFailureShot(page, 'web-e2e-round-trip-think'))
+ // Interaction over the REAL wire-delivered transcript (the fixture-client
+ // tier pins the same gesture against FixtureApiClient; this one runs on
+ // mux-frame-fed state). Runs after the golden capture so the committed
+ // aria surface stays the untouched settled state.
+ const think = page.getByRole('button', { name: /^Think/ }).first()
+ expect(await think.getAttribute('aria-expanded')).toBe('false')
+ await think.click()
+ await expect.poll(() => think.getAttribute('aria-expanded'), { timeout: 5_000 }).toBe('true')
+ await think.click()
+ await expect.poll(() => think.getAttribute('aria-expanded'), { timeout: 5_000 }).toBe('false')
+ })
+
+ it.skipIf(MODE === 'record')('stayed clean: no pageerrors, no reconnect self-healing, no server errors', async () => {
+ expect(tripwire.pageErrors).toEqual([])
+ expect(tripwire.warnings).toEqual([])
+ await assertFixtureInventory(SNAPSHOT_DIR, ['session.jsonl', 'ui.expected.md'])
+ })
+})
diff --git a/apps/web/tests/scaffold.ts b/apps/web/tests/scaffold.ts
new file mode 100644
index 0000000000..34d0e5f123
--- /dev/null
+++ b/apps/web/tests/scaffold.ts
@@ -0,0 +1,474 @@
+// Shared scaffold for the keyless browser e2e lane (Agent Note:
+// .agents/notes/implemented/testing/2026-07-24-web-gui-browser-e2e-lane.md).
+// Boots the REAL web composition — the shipped apps/cli/cordis.yml through
+// the vendored Loader (the same include boot AppCLIEntry drives), patched the
+// snapshot way — so a real chromium exercises the real HTTP/SSE wire, the
+// api-gateway, agent loop, tools, and persistence. Modes ride $DSH_SNAPSHOT:
+// replay (default, keyless: llm-deepseek row disabled, dsh-llm-replay row
+// inserted in providers mode), record (real adapter + key, harvests fixtures
+// from live session memory), refresh (keyless replay that rewrites goldens).
+//
+// Composition divergences from `dsh web`, all deliberate, all via include
+// patches over the SAME tree (never a second yml): temp persistenceRoot;
+// workspace-context disabled (recorded fixtures must not embed this repo's
+// AGENTS.md); session-title-llm disabled (its fire-and-forget title call
+// would race the loop for the session's replay cursor); webserver pinned to
+// port 0 with the built dist; keyless modes disable llm-deepseek and fill
+// the open llm seam post-boot with installLlmReplay on the settled root ctx
+// (the plugin-row path discards the ReplayHandle; the direct install keeps
+// assertConsumed for the teardown fixture-consumption check).
+import { existsSync, readFileSync } from 'node:fs'
+import { mkdtemp, readFile, readdir, realpath, rm, utimes, writeFile } from 'node:fs/promises'
+import { tmpdir } from 'node:os'
+import { join, resolve } from 'node:path'
+import { pathToFileURL } from 'node:url'
+import type { Page } from 'playwright'
+import { expect } from 'vitest'
+import { Context } from 'cordis'
+import Loader from '@cordisjs/plugin-loader'
+import Include, { type PatchOptions } from '@cordisjs/plugin-include'
+import { scrubRequestHeaders } from '@deepseek-ai/dsh-acp-snapshot'
+import { assertEntriesLoaded } from '@deepseek-ai/dsh-app-boot'
+import type { ReplayHandle } from '@deepseek-ai/dsh-llm-replay'
+import { installLlmReplay, parseSessionLog } from '@deepseek-ai/dsh-llm-replay'
+import SessionStore, {
+ packChunkRuns,
+ SESSION_FORMAT_VERSION,
+ SessionId,
+ type Session,
+ type SessionEvent,
+ type SessionHeader,
+} from '@deepseek-ai/dsh-session'
+import SessionPersistenceJsonl from '@deepseek-ai/dsh-session-persistence-jsonl'
+// Empty type imports carry the httpServer/agents/sessionPersistence Context merges.
+import type {} from '@deepseek-ai/dsh-host-webserver'
+import type {} from '@deepseek-ai/dsh-agent'
+import { DIST_INDEX, REPO_ROOT, requireDist } from './support.ts'
+
+/** Snapshot mode for the lane, from $DSH_SNAPSHOT (same vocabulary as the ACP/TUI suites). */
+export type WebSnapshotMode = 'replay' | 'record' | 'refresh'
+
+/**
+ * Resolve and validate the lane's snapshot mode.
+ * @returns the active mode; unset/empty selects replay.
+ */
+export function webSnapshotMode(): WebSnapshotMode {
+ const value = process.env.DSH_SNAPSHOT
+ if (value === undefined || value === '' || value === 'replay') return 'replay'
+ if (value === 'record' || value === 'refresh') return value
+ throw new Error(`DSH_SNAPSHOT must be replay, record, or refresh; got ${JSON.stringify(value)}`)
+}
+
+/** The shipped composition under test: apps/cli's config tree. */
+const CONFIG_PATH = join(REPO_ROOT, 'apps/cli/cordis.yml')
+
+// Replay publishes the provider catalog the gateway routes to (providers
+// mode, never catch-all: with llm-deepseek disabled no adapter exists, so a
+// catch-all would leave resolveModelContext unroutable and compact-basic's
+// post-step pressure check would warn every step). The published
+// contextWindow keeps that pressure path provably inert for small fixtures.
+const REPLAY_PROVIDERS = [{ id: 'deepseek', name: 'DeepSeek', models: [{ id: 'deepseek-v4-flash', contextWindow: 128_000 }] }]
+
+/** Repo-root .env → process.env for record mode (never overrides set vars); the smoke-real convention. */
+function loadRootEnv(): void {
+ const envPath = join(REPO_ROOT, '.env')
+ if (!existsSync(envPath)) return
+ for (const line of readFileSync(envPath, 'utf8').split('\n')) {
+ const m = /^([A-Za-z_][A-Za-z0-9_]*)=(.*)$/.exec(line.trim())
+ if (m !== null && process.env[m[1]!] === undefined) process.env[m[1]!] = m[2]
+ }
+}
+
+/** A booted web scaffold: real composition, mode-selected model backend, temp world. */
+export interface WebScaffold {
+ /** The active snapshot mode this scaffold booted under. */
+ mode: WebSnapshotMode
+ /** Browser-facing origin (http://127.0.0.1:). */
+ baseUrl: string
+ /** Settled root context (the in-process barrier seam; headless event subscription is its sanctioned use). */
+ ctx: Context
+ /** Temp project directory sessions run in (bash/fs tool cwd). */
+ workspaceCwd: string
+ /** Temp persistence root (seeded sessions land here through the real API). */
+ persistenceRoot: string
+ /** Await a settled turn end: in-process turn/end, then the agent's idle flip (which follows the persistence flush). */
+ whenTurnSettled(timeoutMs?: number): Promise
+ /** Tear everything down; asserts the replay fixture was fully consumed first (replay/refresh). */
+ close(): Promise
+}
+
+/** Options for {@link launchWebScaffold}. */
+export interface LaunchOptions {
+ /**
+ * Replay fixture (session.jsonl) served by the inserted dsh-llm-replay row
+ * in replay/refresh modes; ignored in record mode (the real adapter
+ * answers). Omit for scenarios issuing no model calls — a stray stream then
+ * fails loud with NO_ADAPTER (llm-deepseek is disabled and no replay row
+ * mounts).
+ */
+ replayFixture?: string
+ /**
+ * Optional replay.override.json sidecar (whole-script replacement or
+ * `{ patches }` augmentation) for throw/hang scenarios not expressible as
+ * recorded chunks; replay/refresh only.
+ */
+ replayOverride?: string
+ /** Per-chunk replay pacing (ms) so the browser observes genuinely incremental SSE; replay/refresh only. */
+ paceMs?: number
+ /**
+ * Tool presentation mode patched onto the shipped `tools` row (`code`
+ * collapses the wire to run_code + the SDK prompt section). Omit for the
+ * yml default. The code runtime row is always in the tree, so no extra
+ * insertion is needed.
+ */
+ toolsMode?: 'native' | 'code' | 'both'
+}
+
+/** Dispose the booted tree and remove both owned temp roots, reporting every independent cleanup failure. */
+async function cleanupScaffoldWorld(ctx: Context, workspaceCwd: string, persistenceRoot: string): Promise {
+ const failures: unknown[] = []
+ await Promise.resolve(ctx.fiber.dispose()).catch((error: unknown) => failures.push(error))
+ await rm(workspaceCwd, { recursive: true, force: true }).catch((error: unknown) => failures.push(error))
+ await rm(persistenceRoot, { recursive: true, force: true }).catch((error: unknown) => failures.push(error))
+ return failures
+}
+
+/**
+ * Boot the real web composition under the current snapshot mode.
+ * @param options - replay fixture selection and pacing.
+ * @returns the running scaffold.
+ */
+export async function launchWebScaffold(options: LaunchOptions = {}): Promise {
+ requireDist()
+ const mode = webSnapshotMode()
+ if (mode === 'record') {
+ loadRootEnv()
+ if (process.env.DEEPSEEK_API_KEY === undefined || process.env.DEEPSEEK_API_KEY.length === 0) {
+ throw new Error('web e2e record mode needs DEEPSEEK_API_KEY (env or repo-root .env)')
+ }
+ }
+ const workspaceCwd = await realpath(await mkdtemp(join(tmpdir(), 'dsh-web-e2e-ws-')))
+ let persistenceRoot: string
+ try {
+ persistenceRoot = await mkdtemp(join(tmpdir(), 'dsh-web-e2e-sessions-'))
+ } catch (error) {
+ const failures: unknown[] = [error]
+ await rm(workspaceCwd, { recursive: true, force: true }).catch((cleanupError: unknown) => failures.push(cleanupError))
+ if (failures.length > 1) throw new AggregateError(failures, 'web scaffold temp-root setup failed')
+ throw error
+ }
+
+ // The include patch set — the same mechanism AppCLIEntry and the ACP
+ // snapshot overlay use, applied over the SAME shipped tree (a patch id that
+ // stops matching a row fails the boot sweep loudly instead of drifting).
+ const patches: PatchOptions[] = [
+ { id: 'session-persistence-jsonl', config: { root: persistenceRoot } },
+ // storage-json's './.storages' yml default is cwd-relative and resolves
+ // per write; the scaffold restores the original cwd after boot, so the
+ // row gets an absolute temp root (removed with the workspace at close).
+ { id: 'storage-json', config: { root: join(workspaceCwd, '.dsh-storages') } },
+ // fs/bash cwd default to process.cwd(); the gateway injects the same
+ // value into session.cwd — chdir below anchors all three to the temp
+ // workspace, keeping the composition untouched.
+ { id: 'workspace-context', disabled: true },
+ { id: 'session-title-llm', disabled: true },
+ { id: 'webserver', config: { host: '127.0.0.1', port: 0, distIndex: DIST_INDEX } },
+ ...options.toolsMode === undefined ? [] : [{ id: 'tools', config: { mode: options.toolsMode } }],
+ ...mode === 'record' ? [] : [{ id: 'llm-deepseek', disabled: true }],
+ ]
+
+ // Sessions inherit the gateway's process.cwd() default; run the boot from
+ // the temp workspace so tool cwd, session cwd, and fixtures agree.
+ const originalCwd = process.cwd()
+ const ctx = new Context()
+ let port = 0
+ let replayHandle: ReplayHandle | undefined
+ try {
+ process.chdir(workspaceCwd)
+ ctx.baseUrl = pathToFileURL(join(resolve(CONFIG_PATH), '..')).href + '/'
+ await ctx.plugin(Loader)
+ ctx.loader.builtins.include = Include
+ await ctx.loader.create({
+ name: 'cordis:include',
+ config: { path: pathToFileURL(resolve(CONFIG_PATH)).href, patches },
+ })
+ await ctx.loader.await()
+ assertEntriesLoaded(ctx, 'web e2e scaffold')
+ const boundPort = ctx.get('httpServer')?.port
+ if (boundPort === undefined) {
+ throw new Error('web e2e scaffold: httpServer service missing after settled boot')
+ }
+ port = boundPort
+
+ // Fill the open llm seam on the settled root ctx (llm-deepseek is disabled
+ // in keyless modes; a scenario with no fixture leaves the seam empty so a
+ // stray stream fails loud with NO_ADAPTER). The direct install, unlike the
+ // plugin row, returns the ReplayHandle for the teardown consumption check.
+ if (mode !== 'record' && options.replayFixture !== undefined) {
+ replayHandle = installLlmReplay(ctx, {
+ file: options.replayFixture,
+ providers: REPLAY_PROVIDERS,
+ ...(options.replayOverride === undefined ? {} : { overrideFile: options.replayOverride }),
+ ...(options.paceMs === undefined ? {} : { paceMs: options.paceMs }),
+ })
+ }
+ } catch (error) {
+ if (process.cwd() !== originalCwd) process.chdir(originalCwd)
+ const cleanupFailures = await cleanupScaffoldWorld(ctx, workspaceCwd, persistenceRoot)
+ if (cleanupFailures.length > 0) {
+ throw new AggregateError([error, ...cleanupFailures], 'web scaffold setup failed and cleanup was incomplete')
+ }
+ throw error
+ } finally {
+ if (process.cwd() !== originalCwd) process.chdir(originalCwd)
+ }
+
+ return {
+ mode,
+ baseUrl: `http://127.0.0.1:${port}`,
+ ctx,
+ workspaceCwd,
+ persistenceRoot,
+ // Barrier stack: the in-process turn/end identifies the session, then
+ // agent.whenIdle() covers the persistence flush (the idle flip follows
+ // the flush), and the caller's browser settled-poll comes last because
+ // host completion strictly precedes render.
+ whenTurnSettled(timeoutMs = mode === 'record' ? 180_000 : 30_000): Promise {
+ return new Promise((resolveSettled, reject) => {
+ const timer = setTimeout(() => {
+ off()
+ reject(new Error(`no turn/end within ${timeoutMs}ms`))
+ }, timeoutMs)
+ const off = ctx.on('session/event', (session: { id: SessionId }, event: SessionEvent) => {
+ if (event.type !== 'turn/end') return
+ clearTimeout(timer)
+ off()
+ const agent = ctx.agents.get(session.id)
+ if (agent === undefined) {
+ reject(new Error(`turn/end for ${session.id} but no live agent`))
+ return
+ }
+ agent.whenIdle().then(() => { resolveSettled(session.id) }, reject)
+ })
+ })
+ },
+ async close(): Promise {
+ const failures: unknown[] = []
+ // Fixture-consumption check first, while the run's binding state is
+ // still authoritative — a scenario that drove fewer model calls than
+ // recorded fails here instead of drifting green.
+ try {
+ replayHandle?.assertConsumed()
+ } catch (error) {
+ failures.push(error)
+ }
+ failures.push(...await cleanupScaffoldWorld(ctx, workspaceCwd, persistenceRoot))
+ if (failures.length > 0) throw new AggregateError(failures, 'web scaffold teardown failed')
+ },
+ }
+}
+
+/**
+ * Serialize a live session to the canonical raw session-JSONL layout — the
+ * in-memory record-mode harvest, so the on-disk zstd default never matters.
+ */
+function rawSessionLog(session: Session): string {
+ return [
+ JSON.stringify({ type: 'session', ...session.header }),
+ ...packChunkRuns(session.events).map(record => JSON.stringify(record)),
+ '',
+ ].join('\n')
+}
+
+/**
+ * Record-mode fixture write-back: harvest the live session, scrub request
+ * headers to {{system}}/{{tools}} (TODO(web-header-pin): the web lane pins no
+ * header class — a deliberate deviation logged in the Agent Note's deferred
+ * work), tokenize the run-local session id, cwd, and browser RPC id
+ * ({{sessionId}}/{{cwd}}/{{rpcId}}, the committed fixture convention —
+ * re-records then diff only on real content), and write the fixture.
+ * @param scaffold - the record-mode scaffold.
+ * @param sessionId - the driven session.
+ * @param fixturePath - the committed session.jsonl / seed.jsonl target.
+ */
+export async function recordFixture(scaffold: WebScaffold, sessionId: SessionId, fixturePath: string): Promise {
+ const agent = scaffold.ctx.agents.get(sessionId)
+ if (agent === undefined) throw new Error(`record harvest: no live agent for ${sessionId}`)
+ const tokenized = scrubRequestHeaders(rawSessionLog(agent.session))
+ .split(sessionId).join('{{sessionId}}')
+ .split(scaffold.workspaceCwd).join('{{cwd}}')
+ .replace(/"rpcId":"[^"]+"/g, '"rpcId":"{{rpcId}}"')
+ await writeFile(fixturePath, tokenized)
+}
+
+/**
+ * The user prompts recorded in a fixture, in order — the single source tying
+ * spec drive steps to recorded reality so script and fixture cannot drift.
+ * @param fixtureText - raw session.jsonl contents.
+ * @returns the recorded user prompt texts.
+ */
+export function fixtureUserPrompts(fixtureText: string): string[] {
+ return parseSessionLog(fixtureText).flatMap((event) => {
+ if (event.type !== 'user/message' || event.data.source.kind !== 'user') return []
+ const text = event.data.content.filter(block => block.type === 'text').map(block => block.text).join('')
+ return text.length > 0 ? [text] : []
+ })
+}
+
+/**
+ * Seed a recorded session fixture into the scaffold's persistence root
+ * through the REAL backend API (throwaway Context + SessionStore + JSONL
+ * plugin — the semantic-checkpoint precedent), never raw file writes: no
+ * knowledge of bucket hashing, filename encoding, or compression, and
+ * malformed shapes fail loud at seed time. The fixture's tokenized identity
+ * ({{sessionId}}/{{cwd}}) is realized for this world before parsing.
+ * @param scaffold - the target scaffold.
+ * @param fixtureText - raw recorded session.jsonl contents.
+ * @param id - the seeded session id (stable for deterministic goldens).
+ * @returns the seeded id.
+ */
+export async function seedSession(scaffold: WebScaffold, fixtureText: string, id: string): Promise {
+ const realized = fixtureText
+ .split('{{sessionId}}').join(id)
+ .split('{{cwd}}').join(scaffold.workspaceCwd)
+ const fixtureCwd = (JSON.parse(realized.split('\n', 1)[0]!) as { cwd?: string }).cwd
+ const rewritten = fixtureCwd === undefined
+ ? realized
+ : realized.split(fixtureCwd).join(scaffold.workspaceCwd)
+ const events = parseSessionLog(rewritten)
+ if (events.length === 0) throw new Error('seed fixture has no events')
+ const last = events[events.length - 1]!
+ // An open final turn would be mutated by resume's crash repair on first
+ // open; a committed seed must be a closed recording.
+ if (last.type !== 'turn/end') throw new Error(`seed fixture must end in turn/end, got ${last.type}`)
+ const meta: SessionHeader = {
+ version: SESSION_FORMAT_VERSION,
+ id: SessionId(id),
+ createdAt: Date.now() - 60_000,
+ cwd: scaffold.workspaceCwd,
+ delegationDepth: 0,
+ }
+ const seeder = new Context()
+ try {
+ await seeder.plugin(SessionStore)
+ // Same root as the booted tree with the plugin's own default compression,
+ // so the host's directory-scan list() sees one consistent encoding.
+ await seeder.plugin(SessionPersistenceJsonl, { root: scaffold.persistenceRoot })
+ await seeder.sessionPersistence.create(meta)
+ await seeder.sessionPersistence.append(meta.id, events)
+ // Deterministic sidebar order: cold summaries take updatedAt from mtime.
+ const located = seeder.sessionPersistence.locate(meta)
+ if (located !== undefined) {
+ const backdated = new Date(meta.createdAt)
+ await utimes(located.path, backdated, backdated)
+ }
+ } finally {
+ await seeder.fiber.dispose()
+ }
+ return meta.id
+}
+
+/**
+ * Normalize an aria snapshot: uuid, cwd, workspace-basename, and duration
+ * volatility collapse to stable tokens.
+ */
+function normalizeAria(snapshot: string, workspaceCwd: string): string {
+ // The header breadcrumb renders the workspace's basename, not the full
+ // path, so both spellings must collapse to the token.
+ const base = workspaceCwd.split('/').pop()!
+ return snapshot
+ .split(workspaceCwd).join('{{cwd}}')
+ .split(base).join('{{workspace}}')
+ .replace(/[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}/gi, '{{uuid}}')
+ .replace(/\b\d+(?:\.\d+)?(?:ms|s|秒)\b/g, '{{duration}}')
+}
+
+/**
+ * Capture the region's aria snapshot at a settled milestone: poll until two
+ * consecutive normalized captures are equal — a single-shot capture races the
+ * last React commits.
+ * @param page - the page under test.
+ * @param selector - the region locator selector.
+ * @param workspaceCwd - normalization input.
+ * @returns the stable normalized snapshot.
+ */
+export async function captureStableAria(page: Page, selector: string, workspaceCwd: string): Promise {
+ const region = page.locator(selector).first()
+ let previous = normalizeAria(await region.ariaSnapshot(), workspaceCwd)
+ await expect.poll(async () => {
+ const current = normalizeAria(await region.ariaSnapshot(), workspaceCwd)
+ const stable = current === previous
+ previous = current
+ return stable
+ }, { timeout: 5_000, message: 'aria snapshot did not stabilize' }).toBe(true)
+ return previous
+}
+
+/**
+ * Compare a normalized golden, or rewrite it under refresh. Refresh is the
+ * ONLY writer: a missing golden in replay mode fails with the healing command
+ * instead of silently self-bootstrapping.
+ * @param goldenPath - the committed ui.expected.md path.
+ * @param actual - the stable normalized snapshot.
+ * @param mode - the active snapshot mode.
+ */
+export async function compareOrRefreshGolden(goldenPath: string, actual: string, mode: WebSnapshotMode): Promise {
+ const payload = `${actual}\n`
+ if (mode === 'refresh') {
+ await writeFile(goldenPath, payload)
+ return
+ }
+ if (!existsSync(goldenPath)) {
+ throw new Error(`missing golden ${goldenPath} — run DSH_SNAPSHOT=refresh pnpm run test:web to generate it`)
+ }
+ expect(payload).toBe(await readFile(goldenPath, 'utf8'))
+}
+
+/**
+ * Fixture-inventory guard (the TUI afterAll shape): the scenario directory
+ * holds exactly the expected files and every committed JSONL is a scrub
+ * fixed-point without a run-local browser RPC id.
+ * @param dir - the scenario snapshot directory.
+ * @param expected - the exact expected file inventory.
+ */
+export async function assertFixtureInventory(dir: string, expected: string[]): Promise {
+ const entries = (await readdir(dir)).sort()
+ expect(entries).toEqual([...expected].sort())
+ for (const entry of entries.filter(name => name.endsWith('.jsonl'))) {
+ const content = await readFile(join(dir, entry), 'utf8')
+ expect(scrubRequestHeaders(content), `${dir}/${entry} carries request-header bulk`).toBe(content)
+ expect(content, `${dir}/${entry} carries a run-local rpcId`)
+ .not.toMatch(/"rpcId":"(?!\{\{rpcId\}\})[^"]+"/)
+ }
+}
+
+/**
+ * Console tripwires: reconnect/gap-repair self-healing or a pageerror must
+ * fail the scenario, not mask a dead wire behind eventual consistency.
+ * @param page - the page under test.
+ * @returns live warning/pageerror collectors to assert empty at scenario end.
+ */
+export function watchConsole(page: Page): { warnings: string[]; pageErrors: string[] } {
+ const warnings: string[] = []
+ const pageErrors: string[] = []
+ page.on('console', (message) => {
+ const text = message.text()
+ if (/connection lost|gap repair|discontinuous/i.test(text)) warnings.push(text)
+ })
+ page.on('pageerror', (error) => { pageErrors.push(String(error)) })
+ return { warnings, pageErrors }
+}
+
+/**
+ * Remove only connection-loss warnings emitted after an intentional reload.
+ * Earlier warnings and all gap-repair/discontinuity warnings remain fatal.
+ * @param tripwire - the live console-warning collector.
+ * @param warningStart - warning count captured immediately before reloading.
+ */
+export function acknowledgeReloadConnectionLoss(
+ tripwire: ReturnType,
+ warningStart: number,
+): void {
+ const reloadWarnings = tripwire.warnings.splice(warningStart)
+ tripwire.warnings.push(...reloadWarnings.filter(text => !/connection lost/i.test(text)))
+}
diff --git a/apps/web/tests/seeded-history.e2e.ts b/apps/web/tests/seeded-history.e2e.ts
new file mode 100644
index 0000000000..97ebfff0b1
--- /dev/null
+++ b/apps/web/tests/seeded-history.e2e.ts
@@ -0,0 +1,124 @@
+// Web e2e scenario: seeded history. A recorded session seeded cold through
+// the REAL persistence API renders purely from the log — the surface nothing
+// else covers: sidebar cold listing, the implicit resume/attach inside the
+// history RPC, history-page tool views, and the client fold of historical
+// events — with ZERO model calls in replay (no replay fixture; a stray stream
+// fails loud on the open llm seam). The seed is a recorded fixture under the
+// same record discipline as every other: DSH_SNAPSHOT=record drives the turn
+// live through the composer (real read tool against seeded workspace files)
+// and harvests seed.jsonl; replay/refresh seed it cold and only render.
+import { readFile, writeFile, mkdir } from 'node:fs/promises'
+import { fileURLToPath } from 'node:url'
+import type { Browser, Page } from 'playwright'
+import { chromium } from 'playwright'
+import { afterAll, beforeAll, describe, expect, it, onTestFailed } from 'vitest'
+import { join } from 'node:path'
+import {
+ assertFixtureInventory, captureStableAria, compareOrRefreshGolden, fixtureUserPrompts,
+ launchWebScaffold, recordFixture, seedSession, watchConsole, webSnapshotMode, type WebScaffold,
+} from './scaffold.ts'
+import { saveFailureShot } from './support.ts'
+
+const SNAPSHOT_DIR = fileURLToPath(new URL('./snapshots/seeded-history', import.meta.url))
+const SEED = fileURLToPath(new URL('./snapshots/seeded-history/seed.jsonl', import.meta.url))
+const UI_EXPECTED = fileURLToPath(new URL('./snapshots/seeded-history/ui.expected.md', import.meta.url))
+const MODE = webSnapshotMode()
+const SEED_ID = 'seeded-history-web-e2e'
+
+const PROMPT = 'Use the read tool twice in one assistant message: read a.txt and b.txt. Then reply with the single word DONE and stop.'
+
+describe('web e2e: seeded history renders through cold resume', () => {
+ let scaffold: WebScaffold
+ let browser: Browser
+ let page: Page
+ let tripwire: ReturnType
+
+ beforeAll(async () => {
+ scaffold = await launchWebScaffold({})
+ // The workspace-aware flow runs sessions in /workspace
+ // (the composer's default draft name); the read-tool targets must live in
+ // that session cwd. Pre-creating the directory is safe: create-by-name
+ // adopts an existing directory.
+ const sessionCwd = join(scaffold.workspaceCwd, 'workspace')
+ await mkdir(sessionCwd, { recursive: true })
+ await writeFile(join(sessionCwd, 'a.txt'), 'alpha\n')
+ await writeFile(join(sessionCwd, 'b.txt'), 'beta\n')
+ if (MODE !== 'record') {
+ const raw = await readFile(SEED, 'utf8')
+ expect(fixtureUserPrompts(raw), 'seed fixture must carry exactly the drive prompt').toEqual([PROMPT])
+ await seedSession(scaffold, raw, SEED_ID)
+ }
+ browser = await chromium.launch()
+ 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 })
+ }, 120_000)
+
+ afterAll(async () => {
+ await browser?.close()
+ await scaffold?.close()
+ })
+
+ it.skipIf(MODE !== 'record')('records the seed turn live through the composer', async () => {
+ onTestFailed(() => saveFailureShot(page, 'web-e2e-seeded-record'))
+ const input = page.locator('textarea').first()
+ await input.waitFor({ timeout: 10_000 })
+ const settled = scaffold.whenTurnSettled()
+ await input.fill(PROMPT)
+ await input.press('Enter')
+ const sessionId = await settled
+ await recordFixture(scaffold, sessionId, SEED)
+ }, 200_000)
+
+ it.skipIf(MODE === 'record')('lists the seeded session cold and renders its history from the log', async () => {
+ onTestFailed(() => saveFailureShot(page, 'web-e2e-seeded-history'))
+ // The sidebar tree collapses workspace groups by default: click the group
+ // row (treeitem 0) to expand, then 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()
+ // Settled barrier for history: the recorded final assistant text renders.
+ await expect.poll(() => page.getByText('DONE', { exact: true }).count(), { timeout: 15_000 }).toBe(1)
+ // Tool cards render from logged tool/call + tool/result alone (views are
+ // host-recomputed per page; the generic card is the documented default).
+ const toolRows = page.locator('[data-variant], [data-sample]')
+ await expect.poll(() => toolRows.count(), { timeout: 10_000 }).toBeGreaterThanOrEqual(2)
+ expect(await page.getByText('a.txt', { exact: false }).count()).toBeGreaterThan(0)
+ }, 60_000)
+
+ it.skipIf(MODE === 'record')('matches the historical conversation aria golden', async () => {
+ onTestFailed(() => saveFailureShot(page, 'web-e2e-seeded-aria'))
+ const snapshot = (await captureStableAria(page, '[class*="centerCol"]', scaffold.workspaceCwd))
+ .split(SEED_ID).join('{{seededId}}')
+ await compareOrRefreshGolden(UI_EXPECTED, snapshot, MODE)
+ })
+
+ it.skipIf(MODE === 'record')('expands and collapses a tool row rebuilt from the cold log', async () => {
+ onTestFailed(() => saveFailureShot(page, 'web-e2e-seeded-toolrow'))
+ // Interaction over cold-resumed history: read rows are expand-in-place
+ // rows (rowExpands routes the click to toggleExpand, not openDetails), so
+ // the gesture under test is the inline fold over log-rebuilt content.
+ // Runs after the golden capture; still zero model calls.
+ const row = page.locator('[data-variant] [data-clickable][role="button"]').first()
+ await row.waitFor({ timeout: 10_000 })
+ expect(await row.getAttribute('aria-expanded')).toBe('false')
+ await row.click()
+ await expect.poll(() => row.getAttribute('aria-expanded'), { timeout: 5_000 }).toBe('true')
+ // The expanded body renders the recorded tool result (a.txt's contents).
+ await expect.poll(() => page.getByText('alpha', { exact: false }).count(), { timeout: 5_000 }).toBeGreaterThan(0)
+ await row.click()
+ await expect.poll(() => row.getAttribute('aria-expanded'), { timeout: 5_000 }).toBe('false')
+ })
+
+ it.skipIf(MODE === 'record')('issued zero model calls and stayed clean', async () => {
+ // No replay fixture was installed and the llm seam is open — any stray
+ // stream would have failed the turn loudly. Cleanliness pins the wire.
+ expect(tripwire.pageErrors).toEqual([])
+ expect(tripwire.warnings).toEqual([])
+ await assertFixtureInventory(SNAPSHOT_DIR, ['seed.jsonl', 'ui.expected.md'])
+ })
+})
diff --git a/apps/web/tests/session-title.snapshot.ts b/apps/web/tests/session-title.snapshot.ts
index c1616bb724..313573ea94 100644
--- a/apps/web/tests/session-title.snapshot.ts
+++ b/apps/web/tests/session-title.snapshot.ts
@@ -10,9 +10,12 @@ const PLUGINS: readonly (WebBootEntry & { dir: string })[] = [
{ id: '@deepseek-ai/dsh-client-connection', dir: 'connection', url: '/plugins/connection.js', rev: 'fx', inject: [], immediately: true },
{ id: '@deepseek-ai/dsh-client-runtime', dir: 'runtime', url: '/plugins/runtime.js', rev: 'fx', inject: ['@deepseek-ai/dsh-client-connection'], immediately: true },
{ id: '@deepseek-ai/dsh-client-ui-theme', dir: 'ui-theme', url: '/plugins/ui-theme.js', rev: 'fx', inject: [], immediately: true },
- { id: '@deepseek-ai/dsh-client-i18n', dir: 'i18n', url: '/plugins/i18n.js', rev: 'fx', inject: [], immediately: true },
+ { id: '@deepseek-ai/dsh-client-locale', dir: 'locale', url: '/plugins/locale.js', rev: 'fx', inject: [], immediately: true },
{ id: '@deepseek-ai/dsh-client-ui-layout', dir: 'ui-layout', url: '/plugins/ui-layout.js', rev: 'fx', inject: ['@deepseek-ai/dsh-client-runtime'] },
{ id: '@deepseek-ai/dsh-client-ui-sidebar', dir: 'ui-sidebar', url: '/plugins/ui-sidebar.js', rev: 'fx', inject: ['@deepseek-ai/dsh-client-ui-layout'] },
+ { id: '@deepseek-ai/dsh-client-ui-settings', dir: 'ui-settings', url: '/plugins/ui-settings.js', rev: 'fx', inject: ['@deepseek-ai/dsh-client-ui-sidebar'] },
+ { id: '@deepseek-ai/dsh-client-ui-settings-general', dir: 'ui-settings-general', url: '/plugins/ui-settings-general.js', rev: 'fx', inject: ['@deepseek-ai/dsh-client-ui-settings', '@deepseek-ai/dsh-client-locale'] },
+ { id: '@deepseek-ai/dsh-client-ui-models', dir: 'ui-models', url: '/plugins/ui-models.js', rev: 'fx', inject: ['@deepseek-ai/dsh-client-ui-settings'] },
{ id: '@deepseek-ai/dsh-client-ui-conversation', dir: 'ui-conversation', url: '/plugins/ui-conversation.js', rev: 'fx', inject: ['@deepseek-ai/dsh-client-ui-layout'] },
{ id: '@deepseek-ai/dsh-client-ui-workspace', dir: 'ui-workspace', url: '/plugins/ui-workspace.js', rev: 'fx', inject: ['@deepseek-ai/dsh-client-runtime', '@deepseek-ai/dsh-client-ui-conversation', '@deepseek-ai/dsh-client-ui-sidebar'] },
{ id: '@deepseek-ai/dsh-client-ui-trajectory', dir: 'ui-trajectory', url: '/plugins/ui-trajectory.js', rev: 'fx', inject: ['@deepseek-ai/dsh-client-ui-conversation'] },
@@ -94,10 +97,10 @@ it('projects initial and revised durable titles through the built nine-plugin fi
})
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)
+ // The fixture Intent selects the workspace, so the current-group effect
+ // already expanded it; clicking the header would now collapse (the twist
+ // stays live since intent stopped forcing expansion).
+ await within(tree).findByText('4 sessions')
const initialLabel = 'Fixture 历史会话'
const initialRowLabel = await screen.findByText(initialLabel)
diff --git a/apps/web/tests/settings-chrome.e2e.ts b/apps/web/tests/settings-chrome.e2e.ts
new file mode 100644
index 0000000000..90f0b3964b
--- /dev/null
+++ b/apps/web/tests/settings-chrome.e2e.ts
@@ -0,0 +1,170 @@
+// Web e2e scenarios: the settings surface — the modal shell (trigger, nav,
+// section switching, both close paths), the Appearance preference row (the
+// real theme gesture — click 深色 and the whole cascade runs: ThemeService preference -> localStorage dsh.theme
+// -> theme/change -> ui-layout's presenter -> body attribute -> alias token)
+// and the Language row (settings-scoped localization + persisted dsh.locale).
+// Zero model calls: everything is pure client + persistence state on a blank
+// frame, so there is no fixture and a stray stream would fail loud on the
+// open llm seam.
+import { fileURLToPath } from 'node:url'
+import type { Browser, Page } from 'playwright'
+import { chromium } from 'playwright'
+import { afterAll, beforeAll, describe, expect, it, onTestFailed } from 'vitest'
+import { join } from 'node:path'
+import {
+ acknowledgeReloadConnectionLoss, assertFixtureInventory, captureStableAria, compareOrRefreshGolden,
+ launchWebScaffold, watchConsole, webSnapshotMode, type WebScaffold,
+} from './scaffold.ts'
+import { saveFailureShot } from './support.ts'
+
+const SNAPSHOT_DIR = fileURLToPath(new URL('./snapshots/settings-chrome', import.meta.url))
+const DIALOG_EXPECTED = join(SNAPSHOT_DIR, 'dialog.expected.md')
+const MODE = webSnapshotMode()
+
+describe('web e2e: settings modal, appearance gesture, language switch', () => {
+ let scaffold: WebScaffold
+ let browser: Browser
+ let page: Page
+ let tripwire: ReturnType
+
+ beforeAll(async () => {
+ scaffold = await launchWebScaffold({})
+ browser = await chromium.launch()
+ 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 })
+ }, 120_000)
+
+ afterAll(async () => {
+ await browser?.close()
+ await scaffold?.close()
+ })
+
+ it('opens the settings dialog, switches sections, and closes by every path', async () => {
+ onTestFailed(() => saveFailureShot(page, 'web-e2e-settings-shell'))
+ const trigger = page.getByRole('button', { name: '设置', exact: true })
+ expect(await trigger.getAttribute('aria-haspopup')).toBe('dialog')
+ expect(await trigger.getAttribute('aria-expanded')).toBe('false')
+ await trigger.click()
+ const dialog = page.getByRole('dialog', { name: '设置' })
+ await dialog.waitFor({ timeout: 10_000 })
+ expect(await trigger.getAttribute('aria-expanded')).toBe('true')
+ // General is the active section by default; its skeleton rows plus the
+ // functional Language and Appearance rows render.
+ expect(await dialog.getByRole('button', { name: '通用设置' }).getAttribute('aria-current')).toBe('true')
+ await expect.poll(() => dialog.getByText('语言', { exact: true }).count(), { timeout: 5_000 }).toBe(1)
+ await expect.poll(() => dialog.getByText('外观', { exact: true }).count(), { timeout: 5_000 }).toBe(1)
+ // Golden of the freshly opened dialog (default zh, General active).
+ const snapshot = await captureStableAria(page, '[role="dialog"]', scaffold.workspaceCwd)
+ await compareOrRefreshGolden(DIALOG_EXPECTED, snapshot, MODE)
+ // Section switch: aria-current moves; Models is deliberately empty.
+ await dialog.getByRole('button', { name: '模型' }).click()
+ await expect.poll(() => dialog.getByRole('button', { name: '模型' }).getAttribute('aria-current'), { timeout: 5_000 }).toBe('true')
+ expect(await dialog.getByRole('button', { name: '通用设置' }).getAttribute('aria-current')).toBeNull()
+ // Close path 1: Escape.
+ await page.keyboard.press('Escape')
+ await expect.poll(() => page.getByRole('dialog', { name: '设置' }).count(), { timeout: 5_000 }).toBe(0)
+ expect(await trigger.getAttribute('aria-expanded')).toBe('false')
+ // Close path 2: the header close button (focus lands there on open).
+ await trigger.click()
+ await page.getByRole('dialog', { name: '设置' }).getByRole('button', { name: '关闭' }).click()
+ await expect.poll(() => page.getByRole('dialog', { name: '设置' }).count(), { timeout: 5_000 }).toBe(0)
+ expect(tripwire.pageErrors).toEqual([])
+ }, 60_000)
+
+ it('flips the theme through the Appearance cubes and persists across reload', async () => {
+ onTestFailed(() => saveFailureShot(page, 'web-e2e-settings-appearance'))
+ const readState = async (): Promise<{ attr: boolean; token: string; stored: string | null }> =>
+ await page.evaluate(() => ({
+ attr: document.body.hasAttribute('data-ds-dark-theme'),
+ token: getComputedStyle(document.body).getPropertyValue('--dsw-alias-bg-base').trim(),
+ stored: localStorage.getItem('dsh.theme'),
+ }))
+ // Pin the OS scheme to light so the default `system` preference resolves
+ // light and the dark flip below is unambiguously the gesture's doing.
+ await page.emulateMedia({ colorScheme: 'light' })
+ const light = await readState()
+ expect(light.attr).toBe(false)
+
+ await page.getByRole('button', { name: '设置', exact: true }).click()
+ const dialog = page.getByRole('dialog', { name: '设置' })
+ await dialog.waitFor({ timeout: 10_000 })
+ const darkCube = dialog.getByRole('button', { name: '深色' })
+ expect(await darkCube.getAttribute('aria-pressed')).toBe('false')
+ await darkCube.click()
+ // The full cascade: pressed state, persisted preference, body attribute,
+ // alias token flip — all from one real user gesture.
+ await expect.poll(() => darkCube.getAttribute('aria-pressed'), { timeout: 5_000 }).toBe('true')
+ const dark = await readState()
+ expect(dark.attr).toBe(true)
+ expect(dark.stored).toBe('dark')
+ expect(dark.token).not.toBe(light.token)
+ await page.keyboard.press('Escape')
+
+ // Reload: the preference survives boot (restore + presenter initial apply).
+ const warningStart = tripwire.warnings.length
+ await page.reload({ waitUntil: 'load' })
+ await page.waitForSelector('[class*="frame"]', { timeout: 30_000 })
+ acknowledgeReloadConnectionLoss(tripwire, warningStart)
+ await page.emulateMedia({ colorScheme: 'light' })
+ const reloaded = await readState()
+ expect(reloaded.attr).toBe(true)
+ expect(reloaded.stored).toBe('dark')
+
+ // `system` follows the emulated OS scheme (dark stays dark, light clears).
+ await page.getByRole('button', { name: '设置', exact: true }).click()
+ const systemCube = page.getByRole('dialog', { name: '设置' }).getByRole('button', { name: '跟随系统' })
+ await systemCube.click()
+ await expect.poll(() => systemCube.getAttribute('aria-pressed'), { timeout: 5_000 }).toBe('true')
+ await expect.poll(async () => (await readState()).attr, { timeout: 5_000 }).toBe(false)
+ await page.emulateMedia({ colorScheme: 'dark' })
+ await expect.poll(async () => (await readState()).attr, { timeout: 5_000 }).toBe(true)
+ // Restore for the specs that follow: light preference beats the emulated
+ // dark OS scheme, leaving the shared page in the light default.
+ await page.getByRole('dialog', { name: '设置' }).getByRole('button', { name: '浅色' }).click()
+ await expect.poll(async () => (await readState()).attr, { timeout: 5_000 }).toBe(false)
+ await page.keyboard.press('Escape')
+ expect(tripwire.pageErrors).toEqual([])
+ }, 90_000)
+
+ it('switches the settings surface language and persists dsh.locale', async () => {
+ onTestFailed(() => saveFailureShot(page, 'web-e2e-settings-language'))
+ await page.getByRole('button', { name: '设置', exact: true }).click()
+ const zhDialog = page.getByRole('dialog', { name: '设置' })
+ await zhDialog.waitFor({ timeout: 10_000 })
+ // The Language selector pill shows the active locale's own name.
+ const selector = zhDialog.getByRole('button', { name: '中文' })
+ expect(await selector.getAttribute('aria-haspopup')).toBe('menu')
+ await selector.click()
+ await page.getByRole('menuitem', { name: 'English' }).click()
+ // The settings-owned copy re-registers localized: dialog title, nav,
+ // Appearance labels. (Only the settings namespaces are localized today —
+ // the rest of the app's copy is intentionally out of this row's scope.)
+ const enDialog = page.getByRole('dialog', { name: 'Settings' })
+ await enDialog.waitFor({ timeout: 10_000 })
+ expect(await enDialog.getByRole('button', { name: 'General' }).getAttribute('aria-current')).toBe('true')
+ await expect.poll(() => enDialog.getByText('Appearance', { exact: true }).count(), { timeout: 5_000 }).toBe(1)
+ expect(await page.evaluate(() => localStorage.getItem('dsh.locale'))).toBe('en')
+ // Reload keeps English; then restore zh so shared page state (and the
+ // other specs' 设置-anchored selectors + goldens) see the default again.
+ const warningStart = tripwire.warnings.length
+ await page.reload({ waitUntil: 'load' })
+ await page.waitForSelector('[class*="frame"]', { timeout: 30_000 })
+ acknowledgeReloadConnectionLoss(tripwire, warningStart)
+ const enTrigger = page.getByRole('button', { name: 'Settings' })
+ await enTrigger.waitFor({ timeout: 10_000 })
+ await enTrigger.click()
+ await page.getByRole('dialog', { name: 'Settings' }).getByRole('button', { name: 'English' }).click()
+ await page.getByRole('menuitem', { name: '中文' }).click()
+ await page.getByRole('dialog', { name: '设置' }).waitFor({ timeout: 10_000 })
+ expect(await page.evaluate(() => localStorage.getItem('dsh.locale'))).toBe('zh')
+ await page.keyboard.press('Escape')
+ expect(tripwire.pageErrors).toEqual([])
+ }, 90_000)
+
+ it.skipIf(MODE === 'record')('keeps the fixture inventory closed', async () => {
+ expect(tripwire.warnings).toEqual([])
+ await assertFixtureInventory(SNAPSHOT_DIR, ['dialog.expected.md'])
+ })
+})
diff --git a/apps/web/tests/slash-flow.snapshot.ts b/apps/web/tests/slash-flow.snapshot.ts
new file mode 100644
index 0000000000..29c1d68f7a
--- /dev/null
+++ b/apps/web/tests/slash-flow.snapshot.ts
@@ -0,0 +1,191 @@
+// @vitest-environment jsdom
+// Assembled keyless snapshot of the slash/input/session convergence under the
+// agent-parity model: the New Session view state locks the composer until a
+// Workspace is picked (connectWorkspace materializes the full Session+Agent),
+// the '/' menu serves the session's wire command catalog (sessions are always
+// agent-backed — no draft/materialized split), a leadingInput command claims,
+// submits over the wire, and notices its result, and the SAME composer
+// textarea then carries the first plain send, whose ACCEPTANCE (not attempt)
+// flips blank and surfaces the session in lists. This is the user-visible
+// acceptance anchor — package mocks do not substitute for the assembled
+// application transcript.
+import { readFileSync } from 'node:fs'
+import { join } from 'node:path'
+import { act, cleanup, fireEvent, screen, waitFor, within } from '@testing-library/react'
+import { afterEach, beforeEach, expect, it, vi } from 'vitest'
+import type { WebBootEntry } from '@deepseek-ai/dsh-client-modules/client'
+import { AppWebEntry } from '@deepseek-ai/dsh-client-web'
+
+const PLUGINS: readonly (WebBootEntry & { dir: string })[] = [
+ { id: '@deepseek-ai/dsh-client-connection', dir: 'connection', url: '/plugins/connection.js', rev: 'fx', inject: [], immediately: true },
+ { id: '@deepseek-ai/dsh-client-runtime', dir: 'runtime', url: '/plugins/runtime.js', rev: 'fx', inject: ['@deepseek-ai/dsh-client-connection'], immediately: true },
+ { id: '@deepseek-ai/dsh-client-ui-theme', dir: 'ui-theme', url: '/plugins/ui-theme.js', rev: 'fx', inject: [], immediately: true },
+ { id: '@deepseek-ai/dsh-client-locale', dir: 'locale', url: '/plugins/locale.js', rev: 'fx', inject: [], immediately: true },
+ { id: '@deepseek-ai/dsh-client-ui-layout', dir: 'ui-layout', url: '/plugins/ui-layout.js', rev: 'fx', inject: ['@deepseek-ai/dsh-client-runtime'] },
+ { id: '@deepseek-ai/dsh-client-ui-sidebar', dir: 'ui-sidebar', url: '/plugins/ui-sidebar.js', rev: 'fx', inject: ['@deepseek-ai/dsh-client-ui-layout'] },
+ { id: '@deepseek-ai/dsh-client-ui-slash', dir: 'ui-slash', url: '/plugins/ui-slash.js', rev: 'fx', inject: ['@deepseek-ai/dsh-client-runtime'] },
+ { id: '@deepseek-ai/dsh-client-ui-conversation', dir: 'ui-conversation', url: '/plugins/ui-conversation.js', rev: 'fx', inject: ['@deepseek-ai/dsh-client-ui-layout', '@deepseek-ai/dsh-client-ui-slash'] },
+ { id: '@deepseek-ai/dsh-client-ui-command', dir: 'ui-command', url: '/plugins/ui-command.js', rev: 'fx', inject: ['@deepseek-ai/dsh-client-ui-slash', '@deepseek-ai/dsh-client-ui-conversation'] },
+ { id: '@deepseek-ai/dsh-client-ui-skill', dir: 'ui-skill', url: '/plugins/ui-skill.js', rev: 'fx', inject: ['@deepseek-ai/dsh-client-ui-slash'] },
+ { id: '@deepseek-ai/dsh-client-ui-subagent', dir: 'ui-subagent', url: '/plugins/ui-subagent.js', rev: 'fx', inject: ['@deepseek-ai/dsh-client-ui-slash'] },
+ {
+ id: '@deepseek-ai/dsh-client-ui-workspace',
+ dir: 'ui-workspace',
+ url: '/plugins/ui-workspace.js',
+ rev: 'fx',
+ inject: [
+ '@deepseek-ai/dsh-client-runtime',
+ '@deepseek-ai/dsh-client-ui-conversation',
+ '@deepseek-ai/dsh-client-ui-sidebar',
+ ],
+ },
+]
+
+const bundles = new Map(PLUGINS.map(plugin => [
+ plugin.url,
+ readFileSync(join(process.cwd(), 'packages/client', plugin.dir, 'lib/client.js'), 'utf8'),
+]))
+
+interface FixtureWindow extends Window {
+ __DSH_BOOT__?: { rev: string; entries: WebBootEntry[] }
+ __ModuleLoader__?: unknown
+}
+
+class ResizeObserverStub {
+ observe(): void {}
+ disconnect(): void {}
+ unobserve(): void {}
+}
+
+const win = window as FixtureWindow
+let unmount: (() => void) | undefined
+
+beforeEach(() => {
+ localStorage.clear()
+ document.title = 'DeepSeek Harness'
+ vi.stubGlobal('ResizeObserver', ResizeObserverStub)
+ vi.stubGlobal('requestAnimationFrame', (callback: FrameRequestCallback) =>
+ setTimeout(() => { callback(0) }, 0) as unknown as number)
+ vi.stubGlobal('cancelAnimationFrame', (id: number) => { clearTimeout(id) })
+})
+
+afterEach(() => {
+ act(() => { unmount?.() })
+ unmount = undefined
+ cleanup()
+ delete win.__DSH_BOOT__
+ delete win.__ModuleLoader__
+ delete (globalThis as Record).__fxTiming
+ document.body.innerHTML = ''
+ document.head.querySelectorAll('style[data-plugin]').forEach((style) => { style.remove() })
+ document.title = ''
+ history.replaceState(null, '', '/')
+ vi.unstubAllGlobals()
+})
+
+/** Boot the complete built client graph against one keyless fixture branch. */
+function boot(search: string): void {
+ history.replaceState(null, '', `/${search}`)
+ const root = document.createElement('div')
+ root.id = 'root'
+ document.body.appendChild(root)
+ win.__DSH_BOOT__ = { rev: 'fx', entries: PLUGINS.map(({ dir: _dir, ...plugin }) => plugin) }
+ act(() => {
+ const entry = new AppWebEntry(root, {
+ fetchBundle: (url) => {
+ const code = bundles.get(url)
+ return code === undefined ? Promise.reject(new Error(`missing built bundle ${url}`)) : Promise.resolve(code)
+ },
+ executeBundle: (code) => { (0, eval)(code) },
+ })
+ void entry.run()
+ unmount = () => { entry.dispose() }
+ })
+}
+
+/** Collapse decorative whitespace while preserving the text a user sees. */
+function visibleText(element: Element): string {
+ return (element.textContent ?? '').replace(/\s+/g, ' ').trim()
+}
+
+/** Type into the machine-driven composer and let the change echo back. */
+async function typeComposer(composer: HTMLTextAreaElement, value: string): Promise {
+ fireEvent.change(composer, { target: { value } })
+ await waitFor(() => { expect(composer.value).toBe(value) })
+}
+
+it('locked view state, connectWorkspace unlock, /echo claim chain, and blank-on-acceptance ride one resident composer', async () => {
+ boot('?fixture=empty')
+
+ // View state: no session entity — the composer renders locked; only the
+ // workspace picker is live.
+ const locked = await screen.findByPlaceholderText(
+ 'Choose a workspace to start', {}, { timeout: 10_000 },
+ )
+ expect(locked.disabled).toBe(true)
+
+ // Pick (create) a Workspace: connectWorkspace materializes the full
+ // Session+Agent and the provider swaps in the live blank-session hero.
+ fireEvent.click(screen.getAllByRole('button', { name: 'Choose workspace' })
+ .find(el => el.getAttribute('aria-haspopup') === 'menu')!)
+ fireEvent.click(await screen.findByRole('menuitem', { name: 'Create workspace' }))
+ fireEvent.click(await screen.findByRole('menuitem', { name: 'Create a new workspace' }))
+ const dialog = await screen.findByRole('dialog', { name: 'Create a new workspace' })
+ fireEvent.change(within(dialog).getByRole('textbox', { name: 'New workspace name' }), {
+ target: { value: 'nova' },
+ })
+ fireEvent.click(within(dialog).getByRole('button', { name: 'Create workspace' }))
+
+ const composer = await screen.findByPlaceholderText(
+ 'Describe what you want to build', {}, { timeout: 10_000 },
+ )
+ expect(composer.disabled).toBe(false)
+
+ // '/' opens the menu with the session's wire command catalog (the session
+ // is agent-backed from birth — the catalog is the single-address list).
+ await typeComposer(composer, '/')
+ const menu = await screen.findByRole('listbox', { name: 'Trigger suggestions' })
+ await waitFor(() => { expect(visibleText(menu)).toContain('echo') })
+ const menuText = visibleText(menu)
+
+ // Pick /echo (leadingInput): the claim token lands in the same textarea.
+ fireEvent.mouseDown(screen.getByRole('option', { name: /echo/ }))
+ await waitFor(() => { expect(composer.value).toBe('/echo ') })
+
+ // Type args and submit: the claim executes over the wire and notices its
+ // result; the token is consumed and the draft returns to plain text.
+ await typeComposer(composer, '/echo hello parser')
+ fireEvent.keyDown(composer, { key: 'Enter' })
+ await screen.findByText('hello parser', {}, { timeout: 10_000 })
+ await waitFor(() => { expect(composer.value).toBe('') })
+
+ // Slash execution does not flip blank: the selected row remains New Session.
+ const tree = screen.getByRole('tree', { name: 'Sessions' })
+ expect(within(tree).getByText('1 session')).toBeDefined()
+ expect(within(tree).getByText('New Session')).toBeDefined()
+
+ // First plain send through the SAME textarea: acceptance logs the user
+ // message and converts the existing sidebar row out of blank.
+ const before = composer
+ await typeComposer(composer, 'build me a parser')
+ fireEvent.keyDown(composer, { key: 'Enter' })
+ await waitFor(() => {
+ expect(screen.queryByText("Let's start building")).toBeNull()
+ }, { timeout: 10_000 })
+ await waitFor(() => { expect(within(tree).getByText('1 session')).toBeDefined() }, { timeout: 10_000 })
+ const after = document.querySelector('textarea')
+
+ expect({
+ menuHadEcho: menuText.includes('echo'),
+ menuHadCompact: menuText.includes('compact'),
+ composerSurvivedConversion: after === before,
+ sessionListed: visibleText(within(tree).getByText('1 session').closest('[role="treeitem"]')!),
+ }).toMatchInlineSnapshot(`
+ {
+ "composerSurvivedConversion": true,
+ "menuHadCompact": true,
+ "menuHadEcho": true,
+ "sessionListed": "nova1 session",
+ }
+ `)
+})
diff --git a/apps/web/tests/smoke-real.e2e.ts b/apps/web/tests/smoke-real.e2e.ts
index a3d511df16..2980458fec 100644
--- a/apps/web/tests/smoke-real.e2e.ts
+++ b/apps/web/tests/smoke-real.e2e.ts
@@ -24,7 +24,7 @@ import { pathToFileURL } from 'node:url'
import type { Browser, Page } from 'playwright'
import { chromium } from 'playwright'
import { afterAll, beforeAll, describe, expect, it, onTestFailed } from 'vitest'
-import { REPO_ROOT, probeFreePort, requireDist, saveFailureShot } from './support.ts'
+import { REPO_ROOT, connectFreshWorkspace, probeFreePort, requireDist, saveFailureShot } from './support.ts'
/** Repo-root .env → process.env (never overrides an already-set variable). */
function loadRootEnv(): void {
@@ -147,7 +147,7 @@ async function detailsTrack(page: Page): Promise