reference-composer.e2e.ts 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249
  1. // Web e2e scenario: the shipped composition discovers local files and cold
  2. // sessions through the real Host, groups both domains in the shared @ menu,
  3. // and projects each pick as a complete inline range without issuing a model call.
  4. import { writeFile } from 'node:fs/promises'
  5. import { fileURLToPath } from 'node:url'
  6. import { join } from 'node:path'
  7. import type { Browser, Page } from 'playwright'
  8. import { chromium } from 'playwright'
  9. import { afterAll, beforeAll, describe, expect, it, onTestFailed } from 'vitest'
  10. import { createUserMessage } from '@deepseek-ai/dsh-llm'
  11. import {
  12. SESSION_FORMAT_VERSION,
  13. Session,
  14. SessionId,
  15. } from '@deepseek-ai/dsh-session'
  16. import type {} from '@deepseek-ai/dsh-session-reference/types'
  17. import type {} from '@deepseek-ai/dsh-session-title'
  18. import {
  19. assertFixtureInventory,
  20. captureStableAria,
  21. compareOrRefreshGolden,
  22. launchWebScaffold,
  23. seedSession,
  24. watchConsole,
  25. webSnapshotMode,
  26. type WebScaffold,
  27. } from './scaffold.ts'
  28. import { connectFreshWorkspace, newEnglishPage, saveFailureShot } from './support.ts'
  29. const SNAPSHOT_DIR = fileURLToPath(new URL('./expected/reference-composer', import.meta.url))
  30. const MENU_EXPECTED = join(SNAPSHOT_DIR, 'menu.expected.md')
  31. const ORDER_EXPECTED = join(SNAPSHOT_DIR, 'order.expected.md')
  32. const CARET_EXPECTED = join(SNAPSHOT_DIR, 'caret-edits.expected.md')
  33. const MODE = webSnapshotMode()
  34. const SOURCE_SESSION_ID = 'reference-source-session'
  35. const TARGET_SESSION_ID = 'reference-order-target-session'
  36. /** Build one closed source session with a stable title for reference discovery. */
  37. function sourceSessionFixture(): string {
  38. const session = Session.create(SessionId(SOURCE_SESSION_ID))
  39. session.append('turn/start', {
  40. turn: 1,
  41. })
  42. const user = session.append('user/message', createUserMessage({
  43. content: [{ type: 'text', text: 'Research context for the reference menu.' }],
  44. source: { kind: 'user' },
  45. }), { surfaceOp: 'append' })
  46. session.append('session/title', {
  47. title: 'Research notes',
  48. messageSeqs: [user.seq],
  49. source: { kind: 'fallback' },
  50. })
  51. session.append('turn/end', { turn: 1, reason: { kind: 'completed' } })
  52. return [
  53. JSON.stringify({
  54. type: 'session',
  55. version: SESSION_FORMAT_VERSION,
  56. id: '{{sessionId}}',
  57. createdAt: 0,
  58. cwd: '{{cwd}}',
  59. }),
  60. ...session.events.map(event => JSON.stringify(event)),
  61. '',
  62. ].join('\n')
  63. }
  64. /** Build one target log with the direct message durably before its recalled context. */
  65. function targetSessionFixture(): string {
  66. const session = Session.create(SessionId(TARGET_SESSION_ID))
  67. session.append('turn/start', { turn: 1 })
  68. const user = session.append('user/message', createUserMessage({
  69. content: [{ type: 'text', text: '@Research notes what changed?' }],
  70. source: { kind: 'user' },
  71. }), { surfaceOp: 'append' })
  72. session.append('user/message', createUserMessage({
  73. content: [{ type: 'text', text: '## Referenced sessions\n\n<referenced-sessions>snapshot</referenced-sessions>' }],
  74. source: {
  75. kind: 'session-reference',
  76. form: 'recall',
  77. version: 1,
  78. references: [{
  79. sessionId: SOURCE_SESSION_ID,
  80. label: 'Research notes',
  81. capturedThroughSeq: 4,
  82. compacted: false,
  83. originalMessages: 2,
  84. retainedMessages: 2,
  85. omittedMessages: 0,
  86. omittedBytes: 0,
  87. truncated: false,
  88. inputIndex: 0,
  89. }],
  90. },
  91. }), { surfaceOp: 'append' })
  92. session.append('session/title', {
  93. title: 'Reference order target',
  94. messageSeqs: [user.seq],
  95. source: { kind: 'fallback' },
  96. })
  97. session.append('turn/end', { turn: 1, reason: { kind: 'completed' } })
  98. return [
  99. JSON.stringify({
  100. type: 'session',
  101. version: SESSION_FORMAT_VERSION,
  102. id: '{{sessionId}}',
  103. createdAt: 0,
  104. cwd: '{{cwd}}',
  105. }),
  106. ...session.events.map(event => JSON.stringify(event)),
  107. '',
  108. ].join('\n')
  109. }
  110. /**
  111. * Project the composer backdrop into one stable block: the draft it paints and
  112. * each segment in draft order, with the decoration a segment carries.
  113. * @param page - the assembled app page.
  114. * @returns the golden text for the composer's decoration layer.
  115. */
  116. async function composerSegments(page: Page): Promise<string> {
  117. return page.evaluate(() => {
  118. const backdrop = document.querySelector('[data-input-backdrop]')
  119. const textarea = document.querySelector('textarea')
  120. if (backdrop === null || textarea === null) return 'composer absent'
  121. const rows = [...backdrop.childNodes].map((node) => {
  122. if (!(node instanceof HTMLElement)) return `plain ${JSON.stringify(node.textContent ?? '')}`
  123. const decoration = node.dataset['decoration'] ?? 'unknown'
  124. const appearance = node.dataset['referenceAppearance']
  125. const icons = node.querySelectorAll('svg').length
  126. return `${decoration.padEnd(8)} ${JSON.stringify(node.textContent ?? '')}`
  127. + `${appearance === undefined ? '' : ` appearance=${appearance}`} icons=${icons}`
  128. })
  129. return [`draft ${JSON.stringify(textarea.value)}`, ...rows].join('\n')
  130. })
  131. }
  132. describe.skipIf(MODE === 'record')('web e2e: file and session references through the real host', () => {
  133. let scaffold: WebScaffold
  134. let browser: Browser
  135. let page: Page
  136. let tripwire: ReturnType<typeof watchConsole>
  137. beforeAll(async () => {
  138. scaffold = await launchWebScaffold({})
  139. await seedSession(scaffold, sourceSessionFixture(), SOURCE_SESSION_ID)
  140. await seedSession(scaffold, targetSessionFixture(), TARGET_SESSION_ID)
  141. browser = await chromium.launch()
  142. page = await newEnglishPage(browser)
  143. tripwire = watchConsole(page)
  144. await page.goto(scaffold.baseUrl, { waitUntil: 'load' })
  145. await page.waitForSelector('[class*="frame"]', { timeout: 30_000 })
  146. await connectFreshWorkspace(page, scaffold.workspaceCwd)
  147. await writeFile(join(scaffold.workspaceCwd, 'workspace', 'reference.txt'), 'reference fixture\n')
  148. }, 120_000)
  149. afterAll(async () => {
  150. await browser?.close()
  151. await scaffold?.close()
  152. })
  153. it('groups both sources and projects files and sessions as structured inline icon labels', async () => {
  154. onTestFailed(() => saveFailureShot(page, 'web-e2e-reference-composer'))
  155. const input = page.locator('textarea').first()
  156. const menu = page.getByRole('listbox', { name: 'Trigger suggestions' })
  157. await input.fill('@')
  158. await expect.poll(() => menu.getByRole('option').count(), { timeout: 15_000 }).toBeGreaterThanOrEqual(2)
  159. const snapshot = await captureStableAria(page, '[role="listbox"]', scaffold.workspaceCwd)
  160. await compareOrRefreshGolden(MENU_EXPECTED, snapshot, MODE)
  161. expect(snapshot).toContain('Files & folders')
  162. expect(snapshot).toContain('Session conversations')
  163. expect(snapshot).not.toContain('text: reference Files & folders')
  164. expect(snapshot).toContain('File \u00b7 reference.txt')
  165. expect(snapshot).toContain('Session \u00b7 Research notes')
  166. expect(snapshot).not.toContain('text: Subagents')
  167. await input.fill('@reference')
  168. await menu.getByRole('option', { name: /File \u00b7 reference\.txt/ }).click()
  169. const fileReference = page.locator('[data-reference-appearance="file"]')
  170. await expect.poll(() => fileReference.textContent()).toBe('@reference.txt')
  171. await expect.poll(() => fileReference.locator('svg').count()).toBe(1)
  172. await expect.poll(() => input.inputValue()).toBe('@reference.txt ')
  173. await input.fill('@Research')
  174. await menu.getByRole('option', { name: /Session \u00b7 Research notes/ }).click()
  175. const sessionReference = page.locator('[data-reference-appearance="session"]')
  176. await expect.poll(() => sessionReference.textContent()).toBe('@Research notes')
  177. await expect.poll(() => sessionReference.locator('svg').count()).toBe(1)
  178. await expect.poll(() => input.inputValue()).toBe('@Research notes ')
  179. expect(tripwire.pageErrors).toEqual([])
  180. expect(tripwire.warnings).toEqual([])
  181. })
  182. it('keeps a structured reference across caret edits in front of it', async () => {
  183. onTestFailed(() => saveFailureShot(page, 'web-e2e-reference-caret-edits'))
  184. const input = page.locator('textarea').first()
  185. const menu = page.getByRole('listbox', { name: 'Trigger suggestions' })
  186. const sessionReference = page.locator('[data-reference-appearance="session"]')
  187. await input.fill('@Research')
  188. await menu.getByRole('option', { name: /Session \u00b7 Research notes/ }).click()
  189. await expect.poll(() => input.inputValue()).toBe('@Research notes ')
  190. // Only the caret is placed programmatically; both edits below are real key
  191. // presses, which is the whole point — the range a textarea reports for them
  192. // is what the composer has to read, and no synthetic event can stand in.
  193. await input.evaluate((el: HTMLTextAreaElement) => { el.focus(); el.setSelectionRange(0, 0) })
  194. await input.press('@')
  195. await expect.poll(() => input.inputValue()).toBe('@@Research notes ')
  196. await expect.poll(() => sessionReference.count()).toBe(1)
  197. await expect.poll(() => sessionReference.textContent()).toBe('@Research notes')
  198. await expect.poll(() => sessionReference.locator('svg').count()).toBe(1)
  199. // The decoration layer is aria-hidden, so the accessibility tree cannot see
  200. // the chip; the golden projects the backdrop's own segments instead, which
  201. // is where the surviving reference is observable at all.
  202. await compareOrRefreshGolden(CARET_EXPECTED, await composerSegments(page), MODE)
  203. // The caret sits after the typed trigger; this Backspace removes it with a
  204. // collapsed selection, the gesture the reported range cannot describe alone.
  205. await input.press('Backspace')
  206. await expect.poll(() => input.inputValue()).toBe('@Research notes ')
  207. await expect.poll(() => sessionReference.count()).toBe(1)
  208. await expect.poll(() => sessionReference.textContent()).toBe('@Research notes')
  209. expect(tripwire.pageErrors).toEqual([])
  210. expect(tripwire.warnings).toEqual([])
  211. })
  212. it('renders the durable direct-message then recall order', async () => {
  213. onTestFailed(() => saveFailureShot(page, 'web-e2e-reference-order'))
  214. const group = page.getByRole('treeitem', { name: /Ungrouped/ })
  215. await group.waitFor({ timeout: 15_000 })
  216. if (await group.getAttribute('aria-expanded') !== 'true') await group.click()
  217. const target = page.getByRole('treeitem', { name: /Reference order target/ })
  218. await target.waitFor({ timeout: 15_000 })
  219. await target.click()
  220. await page.getByRole('button', { name: /^Session recall\s*Research notes$/ }).waitFor({ timeout: 15_000 })
  221. const snapshot = (await captureStableAria(page, '[class*="centerCol"]', scaffold.workspaceCwd))
  222. .split(TARGET_SESSION_ID).join('{{targetId}}')
  223. await compareOrRefreshGolden(ORDER_EXPECTED, snapshot, MODE)
  224. expect(snapshot.indexOf('Research notes what changed?')).toBeLessThan(snapshot.indexOf('Session recall Research notes'))
  225. expect(tripwire.pageErrors).toEqual([])
  226. expect(tripwire.warnings).toEqual([])
  227. await assertFixtureInventory(SNAPSHOT_DIR, ['caret-edits.expected.md', 'menu.expected.md', 'order.expected.md'])
  228. })
  229. })