queue-image.e2e.ts 7.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155
  1. // Keyless browser coverage for image attachments submitted while a turn is
  2. // running, through the shipped Web composition and real HTTP/SSE wire. A
  3. // text-plus-image submission queues as one occurrence whose dock row renders
  4. // the durable thumbnail, survives a stop as parked work, and delivers as the
  5. // next turn's user message with its image intact — while the session log holds
  6. // only durable attachment references, never base64.
  7. import { existsSync } from 'node:fs'
  8. import { mkdtemp, readFile, rm, writeFile } from 'node:fs/promises'
  9. import { tmpdir } from 'node:os'
  10. import { fileURLToPath } from 'node:url'
  11. import { join } from 'node:path'
  12. import type { Browser, Page } from 'playwright'
  13. import { chromium } from 'playwright'
  14. import { afterEach, describe, expect, it, onTestFailed } from 'vitest'
  15. import { deriveReplayScript, parseSessionLog, type ReplayEntry } from '@deepseek-ai/dsh-llm-replay'
  16. import type { SessionEvent } from '@deepseek-ai/dsh-session'
  17. import {
  18. captureStableAria, compareOrRefreshGolden,
  19. launchWebScaffold, watchConsole, webSnapshotMode, type WebScaffold,
  20. } from './scaffold.ts'
  21. import { connectFreshWorkspace, newEnglishPage, saveFailureShot } from './support.ts'
  22. const SNAPSHOT_DIR = fileURLToPath(new URL('../../../snapshots/web/queued-image', import.meta.url))
  23. const FIXTURE = fileURLToPath(new URL('../../../snapshots/web/live-interactions/session.v2.jsonl', import.meta.url))
  24. const PNG = fileURLToPath(new URL('../../../snapshots/session/read-image/workspace/red.png', import.meta.url))
  25. const QUEUED_EXPECTED = join(SNAPSHOT_DIR, 'queued.expected.md')
  26. const DELIVERED_EXPECTED = join(SNAPSHOT_DIR, 'delivered.expected.md')
  27. const MODE = webSnapshotMode()
  28. const ACTIVE_PROMPT = 'Reply with a one-sentence description of event sourcing, then stop.'
  29. const QUEUED_TEXT = 'Compare with this screenshot'
  30. /** Paste one real PNG into the composer through a genuine clipboard event. */
  31. async function pasteImage(page: Page, bytes: Uint8Array): Promise<void> {
  32. await page.locator('[data-composer-input]').first().evaluate((surface, data) => {
  33. const transfer = new DataTransfer()
  34. transfer.items.add(new File([new Uint8Array(data)], 'queued.png', { type: 'image/png' }))
  35. surface.dispatchEvent(new ClipboardEvent('paste', {
  36. clipboardData: transfer, bubbles: true, cancelable: true,
  37. }))
  38. }, [...bytes])
  39. }
  40. describe('web e2e: queued image submission', () => {
  41. let scaffold: WebScaffold | undefined
  42. let browser: Browser | undefined
  43. let page: Page
  44. let overrideDir: string | undefined
  45. afterEach(async () => {
  46. const failures: unknown[] = []
  47. await browser?.close().catch((error: unknown) => failures.push(error))
  48. browser = undefined
  49. const closing = scaffold
  50. scaffold = undefined
  51. await closing?.close().catch((error: unknown) => failures.push(error))
  52. if (overrideDir !== undefined) {
  53. await rm(overrideDir, { recursive: true, force: true })
  54. .catch((error: unknown) => failures.push(error))
  55. }
  56. overrideDir = undefined
  57. if (failures.length === 1) throw failures[0]
  58. if (failures.length > 1) throw new AggregateError(failures, 'queued-image teardown failed')
  59. })
  60. it.skipIf(MODE === 'record')('queues a text-plus-image submission with a thumbnail and delivers it as the next turn', async () => {
  61. overrideDir = await mkdtemp(join(tmpdir(), 'dsh-web-queued-image-'))
  62. const readyFile = join(overrideDir, '.hang-ready')
  63. const overridePath = join(overrideDir, 'replay.override.json')
  64. const recorded = deriveReplayScript(parseSessionLog(await readFile(FIXTURE, 'utf8')))
  65. expect(recorded).toHaveLength(1)
  66. const replay: ReplayEntry[] = [
  67. { kind: 'hang', readyFile },
  68. recorded[0]!,
  69. recorded[0]!,
  70. ]
  71. await writeFile(overridePath, JSON.stringify(replay))
  72. const sessionEvents: SessionEvent[] = []
  73. scaffold = await launchWebScaffold({ replayFixture: FIXTURE, replayOverride: overridePath, compareReplaySession: false })
  74. scaffold.ctx.on('session/event', (_session, event: SessionEvent) => { sessionEvents.push(event) })
  75. browser = await chromium.launch()
  76. page = await newEnglishPage(browser)
  77. const tripwire = watchConsole(page)
  78. await page.goto(scaffold.authenticatedUrl, { waitUntil: 'load' })
  79. await page.waitForSelector('[class*="frame"]', { timeout: 30_000 })
  80. await connectFreshWorkspace(page, scaffold.workspaceCwd)
  81. onTestFailed(() => saveFailureShot(page, 'web-e2e-queued-image'))
  82. const input = page.locator('[data-composer-input]').first()
  83. const firstSettled = scaffold.whenTurnSettled()
  84. await input.fill(ACTIVE_PROMPT)
  85. await input.press('Enter')
  86. await expect.poll(() => existsSync(readyFile), { timeout: 15_000 }).toBe(true)
  87. // A just-submitted composer is read-only for the prompt round-trip.
  88. await page.locator('[data-composer-input][contenteditable="true"]').first().waitFor({ timeout: 10_000 })
  89. await pasteImage(page, await readFile(PNG))
  90. await page.getByRole('img', { name: 'queued.png' }).waitFor({ timeout: 10_000 })
  91. await input.fill(QUEUED_TEXT)
  92. await input.press('Enter')
  93. // The queued row renders the durable thumbnail beside the text preview.
  94. const dockThumb = page.locator('[data-queue-dock] img[alt="Queued message image"]')
  95. await dockThumb.waitFor({ timeout: 15_000 })
  96. await expect.poll(() => dockThumb.getAttribute('src')).toMatch(/^blob:/)
  97. await page.getByText(QUEUED_TEXT, { exact: true }).waitFor()
  98. await page.getByRole('button', { name: 'Remove queued message' }).waitFor({ timeout: 15_000 })
  99. const queuedSnapshot = await captureStableAria(page, '[class*="centerCol"]', scaffold.workspaceCwd)
  100. await compareOrRefreshGolden(QUEUED_EXPECTED, queuedSnapshot, MODE)
  101. // Stop parks the accepted queue; the next waking send delivers the image
  102. // message first (FIFO), then its own text as the following turn.
  103. await page.getByRole('button', { name: 'Stop generating' }).click()
  104. await firstSettled
  105. await expect.poll(() => page.getByRole('button', { name: 'Stop generating' }).count()).toBe(0)
  106. await dockThumb.waitFor({ timeout: 10_000 })
  107. const settled = scaffold.whenTurnSettled()
  108. await input.fill('Continue with the queued comparison')
  109. await input.press('Enter')
  110. await settled
  111. // The queued image message and the waking text run as two further turns;
  112. // wait for both to end so the final snapshot never captures a mid-reply
  113. // frame (the aborted first turn precedes them).
  114. await expect.poll(
  115. () => sessionEvents.flatMap(event => event.type === 'turn/end' ? [event.data.reason.kind] : []),
  116. { timeout: 15_000 },
  117. ).toEqual(['aborted', 'completed', 'completed'])
  118. // The delivered user message renders its image in Chat from the durable
  119. // reference, and the dock row is gone.
  120. await expect.poll(
  121. () => page.locator('[data-queue-dock]').count(),
  122. { timeout: 15_000 },
  123. ).toBe(0)
  124. const chatImage = page.locator('[class*="userRow"] img')
  125. await chatImage.first().waitFor({ timeout: 15_000 })
  126. const deliveredSnapshot = await captureStableAria(page, '[class*="centerCol"]', scaffold.workspaceCwd)
  127. await compareOrRefreshGolden(DELIVERED_EXPECTED, deliveredSnapshot, MODE)
  128. // Model-visible means logged: the delivered message carries the durable
  129. // reference (never base64), in the composer's canonical images-then-text order.
  130. const delivered = sessionEvents.find(event => event.type === 'user/message'
  131. && event.data.content.some(block => block.type === 'image'))
  132. expect(delivered?.type === 'user/message' && delivered.data.content.map(block => block.type)).toEqual(['image', 'text'])
  133. const imageBlock = delivered?.type === 'user/message'
  134. ? delivered.data.content.find(block => block.type === 'image')
  135. : undefined
  136. expect(imageBlock?.type === 'image' && imageBlock.attachment.name).toBe('queued.png')
  137. expect(JSON.stringify(sessionEvents)).not.toContain('base64')
  138. expect(tripwire.pageErrors).toEqual([])
  139. expect(tripwire.warnings).toEqual([])
  140. }, 120_000)
  141. })