reference-composer.e2e.ts 16 KB

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