agent-preset-selection.e2e.ts 16 KB

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