agent-preset-selection.e2e.ts 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303
  1. // Web e2e scenario: agent-preset selection. Every lane mounts the plugin's
  2. // own shipped presets; this is the lane that puts them in front of a browser.
  3. //
  4. // Two surfaces, one host rule: a session's composition is fixed when the
  5. // session starts. Before that, the new-session chip stages the choice beside
  6. // the workspace picker — the only screen where it still works. After it, the
  7. // session header names what the session runs and offers no control at all,
  8. // because the host answers `agent-preset-locked` to anything else.
  9. //
  10. // Zero model calls: no replay fixture mounts, so a stray stream fails loud.
  11. import { fileURLToPath } from 'node:url'
  12. import { mkdir, writeFile } from 'node:fs/promises'
  13. import { join } from 'node:path'
  14. import type { Browser, Page } from 'playwright'
  15. import { chromium } from 'playwright'
  16. import { afterAll, beforeAll, describe, expect, it, onTestFailed } from 'vitest'
  17. import {
  18. SESSION_FORMAT_VERSION, SessionId as sessionId, type SessionEvent, type SessionId,
  19. } from '@deepseek-ai/dsh-session'
  20. import { snapshotSubagentDescriptor } from '@deepseek-ai/dsh-subagent'
  21. import {
  22. captureStableAria, compareOrRefreshGolden, launchWebScaffold, seedSession, watchConsole,
  23. webSnapshotMode, type WebScaffold,
  24. } from './scaffold.ts'
  25. import { connectFreshWorkspace, newEnglishPage, saveFailureShot } from './support.ts'
  26. const SNAPSHOT_DIR = fileURLToPath(new URL('./expected/agent-preset-selection', import.meta.url))
  27. const HERO_EXPECTED = join(SNAPSHOT_DIR, 'hero.expected.md')
  28. const MENU_EXPECTED = join(SNAPSHOT_DIR, 'menu.expected.md')
  29. const HEADER_EXPECTED = join(SNAPSHOT_DIR, 'header.expected.md')
  30. const MODE = webSnapshotMode()
  31. const SEED_ID = 'agent-preset-selection-web-e2e'
  32. /** A project skill only a preset that mounts `skill-filesystem` can discover. */
  33. const SKILL_NAME = 'preset-catalog-demo'
  34. /**
  35. * Seed one project skill under the connected workspace.
  36. *
  37. * Local skill discovery is a PRESET row, so this file is visible through
  38. * `standard` and invisible through `minimal` — which makes the '/' menu's
  39. * skill group a statement about the session's composition.
  40. * @param workspaceCwd - the scaffold's temp project parent.
  41. */
  42. async function seedWorkspaceSkill(workspaceCwd: string): Promise<void> {
  43. const directory = join(workspaceCwd, 'workspace', '.agents', 'skills', SKILL_NAME)
  44. await mkdir(directory, { recursive: true })
  45. await writeFile(join(directory, 'SKILL.md'), [
  46. '---',
  47. `name: ${SKILL_NAME}`,
  48. 'description: Prove the slash catalog follows the session composition',
  49. '---',
  50. '',
  51. 'Body.',
  52. '',
  53. ].join('\n'))
  54. }
  55. /**
  56. * A settled one-turn session with no model content: this lane asserts chrome
  57. * around a conversation, not a conversation, and a recorded turn would tie
  58. * the golden to a provider's wording for no gain.
  59. * @returns a tokenized session log ending on a closed turn.
  60. */
  61. function seedLog(): string {
  62. const time = 1784974100000
  63. const at = (index: number, event: Record<string, unknown>): string =>
  64. JSON.stringify({ ...event, seq: index, time: time + index })
  65. return [
  66. JSON.stringify({ type: 'session', version: 0, id: '{{sessionId}}', createdAt: time, cwd: '{{cwd}}/workspace' }),
  67. at(0, { type: 'turn/start', data: { turn: 1, trigger: { kind: 'message', source: { kind: 'user', rpcId: 'seed' } } } }),
  68. at(1, {
  69. type: 'user/message',
  70. data: { content: [{ type: 'text', text: 'Seeded turn.' }], source: { kind: 'user', rpcId: 'seed' } },
  71. surfaceOp: 'append',
  72. }),
  73. at(2, { type: 'session/title', data: { title: 'Seeded turn', messageSeqs: [1], source: { kind: 'fallback' } } }),
  74. at(3, { type: 'turn/end', data: { turn: 1, reason: { kind: 'completed' } } }),
  75. ].join('\n')
  76. }
  77. /**
  78. * Persist one child so the assembled header snapshot exercises both action
  79. * contributors whose relative order is the product contract under test.
  80. * @param scaffold - the booted Web scaffold.
  81. * @param parentId - the seeded session whose header the browser opens.
  82. */
  83. async function seedSubagent(scaffold: WebScaffold, parentId: SessionId): Promise<void> {
  84. const childId = sessionId('agent-preset-selection-child')
  85. const createdAt = 1784974100100
  86. await scaffold.ctx.sessionPersistence.create({
  87. version: SESSION_FORMAT_VERSION,
  88. id: childId,
  89. createdAt,
  90. cwd: scaffold.workspaceCwd,
  91. parentSession: parentId,
  92. origin: 'subagent',
  93. delegationDepth: 1,
  94. agentPreset: 'minimal',
  95. })
  96. await scaffold.ctx.sessionPersistence.append(childId, [
  97. {
  98. type: 'turn/start',
  99. seq: 0,
  100. time: createdAt,
  101. data: { turn: 1, trigger: { kind: 'message', source: { kind: 'user' } } },
  102. },
  103. {
  104. type: 'user/message',
  105. seq: 1,
  106. time: createdAt + 1,
  107. data: {
  108. content: [{ type: 'text', text: 'Check the session-header action order.' }],
  109. source: { kind: 'user' },
  110. },
  111. surfaceOp: 'append',
  112. },
  113. {
  114. type: 'subagent/descriptor',
  115. seq: 2,
  116. time: createdAt + 2,
  117. data: snapshotSubagentDescriptor({
  118. mode: 'one-shot', provider: 'spawn', label: 'header order probe',
  119. }),
  120. },
  121. {
  122. type: 'turn/end',
  123. seq: 3,
  124. time: createdAt + 3,
  125. data: { turn: 1, reason: { kind: 'completed' } },
  126. },
  127. ] as SessionEvent[])
  128. await scaffold.ctx.sessionProjectionCache.coldSnapshot(childId)
  129. }
  130. /**
  131. * The preset the host reports for the blank session the workspace connect
  132. * produced. Addressed by id rather than by scanning the serialized list: the
  133. * seeded session records `minimal` too, so a substring match over the whole
  134. * list answers before the switch has landed.
  135. * @param baseUrl - the scaffold's origin.
  136. * @returns the live session's preset, or undefined before it is listed.
  137. */
  138. async function livePreset(baseUrl: string): Promise<string | undefined> {
  139. const response = await fetch(`${baseUrl}/api/session/list`, {
  140. method: 'POST',
  141. headers: { 'content-type': 'application/json' },
  142. body: JSON.stringify({
  143. type: 'client-request', rpcId: 'agent-preset-live', method: 'session/list',
  144. payload: { args: { _request: {} } },
  145. }),
  146. })
  147. const body = await response.json() as {
  148. result: {
  149. value?: {
  150. items: {
  151. sessionId: string
  152. projections?: { values: { agentPreset?: string | null } }
  153. }[]
  154. }
  155. }
  156. }
  157. const preset = body.result.value?.items.find(item => item.sessionId !== SEED_ID)
  158. ?.projections?.values.agentPreset
  159. return typeof preset === 'string' ? preset : undefined
  160. }
  161. /** Every option label the trigger menu currently lists. */
  162. async function menuOptions(page: Page): Promise<string[]> {
  163. const menu = page.getByRole('listbox', { name: 'Trigger suggestions' })
  164. await menu.waitFor({ timeout: 10_000 })
  165. return await menu.getByRole('option').allTextContents()
  166. }
  167. describe('web e2e: agent-preset selection', () => {
  168. let scaffold: WebScaffold
  169. let browser: Browser
  170. let page: Page
  171. let tripwire: ReturnType<typeof watchConsole>
  172. beforeAll(async () => {
  173. // The scaffold's default roster pin is exactly this scenario's shape: the
  174. // plugin's shipped presets, default `standard`.
  175. scaffold = await launchWebScaffold({})
  176. // A resumed session runs what it was created with; seeding one that
  177. // records `minimal` is what makes the header label a claim about the
  178. // session rather than an echo of the current default.
  179. const seededId = await seedSession(scaffold, seedLog(), SEED_ID, 'minimal')
  180. await seedSubagent(scaffold, seededId)
  181. await seedWorkspaceSkill(scaffold.workspaceCwd)
  182. browser = await chromium.launch()
  183. page = await newEnglishPage(browser)
  184. tripwire = watchConsole(page)
  185. await page.goto(scaffold.baseUrl, { waitUntil: 'load' })
  186. await page.waitForSelector('[class*="frame"]', { timeout: 30_000 })
  187. }, 120_000)
  188. afterAll(async () => {
  189. await browser?.close()
  190. await scaffold?.close()
  191. })
  192. it('offers the chip on the new-session screen, beside the workspace picker', async () => {
  193. onTestFailed(() => saveFailureShot(page, 'web-e2e-agent-preset-hero'))
  194. await connectFreshWorkspace(page, scaffold.workspaceCwd)
  195. const snapshot = await captureStableAria(page, '[class*="heroWorkspaceRow"]', scaffold.workspaceCwd)
  196. await compareOrRefreshGolden(HERO_EXPECTED, snapshot, MODE)
  197. // The chip opens on the deployment default, by the name that preset
  198. // publishes rather than its directory name.
  199. expect(snapshot).toContain('Standard mode')
  200. })
  201. it('names every preset and what it is for', async () => {
  202. onTestFailed(() => saveFailureShot(page, 'web-e2e-agent-preset-menu'))
  203. await page.getByRole('button', { name: 'Standard mode' }).click()
  204. const menu = page.getByRole('menu')
  205. await menu.waitFor({ timeout: 10_000 })
  206. const snapshot = await captureStableAria(page, '[role="menu"]', scaffold.workspaceCwd)
  207. await compareOrRefreshGolden(MENU_EXPECTED, snapshot, MODE)
  208. // Every shipped preset, each with the sentence saying what it composes —
  209. // the id alone never said what a preset does.
  210. expect(snapshot).toContain('Minimal mode')
  211. expect(snapshot).toContain('Creator mode')
  212. await page.keyboard.press('Escape')
  213. })
  214. it('applies the staged pick to the blank session, and the host honors it', async () => {
  215. onTestFailed(() => saveFailureShot(page, 'web-e2e-agent-preset-stage'))
  216. await page.getByRole('button', { name: 'Standard mode' }).click()
  217. await page.getByRole('menuitem', { name: /Minimal mode/ }).click()
  218. // The chip stages; the blank session the workspace connect produced is
  219. // what the stage lands on. The host's own answer is what comes back.
  220. await expect.poll(() => livePreset(scaffold.baseUrl), { timeout: 15_000 }).toBe('minimal')
  221. })
  222. it('re-reads the slash catalog through the composition the switch installed', async () => {
  223. // Continues the previous case: the chip has already applied `minimal` to
  224. // the blank session, and this one reads the menu that switch left behind.
  225. onTestFailed(() => saveFailureShot(page, 'web-e2e-agent-preset-slash-catalog'))
  226. const composer = page.locator('textarea:enabled').last()
  227. // `minimal` mounts neither the compaction group nor plan mode nor local
  228. // skill discovery, so the catalog the composer warmed under the
  229. // deployment default must not survive the switch.
  230. await composer.fill('/')
  231. await expect.poll(() => menuOptions(page), { timeout: 15_000 })
  232. .not.toEqual(expect.arrayContaining([expect.stringContaining(SKILL_NAME)]))
  233. const onMinimal = await menuOptions(page)
  234. expect(onMinimal.some(option => option.startsWith('compact'))).toBe(false)
  235. expect(onMinimal.some(option => option.startsWith('plan'))).toBe(false)
  236. // Preset-scoped commands follow the switch; the client's own model command
  237. // remains outside every preset.
  238. expect(onMinimal.some(option => option.startsWith('goal'))).toBe(false)
  239. expect(onMinimal.some(option => option.startsWith('model'))).toBe(true)
  240. await composer.fill('')
  241. // Switching back up reaches the host at all — the chip compares the pick
  242. // against its list row, so a row that never reprojected the first switch
  243. // answers "already standard" and sends nothing — and restores the catalog
  244. // instead of leaving the session reading the narrower composition.
  245. await page.getByRole('button', { name: 'Minimal mode' }).click()
  246. await page.getByRole('menuitem', { name: /^Standard mode/ }).first().click()
  247. await expect.poll(() => livePreset(scaffold.baseUrl), { timeout: 15_000 }).toBe('standard')
  248. await composer.fill('/')
  249. await expect.poll(() => menuOptions(page), { timeout: 15_000 })
  250. .toEqual(expect.arrayContaining([expect.stringContaining(SKILL_NAME)]))
  251. const onStandard = await menuOptions(page)
  252. expect(onStandard.some(option => option.startsWith('compact'))).toBe(true)
  253. expect(onStandard.some(option => option.startsWith('goal'))).toBe(true)
  254. expect(onStandard.some(option => option.startsWith('plan'))).toBe(true)
  255. await composer.fill('')
  256. }, 90_000)
  257. it('labels a resumed session with the preset it was created under', async () => {
  258. onTestFailed(() => saveFailureShot(page, 'web-e2e-agent-preset-header'))
  259. // The seeded session's cwd is the scaffold root rather than the connected
  260. // workspace, so it lists under Ungrouped; the group collapses by default.
  261. await page.getByRole('treeitem', { name: /^Ungrouped/ }).click()
  262. await page.locator('[role="treeitem"]').last().click()
  263. await page.getByText('Seeded turn.').waitFor({ timeout: 15_000 })
  264. const snapshot = await captureStableAria(page, '[class*="titleRow"]', scaffold.workspaceCwd)
  265. await compareOrRefreshGolden(HEADER_EXPECTED, snapshot, MODE)
  266. expect(snapshot).toContain('Minimal mode')
  267. expect(snapshot).toContain('button "1 subagent"')
  268. expect(snapshot.indexOf('button "1 subagent"')).toBeLessThan(snapshot.indexOf('Minimal mode'))
  269. expect(snapshot.indexOf('Minimal mode')).toBeLessThan(snapshot.indexOf('button "Session log"'))
  270. // Static chrome, not a control: the header can only report a composition
  271. // the host would refuse to change.
  272. expect(snapshot).not.toContain('button "Minimal mode"')
  273. })
  274. it('drove every surface without a page error or a stream warning', () => {
  275. expect(tripwire.pageErrors).toEqual([])
  276. expect(tripwire.warnings).toEqual([])
  277. })
  278. })