agent-preset-selection.e2e.ts 19 KB

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