reference-composer.e2e.ts 20 KB

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