seeded-history.e2e.ts 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422
  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, the implicit resume/attach inside the
  4. // history RPC, 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 the one
  7. // keyless command-row surface: an Access-chip pick runs `/permission` on the
  8. // host, so the settled row's copy has a golden here. The seed is a recorded
  9. // fixture under the
  10. // 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 seed.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 } 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 { TokenMeterService } from '@deepseek-ai/dsh-token-meter'
  23. import { join } from 'node:path'
  24. import {
  25. assertFixtureInventory, captureStableAria, compareOrRefreshGolden, fixtureUserPrompts,
  26. launchWebScaffold, realizeSeedFixture, recordFixture, seedSession, watchConsole, webSnapshotMode, type WebScaffold,
  27. } from './scaffold.ts'
  28. import { newEnglishPage, saveFailureShot } from './support.ts'
  29. const SNAPSHOT_DIR = fileURLToPath(new URL('./snapshots/seeded-history', import.meta.url))
  30. const SEED = fileURLToPath(new URL('./snapshots/seeded-history/seed.jsonl', import.meta.url))
  31. const UI_EXPECTED = fileURLToPath(new URL('./snapshots/seeded-history/ui.expected.md', import.meta.url))
  32. // The command-row golden: the same conversation after one /permission switch,
  33. // which is the only surface that shows a settled command row's copy.
  34. const COMMAND_ROW_EXPECTED = fileURLToPath(new URL('./snapshots/seeded-history/command-row.expected.md', import.meta.url))
  35. const MODE = webSnapshotMode()
  36. const SEED_ID = 'seeded-history-web-e2e'
  37. 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.'
  38. /**
  39. * Append a complete, valid compaction transaction over the recorded turn's own
  40. * surface. The recording stays model-authentic and reusable; replay adds this
  41. * deterministic condition before seeding it cold, so the scenario pins the bug
  42. * this change fixes — a landed compaction must not erase history the reader
  43. * already saw — through the real host and the real browser.
  44. * @param raw - the seed fixture text, already realized (placeholder-free) so
  45. * the shadow price below is computed from the exact strings the host folds.
  46. * @param meter - the composed token meter; the appended `compact/summary`'s
  47. * shadow price must be the exact heuristic price of the shadowed nodes, the
  48. * way compact-basic derives it, because the token-meter projections subtract
  49. * it verbatim.
  50. * @returns the fixture with a compacted turn appended.
  51. */
  52. function withCompaction(raw: string, meter: TokenMeterService): string {
  53. const lines = raw.trimEnd().split('\n')
  54. const events = lines.slice(1).map(line => JSON.parse(line) as {
  55. type: string
  56. seq: number
  57. time: number
  58. surfaceOp?: unknown
  59. data?: { turn?: unknown; message?: unknown; content?: unknown; callId?: unknown; isError?: unknown }
  60. })
  61. const surfaceSeqs = events
  62. .filter(event => event.surfaceOp === 'append'
  63. && (event.type === 'user/message'
  64. || event.type === 'assistant/message'
  65. || event.type === 'tool/result'))
  66. .map(event => event.seq)
  67. const first = surfaceSeqs[0]
  68. const last = surfaceSeqs.at(-1)
  69. const tail = events.at(-1)
  70. if (first === undefined || last === undefined || tail === undefined) {
  71. throw new Error('seeded-history compaction requires a non-empty closed surface')
  72. }
  73. // The transaction opens the turn after the recording's last closed one; read
  74. // it from the fixture so a re-recording with a different turn count stays
  75. // valid instead of appending a duplicate turn number.
  76. const lastTurn = events.filter(event => event.type === 'turn/end').at(-1)?.data?.turn
  77. if (typeof lastTurn !== 'number') {
  78. throw new Error('seeded-history compaction requires a recording ending on a closed turn')
  79. }
  80. const turn = lastTurn + 1
  81. let seq = tail.seq + 1
  82. let time = tail.time + 1
  83. /**
  84. * Append one event at the next seq/time.
  85. * @param event - the event body, without seq/time.
  86. * @returns the seq it took, so provenance cites the push instead of arithmetic over the push order below.
  87. */
  88. const at = (event: Record<string, unknown>): number => {
  89. const taken = seq++
  90. lines.push(JSON.stringify({ ...event, seq: taken, time: time++ }))
  91. return taken
  92. }
  93. at({ type: 'turn/start', data: { turn } })
  94. const startSeq = at({ type: 'compact/start', data: { turn } })
  95. // Load-bearing exactness: the projections subtract this count verbatim, so
  96. // it must equal what the host's fold prices for these nodes. The estimator
  97. // prices message CONTENT only, so a minimal wrapper per storage shape is
  98. // exact — pre-identity rows carry bare `content` (the persistence read path
  99. // upgrades them), a current row carries the full `message` envelope.
  100. const priceRow = (row: (typeof events)[number]): number => {
  101. if (row.data?.message !== undefined) {
  102. const message = deriveEventMessage(row as unknown as SessionEvent)
  103. return message === null ? 0 : meter.estimateMessage(message)
  104. }
  105. const content = row.data?.content as ContentBlock[]
  106. if (row.type === 'tool/result') {
  107. return meter.estimateMessage({
  108. content: [{ type: 'tool-result', toolCallId: row.data?.callId, content, isError: row.data?.isError === true }],
  109. } as unknown as Message)
  110. }
  111. // An empty-content assistant message derives no transcript entry.
  112. if (row.type === 'assistant/message' && content.length === 0) return 0
  113. return meter.estimateMessage({ content } as unknown as Message)
  114. }
  115. const shadowedTokenCount = surfaceSeqs.reduce((total, surfaceSeq) => {
  116. const event = events.find(candidate => candidate.seq === surfaceSeq)
  117. if (event === undefined) throw new Error(`seeded-history compaction: shadowed seq ${surfaceSeq} is not in the seed`)
  118. return total + priceRow(event)
  119. }, 0)
  120. const summarySeq = at({
  121. type: 'compact/summary',
  122. data: {
  123. summary: [{
  124. type: 'text',
  125. text: '## Cold resume compact summary\n\n- The exact summary remains available.',
  126. }],
  127. shadowedRange: { start: first, end: last },
  128. shadowedSeqs: surfaceSeqs,
  129. shadowedTokenCount,
  130. provider: 'snapshot',
  131. model: 'snapshot-compactor',
  132. },
  133. })
  134. at({
  135. type: 'user/message',
  136. data: {
  137. content: [{
  138. type: 'text',
  139. text: '<context_checkpoint>Model-only compact checkpoint.</context_checkpoint>',
  140. }],
  141. source: { kind: 'plugin', plugin: 'compact' },
  142. },
  143. surfaceOp: { op: 'replace', start: first, end: last },
  144. sourceEventSeqs: [startSeq, summarySeq, ...surfaceSeqs],
  145. })
  146. at({ type: 'compact/end', data: { turn } })
  147. at({ type: 'turn/end', data: { turn, reason: { kind: 'completed' } } })
  148. return `${lines.join('\n')}\n`
  149. }
  150. describe('web e2e: seeded history renders through cold resume', () => {
  151. let scaffold: WebScaffold
  152. let browser: Browser
  153. let page: Page
  154. let tripwire: ReturnType<typeof watchConsole>
  155. beforeAll(async () => {
  156. scaffold = await launchWebScaffold({})
  157. // The workspace-aware flow runs sessions in <workspaceCwd>/workspace
  158. // (the composer's default draft name); the read-tool targets must live in
  159. // that session cwd. Pre-creating the directory is safe: create-by-name
  160. // adopts an existing directory.
  161. const sessionCwd = join(scaffold.workspaceCwd, 'workspace')
  162. await mkdir(sessionCwd, { recursive: true })
  163. await writeFile(join(sessionCwd, 'a.txt'), 'alpha\n')
  164. await writeFile(join(sessionCwd, 'b.txt'), 'beta\n')
  165. if (MODE !== 'record') {
  166. const raw = await readFile(SEED, 'utf8')
  167. expect(fixtureUserPrompts(raw), 'seed fixture must carry exactly the drive prompt').toEqual([PROMPT])
  168. const meter = scaffold.ctx.get('tokenMeter')
  169. if (meter === undefined) throw new Error('seeded-history requires the composed token meter')
  170. const realized = realizeSeedFixture(scaffold, raw, SEED_ID)
  171. await seedSession(scaffold, withCompaction(realized, meter), SEED_ID)
  172. }
  173. browser = await chromium.launch()
  174. page = await newEnglishPage(browser)
  175. tripwire = watchConsole(page)
  176. await page.goto(scaffold.baseUrl, { waitUntil: 'load' })
  177. await page.waitForSelector('[class*="frame"]', { timeout: 30_000 })
  178. }, 120_000)
  179. afterAll(async () => {
  180. await browser?.close()
  181. await scaffold?.close()
  182. })
  183. it.skipIf(MODE !== 'record')('records the seed turn live through the composer', async () => {
  184. onTestFailed(() => saveFailureShot(page, 'web-e2e-seeded-record'))
  185. const input = page.locator('textarea').first()
  186. await input.waitFor({ timeout: 10_000 })
  187. const settled = scaffold.whenTurnSettled()
  188. await input.fill(PROMPT)
  189. await input.press('Enter')
  190. const sessionId = await settled
  191. await recordFixture(scaffold, sessionId, SEED)
  192. }, 200_000)
  193. it.skipIf(MODE === 'record')('serves the projections baseline on the real composition tail page', async () => {
  194. // Composition regression tripwire: the projection registry must be a row
  195. // in the SHIPPED cordis.yml — with it absent every domain unit's optional
  196. // injection stays silent and this block disappears (no titles/todos on
  197. // the web), while fixture-level suites stay green. Assert through the
  198. // real HTTP wire against the booted real host.
  199. const response = await fetch(`${scaffold.baseUrl}/api/session.history`, {
  200. method: 'POST',
  201. headers: { 'content-type': 'application/json' },
  202. body: JSON.stringify({
  203. type: 'client-request', rpcId: 'seeded-projections', method: 'session.history',
  204. payload: { sessionId: SEED_ID },
  205. }),
  206. })
  207. expect(response.ok).toBe(true)
  208. const body = await response.json() as {
  209. result: { ok: boolean; value?: { projections?: { asOfSeq: number; values: Record<string, unknown> } } }
  210. }
  211. expect(body.result.ok).toBe(true)
  212. const projections = body.result.value?.projections
  213. expect(projections).toBeDefined()
  214. expect(projections?.asOfSeq).toBeGreaterThanOrEqual(0)
  215. // The seed carries a session/title event: the title unit must serve it.
  216. expect(typeof projections?.values.title).toBe('string')
  217. // tool-todo is composed but the seed has no todo/write: whole-value null,
  218. // key PRESENT (absence would mean the unit never registered).
  219. expect(projections?.values).toHaveProperty('todos', null)
  220. })
  221. it.skipIf(MODE === 'record')('lists the seeded session cold and renders its history from the log', async () => {
  222. onTestFailed(() => saveFailureShot(page, 'web-e2e-seeded-history'))
  223. // The sidebar tree collapses workspace groups by default: click the group
  224. // row (treeitem 0) to expand, then the revealed session row.
  225. const groupRow = page.locator('[role="treeitem"]').first()
  226. await groupRow.waitFor({ timeout: 15_000 })
  227. await groupRow.click()
  228. const sessionRow = page.locator('[role="treeitem"]').nth(1)
  229. await sessionRow.waitFor({ timeout: 10_000 })
  230. await sessionRow.click()
  231. // Settled barrier for history: the recorded final assistant text renders.
  232. await expect.poll(() => page.getByText('DONE', { exact: true }).count(), { timeout: 15_000 }).toBe(1)
  233. await expect.poll(() => page.getByText('Context compacted', { exact: true }).count(), { timeout: 10_000 }).toBe(1)
  234. // Tool cards render from logged tool/call + tool/result alone (views are
  235. // host-recomputed per page; the generic card is the documented default).
  236. const toolRows = page.locator('[data-variant], [data-sample]')
  237. await expect.poll(() => toolRows.count(), { timeout: 10_000 }).toBeGreaterThanOrEqual(2)
  238. expect(await page.getByText('a.txt', { exact: false }).count()).toBeGreaterThan(0)
  239. // The bug this fixes: the compaction shadowed the whole recorded surface on
  240. // the model side, and the prompt and full tool output are still on screen.
  241. expect(await page.getByText(PROMPT, { exact: true }).count()).toBe(1)
  242. const agent = scaffold.ctx.agents.get(SessionId(SEED_ID))
  243. if (agent === undefined) throw new Error('seeded session did not attach an agent')
  244. agent.session.append('user/message', createUserMessage({
  245. content: [{
  246. type: 'text',
  247. text: '<system-reminder>\n'
  248. + 'The following workspace instructions may be relevant to your work. '
  249. + 'Use them as guidance when applicable.\n\n'
  250. + Array.from({ length: 24 }, (_, index) => `Instruction ${index + 1}: preserve the logged context contract.`).join('\n')
  251. + '\n</system-reminder>',
  252. }],
  253. source: {
  254. kind: 'workspace-instructions',
  255. baseline: true,
  256. changes: [{
  257. action: 'set',
  258. scope: '.\u0000AGENTS.md',
  259. path: 'AGENTS.md',
  260. digest: 'context-injection-browser-snapshot',
  261. }],
  262. },
  263. }), { surfaceOp: 'append' })
  264. await page.getByRole('button', { name: 'Context injection' }).waitFor({ timeout: 10_000 })
  265. }, 60_000)
  266. it.skipIf(MODE === 'record')('matches the historical conversation aria golden', async () => {
  267. onTestFailed(() => saveFailureShot(page, 'web-e2e-seeded-aria'))
  268. // This scenario deliberately leaves the LLM seam open to prove zero
  269. // model calls. History still restores the routed id, but without an
  270. // advertised catalog row the selector prompts for a listed replacement.
  271. await page.getByRole('button', { name: 'Select model', exact: true })
  272. .waitFor({ timeout: 10_000 })
  273. const snapshot = (await captureStableAria(page, '[class*="centerCol"]', scaffold.workspaceCwd))
  274. .split(SEED_ID).join('{{seededId}}')
  275. await compareOrRefreshGolden(UI_EXPECTED, snapshot, MODE)
  276. })
  277. it.skipIf(MODE === 'record')('matches the Figma context disclosure geometry', async () => {
  278. onTestFailed(() => saveFailureShot(page, 'web-e2e-context-injection'))
  279. const disclosure = page.getByRole('button', { name: 'Context injection' })
  280. expect(await disclosure.getAttribute('aria-expanded')).toBe('false')
  281. const collapsedIcon = disclosure.locator('svg').first()
  282. const collapsedIconBox = await collapsedIcon.boundingBox()
  283. expect(collapsedIconBox?.width).toBe(14)
  284. expect(collapsedIconBox?.height).toBe(14)
  285. await disclosure.click()
  286. await expect.poll(() => disclosure.getAttribute('aria-expanded')).toBe('true')
  287. const body = page.locator('[data-context-injection-body]')
  288. await body.waitFor({ timeout: 5_000 })
  289. const headerBox = await disclosure.boundingBox()
  290. const bodyBox = await body.boundingBox()
  291. if (headerBox === null || bodyBox === null) throw new Error('context disclosure geometry is not measurable')
  292. expect(headerBox.height).toBe(24)
  293. expect(bodyBox.x - headerBox.x).toBe(22)
  294. expect(bodyBox.y - headerBox.y - headerBox.height).toBe(4)
  295. expect(bodyBox.height).toBe(141)
  296. const style = await body.evaluate((element) => {
  297. const computed = getComputedStyle(element)
  298. return {
  299. backgroundColor: computed.backgroundColor,
  300. borderRadius: computed.borderRadius,
  301. color: computed.color,
  302. fontSize: computed.fontSize,
  303. lineHeight: computed.lineHeight,
  304. padding: [
  305. computed.paddingTop,
  306. computed.paddingRight,
  307. computed.paddingBottom,
  308. computed.paddingLeft,
  309. ],
  310. scrolls: element.scrollHeight > element.clientHeight,
  311. }
  312. })
  313. expect(style).toEqual({
  314. backgroundColor: 'rgb(249, 250, 251)',
  315. borderRadius: '8px',
  316. color: 'rgb(129, 133, 140)',
  317. fontSize: '11px',
  318. lineHeight: '16px',
  319. padding: ['10px', '16px', '12px', '12px'],
  320. scrolls: true,
  321. })
  322. await disclosure.click()
  323. await expect.poll(() => disclosure.getAttribute('aria-expanded')).toBe('false')
  324. })
  325. it.skipIf(MODE === 'record')('file-path tool rows rebuilt from the cold log stay details-inert', async () => {
  326. onTestFailed(() => saveFailureShot(page, 'web-e2e-seeded-toolrow'))
  327. // Interaction over cold-resumed history: read summaries are host-open
  328. // file links (not expand-in-place / not details). Runs after the golden
  329. // capture; still zero model calls.
  330. const fileLink = page.locator('[data-variant="read"] button').first()
  331. await fileLink.waitFor({ timeout: 10_000 })
  332. const frame = page.locator('[style*="grid-template-columns"]').first()
  333. expect(await frame.getAttribute('data-details-collapsed')).toBe('true')
  334. await fileLink.click()
  335. await expect.poll(() => frame.getAttribute('data-details-collapsed'), { timeout: 5_000 }).toBe('true')
  336. // Path label survives from the recorded args (a.txt).
  337. await expect.poll(() => page.getByText('a.txt', { exact: false }).count(), { timeout: 5_000 }).toBeGreaterThan(0)
  338. })
  339. it.skipIf(MODE === 'record')('expands the cold-resumed compact summary', async () => {
  340. onTestFailed(() => saveFailureShot(page, 'web-e2e-seeded-compaction'))
  341. const marker = page.getByRole('button', { name: /Context compacted/ })
  342. await marker.waitFor({ timeout: 10_000 })
  343. expect(await marker.getAttribute('aria-expanded')).toBe('false')
  344. await marker.click()
  345. await expect.poll(() => marker.getAttribute('aria-expanded'), { timeout: 5_000 }).toBe('true')
  346. await expect.poll(() => page.getByRole('heading', { name: 'Cold resume compact summary' }).count(), {
  347. timeout: 5_000,
  348. }).toBe(1)
  349. expect(await page.getByText('The exact summary remains available.', { exact: false }).count()).toBeGreaterThan(0)
  350. // Restore the shared page state for any later case.
  351. await marker.click()
  352. await expect.poll(() => marker.getAttribute('aria-expanded'), { timeout: 5_000 }).toBe('false')
  353. })
  354. it.skipIf(MODE === 'record')('an Access-chip switch lands one command row: bare name, non-repeating settlement text', async () => {
  355. onTestFailed(() => saveFailureShot(page, 'web-e2e-seeded-command-row'))
  356. // The Access chip submits `/permission <preset>` — a host command with no
  357. // model call, so the settled row renders keylessly over this cold history.
  358. // The row copy is the assertion: `permission · preset read-only`,
  359. // where neither half repeats the other (the dispatched `/` and its
  360. // argument stay out of the title, and the settlement text never restates
  361. // the command's own name).
  362. await page.getByRole('button', { name: 'Access mode, current: Workspace Write' }).click()
  363. await page.getByRole('menuitem', { name: 'Read Only' }).click()
  364. await page.getByRole('button', { name: 'Access mode, current: Read Only' }).waitFor({ timeout: 10_000 })
  365. // Scoped to the row itself, so unrelated page text that happens to read
  366. // `permission` (a future resident slash menu) cannot satisfy or break it.
  367. const row = page.locator('[data-variant="others"]').filter({ hasText: 'preset read-only' })
  368. await expect.poll(() => row.count(), { timeout: 10_000 }).toBe(1)
  369. expect(await row.getByText('permission', { exact: true }).count()).toBe(1)
  370. expect(await row.getByText('/permission read-only', { exact: true }).count()).toBe(0)
  371. const snapshot = (await captureStableAria(page, '[class*="centerCol"]', scaffold.workspaceCwd))
  372. .split(SEED_ID).join('{{seededId}}')
  373. await compareOrRefreshGolden(COMMAND_ROW_EXPECTED, snapshot, MODE)
  374. }, 60_000)
  375. it.skipIf(MODE === 'record')('fits short logged context without a scrollport', async () => {
  376. const agent = scaffold.ctx.agents.get(SessionId(SEED_ID))
  377. if (agent === undefined) throw new Error('seeded session did not attach an agent')
  378. agent.session.append('user/message', createUserMessage({
  379. content: [{ type: 'text', text: 'Short injected context.' }],
  380. source: { kind: 'plugin', plugin: 'fixture' },
  381. }), { surfaceOp: 'append' })
  382. const disclosures = page.getByRole('button', { name: 'Context injection' })
  383. await expect.poll(() => disclosures.count(), { timeout: 10_000 }).toBe(2)
  384. const disclosure = disclosures.nth(1)
  385. await disclosure.click()
  386. await expect.poll(() => disclosure.getAttribute('aria-expanded')).toBe('true')
  387. const body = page.locator('[data-context-injection-body]')
  388. const bodyBox = await body.boundingBox()
  389. if (bodyBox === null) throw new Error('short context disclosure geometry is not measurable')
  390. expect(bodyBox.height).toBeLessThan(141)
  391. expect(await body.evaluate(element => element.scrollHeight > element.clientHeight)).toBe(false)
  392. })
  393. it.skipIf(MODE === 'record')('issued zero model calls and stayed clean', async () => {
  394. // No replay fixture was installed and the llm seam is open — any stray
  395. // stream would have failed the turn loudly. Cleanliness pins the wire.
  396. expect(tripwire.pageErrors).toEqual([])
  397. expect(tripwire.warnings).toEqual([])
  398. await assertFixtureInventory(SNAPSHOT_DIR, ['command-row.expected.md', 'seed.jsonl', 'ui.expected.md'])
  399. })
  400. })