reference-composer.e2e.ts 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415
  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 { homedir } from 'node:os'
  7. import { join } from 'node:path'
  8. import type { Browser, Locator, Page } from 'playwright'
  9. import { chromium } from 'playwright'
  10. import { afterAll, beforeAll, describe, expect, it, onTestFailed } from 'vitest'
  11. import { createUserMessage } from '@deepseek-ai/dsh-llm'
  12. import { abbreviateHomePath } from '@deepseek-ai/dsh-util-workspace-path'
  13. import {
  14. SESSION_FORMAT_VERSION,
  15. Session,
  16. SessionId,
  17. SessionSeq,
  18. } from '@deepseek-ai/dsh-session'
  19. import type {} from '@deepseek-ai/dsh-session-reference/types'
  20. import type {} from '@deepseek-ai/dsh-session-title'
  21. import {
  22. assertFixtureInventory,
  23. captureStableAria,
  24. compareOrRefreshGolden,
  25. launchWebScaffold,
  26. seedSession,
  27. watchConsole,
  28. webSnapshotMode,
  29. type WebScaffold,
  30. } from './scaffold.ts'
  31. import { connectFreshWorkspace, newEnglishPage, saveFailureShot, writeComposerDraft } from './support.ts'
  32. const SNAPSHOT_DIR = fileURLToPath(new URL('./expected/reference-composer', import.meta.url))
  33. const MENU_EXPECTED = join(SNAPSHOT_DIR, 'menu.expected.md')
  34. const ORDER_EXPECTED = join(SNAPSHOT_DIR, 'order.expected.md')
  35. const MODE = webSnapshotMode()
  36. const SOURCE_SESSION_ID = 'reference-source-session'
  37. const TARGET_SESSION_ID = 'reference-order-target-session'
  38. async function settledSourceOption(menu: Locator): Promise<Locator> {
  39. await expect.poll(
  40. () => menu.getByRole('option', { name: new RegExp(TARGET_SESSION_ID) }).count(),
  41. { timeout: 15_000 },
  42. ).toBe(0)
  43. const source = menu.getByRole('option', { name: new RegExp(SOURCE_SESSION_ID) })
  44. await expect.poll(() => source.count(), { timeout: 15_000 }).toBe(1)
  45. return source
  46. }
  47. // Clear retained suggestions and insert one complete query so an intermediate
  48. // prefix cannot satisfy the caller's wait for a ready result row.
  49. async function replaceReferenceQuery(page: Page, input: Locator, text: string): Promise<void> {
  50. await writeComposerDraft(page, input, '')
  51. await page.getByRole('listbox', { name: 'Trigger suggestions' }).waitFor({ state: 'hidden' })
  52. await input.click()
  53. await page.keyboard.insertText(text)
  54. }
  55. /** Build one closed source session with a stable title for reference discovery. */
  56. function sourceSessionFixture(): string {
  57. const session = Session.create(SessionId(SOURCE_SESSION_ID))
  58. session.append('turn/start', {
  59. turn: 1,
  60. })
  61. const user = session.append('user/message', createUserMessage({
  62. content: [{ type: 'text', text: 'Research context for the reference menu.' }],
  63. source: { kind: 'user' },
  64. }), { surfaceOp: 'append' })
  65. session.append('session/title', {
  66. title: 'Research notes',
  67. messageSeqs: [user.seq],
  68. source: { kind: 'fallback' },
  69. })
  70. session.append('turn/end', { turn: 1, reason: { kind: 'completed' } })
  71. return [
  72. JSON.stringify({
  73. type: 'session',
  74. version: SESSION_FORMAT_VERSION,
  75. id: '{{sessionId}}',
  76. createdAt: 0,
  77. cwd: '{{cwd}}',
  78. isSeeded: false,
  79. delegationDepth: 0,
  80. }),
  81. ...session.snapshotEvents().map(event => JSON.stringify(event)),
  82. '',
  83. ].join('\n')
  84. }
  85. /** Build one target log with the direct message durably before its recalled context. */
  86. function targetSessionFixture(): string {
  87. const session = Session.create(SessionId(TARGET_SESSION_ID))
  88. session.append('turn/start', { turn: 1 })
  89. const user = session.append('user/message', createUserMessage({
  90. content: [{ type: 'text', text: '@Research notes what changed?' }],
  91. source: { kind: 'user' },
  92. }), { surfaceOp: 'append' })
  93. session.append('user/message', createUserMessage({
  94. content: [{ type: 'text', text: '## Referenced sessions\n\n<referenced-sessions>snapshot</referenced-sessions>' }],
  95. source: {
  96. kind: 'session-reference',
  97. form: 'recall',
  98. version: 1,
  99. references: [{
  100. sessionId: SOURCE_SESSION_ID,
  101. label: 'Research notes',
  102. capturedThroughSeq: SessionSeq(4),
  103. compacted: false,
  104. originalMessages: 2,
  105. retainedMessages: 2,
  106. omittedMessages: 0,
  107. omittedBytes: 0,
  108. truncated: false,
  109. inputIndex: 0,
  110. }],
  111. },
  112. }), { surfaceOp: 'append' })
  113. session.append('session/title', {
  114. title: 'Reference order target',
  115. messageSeqs: [user.seq],
  116. source: { kind: 'fallback' },
  117. })
  118. session.append('turn/end', { turn: 1, reason: { kind: 'completed' } })
  119. return [
  120. JSON.stringify({
  121. type: 'session',
  122. version: SESSION_FORMAT_VERSION,
  123. id: '{{sessionId}}',
  124. createdAt: 0,
  125. cwd: '{{cwd}}',
  126. isSeeded: false,
  127. delegationDepth: 0,
  128. }),
  129. ...session.snapshotEvents().map(event => JSON.stringify(event)),
  130. '',
  131. ].join('\n')
  132. }
  133. describe.skipIf(MODE === 'record')('web e2e: file and session references through the real host', () => {
  134. let scaffold: WebScaffold
  135. let browser: Browser
  136. let page: Page
  137. let tripwire: ReturnType<typeof watchConsole>
  138. beforeAll(async () => {
  139. scaffold = await launchWebScaffold({})
  140. const targetCreatedAt = Date.now() - 60_000
  141. await seedSession(scaffold, sourceSessionFixture(), SOURCE_SESSION_ID, undefined, { createdAt: targetCreatedAt - 1 })
  142. await seedSession(scaffold, targetSessionFixture(), TARGET_SESSION_ID, undefined, { createdAt: targetCreatedAt })
  143. browser = await chromium.launch()
  144. page = await newEnglishPage(browser)
  145. tripwire = watchConsole(page)
  146. // Fixture files land before the workspace connects so the Host's file
  147. // index never races their creation (the connect helper mkdirs the same
  148. // directory and tolerates it existing).
  149. await mkdir(join(scaffold.workspaceCwd, 'workspace'), { recursive: true })
  150. await writeFile(join(scaffold.workspaceCwd, 'workspace', 'reference.txt'), 'reference fixture\n')
  151. await mkdir(join(scaffold.workspaceCwd, 'workspace', 'folderx'), { recursive: true })
  152. await writeFile(join(scaffold.workspaceCwd, 'workspace', 'folderx', 'child.txt'), 'child fixture\n')
  153. // Two levels down: the breadcrumb needs a step above the current one to
  154. // return to, and a bare '@' lists only the top level, so the deeper tree
  155. // stays out of the menu golden.
  156. await mkdir(join(scaffold.workspaceCwd, 'workspace', 'folderx', 'nested'), { recursive: true })
  157. await writeFile(join(scaffold.workspaceCwd, 'workspace', 'folderx', 'nested', 'leaf.txt'), 'leaf fixture\n')
  158. await page.goto(scaffold.authenticatedUrl, { waitUntil: 'load' })
  159. await page.waitForSelector('[class*="frame"]', { timeout: 30_000 })
  160. await connectFreshWorkspace(page, scaffold.workspaceCwd)
  161. }, 120_000)
  162. afterAll(async () => {
  163. await browser?.close()
  164. await scaffold?.close()
  165. })
  166. it('groups both sources and projects files and sessions as structured inline icon labels', async () => {
  167. onTestFailed(() => saveFailureShot(page, 'web-e2e-reference-composer'))
  168. const input = page.locator('[data-composer-input]').first()
  169. const menu = page.getByRole('listbox', { name: 'Trigger suggestions' })
  170. await writeComposerDraft(page, input, '@')
  171. await expect.poll(() => menu.getByRole('option').count(), { timeout: 15_000 }).toBeGreaterThanOrEqual(2)
  172. // Session rows are dated from the live Host list, so their age bucket
  173. // advances while the suite runs.
  174. const snapshot = await captureStableAria(
  175. page, '[role="listbox"]', scaffold.workspaceCwd, {
  176. normalizeAge: true,
  177. replacements: [[abbreviateHomePath(scaffold.workspaceCwd, homedir()), '{{cwd}}']],
  178. },
  179. )
  180. await compareOrRefreshGolden(MENU_EXPECTED, snapshot, MODE)
  181. expect(snapshot).toContain('Files & folders')
  182. expect(snapshot).toContain('Sessions')
  183. expect(snapshot).not.toContain('text: reference Files & folders')
  184. expect(snapshot).toContain('reference.txt')
  185. // A seed reaches disk as a log alone, and the Host labels a session from
  186. // its projections: no checkpoint, so the row is its id. The fixture's own
  187. // title (`Research notes`) is unreachable here by construction, and the
  188. // package suite owns the titled paths.
  189. expect(snapshot).toContain(SOURCE_SESSION_ID)
  190. expect(snapshot).not.toContain('Research notes')
  191. expect(snapshot).not.toContain('text: Subagents')
  192. await writeComposerDraft(page, input, '@reference')
  193. // The open menu keeps the previous query's rows while the new one loads
  194. // (stale-while-revalidate), and rows are keyed by index, so a click
  195. // resolved against a stale row lands on whatever settles into that slot.
  196. // `folderx/` matches only the bare '@' query: its disappearance marks the
  197. // settled result set.
  198. await expect.poll(() => menu.getByRole('option', { name: /folderx/ }).count(), { timeout: 15_000 }).toBe(0)
  199. await menu.getByRole('option', { name: /reference\.txt/ }).click()
  200. // The pick lands an atomic chip: a real DOM capsule carrying the domain
  201. // icon and the label (the canonical reference text lives on the node and
  202. // expands on submit; the surface text is the label plus the separator).
  203. const fileReference = page.locator('[data-composer-chip]').last()
  204. await expect.poll(() => fileReference.textContent()).toBe('reference.txt')
  205. await expect.poll(() => fileReference.locator('svg').count()).toBe(1)
  206. await expect.poll(() => input.textContent()).toBe('reference.txt ')
  207. await writeComposerDraft(page, input, '@reference-source')
  208. await (await settledSourceOption(menu)).click()
  209. const sessionReference = page.locator('[data-composer-chip]').last()
  210. await expect.poll(() => sessionReference.textContent()).toBe(SOURCE_SESSION_ID)
  211. await expect.poll(() => sessionReference.locator('svg').count()).toBe(1)
  212. await expect.poll(() => input.textContent()).toBe(`${SOURCE_SESSION_ID} `)
  213. expect(tripwire.pageErrors).toEqual([])
  214. expect(tripwire.warnings).toEqual([])
  215. })
  216. it('typing a trigger directly ahead of a chip inserts without disturbing it', async () => {
  217. onTestFailed(() => saveFailureShot(page, 'web-e2e-reference-type-ahead'))
  218. const input = page.locator('[data-composer-input]').first()
  219. const menu = page.getByRole('listbox', { name: 'Trigger suggestions' })
  220. await writeComposerDraft(page, input, '@reference.txt')
  221. await expect.poll(() => input.locator('[data-composer-chip]').count()).toBe(0)
  222. await expect.poll(() => menu.getByRole('option').allTextContents()).toEqual(['reference.txt'])
  223. await menu.getByRole('option', { name: 'reference.txt', exact: true }).click()
  224. await expect.poll(() => input.locator('[data-composer-chip]').count()).toBe(1)
  225. // The #2813 gesture: collapse the caret to the document start, directly
  226. // ahead of the chip, and open the trigger menu there.
  227. await input.click()
  228. await page.keyboard.press('ControlOrMeta+A')
  229. await page.keyboard.press('ArrowLeft')
  230. await page.keyboard.type('@reference-source')
  231. await (await settledSourceOption(menu)).click()
  232. // Both chips survive the boundary insert: the session chip lands ahead of
  233. // the intact file chip.
  234. const chips = input.locator('[data-composer-chip]')
  235. await expect.poll(() => chips.count()).toBe(2)
  236. await expect.poll(() => chips.first().textContent()).toBe(SOURCE_SESSION_ID)
  237. await expect.poll(() => chips.last().textContent()).toBe('reference.txt')
  238. await expect.poll(() => input.textContent()).toBe(`${SOURCE_SESSION_ID} reference.txt `)
  239. expect(tripwire.pageErrors).toEqual([])
  240. expect(tripwire.warnings).toEqual([])
  241. })
  242. it('arrows step across a chip in one move and Backspace removes it whole', async () => {
  243. onTestFailed(() => saveFailureShot(page, 'web-e2e-reference-keyboard'))
  244. const input = page.locator('[data-composer-input]').first()
  245. const menu = page.getByRole('listbox', { name: 'Trigger suggestions' })
  246. await writeComposerDraft(page, input, '@reference.txt')
  247. await expect.poll(() => input.locator('[data-composer-chip]').count()).toBe(0)
  248. await expect.poll(() => menu.getByRole('option').allTextContents()).toEqual(['reference.txt'])
  249. await menu.getByRole('option', { name: 'reference.txt', exact: true }).click()
  250. await expect.poll(() => input.locator('[data-composer-chip]').count()).toBe(1)
  251. // First ArrowLeft crosses the trailing space; the second steps across the
  252. // chip in one move — no keyboard-selected intermediate state — and typing
  253. // continues normally on the far side.
  254. await page.keyboard.press('ArrowLeft')
  255. await page.keyboard.press('ArrowLeft')
  256. await page.keyboard.type('pre')
  257. await expect.poll(() => input.textContent()).toBe('prereference.txt ')
  258. await expect.poll(() => input.locator('[data-composer-chip]').count()).toBe(1)
  259. // A collapsed Backspace directly ahead of the chip removes the typed
  260. // character only; the chip's identity is untouched (#2814's gesture).
  261. await page.keyboard.press('Backspace')
  262. await expect.poll(() => input.textContent()).toBe('prreference.txt ')
  263. await expect.poll(() => input.locator('[data-composer-chip]').count()).toBe(1)
  264. // ArrowRight steps back across the chip; Backspace directly behind it
  265. // removes the whole chip in one keystroke.
  266. await page.keyboard.press('ArrowRight')
  267. await page.keyboard.press('Backspace')
  268. await expect.poll(() => input.locator('[data-composer-chip]').count()).toBe(0)
  269. await expect.poll(() => input.textContent()).toBe('pr ')
  270. expect(tripwire.pageErrors).toEqual([])
  271. expect(tripwire.warnings).toEqual([])
  272. })
  273. it('settles a folder as an atomic chip; Tab and the chevron drill instead', async () => {
  274. onTestFailed(() => saveFailureShot(page, 'web-e2e-reference-folder'))
  275. const input = page.locator('[data-composer-input]').first()
  276. const menu = page.getByRole('listbox', { name: 'Trigger suggestions' })
  277. // Settle: Enter on the highlighted folder row resolves the folder itself
  278. // as an atomic chip — folder glyph, no trigger character, one unit.
  279. await replaceReferenceQuery(page, input, '@folderx')
  280. // First folder query on this page: allow the Host index a cold start.
  281. await menu.getByRole('option', { name: /^folderx\// }).waitFor({ timeout: 60_000 })
  282. await page.keyboard.press('Enter')
  283. const chip = input.locator('[data-composer-chip]').last()
  284. await expect.poll(() => chip.textContent()).toBe('folderx/')
  285. await expect.poll(() => chip.locator('svg').count()).toBe(1)
  286. await expect.poll(() => input.textContent()).toBe('folderx/ ')
  287. // Tab drills: the literal descent text stays editable and the open menu
  288. // lists the folder's children.
  289. await replaceReferenceQuery(page, input, '@folderx')
  290. await menu.getByRole('option', { name: /^folderx\// }).waitFor()
  291. await page.keyboard.press('Tab')
  292. await expect.poll(() => input.textContent()).toBe('@folderx/')
  293. await menu.getByRole('option', { name: /child\.txt/ }).waitFor()
  294. // The row chevron drills the same way by pointer, header included: a
  295. // pointer descent reaches the same listing a Tab descent does.
  296. await replaceReferenceQuery(page, input, '@folderx')
  297. const row = menu.getByRole('option', { name: /^folderx\// })
  298. await row.waitFor()
  299. await row.getByRole('button', { name: 'Browse folder' }).click()
  300. await expect.poll(() => input.textContent()).toBe('@folderx/')
  301. await menu.getByRole('option', { name: /child\.txt/ }).waitFor()
  302. await expect.poll(() => page.getByRole('navigation', { name: 'Folder navigation' })
  303. .getByRole('button').allTextContents()).toEqual(['Workspace', 'folderx'])
  304. // The listing knows it was drilled into, so its rows drop the location the
  305. // header already carries.
  306. await expect.poll(() => menu.getByRole('option', { name: /child\.txt/ }).textContent())
  307. .toBe('child.txt')
  308. await page.keyboard.press('Escape')
  309. expect(tripwire.pageErrors).toEqual([])
  310. expect(tripwire.warnings).toEqual([])
  311. })
  312. it('a drilled listing carries a breadcrumb back to the workspace root', async () => {
  313. onTestFailed(() => saveFailureShot(page, 'web-e2e-reference-breadcrumb'))
  314. const input = page.locator('[data-composer-input]').first()
  315. const menu = page.getByRole('listbox', { name: 'Trigger suggestions' })
  316. const crumbs = page.getByRole('navigation', { name: 'Folder navigation' })
  317. // A path the user typed carries its own context: no header.
  318. await replaceReferenceQuery(page, input, '@folderx/')
  319. await menu.getByRole('option', { name: /child\.txt/ }).waitFor({ timeout: 60_000 })
  320. await expect.poll(() => crumbs.count()).toBe(0)
  321. // The same listing reached by drilling owes the user the way back.
  322. await replaceReferenceQuery(page, input, '@folderx')
  323. await menu.getByRole('option', { name: /^folderx\// }).waitFor()
  324. await page.keyboard.press('Tab')
  325. await menu.getByRole('option', { name: /child\.txt/ }).waitFor()
  326. await crumbs.waitFor()
  327. await expect.poll(() => crumbs.getByRole('button').allTextContents())
  328. .toEqual(['Workspace', 'folderx'])
  329. // The listed folder is where the menu already is: its crumb is inert, and
  330. // the rows drop the location the header now carries.
  331. await expect.poll(() => crumbs.getByRole('button', { name: 'folderx' }).isDisabled()).toBe(true)
  332. await expect.poll(() => menu.getByRole('option', { name: /child\.txt/ }).textContent())
  333. .toBe('child.txt')
  334. // A crumb above the current step re-lists that directory and keeps the
  335. // header, which now names the step it returned to.
  336. await replaceReferenceQuery(page, input, '@folderx/nested')
  337. await expect.poll(() => menu.getByRole('option', { name: /child\.txt/ }).count()).toBe(0)
  338. const nested = menu.getByRole('option', { name: /^nested\// })
  339. await nested.waitFor()
  340. await nested.getByRole('button', { name: 'Browse folder' }).click()
  341. await expect.poll(() => input.textContent()).toBe('@folderx/nested/')
  342. await expect.poll(() => crumbs.getByRole('button').allTextContents())
  343. .toEqual(['Workspace', 'folderx', 'nested'])
  344. await crumbs.getByRole('button', { name: 'folderx' }).click()
  345. await expect.poll(() => input.textContent()).toBe('@folderx/')
  346. await expect.poll(() => crumbs.getByRole('button').allTextContents())
  347. .toEqual(['Workspace', 'folderx'])
  348. // Clicking the root crumb rewrites the token back to a bare trigger.
  349. await crumbs.getByRole('button', { name: 'Workspace' }).click()
  350. await expect.poll(() => input.textContent()).toBe('@')
  351. await expect.poll(() => crumbs.count()).toBe(0)
  352. await menu.getByRole('option', { name: /^folderx\// }).waitFor()
  353. await page.keyboard.press('Escape')
  354. expect(tripwire.pageErrors).toEqual([])
  355. expect(tripwire.warnings).toEqual([])
  356. })
  357. it('renders the durable direct-message then recall order', async () => {
  358. onTestFailed(() => saveFailureShot(page, 'web-e2e-reference-order'))
  359. const group = page.getByRole('treeitem', { name: /Ungrouped/ })
  360. await group.waitFor({ timeout: 15_000 })
  361. if (await group.getAttribute('aria-expanded') !== 'true') await group.click()
  362. // Both logs were written behind the running Host and have no cache rows, so
  363. // cold listing uses their shared Workspace fallback. Explicit creation
  364. // times keep the target first without opening either body for a title.
  365. const groupSection = group.locator('xpath=ancestor::*[contains(@class, "groupSection")][1]')
  366. const target = groupSection.locator('[role="treeitem"]').nth(1)
  367. await target.waitFor({ timeout: 15_000 })
  368. await target.click()
  369. await page.getByRole('button', { name: /^Session recall\s*Research notes$/ }).waitFor({ timeout: 15_000 })
  370. const snapshot = (await captureStableAria(page, '[class*="centerCol"]', scaffold.workspaceCwd))
  371. .split(TARGET_SESSION_ID).join('{{targetId}}')
  372. await compareOrRefreshGolden(ORDER_EXPECTED, snapshot, MODE)
  373. expect(snapshot.indexOf('Research notes what changed?')).toBeLessThan(snapshot.indexOf('Session recall Research notes'))
  374. expect(tripwire.pageErrors).toEqual([])
  375. expect(tripwire.warnings).toEqual([])
  376. await assertFixtureInventory(SNAPSHOT_DIR, ['menu.expected.md', 'order.expected.md'])
  377. })
  378. })