seeded-history.e2e.ts 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553
  1. // Web e2e scenario: seeded history. A recorded session seeded cold through
  2. // the REAL persistence API renders purely from the log — the surface nothing
  3. // else covers: sidebar cold listing, cold history paging without Agent
  4. // activation, history-page tool views, and the client's log-ordered transcript
  5. // events — with ZERO model calls in replay (no replay fixture; a stray stream
  6. // fails loud on the open llm seam). The cold session also carries keyless
  7. // command-row surfaces: the seeded manual `/compact` lifecycle folds into its
  8. // checkpoint, an Access-chip pick later runs `/permission` on the host, and
  9. // `/feedback` pins its expandable correlation ids. The seed is a recorded
  10. // fixture under the same record discipline as every other: DSH_SNAPSHOT=record drives the turn
  11. // live through the composer (real read tool against seeded workspace files)
  12. // and harvests session.jsonl; replay/refresh seed it cold and only render.
  13. import { readFile, writeFile, mkdir } from 'node:fs/promises'
  14. import { fileURLToPath } from 'node:url'
  15. import type { Browser, Page } from 'playwright'
  16. import { chromium } from 'playwright'
  17. import { afterAll, beforeAll, describe, expect, it, onTestFailed, vi } from 'vitest'
  18. import { createUserMessage } from '@deepseek-ai/dsh-llm'
  19. import type { ContentBlock, Message } from '@deepseek-ai/dsh-llm'
  20. import { deriveEventMessage, SessionId } from '@deepseek-ai/dsh-session'
  21. import type { SessionEvent } from '@deepseek-ai/dsh-session'
  22. import type { TokenMeter } from '@deepseek-ai/dsh-token-meter'
  23. import { join } from 'node:path'
  24. import {
  25. assertFixtureInventory, captureStableAria, compareOrRefreshGolden, fixtureUserPrompts,
  26. launchWebScaffold, parseSeedFixture, realizeSeedFixture, recordFixture, renderSeedFixture, seedSession, watchConsole,
  27. webSnapshotMode, type WebScaffold,
  28. } from './scaffold.ts'
  29. import { newEnglishPage, saveFailureShot } from './support.ts'
  30. const SNAPSHOT_DIR = fileURLToPath(new URL('../../../snapshots/web/seeded-history', import.meta.url))
  31. const SEED = fileURLToPath(new URL('../../../snapshots/web/seeded-history/session.jsonl', import.meta.url))
  32. const UI_EXPECTED = fileURLToPath(new URL('../../../snapshots/web/seeded-history/ui.expected.md', import.meta.url))
  33. // Command-row goldens over the same conversation after direct host commands.
  34. const COMMAND_ROW_EXPECTED = fileURLToPath(new URL('../../../snapshots/web/seeded-history/command-row.expected.md', import.meta.url))
  35. const FEEDBACK_ROW_EXPECTED = fileURLToPath(new URL('../../../snapshots/web/seeded-history/feedback-row.expected.md', import.meta.url))
  36. const FILE_OPEN_FAILURE_EXPECTED = fileURLToPath(new URL('../../../snapshots/web/seeded-history/file-open-failure.expected.md', import.meta.url))
  37. const MODE = webSnapshotMode()
  38. const SEED_ID = 'seeded-history-web-e2e'
  39. 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.'
  40. /**
  41. * Append a complete manual `/compact` lifecycle and valid compaction transaction
  42. * over the recorded turn's own surface. The recording stays model-authentic and
  43. * reusable; replay adds this deterministic condition before seeding it cold, so
  44. * the scenario pins both the log-preserving marker and its single-card command
  45. * presentation through the real host and browser.
  46. * @param raw - the seed fixture text, already realized (placeholder-free) so
  47. * the shadow price below is computed from the exact strings the host folds.
  48. * @param meter - the composed token meter; the appended `compaction/summary`'s
  49. * shadow price must be the exact heuristic price of the shadowed nodes, the
  50. * way compaction-basic derives it, because the token-meter projections subtract
  51. * it verbatim.
  52. * @returns the fixture with a manual compaction lifecycle appended.
  53. */
  54. function withCompaction(raw: string, meter: TokenMeter): string {
  55. const decoded = parseSeedFixture(raw)
  56. const events = decoded.events as unknown as Array<{
  57. type: string
  58. seq: number
  59. time: number
  60. surfaceOp?: unknown
  61. data?: { turn?: unknown; message?: unknown; content?: unknown; callId?: unknown; isError?: unknown }
  62. }>
  63. const surfaceSeqs = events
  64. .filter(event => event.surfaceOp === 'append'
  65. && (event.type === 'user/message'
  66. || event.type === 'assistant/message'
  67. || event.type === 'tool/result'))
  68. .map(event => event.seq)
  69. const first = surfaceSeqs[0]
  70. const last = surfaceSeqs.at(-1)
  71. const tail = events.at(-1)
  72. if (first === undefined || last === undefined || tail === undefined) {
  73. throw new Error('seeded-history compaction requires a non-empty closed surface')
  74. }
  75. const lastTurn = events.filter(event => event.type === 'turn/end').at(-1)?.data?.turn
  76. if (typeof lastTurn !== 'number') {
  77. throw new Error('seeded-history compaction requires a recording ending on a closed turn')
  78. }
  79. let seq = tail.seq + 1
  80. let time = tail.time + 1
  81. /**
  82. * Append one event at the next seq/time.
  83. * @param event - the event body, without seq/time.
  84. * @returns the assigned seq, so later `sourceEventSeqs` cite the pushed event directly.
  85. */
  86. const at = (event: { type: string } & Record<string, unknown>): number => {
  87. const taken = seq++
  88. events.push({ ...event, seq: taken, time: time++ })
  89. return taken
  90. }
  91. const commandId = 'cmd-seeded-manual-compact'
  92. const compactionId = 'compact-seeded-manual-compact'
  93. at({
  94. type: 'command/run',
  95. data: { commandId, name: 'compact', args: '', source: { kind: 'user' } },
  96. })
  97. const startSeq = at({
  98. type: 'compaction/start',
  99. data: { compactionId, sourceCommandId: commandId, turn: null },
  100. })
  101. // Load-bearing exactness: the projections subtract this count verbatim, so
  102. // it must equal what the host's fold prices for these nodes. The estimator
  103. // prices message CONTENT only, so a minimal wrapper for each stored event format is
  104. // exact — pre-identity rows carry bare `content` (the persistence read path
  105. // upgrades them), a current row carries the full `message` envelope.
  106. const priceRow = (row: (typeof events)[number]): number => {
  107. if (row.data?.message !== undefined) {
  108. const message = deriveEventMessage(row as unknown as SessionEvent)
  109. return message === null ? 0 : meter.estimateMessage(message)
  110. }
  111. const content = row.data?.content as ContentBlock[]
  112. if (row.type === 'tool/result') {
  113. return meter.estimateMessage({
  114. content: [{ type: 'tool-result', toolCallId: row.data?.callId, content, isError: row.data?.isError === true }],
  115. } as unknown as Message)
  116. }
  117. // An empty-content assistant message derives no transcript entry.
  118. if (row.type === 'assistant/message' && content.length === 0) return 0
  119. return meter.estimateMessage({ content } as unknown as Message)
  120. }
  121. const shadowedTokenCount = surfaceSeqs.reduce((total, surfaceSeq) => {
  122. const event = events.find(candidate => candidate.seq === surfaceSeq)
  123. if (event === undefined) throw new Error(`seeded-history compaction: shadowed seq ${surfaceSeq} is not in the seed`)
  124. return total + priceRow(event)
  125. }, 0)
  126. const summarySeq = at({
  127. type: 'compaction/summary',
  128. data: {
  129. compactionId,
  130. sourceCommandId: commandId,
  131. summary: [{
  132. type: 'text',
  133. text: '## Cold resume compact summary\n\n- The exact summary remains available.',
  134. }],
  135. shadowedRange: { start: first, end: last },
  136. shadowedSeqs: surfaceSeqs,
  137. shadowedTokenCount,
  138. provider: 'snapshot',
  139. model: 'snapshot-compactor',
  140. },
  141. })
  142. at({
  143. type: 'user/message',
  144. data: {
  145. content: [{
  146. type: 'text',
  147. text: '<context_checkpoint>Model-only compact checkpoint.</context_checkpoint>',
  148. }],
  149. source: {
  150. kind: 'plugin', plugin: 'compact', compactionId, sourceCommandId: commandId,
  151. },
  152. },
  153. surfaceOp: { op: 'replace', start: first, end: last },
  154. sourceEventSeqs: [startSeq, summarySeq, ...surfaceSeqs],
  155. })
  156. at({
  157. type: 'compaction/end',
  158. data: { compactionId, sourceCommandId: commandId, turn: null },
  159. })
  160. at({
  161. type: 'command/done',
  162. data: {
  163. commandId,
  164. kind: 'success',
  165. text: `Compacted ${surfaceSeqs.length} history items (~${shadowedTokenCount} tokens).`,
  166. sourceEventSeq: summarySeq,
  167. },
  168. })
  169. // The persistence seed helper requires a terminal turn/end. Keep the manual
  170. // command standalone, then add a closed zero-step turn after it.
  171. const closureTurn = lastTurn + 1
  172. at({ type: 'turn/start', data: { turn: closureTurn } })
  173. at({ type: 'turn/end', data: { turn: closureTurn, reason: { kind: 'completed' } } })
  174. return renderSeedFixture(decoded.headerLine, events)
  175. }
  176. describe('web e2e: seeded history renders through cold resume', () => {
  177. let scaffold: WebScaffold
  178. let browser: Browser
  179. let page: Page
  180. let tripwire: ReturnType<typeof watchConsole>
  181. let seededThroughSeq = -1
  182. beforeAll(async () => {
  183. scaffold = await launchWebScaffold({})
  184. // The workspace-aware flow runs sessions in <workspaceCwd>/workspace
  185. // (the composer's default draft name); the read-tool targets must live in
  186. // that session cwd. Pre-creating the directory is safe because the picker
  187. // adopts an existing directory by path.
  188. const sessionCwd = join(scaffold.workspaceCwd, 'workspace')
  189. await mkdir(sessionCwd, { recursive: true })
  190. await writeFile(join(sessionCwd, 'a.txt'), 'alpha\n')
  191. await writeFile(join(sessionCwd, 'b.txt'), 'beta\n')
  192. if (MODE !== 'record') {
  193. const raw = await readFile(SEED, 'utf8')
  194. expect(fixtureUserPrompts(raw), 'seed fixture must carry exactly the drive prompt').toEqual([PROMPT])
  195. // The meter is host-plane — it takes no configuration and keys every
  196. // fold by Session — so pricing fixture content needs no agent at all.
  197. const meter = scaffold.ctx.get('tokenMeter')
  198. if (meter === undefined) throw new Error('seeded-history requires the host token meter')
  199. const realizedWithCompaction = withCompaction(realizeSeedFixture(scaffold, raw, SEED_ID), meter)
  200. seededThroughSeq = parseSeedFixture(realizedWithCompaction).events.at(-1)?.seq ?? -1
  201. await seedSession(scaffold, realizedWithCompaction, SEED_ID)
  202. }
  203. browser = await chromium.launch()
  204. page = await newEnglishPage(browser)
  205. tripwire = watchConsole(page)
  206. await page.goto(scaffold.baseUrl, { waitUntil: 'load' })
  207. await page.waitForSelector('[class*="frame"]', { timeout: 30_000 })
  208. }, 120_000)
  209. afterAll(async () => {
  210. await browser?.close()
  211. await scaffold?.close()
  212. })
  213. it.skipIf(MODE !== 'record')('records the seed turn live through the composer', async () => {
  214. onTestFailed(() => saveFailureShot(page, 'web-e2e-seeded-record'))
  215. const input = page.locator('textarea').first()
  216. await input.waitFor({ timeout: 10_000 })
  217. const settled = scaffold.whenTurnSettled()
  218. await input.fill(PROMPT)
  219. await input.press('Enter')
  220. const sessionId = await settled
  221. await recordFixture(scaffold, sessionId, SEED)
  222. }, 200_000)
  223. it.skipIf(MODE === 'record')('serves the projections baseline on the real composition opening snapshot', async () => {
  224. // Composition regression tripwire: the projection registry must be a row
  225. // in the SHIPPED cordis.yml — with it absent every domain unit's optional
  226. // injection stays silent and this block disappears (no titles/todos on
  227. // the web), while fixture-level suites stay green. Assert through the
  228. // production Session Controller against the booted real host.
  229. const controller = new AbortController()
  230. const stream = scaffold.ctx.sessionController.follow({
  231. address: { kind: 'session', sessionId: SessionId(SEED_ID) },
  232. }, controller.signal)[Symbol.asyncIterator]()
  233. const first = await stream.next()
  234. controller.abort()
  235. if (first.done || first.value.type !== 'snapshot') {
  236. throw new Error('session follow did not publish its opening snapshot')
  237. }
  238. expect(first.value.cursor).toBe(seededThroughSeq)
  239. const projections = first.value.projections
  240. expect(projections.asOfSeq).toBe(seededThroughSeq)
  241. // The seed carries a session/title event: the title unit is host-plane, so
  242. // it folds the detached log and serves the value with nothing composed.
  243. expect(typeof projections.values.title).toBe('string')
  244. // `todos` is absent because its unit belongs to the agent preset and this
  245. // directly seeded session never composed that preset. History computes
  246. // the baseline through the standard projection registry without mounting
  247. // an Agent composition as a read side effect.
  248. expect(projections.values).not.toHaveProperty('todos')
  249. // The session-stats unit is a shipped web-app bundle row: whole-log
  250. // turn/step counts ride the same tail block (the stats strip's source).
  251. const sessionStats = projections.values.sessionStats as { turns: number; steps: number } | undefined
  252. expect(sessionStats).toBeDefined()
  253. expect(sessionStats?.turns).toBeGreaterThanOrEqual(1)
  254. expect(sessionStats?.steps).toBeGreaterThanOrEqual(sessionStats?.turns ?? 0)
  255. })
  256. it.skipIf(MODE === 'record')('lists the seeded session cold and renders its history from the log', async () => {
  257. onTestFailed(() => saveFailureShot(page, 'web-e2e-seeded-history'))
  258. // The sidebar tree collapses workspace groups by default: click the group
  259. // row (treeitem 0) to expand, then the revealed session row.
  260. const groupRow = page.locator('[role="treeitem"]').first()
  261. await groupRow.waitFor({ timeout: 15_000 })
  262. await groupRow.click()
  263. const sessionRow = page.locator('[role="treeitem"]').nth(1)
  264. await sessionRow.waitFor({ timeout: 10_000 })
  265. await sessionRow.click()
  266. // Settled barrier for history: the recorded final assistant text renders.
  267. await expect.poll(() => page.getByText('DONE', { exact: true }).count(), { timeout: 15_000 }).toBe(1)
  268. await expect.poll(() => page.getByText('compact', { exact: true }).count(), { timeout: 10_000 }).toBe(1)
  269. await expect.poll(() => page.getByText(/^Compacted \d+ history items \(~\d+ tokens\)$/).count(), {
  270. timeout: 10_000,
  271. }).toBe(1)
  272. expect(await page.getByText('Context compacted', { exact: true }).count()).toBe(0)
  273. // Tool cards render from logged tool/call + tool/result alone (views are
  274. // host-recomputed per page; the generic card is the documented default).
  275. const toolRows = page.locator('[data-variant], [data-sample]')
  276. await expect.poll(() => toolRows.count(), { timeout: 10_000 }).toBeGreaterThanOrEqual(2)
  277. expect(await page.getByText('a.txt', { exact: false }).count()).toBeGreaterThan(0)
  278. // The pinned hazard: compaction shadows the surface on the model side
  279. // only — the prompt and full tool output must stay on screen.
  280. expect(await page.getByText(PROMPT, { exact: true }).count()).toBe(1)
  281. const agent = scaffold.ctx.agents.get(SessionId(SEED_ID))
  282. if (agent === undefined) throw new Error('seeded session did not attach an agent')
  283. agent.session.append('user/message', createUserMessage({
  284. content: [{
  285. type: 'text',
  286. text: '<system-reminder>\n'
  287. + 'The following workspace instructions may be relevant to your work. '
  288. + 'Use them as guidance when applicable.\n\n'
  289. + Array.from({ length: 24 }, (_, index) => `Instruction ${index + 1}: preserve the logged context contract.`).join('\n')
  290. + '\n</system-reminder>',
  291. }],
  292. source: {
  293. kind: 'agent-instructions',
  294. form: 'instructions',
  295. baseline: true,
  296. changes: [{
  297. action: 'set',
  298. scope: '.\u0000AGENTS.md',
  299. path: 'AGENTS.md',
  300. digest: 'context-injection-browser-snapshot',
  301. }],
  302. },
  303. }), { surfaceOp: 'append' })
  304. // The header names the producer the durable source records, so the
  305. // reconciled instruction file is readable without expanding the row.
  306. await page.getByRole('button', { name: 'Context injection AGENTS.md', exact: true })
  307. .waitFor({ timeout: 10_000 })
  308. }, 60_000)
  309. it.skipIf(MODE === 'record')('matches the historical conversation aria golden', async () => {
  310. onTestFailed(() => saveFailureShot(page, 'web-e2e-seeded-aria'))
  311. // This scenario issues zero model calls — the scaffold's route-only
  312. // adapter serves the catalog and refuses to stream — so history restores
  313. // the routed id and the seat resolves it against an advertised row.
  314. await page.getByRole('button', { name: /^Select model, current/ })
  315. .waitFor({ timeout: 10_000 })
  316. const snapshot = (await captureStableAria(page, '[class*="centerCol"]', scaffold.workspaceCwd))
  317. .split(SEED_ID).join('{{seededId}}')
  318. await compareOrRefreshGolden(UI_EXPECTED, snapshot, MODE)
  319. })
  320. it.skipIf(MODE === 'record')('matches the Figma context disclosure geometry', async () => {
  321. onTestFailed(() => saveFailureShot(page, 'web-e2e-context-injection'))
  322. const disclosure = page.getByRole('button', { name: 'Context injection AGENTS.md', exact: true })
  323. expect(await disclosure.getAttribute('aria-expanded')).toBe('false')
  324. const collapsedIcon = disclosure.locator('svg').first()
  325. const collapsedIconBox = await collapsedIcon.boundingBox()
  326. expect(collapsedIconBox?.width).toBe(14)
  327. expect(collapsedIconBox?.height).toBe(14)
  328. await disclosure.click()
  329. await expect.poll(() => disclosure.getAttribute('aria-expanded')).toBe('true')
  330. const body = page.locator('[data-context-injection-body]')
  331. await body.waitFor({ timeout: 5_000 })
  332. // The instructions form names the file it reconciled above the text, and
  333. // the text keeps the framing the model read rather than a cleaned excerpt.
  334. expect(await body.locator('[data-context-files] li').allInnerTexts()).toEqual(['AGENTS.md\nloaded'])
  335. expect(await body.locator('[data-context-text]').innerText()).toContain('<system-reminder>')
  336. const headerBox = await disclosure.boundingBox()
  337. const bodyBox = await body.boundingBox()
  338. if (headerBox === null || bodyBox === null) throw new Error('context disclosure geometry is not measurable')
  339. expect(headerBox.height).toBe(24)
  340. expect(bodyBox.x - headerBox.x).toBe(22)
  341. expect(bodyBox.y - headerBox.y - headerBox.height).toBe(4)
  342. expect(bodyBox.height).toBe(141)
  343. const style = await body.evaluate((element) => {
  344. const computed = getComputedStyle(element)
  345. return {
  346. backgroundColor: computed.backgroundColor,
  347. borderRadius: computed.borderRadius,
  348. color: computed.color,
  349. fontSize: computed.fontSize,
  350. lineHeight: computed.lineHeight,
  351. padding: [
  352. computed.paddingTop,
  353. computed.paddingRight,
  354. computed.paddingBottom,
  355. computed.paddingLeft,
  356. ],
  357. scrolls: element.scrollHeight > element.clientHeight,
  358. }
  359. })
  360. expect(style).toEqual({
  361. backgroundColor: 'rgb(249, 250, 251)',
  362. borderRadius: '8px',
  363. color: 'rgb(129, 133, 140)',
  364. fontSize: '11px',
  365. lineHeight: '16px',
  366. padding: ['10px', '16px', '12px', '12px'],
  367. scrolls: true,
  368. })
  369. await disclosure.click()
  370. await expect.poll(() => disclosure.getAttribute('aria-expanded')).toBe('false')
  371. })
  372. it.skipIf(MODE === 'record')('file-path tool rows rebuilt from the cold log stay details-inert', async () => {
  373. onTestFailed(() => saveFailureShot(page, 'web-e2e-seeded-toolrow'))
  374. // Interaction over cold-resumed history: read summaries are host-open
  375. // file links (not expand-in-place / not details). Runs after the golden
  376. // capture; still zero model calls.
  377. const fileLink = page.locator('[data-variant="read"] button').first()
  378. await fileLink.waitFor({ timeout: 10_000 })
  379. const frame = page.locator('[style*="grid-template-columns"]').first()
  380. expect(await frame.getAttribute('data-details-collapsed')).toBe('true')
  381. const openPath = vi.spyOn(scaffold.ctx.apiProxy.host, 'openPath')
  382. .mockImplementation(async (request, _signal) => ({
  383. rpcId: request.rpcId,
  384. result: { ok: true, value: { opened: true as const } },
  385. }))
  386. try {
  387. await fileLink.click()
  388. await expect.poll(() => frame.getAttribute('data-details-collapsed'), { timeout: 5_000 }).toBe('true')
  389. } finally {
  390. openPath.mockRestore()
  391. }
  392. // Path label survives from the recorded args (a.txt).
  393. await expect.poll(() => page.getByText('a.txt', { exact: false }).count(), { timeout: 5_000 }).toBeGreaterThan(0)
  394. })
  395. it.skipIf(MODE === 'record')('a Host open refusal keeps the reason and retries the same path', async () => {
  396. onTestFailed(() => saveFailureShot(page, 'web-e2e-seeded-file-open-failure'))
  397. const fileLink = page.locator('[data-variant="read"] button').first()
  398. await fileLink.waitFor({ timeout: 10_000 })
  399. const openPath = vi.spyOn(scaffold.ctx.apiProxy.host, 'openPath')
  400. .mockImplementation(async (request, _signal) => ({
  401. rpcId: request.rpcId,
  402. result: {
  403. ok: false as const,
  404. error: { code: 'internal', message: 'xdg-open is not available', details: {} },
  405. },
  406. }))
  407. try {
  408. await fileLink.click()
  409. const dialog = page.getByRole('dialog', { name: 'Couldn’t open file' })
  410. await dialog.waitFor({ timeout: 5_000 })
  411. const snapshot = await captureStableAria(page, '[role="dialog"]', scaffold.workspaceCwd)
  412. await compareOrRefreshGolden(FILE_OPEN_FAILURE_EXPECTED, snapshot, MODE)
  413. await expect.poll(() => dialog.innerText(), { timeout: 5_000 })
  414. .toContain('path open failed: xdg-open is not available')
  415. await page.getByRole('button', { name: 'Retry' }).click()
  416. await expect.poll(() => openPath.mock.calls.length, { timeout: 5_000 }).toBe(2)
  417. expect(openPath.mock.calls[0]![0].payload).toEqual(openPath.mock.calls[1]![0].payload)
  418. await page.getByRole('button', { name: 'Cancel' }).click()
  419. await expect.poll(() => page.getByRole('dialog', { name: 'Couldn’t open file' }).count(), {
  420. timeout: 5_000,
  421. }).toBe(0)
  422. } finally {
  423. // Shared page: a leftover mask blocks later cases even when this one fails.
  424. if (await page.getByRole('dialog', { name: 'Couldn’t open file' }).count() > 0) {
  425. await page.keyboard.press('Escape')
  426. }
  427. openPath.mockRestore()
  428. }
  429. })
  430. it.skipIf(MODE === 'record')('expands the cold-resumed compact summary', async () => {
  431. onTestFailed(() => saveFailureShot(page, 'web-e2e-seeded-compaction'))
  432. const marker = page.getByRole('button', { name: /compact Compacted \d+ history items/ })
  433. await marker.waitFor({ timeout: 10_000 })
  434. expect(await marker.getAttribute('aria-expanded')).toBe('false')
  435. await marker.click()
  436. await expect.poll(() => marker.getAttribute('aria-expanded'), { timeout: 5_000 }).toBe('true')
  437. await expect.poll(() => page.getByRole('heading', { name: 'Cold resume compact summary' }).count(), {
  438. timeout: 5_000,
  439. }).toBe(1)
  440. expect(await page.getByText('The exact summary remains available.', { exact: false }).count()).toBeGreaterThan(0)
  441. // Restore the shared page state for any later case.
  442. await marker.click()
  443. await expect.poll(() => marker.getAttribute('aria-expanded'), { timeout: 5_000 }).toBe('false')
  444. })
  445. it.skipIf(MODE === 'record')('an Access-chip switch lands one command row: bare name, non-repeating settlement text', async () => {
  446. onTestFailed(() => saveFailureShot(page, 'web-e2e-seeded-command-row'))
  447. // The Access chip submits `/permission <preset>` — a host command with no
  448. // model call, so the settled row renders keylessly over this cold history.
  449. // The row copy is the assertion: `permission · preset read-only`,
  450. // where neither half repeats the other (the dispatched `/` and its
  451. // argument stay out of the title, and the settlement text never restates
  452. // the command's own name).
  453. await page.getByRole('button', { name: 'Access mode, current: Workspace Write' }).click()
  454. await page.getByRole('menuitem', { name: 'Read Only' }).click()
  455. await page.getByRole('button', { name: 'Access mode, current: Read Only' }).waitFor({ timeout: 10_000 })
  456. // Scoped to the row itself, so unrelated page text that happens to read
  457. // `permission` (a future resident slash menu) cannot satisfy or break it.
  458. const row = page.locator('[data-variant="others"]').filter({ hasText: 'preset read-only' })
  459. await expect.poll(() => row.count(), { timeout: 10_000 }).toBe(1)
  460. expect(await row.getByText('permission', { exact: true }).count()).toBe(1)
  461. expect(await row.getByText('/permission read-only', { exact: true }).count()).toBe(0)
  462. const snapshot = (await captureStableAria(page, '[class*="centerCol"]', scaffold.workspaceCwd))
  463. .split(SEED_ID).join('{{seededId}}')
  464. await compareOrRefreshGolden(COMMAND_ROW_EXPECTED, snapshot, MODE)
  465. }, 60_000)
  466. it.skipIf(MODE === 'record')('reports full feedback correlation ids in an expandable two-line row', async () => {
  467. onTestFailed(() => saveFailureShot(page, 'web-e2e-seeded-feedback-row'))
  468. const previousDshHome = process.env.DSH_HOME
  469. process.env.DSH_HOME = scaffold.harnessHome
  470. try {
  471. const input = page.locator('textarea').first()
  472. await input.fill('/feedback the diff view is unreadable')
  473. await input.press('Enter')
  474. const row = page.locator('[data-variant="others"]').filter({
  475. hasText: `Feedback recorded for session ${SEED_ID}`,
  476. })
  477. await row.waitFor({ timeout: 10_000 })
  478. const disclosure = row.locator('[data-expandable]')
  479. expect(await disclosure.getAttribute('aria-expanded')).toBe('false')
  480. await disclosure.click()
  481. await expect.poll(() => disclosure.getAttribute('aria-expanded')).toBe('true')
  482. const agent = scaffold.ctx.agents.get(SessionId(SEED_ID))
  483. if (agent === undefined) throw new Error('seeded session did not attach an agent')
  484. const done = agent.session.events.filter(event => event.type === 'command/done').at(-1)
  485. if (done?.type !== 'command/done') throw new Error('feedback command did not settle')
  486. const [sessionLine, userLine, extraLine] = done.data.text?.split('\n') ?? []
  487. expect(sessionLine).toBe(`Feedback recorded for session ${SEED_ID}`)
  488. expect(userLine).toMatch(/^Anonymous user: [0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}\./i)
  489. expect(extraLine).toBeUndefined()
  490. const userId = userLine?.match(/^Anonymous user: ([0-9a-f-]+)/i)?.[1]
  491. if (userId === undefined) throw new Error('feedback command omitted the user id')
  492. const snapshot = (await captureStableAria(page, '[class*="centerCol"]', scaffold.workspaceCwd))
  493. .split(SEED_ID).join('{{seededId}}')
  494. .split(userId).join('{{userId}}')
  495. await compareOrRefreshGolden(FEEDBACK_ROW_EXPECTED, snapshot, MODE)
  496. } finally {
  497. if (previousDshHome === undefined) delete process.env.DSH_HOME
  498. else process.env.DSH_HOME = previousDshHome
  499. }
  500. }, 60_000)
  501. it.skipIf(MODE === 'record')('fits short logged context without a scrollport', async () => {
  502. const agent = scaffold.ctx.agents.get(SessionId(SEED_ID))
  503. if (agent === undefined) throw new Error('seeded session did not attach an agent')
  504. agent.session.append('user/message', createUserMessage({
  505. content: [{ type: 'text', text: 'Short injected context.' }],
  506. source: { kind: 'plugin', plugin: 'fixture' },
  507. }), { surfaceOp: 'append' })
  508. const disclosure = page.getByRole('button', { name: 'Context injection fixture', exact: true })
  509. await disclosure.waitFor({ timeout: 10_000 })
  510. await disclosure.click()
  511. await expect.poll(() => disclosure.getAttribute('aria-expanded')).toBe('true')
  512. // The instructions row above stays expanded from the geometry case; the
  513. // opaque body is the one without a declared form.
  514. const body = page.locator('[data-context-injection-body]:not([data-context-form])')
  515. const bodyBox = await body.boundingBox()
  516. if (bodyBox === null) throw new Error('short context disclosure geometry is not measurable')
  517. expect(bodyBox.height).toBeLessThan(141)
  518. expect(await body.evaluate(element => element.scrollHeight > element.clientHeight)).toBe(false)
  519. })
  520. it.skipIf(MODE === 'record')('issued zero model calls and stayed clean', async () => {
  521. // No replay fixture was installed and the llm seam is open — any stray
  522. // stream would have failed the turn loudly. Cleanliness pins the wire.
  523. expect(tripwire.pageErrors).toEqual([])
  524. expect(tripwire.warnings).toEqual([])
  525. await assertFixtureInventory(SNAPSHOT_DIR, ['command-row.expected.md', 'feedback-row.expected.md', 'file-open-failure.expected.md', 'session.jsonl', 'ui.expected.md'])
  526. })
  527. })