cordis-tool-round.e2e.ts 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198
  1. // Web e2e scenario for the opt-in Cordis tools. Record mode drives a real
  2. // model through inspect, define, run, and stop; replay pins the same shipped Web
  3. // composition, durable calls, Cordis-owned rows, the define card's own source view,
  4. // and conversation accessibility tree.
  5. //
  6. // The approval is never in the fixture. The fixture pins what the MODEL said;
  7. // tools execute for real, and this test answers the approval before starting the
  8. // stop turn. The package therefore carries a browser half whose only
  9. // job is to be visible (`[data-snapshot-probe]`): its absence before the answer
  10. // and presence after it is the v3 user gate, proven rather than described.
  11. import { readFile } from 'node:fs/promises'
  12. import { fileURLToPath } from 'node:url'
  13. import type { Browser, Page } from 'playwright'
  14. import { chromium } from 'playwright'
  15. import { afterAll, beforeAll, describe, expect, it, onTestFailed } from 'vitest'
  16. import type { SessionEvent } from '@deepseek-ai/dsh-session'
  17. import {
  18. captureStableAria, compareOrRefreshGolden, fixtureUserPrompts,
  19. launchWebScaffold, recordFixture, watchConsole, webSnapshotMode, type WebScaffold,
  20. } from './scaffold.ts'
  21. import { connectFreshWorkspace, newEnglishPage, saveFailureShot } from './support.ts'
  22. const FIXTURE = fileURLToPath(new URL('../../../snapshots/web/cordis-tool-round/session.jsonl', import.meta.url))
  23. const UI_EXPECTED = fileURLToPath(new URL('../../../snapshots/web/cordis-tool-round/ui.expected.md', import.meta.url))
  24. const MODE = webSnapshotMode()
  25. const CORDIS_TOOLS = ['cordis_inspect_self', 'cordis_define', 'cordis_run', 'cordis_stop'] as const
  26. const PACKAGE_CODE = 'return { name: "snapshot-noop", apply(ctx) {} }'
  27. // The browser half is the PROBE this scenario turns on: it renders a marker into
  28. // the frame-wide overlay, so "did the plugin actually run in this page" becomes a
  29. // DOM fact. A host-only package would sidestep the approval round trip entirely
  30. // (the host runs those immediately), which would drop the v3 user gate out of
  31. // coverage — the one thing this scenario exists to prove.
  32. const CLIENT_CODE = 'return { inject: ["slots"], apply(ctx) { ctx.slots.register('
  33. + '{ name: "shell.overlay", id: "snapshot-probe" }, '
  34. + '() => React.createElement("div", { "data-snapshot-probe": "loaded" })) } }'
  35. const PROMPT = 'Use only Cordis tools. First call cordis_inspect_self with no arguments. '
  36. + 'Then call cordis_define with plugin kind "new", idPrefix "snap", name "snapshot noop", '
  37. + 'purpose "does nothing, for the snapshot", '
  38. + `code.host exactly ${JSON.stringify(PACKAGE_CODE)} and code.client exactly ${JSON.stringify(CLIENT_CODE)}. `
  39. + 'Read its returned pluginId and packageId, then call cordis_run with those exact IDs and mode "run". '
  40. + 'After the run request returns, reply exactly CORDIS_UI_READY and stop.'
  41. const STOP_PROMPT = 'Use only Cordis tools. Call cordis_stop with pluginId "snap-1". '
  42. + 'After it succeeds, reply exactly CORDIS_UI_DONE and stop.'
  43. function assertCompleteCordisLifecycle(events: readonly SessionEvent[]): void {
  44. const turnEnd = events.findLast(
  45. (event): event is Extract<SessionEvent, { type: 'turn/end' }> => event.type === 'turn/end',
  46. )
  47. const reason = turnEnd?.data.reason
  48. expect(reason).toEqual({ kind: 'completed' })
  49. const calls = events.filter(
  50. (event): event is Extract<SessionEvent, { type: 'tool/call' }> => event.type === 'tool/call',
  51. )
  52. expect(calls.map(event => event.data.name)).toEqual(CORDIS_TOOLS)
  53. const callIds = new Set(calls.map(event => String(event.data.callId)))
  54. const results = events.filter(
  55. (event): event is Extract<SessionEvent, { type: 'tool/result' }> =>
  56. event.type === 'tool/result' && callIds.has(String(event.data.message.source.callId)),
  57. )
  58. expect(results).toHaveLength(CORDIS_TOOLS.length)
  59. expect(results.every(event => !event.data.message.content[0].isError)).toBe(true)
  60. }
  61. describe('web e2e: Cordis tools use their owned cards', () => {
  62. let scaffold: WebScaffold
  63. let browser: Browser
  64. let page: Page
  65. let tripwire: ReturnType<typeof watchConsole>
  66. const sessionEvents: SessionEvent[] = []
  67. const modelFrames: string[] = []
  68. const modelChanges: string[] = []
  69. beforeAll(async () => {
  70. scaffold = await launchWebScaffold({
  71. cordisTools: true,
  72. compareReplaySession: true,
  73. ...(MODE === 'record' ? {} : { replayFixture: FIXTURE, paceMs: 15 }),
  74. })
  75. scaffold.ctx.on('session/event', (_session, event: SessionEvent) => { sessionEvents.push(event) })
  76. scaffold.ctx.sessionProjections.onChanged((_session, key, value, seq) => {
  77. if (key === 'modelSelection') modelChanges.push(`${String(seq)}:${JSON.stringify(value)}`)
  78. })
  79. browser = await chromium.launch()
  80. page = await newEnglishPage(browser)
  81. page.on('websocket', (socket) => {
  82. socket.on('framereceived', (frame) => {
  83. const payload = String(frame.payload)
  84. if (payload.includes('modelSelection')) modelFrames.push(payload)
  85. })
  86. })
  87. tripwire = watchConsole(page)
  88. await page.goto(scaffold.baseUrl, { waitUntil: 'load' })
  89. await page.waitForSelector('[class*="frame"]', { timeout: 30_000 })
  90. await connectFreshWorkspace(page, scaffold.workspaceCwd)
  91. }, 120_000)
  92. afterAll(async () => {
  93. await browser?.close()
  94. await scaffold?.close()
  95. })
  96. it('drives the recorded Cordis lifecycle to a settled turn (all modes)', async () => {
  97. onTestFailed(() => saveFailureShot(page, 'web-e2e-cordis-drive'))
  98. if (MODE !== 'record') {
  99. expect(fixtureUserPrompts(await readFile(FIXTURE, 'utf8'))).toEqual([PROMPT, STOP_PROMPT])
  100. }
  101. const input = page.locator('textarea').first()
  102. await input.waitFor({ timeout: 10_000 })
  103. const runTurnSettled = scaffold.whenTurnSettled()
  104. await input.fill(PROMPT)
  105. await input.press('Enter')
  106. // The approval is the TEST's action in every mode: the fixture pins what the
  107. // model said, and the gate is a real round trip through the real panel.
  108. const approve = page.locator('[data-cordis-approve]').first()
  109. await approve.waitFor({ timeout: 90_000 })
  110. // The one assertion this scenario cannot give up: the model asking to run is
  111. // NOT the plugin running. Until a person answers, the browser half has not
  112. // been fetched, evaluated, or mounted anywhere on this page.
  113. expect(await page.locator('[data-snapshot-probe]').count()).toBe(0)
  114. const sessionId = await runTurnSettled
  115. // Approving from idle makes the run-outcome steer a distinct continuation
  116. // turn, matching the recorded replay and keeping turn grouping deterministic.
  117. const approvalTurnSettled = scaffold.whenTurnSettled()
  118. await approve.click()
  119. await expect.poll(() => page.locator('[data-snapshot-probe]').count(), { timeout: 30_000 }).toBe(1)
  120. await approvalTurnSettled
  121. await expect.poll(() => page.getByText('The Cordis Plugin is running.', { exact: true }).count(), { timeout: 15_000 })
  122. .toBeGreaterThanOrEqual(1)
  123. await expect.poll(() => input.isEnabled(), { timeout: 15_000 }).toBe(true)
  124. const stopTurnSettled = scaffold.whenTurnSettled()
  125. await input.fill(STOP_PROMPT)
  126. await input.press('Enter')
  127. await stopTurnSettled
  128. if (MODE === 'record') {
  129. assertCompleteCordisLifecycle(sessionEvents)
  130. await expect.poll(() => page.getByText('CORDIS_UI_DONE', { exact: true }).count(), { timeout: 15_000 })
  131. .toBeGreaterThanOrEqual(1)
  132. await recordFixture(scaffold, sessionId, FIXTURE)
  133. }
  134. }, 200_000)
  135. it.skipIf(MODE === 'record')('the durable log carries one complete Cordis lifecycle', () => {
  136. assertCompleteCordisLifecycle(sessionEvents)
  137. })
  138. it.skipIf(MODE === 'record')('renders localized Cordis lifecycle cards', async () => {
  139. onTestFailed(() => saveFailureShot(page, 'web-e2e-cordis-rows'))
  140. await expect.poll(() => page.getByText('CORDIS_UI_DONE', { exact: true }).count(), { timeout: 15_000 })
  141. .toBeGreaterThanOrEqual(1)
  142. const inspectRow = page.locator('[data-tool="cordis_inspect_self"]').filter({ hasText: 'Inspect' }).first()
  143. await inspectRow.waitFor({ timeout: 10_000 })
  144. // cordis_define does NOT go through the generic row: ui-cordis registers a
  145. // keyed toolview for it, and a keyed hit replaces the generic card. So the
  146. // title here is the CARD's ("Cordis Plugin"), and the expanded body is the
  147. // card's own two code sections rather than a generic args dump.
  148. const defineRow = page.locator('[data-tool="cordis_define"]').filter({ hasText: 'Cordis Plugin' }).first()
  149. await defineRow.waitFor({ timeout: 10_000 })
  150. // The whole summary row is the expand toggle (unified tool-row interaction).
  151. await defineRow.locator('[aria-expanded]').first().click()
  152. await expect.poll(() => defineRow.textContent(), { timeout: 10_000 }).toContain('data-snapshot-probe')
  153. await defineRow.getByRole('tab', { name: 'Host' }).click()
  154. await expect.poll(() => defineRow.textContent()).toContain(PACKAGE_CODE)
  155. const runRow = page.locator('[data-tool="cordis_run"]').filter({ hasText: 'Run Cordis Plugin' }).first()
  156. await runRow.waitFor({ timeout: 10_000 })
  157. await expect.poll(() => runRow.textContent()).toContain('snap-')
  158. const stopRow = page.locator('[data-tool="cordis_stop"]').filter({ hasText: 'Stop Cordis Plugin' }).first()
  159. await stopRow.waitFor({ timeout: 10_000 })
  160. await expect.poll(() => stopRow.textContent()).toContain('snap-')
  161. await expect(stopRow.getAttribute('data-state')).resolves.toBe('ok')
  162. // Stopping withdraws the browser half from every page, probe included.
  163. await expect.poll(() => page.locator('[data-snapshot-probe]').count(), { timeout: 15_000 }).toBe(0)
  164. })
  165. it.skipIf(MODE === 'record')('matches the conversation aria golden', async () => {
  166. onTestFailed(() => saveFailureShot(page, 'web-e2e-cordis-aria'))
  167. console.log('MODEL_TRACE', { modelChanges, frameCount: modelFrames.length, modelFrames })
  168. await page.locator('[data-conversation-scroll]').evaluate((host) => { host.scrollTop = host.scrollHeight })
  169. await expect.poll(
  170. async () => page.getByRole('button', { name: 'Back to bottom', exact: true }).count(),
  171. { timeout: 10_000 },
  172. ).toBe(0)
  173. await page.mouse.move(0, 0)
  174. const snapshot = await captureStableAria(page, '[class*="centerCol"]', scaffold.workspaceCwd)
  175. await compareOrRefreshGolden(UI_EXPECTED, snapshot, MODE)
  176. })
  177. it.skipIf(MODE === 'record')('stayed clean: no page errors or reconnect churn', () => {
  178. expect(tripwire.pageErrors).toEqual([])
  179. expect(tripwire.warnings).toEqual([])
  180. })
  181. })