reference-composer.e2e.ts 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377
  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 { mkdir, 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. SessionSeq,
  16. } from '@deepseek-ai/dsh-session'
  17. import type {} from '@deepseek-ai/dsh-session-reference/types'
  18. import type {} from '@deepseek-ai/dsh-session-title'
  19. import {
  20. assertFixtureInventory,
  21. captureStableAria,
  22. compareOrRefreshGolden,
  23. launchWebScaffold,
  24. seedSession,
  25. watchConsole,
  26. webSnapshotMode,
  27. type WebScaffold,
  28. } from './scaffold.ts'
  29. import { connectFreshWorkspace, newEnglishPage, saveFailureShot, writeComposerDraft } from './support.ts'
  30. const SNAPSHOT_DIR = fileURLToPath(new URL('./expected/reference-composer', import.meta.url))
  31. const MENU_EXPECTED = join(SNAPSHOT_DIR, 'menu.expected.md')
  32. const ORDER_EXPECTED = join(SNAPSHOT_DIR, 'order.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.snapshotEvents().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: SessionSeq(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.snapshotEvents().map(event => JSON.stringify(event)),
  107. '',
  108. ].join('\n')
  109. }
  110. describe.skipIf(MODE === 'record')('web e2e: file and session references through the real host', () => {
  111. let scaffold: WebScaffold
  112. let browser: Browser
  113. let page: Page
  114. let tripwire: ReturnType<typeof watchConsole>
  115. beforeAll(async () => {
  116. scaffold = await launchWebScaffold({})
  117. await seedSession(scaffold, sourceSessionFixture(), SOURCE_SESSION_ID)
  118. await seedSession(scaffold, targetSessionFixture(), TARGET_SESSION_ID)
  119. browser = await chromium.launch()
  120. page = await newEnglishPage(browser)
  121. tripwire = watchConsole(page)
  122. // Fixture files land before the workspace connects so the Host's file
  123. // index never races their creation (the connect helper mkdirs the same
  124. // directory and tolerates it existing).
  125. await mkdir(join(scaffold.workspaceCwd, 'workspace'), { recursive: true })
  126. await writeFile(join(scaffold.workspaceCwd, 'workspace', 'reference.txt'), 'reference fixture\n')
  127. await mkdir(join(scaffold.workspaceCwd, 'workspace', 'folderx'), { recursive: true })
  128. await writeFile(join(scaffold.workspaceCwd, 'workspace', 'folderx', 'child.txt'), 'child fixture\n')
  129. // Two levels down: the breadcrumb needs a step above the current one to
  130. // return to, and a bare '@' lists only the top level, so the deeper tree
  131. // stays out of the menu golden.
  132. await mkdir(join(scaffold.workspaceCwd, 'workspace', 'folderx', 'nested'), { recursive: true })
  133. await writeFile(join(scaffold.workspaceCwd, 'workspace', 'folderx', 'nested', 'leaf.txt'), 'leaf fixture\n')
  134. await page.goto(scaffold.authenticatedUrl, { waitUntil: 'load' })
  135. await page.waitForSelector('[class*="frame"]', { timeout: 30_000 })
  136. await connectFreshWorkspace(page, scaffold.workspaceCwd)
  137. }, 120_000)
  138. afterAll(async () => {
  139. await browser?.close()
  140. await scaffold?.close()
  141. })
  142. it('groups both sources and projects files and sessions as structured inline icon labels', async () => {
  143. onTestFailed(() => saveFailureShot(page, 'web-e2e-reference-composer'))
  144. const input = page.locator('[data-composer-input]').first()
  145. const menu = page.getByRole('listbox', { name: 'Trigger suggestions' })
  146. await input.fill('@')
  147. await expect.poll(() => menu.getByRole('option').count(), { timeout: 15_000 }).toBeGreaterThanOrEqual(2)
  148. // Session rows are dated from the live Host list, so their age bucket
  149. // advances while the suite runs.
  150. const snapshot = await captureStableAria(
  151. page, '[role="listbox"]', scaffold.workspaceCwd, { normalizeAge: true },
  152. )
  153. await compareOrRefreshGolden(MENU_EXPECTED, snapshot, MODE)
  154. expect(snapshot).toContain('Files & folders')
  155. expect(snapshot).toContain('Sessions')
  156. expect(snapshot).not.toContain('text: reference Files & folders')
  157. expect(snapshot).toContain('reference.txt')
  158. // A seed reaches disk as a log alone, and the Host labels a session from
  159. // its projections: no checkpoint, so the row is its id. The fixture's own
  160. // title (`Research notes`) is unreachable here by construction, and the
  161. // package suite owns the titled paths.
  162. expect(snapshot).toContain(SOURCE_SESSION_ID)
  163. expect(snapshot).not.toContain('Research notes')
  164. expect(snapshot).not.toContain('text: Subagents')
  165. await input.fill('@reference')
  166. // The open menu keeps the previous query's rows while the new one loads
  167. // (stale-while-revalidate), and rows are keyed by index, so a click
  168. // resolved against a stale row lands on whatever settles into that slot.
  169. // `folderx/` matches only the bare '@' query: its disappearance marks the
  170. // settled result set.
  171. await expect.poll(() => menu.getByRole('option', { name: /folderx/ }).count(), { timeout: 15_000 }).toBe(0)
  172. await menu.getByRole('option', { name: /reference\.txt/ }).click()
  173. // The pick lands an atomic chip: a real DOM capsule carrying the domain
  174. // icon and the label (the canonical reference text lives on the node and
  175. // expands on submit; the surface text is the label plus the separator).
  176. const fileReference = page.locator('[data-composer-chip]').last()
  177. await expect.poll(() => fileReference.textContent()).toBe('reference.txt')
  178. await expect.poll(() => fileReference.locator('svg').count()).toBe(1)
  179. await expect.poll(() => input.textContent()).toBe('reference.txt ')
  180. await input.fill('@reference-source')
  181. await menu.getByRole('option', { name: new RegExp(SOURCE_SESSION_ID) }).click()
  182. const sessionReference = page.locator('[data-composer-chip]').last()
  183. await expect.poll(() => sessionReference.textContent()).toBe(SOURCE_SESSION_ID)
  184. await expect.poll(() => sessionReference.locator('svg').count()).toBe(1)
  185. await expect.poll(() => input.textContent()).toBe(`${SOURCE_SESSION_ID} `)
  186. expect(tripwire.pageErrors).toEqual([])
  187. expect(tripwire.warnings).toEqual([])
  188. })
  189. it('typing a trigger directly ahead of a chip inserts without disturbing it', async () => {
  190. onTestFailed(() => saveFailureShot(page, 'web-e2e-reference-type-ahead'))
  191. const input = page.locator('[data-composer-input]').first()
  192. const menu = page.getByRole('listbox', { name: 'Trigger suggestions' })
  193. await input.fill('@reference')
  194. await menu.getByRole('option', { name: /reference\.txt/ }).click()
  195. await expect.poll(() => input.locator('[data-composer-chip]').count()).toBe(1)
  196. // The #2813 gesture: collapse the caret to the document start, directly
  197. // ahead of the chip, and open the trigger menu there.
  198. await input.click()
  199. await page.keyboard.press('ControlOrMeta+A')
  200. await page.keyboard.press('ArrowLeft')
  201. await page.keyboard.type('@reference-source')
  202. await menu.getByRole('option', { name: new RegExp(SOURCE_SESSION_ID) }).click()
  203. // Both chips survive the boundary insert: the session chip lands ahead of
  204. // the intact file chip.
  205. const chips = input.locator('[data-composer-chip]')
  206. await expect.poll(() => chips.count()).toBe(2)
  207. await expect.poll(() => chips.first().textContent()).toBe(SOURCE_SESSION_ID)
  208. await expect.poll(() => chips.last().textContent()).toBe('reference.txt')
  209. await expect.poll(() => input.textContent()).toBe(`${SOURCE_SESSION_ID} reference.txt `)
  210. expect(tripwire.pageErrors).toEqual([])
  211. expect(tripwire.warnings).toEqual([])
  212. })
  213. it('arrows step across a chip in one move and Backspace removes it whole', async () => {
  214. onTestFailed(() => saveFailureShot(page, 'web-e2e-reference-keyboard'))
  215. const input = page.locator('[data-composer-input]').first()
  216. const menu = page.getByRole('listbox', { name: 'Trigger suggestions' })
  217. await input.fill('@reference')
  218. await menu.getByRole('option', { name: /reference\.txt/ }).click()
  219. await expect.poll(() => input.locator('[data-composer-chip]').count()).toBe(1)
  220. // First ArrowLeft crosses the trailing space; the second steps across the
  221. // chip in one move — no keyboard-selected intermediate state — and typing
  222. // continues normally on the far side.
  223. await page.keyboard.press('ArrowLeft')
  224. await page.keyboard.press('ArrowLeft')
  225. await page.keyboard.type('pre')
  226. await expect.poll(() => input.textContent()).toBe('prereference.txt ')
  227. await expect.poll(() => input.locator('[data-composer-chip]').count()).toBe(1)
  228. // A collapsed Backspace directly ahead of the chip removes the typed
  229. // character only; the chip's identity is untouched (#2814's gesture).
  230. await page.keyboard.press('Backspace')
  231. await expect.poll(() => input.textContent()).toBe('prreference.txt ')
  232. await expect.poll(() => input.locator('[data-composer-chip]').count()).toBe(1)
  233. // ArrowRight steps back across the chip; Backspace directly behind it
  234. // removes the whole chip in one keystroke.
  235. await page.keyboard.press('ArrowRight')
  236. await page.keyboard.press('Backspace')
  237. await expect.poll(() => input.locator('[data-composer-chip]').count()).toBe(0)
  238. await expect.poll(() => input.textContent()).toBe('pr ')
  239. expect(tripwire.pageErrors).toEqual([])
  240. expect(tripwire.warnings).toEqual([])
  241. })
  242. it('settles a folder as an atomic chip; Tab and the chevron drill instead', async () => {
  243. onTestFailed(() => saveFailureShot(page, 'web-e2e-reference-folder'))
  244. const input = page.locator('[data-composer-input]').first()
  245. const menu = page.getByRole('listbox', { name: 'Trigger suggestions' })
  246. // Settle: Enter on the highlighted folder row resolves the folder itself
  247. // as an atomic chip — folder glyph, no trigger character, one unit.
  248. await writeComposerDraft(page, input, '@folderx')
  249. // First folder query on this page: allow the Host index a cold start.
  250. await menu.getByRole('option', { name: /^folderx\// }).waitFor({ timeout: 60_000 })
  251. await page.keyboard.press('Enter')
  252. const chip = input.locator('[data-composer-chip]').last()
  253. await expect.poll(() => chip.textContent()).toBe('folderx/')
  254. await expect.poll(() => chip.locator('svg').count()).toBe(1)
  255. await expect.poll(() => input.textContent()).toBe('folderx/ ')
  256. // Tab drills: the literal descent text stays editable and the open menu
  257. // lists the folder's children.
  258. await writeComposerDraft(page, input, '@folderx')
  259. await menu.getByRole('option', { name: /^folderx\// }).waitFor()
  260. await page.keyboard.press('Tab')
  261. await expect.poll(() => input.textContent()).toBe('@folderx/')
  262. await menu.getByRole('option', { name: /child\.txt/ }).waitFor()
  263. // The row chevron drills the same way by pointer, header included: a
  264. // pointer descent reaches the same listing a Tab descent does.
  265. await writeComposerDraft(page, input, '@folderx')
  266. const row = menu.getByRole('option', { name: /^folderx\// })
  267. await row.waitFor()
  268. await row.getByRole('button', { name: 'Browse folder' }).click()
  269. await expect.poll(() => input.textContent()).toBe('@folderx/')
  270. await menu.getByRole('option', { name: /child\.txt/ }).waitFor()
  271. await expect.poll(() => page.getByRole('navigation', { name: 'Folder navigation' })
  272. .getByRole('button').allTextContents()).toEqual(['Workspace', 'folderx'])
  273. // The listing knows it was drilled into, so its rows drop the location the
  274. // header already carries.
  275. await expect.poll(() => menu.getByRole('option', { name: /child\.txt/ }).textContent())
  276. .toBe('child.txt')
  277. await page.keyboard.press('Escape')
  278. expect(tripwire.pageErrors).toEqual([])
  279. expect(tripwire.warnings).toEqual([])
  280. })
  281. it('a drilled listing carries a breadcrumb back to the workspace root', async () => {
  282. onTestFailed(() => saveFailureShot(page, 'web-e2e-reference-breadcrumb'))
  283. const input = page.locator('[data-composer-input]').first()
  284. const menu = page.getByRole('listbox', { name: 'Trigger suggestions' })
  285. const crumbs = page.getByRole('navigation', { name: 'Folder navigation' })
  286. // A path the user typed carries its own context: no header.
  287. await writeComposerDraft(page, input, '@folderx/')
  288. await menu.getByRole('option', { name: /child\.txt/ }).waitFor({ timeout: 60_000 })
  289. await expect.poll(() => crumbs.count()).toBe(0)
  290. // The same listing reached by drilling owes the user the way back.
  291. await writeComposerDraft(page, input, '@folderx')
  292. await menu.getByRole('option', { name: /^folderx\// }).waitFor()
  293. await page.keyboard.press('Tab')
  294. await menu.getByRole('option', { name: /child\.txt/ }).waitFor()
  295. await crumbs.waitFor()
  296. await expect.poll(() => crumbs.getByRole('button').allTextContents())
  297. .toEqual(['Workspace', 'folderx'])
  298. // The listed folder is where the menu already is: its crumb is inert, and
  299. // the rows drop the location the header now carries.
  300. await expect.poll(() => crumbs.getByRole('button', { name: 'folderx' }).isDisabled()).toBe(true)
  301. await expect.poll(() => menu.getByRole('option', { name: /child\.txt/ }).textContent())
  302. .toBe('child.txt')
  303. // A crumb above the current step re-lists that directory and keeps the
  304. // header, which now names the step it returned to.
  305. await writeComposerDraft(page, input, '@folderx/nested')
  306. const nested = menu.getByRole('option', { name: /^nested\// })
  307. await nested.waitFor()
  308. await nested.getByRole('button', { name: 'Browse folder' }).click()
  309. await expect.poll(() => input.textContent()).toBe('@folderx/nested/')
  310. await expect.poll(() => crumbs.getByRole('button').allTextContents())
  311. .toEqual(['Workspace', 'folderx', 'nested'])
  312. await crumbs.getByRole('button', { name: 'folderx' }).click()
  313. await expect.poll(() => input.textContent()).toBe('@folderx/')
  314. await expect.poll(() => crumbs.getByRole('button').allTextContents())
  315. .toEqual(['Workspace', 'folderx'])
  316. // Clicking the root crumb rewrites the token back to a bare trigger.
  317. await crumbs.getByRole('button', { name: 'Workspace' }).click()
  318. await expect.poll(() => input.textContent()).toBe('@')
  319. await expect.poll(() => crumbs.count()).toBe(0)
  320. await menu.getByRole('option', { name: /^folderx\// }).waitFor()
  321. await page.keyboard.press('Escape')
  322. expect(tripwire.pageErrors).toEqual([])
  323. expect(tripwire.warnings).toEqual([])
  324. })
  325. it('renders the durable direct-message then recall order', async () => {
  326. onTestFailed(() => saveFailureShot(page, 'web-e2e-reference-order'))
  327. const group = page.getByRole('treeitem', { name: /Ungrouped/ })
  328. await group.waitFor({ timeout: 15_000 })
  329. if (await group.getAttribute('aria-expanded') !== 'true') await group.click()
  330. const target = page.getByRole('treeitem', { name: /Reference order target/ })
  331. await target.waitFor({ timeout: 15_000 })
  332. await target.click()
  333. await page.getByRole('button', { name: /^Session recall\s*Research notes$/ }).waitFor({ timeout: 15_000 })
  334. const snapshot = (await captureStableAria(page, '[class*="centerCol"]', scaffold.workspaceCwd))
  335. .split(TARGET_SESSION_ID).join('{{targetId}}')
  336. await compareOrRefreshGolden(ORDER_EXPECTED, snapshot, MODE)
  337. expect(snapshot.indexOf('Research notes what changed?')).toBeLessThan(snapshot.indexOf('Session recall Research notes'))
  338. expect(tripwire.pageErrors).toEqual([])
  339. expect(tripwire.warnings).toEqual([])
  340. await assertFixtureInventory(SNAPSHOT_DIR, ['menu.expected.md', 'order.expected.md'])
  341. })
  342. })