agent-preset-selection.e2e.ts 13 KB

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