message-actions.e2e.ts 9.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192
  1. // Web e2e scenario: message IconActions + clocks. Cold-seeds a deterministic
  2. // completed-turn-tail fork case (zero model calls) and pins the settled
  3. // conversation aria after the footers are focus-revealed — the surface package
  4. // jsdom tests cannot substitute for (docs/testing.md snapshot rule).
  5. import { mkdir, readFile, writeFile } from 'node:fs/promises'
  6. import { join } from 'node:path'
  7. import { fileURLToPath } from 'node:url'
  8. import type { Browser, Page } from 'playwright'
  9. import { chromium } from 'playwright'
  10. import { afterAll, beforeAll, describe, expect, it, onTestFailed } from 'vitest'
  11. import { SessionId } from '@deepseek-ai/dsh-session'
  12. import {
  13. assertFixtureInventory, captureStableAria, compareOrRefreshGolden, fixtureUserPrompts,
  14. launchWebScaffold, seedSession, watchConsole, webSnapshotMode, type WebScaffold,
  15. } from './scaffold.ts'
  16. import { newEnglishPage, saveFailureShot } from './support.ts'
  17. const SNAPSHOT_DIR = fileURLToPath(new URL('./snapshots/message-actions', import.meta.url))
  18. // Borrowed read-only: this scenario needs any settled user+assistant pair, not
  19. // a new recording (workspace-management / sidebar-scrollbar pattern).
  20. const SEED = fileURLToPath(new URL('./snapshots/seeded-history/seed.jsonl', import.meta.url))
  21. const UI_EXPECTED = join(SNAPSHOT_DIR, 'ui.expected.md')
  22. const FORK_EXPECTED = join(SNAPSHOT_DIR, 'fork.expected.md')
  23. const MODE = webSnapshotMode()
  24. const SEED_ID = 'message-actions-web-e2e'
  25. 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.'
  26. const MID_TURN_TEXT = 'I will read both files before answering.'
  27. const SECOND_PROMPT = 'Now give the final answer.'
  28. /**
  29. * Adapt the borrowed recording into response -> tools -> interrupted Think,
  30. * followed by one ordinary completed response. The first response keeps
  31. * copy/clock but is not a legal branch point; the second is the real turn tail.
  32. * @param raw - Recorded seeded-history JSONL.
  33. * @returns A contiguous, closed two-turn fixture.
  34. */
  35. function completedTailFixture(raw: string): string {
  36. const kept: string[] = []
  37. for (const line of raw.trimEnd().split('\n')) {
  38. const row = JSON.parse(line) as {
  39. type: string
  40. seq?: number
  41. seq0?: number
  42. data?: { content?: unknown[] }
  43. }
  44. const firstSeq = row.seq ?? row.seq0
  45. if (firstSeq !== undefined && firstSeq >= 101) break
  46. if (row.type === 'assistant/message' && row.seq === 64) {
  47. const content = row.data?.content
  48. if (!Array.isArray(content)) throw new Error('borrowed step-one assistant message has no content')
  49. content.splice(1, 0, { type: 'text', text: MID_TURN_TEXT })
  50. kept.push(JSON.stringify(row))
  51. } else {
  52. kept.push(line)
  53. }
  54. }
  55. const tail = [
  56. { type: 'step/end', seq: 101, time: 1784974102749, data: { turn: 1, step: 2 } },
  57. { type: 'turn/end', seq: 102, time: 1784974102750, data: { turn: 1, reason: { kind: 'aborted' } } },
  58. { type: 'turn/start', seq: 103, time: 1784974103000, data: { turn: 2, trigger: { kind: 'message', source: { kind: 'user', rpcId: '{{rpcId}}' } } } },
  59. { type: 'user/message', seq: 104, time: 1784974103001, data: { content: [{ type: 'text', text: SECOND_PROMPT }], source: { kind: 'user', rpcId: '{{rpcId}}' } }, surfaceOp: 'append' },
  60. { type: 'step/start', seq: 105, time: 1784974103002, data: { turn: 2, step: 1 } },
  61. { type: 'assistant/message', seq: 106, time: 1784974103003, data: { turn: 2, step: 1, content: [{ type: 'text', text: 'DONE' }], provenance: { provider: 'deepseek-official', model: 'deepseek-v4-flash' } }, sourceEventSeqs: [], surfaceOp: 'append' },
  62. { type: 'step/end', seq: 107, time: 1784974103004, data: { turn: 2, step: 1 } },
  63. { type: 'turn/end', seq: 108, time: 1784974103005, data: { turn: 2, reason: { kind: 'completed' } } },
  64. ]
  65. return `${[...kept, ...tail.map(row => JSON.stringify(row))].join('\n')}\n`
  66. }
  67. describe('web e2e: message IconActions and clocks on settled history', () => {
  68. let scaffold: WebScaffold
  69. let browser: Browser
  70. let page: Page
  71. let tripwire: ReturnType<typeof watchConsole>
  72. beforeAll(async () => {
  73. scaffold = await launchWebScaffold({})
  74. const sessionCwd = join(scaffold.workspaceCwd, 'workspace')
  75. await mkdir(sessionCwd, { recursive: true })
  76. await writeFile(join(sessionCwd, 'a.txt'), 'alpha\n')
  77. await writeFile(join(sessionCwd, 'b.txt'), 'beta\n')
  78. const raw = completedTailFixture(await readFile(SEED, 'utf8'))
  79. expect(fixtureUserPrompts(raw), 'adapted seed must carry both prompts').toEqual([PROMPT, SECOND_PROMPT])
  80. await seedSession(scaffold, raw, SEED_ID)
  81. browser = await chromium.launch()
  82. page = await newEnglishPage(browser)
  83. tripwire = watchConsole(page)
  84. await page.goto(scaffold.baseUrl, { waitUntil: 'load' })
  85. await page.waitForSelector('[class*="frame"]', { timeout: 30_000 })
  86. }, 120_000)
  87. afterAll(async () => {
  88. await browser?.close()
  89. await scaffold?.close()
  90. })
  91. it.skipIf(MODE === 'record')('enables branch only on the completed transcript tail', async () => {
  92. onTestFailed(() => saveFailureShot(page, 'web-e2e-message-actions'))
  93. const groupRow = page.locator('[role="treeitem"]').first()
  94. await groupRow.waitFor({ timeout: 15_000 })
  95. await groupRow.click()
  96. const sessionRow = page.locator('[role="treeitem"]').nth(1)
  97. await sessionRow.waitFor({ timeout: 10_000 })
  98. await sessionRow.click()
  99. await expect.poll(() => page.getByText(MID_TURN_TEXT, { exact: true }).count(), { timeout: 15_000 }).toBe(1)
  100. await expect.poll(() => page.getByText('DONE', { exact: true }).count(), { timeout: 15_000 }).toBe(1)
  101. // Focus-reveal the footers (hover:hover keeps them opacity-hidden until
  102. // hover/focus-within). Every durable message footer keeps branch visible,
  103. // but only the final assistant at a completed transcript tail enables it.
  104. const copyButtons = page.getByRole('button', { name: 'Copy' })
  105. await expect.poll(() => copyButtons.count(), { timeout: 10_000 }).toBeGreaterThanOrEqual(4)
  106. await copyButtons.first().focus()
  107. const branchButtons = page.getByRole('button', { name: 'Branch into a new conversation' })
  108. await expect.poll(() => branchButtons.count(), { timeout: 5_000 }).toBe(4)
  109. await expect.poll(
  110. () => branchButtons.evaluateAll(buttons => buttons.map(button => button.getAttribute('aria-disabled'))),
  111. { timeout: 5_000 },
  112. ).toEqual(['true', 'true', 'true', null])
  113. await branchButtons.first().focus()
  114. await expect.poll(() => page.getByRole('tooltip').textContent(), { timeout: 5_000 })
  115. .toBe('Available only on the last message of a completed turn')
  116. await expect.poll(() => page.getByRole('button', { name: 'Edit' }).count(), { timeout: 5_000 }).toBe(0)
  117. }, 60_000)
  118. it.skipIf(MODE === 'record')('matches the conversation aria golden with IconActions and clocks', async () => {
  119. onTestFailed(() => saveFailureShot(page, 'web-e2e-message-actions-aria'))
  120. await page.getByRole('button', { name: 'Select model', exact: true })
  121. .waitFor({ timeout: 10_000 })
  122. // Keep a footer focused so opacity-hidden actions stay in the a11y tree
  123. // as an active/focused control during the capture.
  124. await page.getByRole('button', { name: 'Copy' }).first().focus()
  125. const snapshot = (await captureStableAria(page, '[class*="centerCol"]', scaffold.workspaceCwd))
  126. .split(SEED_ID).join('{{seededId}}')
  127. await compareOrRefreshGolden(UI_EXPECTED, snapshot, MODE)
  128. })
  129. it.skipIf(MODE === 'record')('forks through the settled-message and session-row actions', async () => {
  130. onTestFailed(() => saveFailureShot(page, 'web-e2e-message-fork'))
  131. // The last message action belongs to the completed second-turn assistant.
  132. await page.getByRole('button', { name: 'Branch into a new conversation' }).last().click()
  133. await expect.poll(
  134. () => scaffold.ctx.agents.list().find(agent => agent.session.header.parentSession === SessionId(SEED_ID)),
  135. { timeout: 15_000 },
  136. ).toBeDefined()
  137. await expect.poll(
  138. () => page.locator('[role="treeitem"]').count(),
  139. { timeout: 10_000 },
  140. ).toBe(3)
  141. await expect.poll(
  142. () => page.locator('[role="treeitem"][aria-selected="true"]').count(),
  143. { timeout: 10_000 },
  144. ).toBe(1)
  145. // The row action owns a distinct ui-workspace injection from the message
  146. // action above, so exercise both through the loaded app before capture.
  147. const sourceRow = page.locator('[role="treeitem"][aria-selected="true"]')
  148. const rowBox = await sourceRow.boundingBox()
  149. if (rowBox === null) throw new Error('fork source row has no layout box')
  150. const actionButton = sourceRow.locator('button[aria-label^="Session actions for "]')
  151. await sourceRow.hover({ position: { x: rowBox.width - 16, y: rowBox.height / 2 } })
  152. await expect.poll(() => actionButton.isVisible(), { timeout: 2_000 }).toBe(true)
  153. const buttonBox = await actionButton.boundingBox()
  154. if (buttonBox === null) throw new Error('fork source row action has no layout box')
  155. await page.mouse.click(buttonBox.x + buttonBox.width / 2, buttonBox.y + buttonBox.height / 2)
  156. await page.getByRole('menuitem', { name: 'Fork session' }).click()
  157. await expect.poll(
  158. () => scaffold.ctx.agents.list().filter(agent => agent.session.header.parentSession !== undefined).length,
  159. { timeout: 15_000 },
  160. ).toBe(2)
  161. await expect.poll(
  162. () => page.locator('[role="treeitem"]').count(),
  163. { timeout: 10_000 },
  164. ).toBe(4)
  165. await expect.poll(
  166. () => page.locator('[role="treeitem"][aria-selected="true"]').count(),
  167. { timeout: 10_000 },
  168. ).toBe(1)
  169. const tree = await captureStableAria(
  170. page,
  171. '[role="tree"][aria-label="Sessions"]',
  172. scaffold.workspaceCwd,
  173. )
  174. await compareOrRefreshGolden(FORK_EXPECTED, tree, MODE)
  175. })
  176. it.skipIf(MODE === 'record')('issued zero model calls and kept a closed inventory', async () => {
  177. expect(tripwire.pageErrors).toEqual([])
  178. expect(tripwire.warnings).toEqual([])
  179. await assertFixtureInventory(SNAPSHOT_DIR, ['fork.expected.md', 'ui.expected.md'])
  180. })
  181. })