reference-composer.e2e.ts 19 KB

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