subagent-conversation.e2e.ts 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549
  1. import { mkdtemp, readFile, rm, writeFile } from 'node:fs/promises'
  2. import { tmpdir } from 'node:os'
  3. import { fileURLToPath } from 'node:url'
  4. import { join } from 'node:path'
  5. import type { Browser, Page } from 'playwright'
  6. import { chromium } from 'playwright'
  7. import { afterAll, beforeAll, describe, expect, it, onTestFailed } from 'vitest'
  8. import {
  9. SESSION_FORMAT_VERSION, SessionId as sessionId, type SessionEvent, type SessionId,
  10. } from '@deepseek-ai/dsh-session'
  11. import type {} from '@deepseek-ai/dsh-agent'
  12. import { snapshotSubagentDescriptor } from '@deepseek-ai/dsh-subagent'
  13. import {
  14. acknowledgeReloadConnectionLoss, captureStableAria, compareOrRefreshGolden,
  15. launchWebScaffold, watchConsole,
  16. webSnapshotMode, type WebScaffold,
  17. } from './scaffold.ts'
  18. import { connectFreshWorkspace, newEnglishPage, saveFailureShot } from './support.ts'
  19. const BASE_FIXTURE = fileURLToPath(new URL('../../../snapshots/web/live-interactions/session.jsonl', import.meta.url))
  20. const AVAILABLE_CHILD_EXPECTED = fileURLToPath(new URL('../../../snapshots/web/subagent-conversation/ui.expected.md', import.meta.url))
  21. const TREE_EXPECTED = fileURLToPath(new URL('../../../snapshots/web/subagent-conversation/tree.expected.md', import.meta.url))
  22. const BRANCHLESS_EXPECTED = fileURLToPath(new URL('../../../snapshots/web/subagent-conversation/branchless.expected.md', import.meta.url))
  23. const STALE_CATALOG_EXPECTED = fileURLToPath(new URL('../../../snapshots/web/subagent-conversation/stale-catalog.expected.md', import.meta.url))
  24. const SIDEBAR_EXPECTED = fileURLToPath(new URL('../../../snapshots/web/subagent-conversation/sidebar.expected.md', import.meta.url))
  25. const UNAVAILABLE_GRANDCHILD_EXPECTED = fileURLToPath(new URL('../../../snapshots/web/subagent-conversation/nested.expected.md', import.meta.url))
  26. const FORK_EXPECTED = fileURLToPath(new URL('../../../snapshots/web/subagent-conversation/fork.expected.md', import.meta.url))
  27. const MODE = webSnapshotMode()
  28. const LABEL = 'event-sourcing researcher'
  29. const ONE_SHOT_LABEL = 'event-sourcing reviewer'
  30. const NESTED_LABEL = 'example editor'
  31. const PARENT_PROMPT = 'Ask a research subagent to explain event sourcing.'
  32. const INITIAL_PROMPT = 'Explain event sourcing in one sentence.'
  33. /** The grandchild's own first message; its arrival is what says its history finished loading. */
  34. const NESTED_PROMPT = 'Give one concrete event sourcing example.'
  35. const FOLLOWUP = 'Now give the same explanation to a human reader.'
  36. const POST_FORK_FOLLOWUP = 'Continue the original conversation after the fork.'
  37. function childFixture(source: string, fixtureId: string, withContinuation: boolean): string {
  38. const [header, ...eventLines] = source.trimEnd().split('\n')
  39. if (header === undefined) throw new Error('base replay fixture has no header')
  40. const childHeader = header
  41. .replace('"id":"{{sessionId}}"', `"id":"${fixtureId}"`)
  42. .replace(/"createdAt":\d+/, '"createdAt":1784998084442')
  43. if (!withContinuation) return [childHeader, ...eventLines, ''].join('\n')
  44. const continued = eventLines.map(line => line
  45. .replace(/"seq":(\d+)/g, (_match, seq: string) => `"seq":${String(Number(seq) + 100)}`)
  46. .replace(/"seq0":(\d+)/g, (_match, seq: string) => `"seq0":${String(Number(seq) + 100)}`)
  47. .replaceAll('"turn":1', '"turn":2'))
  48. return [childHeader, ...eventLines, ...continued, ''].join('\n')
  49. }
  50. async function waitForAgentToSettle(scaffold: WebScaffold, id: SessionId): Promise<void> {
  51. const deadline = Date.now() + 30_000
  52. while (scaffold.ctx.agents.get(id) !== undefined) {
  53. if (Date.now() >= deadline) throw new Error(`subagent ${id} did not settle`)
  54. await new Promise<void>(resolve => setTimeout(resolve, 10))
  55. }
  56. }
  57. describe('web e2e: persisted subagent conversation and human continuation', () => {
  58. let scaffold: WebScaffold
  59. let browser: Browser
  60. let page: Page
  61. let sidecarRoot: string
  62. let childId: SessionId
  63. let oneShotId: SessionId
  64. let grandchildId: SessionId
  65. let tripwire: ReturnType<typeof watchConsole>
  66. const apiCalls: string[] = []
  67. beforeAll(async () => {
  68. if (MODE === 'record') throw new Error('subagent conversation is a keyless assembled snapshot')
  69. const baseFixture = await readFile(BASE_FIXTURE, 'utf8')
  70. sidecarRoot = await mkdtemp(join(tmpdir(), 'dsh-web-subagent-'))
  71. const childFixturePath = join(sidecarRoot, 'child.jsonl')
  72. await writeFile(childFixturePath, childFixture(baseFixture, 'recorded-subagent', true))
  73. scaffold = await launchWebScaffold({
  74. replayFixture: BASE_FIXTURE,
  75. compareReplaySession: false,
  76. replayChildFixtures: [childFixturePath],
  77. paceMs: 25,
  78. })
  79. browser = await chromium.launch()
  80. page = await newEnglishPage(browser)
  81. page.on('request', (request) => {
  82. const path = new URL(request.url()).pathname
  83. if (path.startsWith('/api/')) apiCalls.push(path)
  84. })
  85. tripwire = watchConsole(page)
  86. await page.goto(scaffold.baseUrl, { waitUntil: 'load' })
  87. await page.waitForSelector('[class*="frame"]', { timeout: 30_000 })
  88. await connectFreshWorkspace(page, scaffold.workspaceCwd)
  89. const parent = scaffold.ctx.agents.roots()[0]
  90. if (parent === undefined) throw new Error('fresh workspace did not publish its parent Agent')
  91. const parentSettled = scaffold.whenTurnSettled()
  92. const parentInput = page.locator('textarea:enabled').first()
  93. await parentInput.fill(PARENT_PROMPT)
  94. await parentInput.press('Enter')
  95. expect(await parentSettled).toBe(parent.id)
  96. const started = await scaffold.ctx.subagents.startContinuable({
  97. provider: 'spawn',
  98. label: LABEL,
  99. signal: new AbortController().signal,
  100. request: {
  101. prompt: [{ type: 'text', text: INITIAL_PROMPT }],
  102. parent,
  103. },
  104. })
  105. childId = started.childId
  106. await waitForAgentToSettle(scaffold, childId)
  107. oneShotId = sessionId('recorded-one-shot')
  108. const oneShotDurationMs = 192 * 24 * 60 * 60 * 1_000
  109. const oneShotAt = Date.now() - oneShotDurationMs
  110. await scaffold.ctx.sessionPersistence.create({
  111. version: SESSION_FORMAT_VERSION,
  112. id: oneShotId,
  113. createdAt: oneShotAt,
  114. cwd: scaffold.workspaceCwd,
  115. parentSession: parent.id,
  116. origin: 'subagent',
  117. delegationDepth: 1,
  118. })
  119. await scaffold.ctx.sessionPersistence.append(oneShotId, [
  120. {
  121. type: 'turn/start',
  122. seq: 0,
  123. time: oneShotAt,
  124. data: { turn: 1, trigger: { kind: 'message', source: { kind: 'user' } } },
  125. },
  126. {
  127. type: 'user/message',
  128. seq: 1,
  129. time: oneShotAt + 1,
  130. data: {
  131. content: [{ type: 'text', text: 'Review the event sourcing explanation.' }],
  132. source: { kind: 'user' },
  133. },
  134. surfaceOp: 'append',
  135. },
  136. {
  137. type: 'subagent/descriptor',
  138. seq: 2,
  139. time: oneShotAt + 2,
  140. data: snapshotSubagentDescriptor({
  141. mode: 'one-shot', provider: 'spawn', label: ONE_SHOT_LABEL,
  142. }),
  143. },
  144. {
  145. type: 'turn/end',
  146. seq: 3,
  147. time: oneShotAt + oneShotDurationMs,
  148. data: { turn: 1, reason: { kind: 'completed' } },
  149. },
  150. ] as SessionEvent[])
  151. await scaffold.ctx.sessionProjectionCache.coldSnapshot(oneShotId)
  152. grandchildId = sessionId('recorded-grandchild')
  153. const authoredAt = Date.now()
  154. await scaffold.ctx.sessionPersistence.create({
  155. version: SESSION_FORMAT_VERSION,
  156. id: grandchildId,
  157. createdAt: authoredAt,
  158. cwd: scaffold.workspaceCwd,
  159. parentSession: childId,
  160. origin: 'subagent',
  161. delegationDepth: 2,
  162. })
  163. await scaffold.ctx.sessionPersistence.append(grandchildId, [
  164. {
  165. type: 'turn/start',
  166. seq: 0,
  167. time: authoredAt,
  168. data: { turn: 1, trigger: { kind: 'message', source: { kind: 'user' } } },
  169. },
  170. {
  171. type: 'user/message',
  172. seq: 1,
  173. time: authoredAt + 1,
  174. data: {
  175. content: [{ type: 'text', text: NESTED_PROMPT }],
  176. source: { kind: 'user' },
  177. },
  178. surfaceOp: 'append',
  179. },
  180. {
  181. type: 'subagent/descriptor',
  182. seq: 2,
  183. time: authoredAt + 2,
  184. data: snapshotSubagentDescriptor({
  185. mode: 'continuable', provider: 'spawn', label: NESTED_LABEL,
  186. }),
  187. },
  188. {
  189. type: 'turn/end',
  190. seq: 3,
  191. time: authoredAt + 3,
  192. data: { turn: 1, reason: { kind: 'completed' } },
  193. },
  194. ] as SessionEvent[])
  195. await scaffold.ctx.sessionProjectionCache.coldSnapshot(grandchildId)
  196. expect(scaffold.ctx.agents.get(childId)).toBeUndefined()
  197. expect(scaffold.ctx.agents.get(oneShotId)).toBeUndefined()
  198. expect(scaffold.ctx.agents.get(grandchildId)).toBeUndefined()
  199. await expect(scaffold.ctx.subagents.listChildren(parent.id)).resolves.toMatchObject([
  200. {
  201. kind: 'child', id: oneShotId, mode: 'one-shot',
  202. label: ONE_SHOT_LABEL, activity: 'inactive', hasChildren: false,
  203. },
  204. {
  205. kind: 'child', id: childId, mode: 'continuable', label: LABEL,
  206. activity: 'inactive', hasChildren: true,
  207. },
  208. ])
  209. await expect(scaffold.ctx.subagents.listChildren(childId)).resolves.toMatchObject([
  210. {
  211. kind: 'child', id: grandchildId, mode: 'continuable',
  212. label: NESTED_LABEL, activity: 'inactive', hasChildren: false,
  213. },
  214. ])
  215. // These two cold fixtures were authored after the page's initial
  216. // session.list and intentionally emitted no api-session/added event. Reload
  217. // to exercise the restart baseline that discovers their full lineage.
  218. const warningStart = tripwire.warnings.length
  219. await page.reload({ waitUntil: 'load' })
  220. await page.waitForSelector('[class*="frame"]', { timeout: 30_000 })
  221. const catalogButton = page.getByRole('button', { name: /subagents/ })
  222. await catalogButton.waitFor({ timeout: 15_000 })
  223. await catalogButton.hover()
  224. const catalogTree = page.getByRole('tree', { name: 'Subagent sessions' })
  225. await catalogTree.getByRole('treeitem').nth(1).waitFor({ timeout: 15_000 })
  226. await catalogTree.press('Escape')
  227. await page.getByRole('button', { name: '3 subagents' }).waitFor({ timeout: 15_000 })
  228. acknowledgeReloadConnectionLoss(tripwire, warningStart)
  229. }, 120_000)
  230. afterAll(async () => {
  231. const failures: unknown[] = []
  232. await browser?.close().catch((error: unknown) => failures.push(error))
  233. await scaffold?.close().catch((error: unknown) => failures.push(error))
  234. if (sidecarRoot !== undefined) {
  235. await rm(sidecarRoot, { recursive: true, force: true })
  236. .catch((error: unknown) => failures.push(error))
  237. }
  238. if (failures.length === 1) throw failures[0]
  239. if (failures.length > 1) throw new AggregateError(failures, 'subagent Web teardown failed')
  240. })
  241. it('keeps known descendants reachable across a stale empty catalog response', async () => {
  242. onTestFailed(() => saveFailureShot(page, 'web-e2e-subagent-stale-catalog'))
  243. const pattern = '**/api/subagent.list'
  244. let firstClaimed = false
  245. let emptyDelivered = false
  246. let trailingRequested = false
  247. let releaseCatalog = (): void => {}
  248. const catalogHeld = new Promise<void>((resolve) => { releaseCatalog = resolve })
  249. await page.route(pattern, async (route) => {
  250. if (firstClaimed) {
  251. const response = await route.fetch()
  252. trailingRequested = true
  253. await catalogHeld
  254. await route.fulfill({ response })
  255. return
  256. }
  257. firstClaimed = true
  258. const response = await route.fetch()
  259. const body = await response.json() as {
  260. result: { ok: true; value: { entries: unknown[] } } | { ok: false }
  261. }
  262. if (body.result.ok) body.result.value.entries = []
  263. await route.fulfill({ response, json: body })
  264. emptyDelivered = true
  265. })
  266. const warningStart = tripwire.warnings.length
  267. try {
  268. await page.reload({ waitUntil: 'load' })
  269. await page.waitForSelector('[class*="frame"]', { timeout: 30_000 })
  270. await expect.poll(() => emptyDelivered, { timeout: 15_000 }).toBe(true)
  271. await page.getByRole('button', { name: '3 subagents' }).waitFor({ timeout: 15_000 })
  272. acknowledgeReloadConnectionLoss(tripwire, warningStart)
  273. await page.getByRole('button', { name: '3 subagents' }).hover()
  274. await expect.poll(() => trailingRequested, { timeout: 15_000 }).toBe(true)
  275. const tree = page.getByRole('tree', { name: 'Subagent sessions' })
  276. await tree.getByRole('treeitem', { name: 'Loading subagents' }).first().waitFor()
  277. expect(await tree.getByRole('treeitem', { name: 'Loading subagents' }).count()).toBe(2)
  278. await compareOrRefreshGolden(
  279. STALE_CATALOG_EXPECTED,
  280. await captureStableAria(page, '[role="tree"][aria-label="Subagent sessions"]', scaffold.workspaceCwd),
  281. MODE,
  282. )
  283. releaseCatalog()
  284. await tree.getByRole('treeitem', { name: new RegExp(LABEL) }).waitFor({ timeout: 15_000 })
  285. await tree.press('Escape')
  286. } finally {
  287. releaseCatalog()
  288. await page.unroute(pattern)
  289. }
  290. })
  291. it('expands a persisted grandchild progressively without activating either level', async () => {
  292. onTestFailed(() => saveFailureShot(page, 'web-e2e-subagent-tree'))
  293. await page.getByRole('button', { name: '3 subagents' }).hover()
  294. const catalogTree = page.getByRole('tree', { name: 'Subagent sessions' })
  295. expect(await catalogTree.evaluate((element) => {
  296. const rect = element.getBoundingClientRect()
  297. const hit = document.elementFromPoint(rect.left + 8, rect.top + 8)
  298. return hit !== null && element.contains(hit)
  299. })).toBe(true)
  300. expect(await page.getByRole('button', {
  301. name: `Expand ${ONE_SHOT_LABEL} descendants`,
  302. }).count()).toBe(0)
  303. const oneShotRow = page.getByRole('treeitem', { name: new RegExp(ONE_SHOT_LABEL) })
  304. expect(await oneShotRow.getByText('~6mo 12d', { exact: true }).count()).toBe(1)
  305. expect(await oneShotRow.getAttribute('aria-label')).toContain('192d 00h 00m 00s')
  306. await page.getByRole('button', { name: `Expand ${LABEL} descendants` }).click()
  307. const childRow = page.getByRole('treeitem', { name: new RegExp(LABEL) })
  308. const childLabel = await childRow.getAttribute('aria-label')
  309. await page.waitForTimeout(1_100)
  310. expect(await childRow.getAttribute('aria-label')).toBe(childLabel)
  311. await page.getByRole('treeitem', { name: new RegExp(NESTED_LABEL) }).waitFor({ timeout: 15_000 })
  312. expect(scaffold.ctx.agents.get(childId)).toBeUndefined()
  313. expect(scaffold.ctx.agents.get(grandchildId)).toBeUndefined()
  314. const snapshot = await captureStableAria(
  315. page,
  316. '[role="tree"][aria-label="Subagent sessions"]',
  317. scaffold.workspaceCwd,
  318. )
  319. await compareOrRefreshGolden(TREE_EXPECTED, snapshot, MODE)
  320. await page.getByRole('tree', { name: 'Subagent sessions' }).press('Escape')
  321. })
  322. it('opens the completed child from persistence without activating it', async () => {
  323. onTestFailed(() => saveFailureShot(page, 'web-e2e-subagent-open'))
  324. await page.getByRole('button', { name: '3 subagents' }).hover()
  325. await page.getByRole('treeitem', { name: new RegExp(LABEL) }).click()
  326. await expect.poll(
  327. () => page.getByText(INITIAL_PROMPT, { exact: true }).count(),
  328. { timeout: 15_000 },
  329. ).toBe(1)
  330. if (scaffold.ctx.agents.get(childId) !== undefined) {
  331. throw new Error(`viewing the child activated it; API calls: ${apiCalls.join(', ')}`)
  332. }
  333. const hierarchy = page.getByRole('navigation', { name: 'Session hierarchy' })
  334. await hierarchy.getByRole('button', { name: `Switch subagent: ${LABEL}` }).waitFor()
  335. const sidebar = await captureStableAria(
  336. page,
  337. '[role="tree"][aria-label="Sessions"]',
  338. scaffold.workspaceCwd,
  339. )
  340. await compareOrRefreshGolden(SIDEBAR_EXPECTED, sidebar, MODE)
  341. })
  342. it('keeps a restored child neutral until its parent availability arrives', async () => {
  343. onTestFailed(() => saveFailureShot(page, 'web-e2e-subagent-restore'))
  344. const pattern = '**/api/subagent.list'
  345. let requested = false
  346. let releaseCatalog = (): void => {}
  347. const catalogHeld = new Promise<void>((resolve) => { releaseCatalog = resolve })
  348. await page.route(pattern, async (route) => {
  349. const response = await route.fetch()
  350. requested = true
  351. await catalogHeld
  352. await route.fulfill({ response })
  353. })
  354. const warningStart = tripwire.warnings.length
  355. try {
  356. await page.reload({ waitUntil: 'load' })
  357. await page.waitForSelector('[class*="frame"]', { timeout: 30_000 })
  358. await expect.poll(() => requested, { timeout: 15_000 }).toBe(true)
  359. expect(await page.getByText('This subagent is read-only for now', { exact: true }).count()).toBe(0)
  360. expect(await page.locator('[data-composer-seat]').evaluate(element =>
  361. getComputedStyle(element).visibility)).toBe('hidden')
  362. releaseCatalog()
  363. const input = page.getByRole('textbox', { name: 'Message the agent' })
  364. await input.waitFor({ timeout: 15_000 })
  365. await expect.poll(() => input.isEnabled(), { timeout: 15_000 }).toBe(true)
  366. acknowledgeReloadConnectionLoss(tripwire, warningStart)
  367. } finally {
  368. releaseCatalog()
  369. await page.unroute(pattern)
  370. }
  371. })
  372. it('continues through FIFO follow-up admission and receives the child follow events', async () => {
  373. onTestFailed(() => saveFailureShot(page, 'web-e2e-subagent-followup'))
  374. const ended = new Promise<void>((resolveEnded, reject) => {
  375. const timer = setTimeout(() => {
  376. off()
  377. reject(new Error('subagent follow-up did not reach turn/end'))
  378. }, 30_000)
  379. const off = scaffold.ctx.on('session/event', (session: { id: SessionId }, event: SessionEvent) => {
  380. if (session.id !== childId || event.type !== 'turn/end') return
  381. clearTimeout(timer)
  382. off()
  383. resolveEnded()
  384. })
  385. })
  386. const input = page.getByRole('textbox', { name: 'Message the agent' })
  387. await input.fill(FOLLOWUP)
  388. await input.press('Enter')
  389. await expect.poll(
  390. () => scaffold.ctx.agents.get(childId)?.status,
  391. { timeout: 10_000 },
  392. ).toBe('running')
  393. await ended
  394. await expect.poll(() => page.getByText(FOLLOWUP, { exact: true }).count(), { timeout: 10_000 }).toBe(1)
  395. await expect.poll(() => scaffold.ctx.agents.get(childId), { timeout: 10_000 }).toBeUndefined()
  396. expect(await page.getByRole('button', { name: 'Stop generating' }).count()).toBe(0)
  397. })
  398. it('matches the settled addressed-conversation aria golden and stays clean', async () => {
  399. onTestFailed(() => saveFailureShot(page, 'web-e2e-subagent-aria'))
  400. const snapshot = await captureStableAria(page, '[class*="centerCol"]', scaffold.workspaceCwd)
  401. await compareOrRefreshGolden(AVAILABLE_CHILD_EXPECTED, snapshot, MODE)
  402. expect(tripwire.pageErrors).toEqual([])
  403. expect(tripwire.warnings).toEqual([])
  404. })
  405. it('opens an unavailable persisted grandchild after recording the available child', async () => {
  406. onTestFailed(() => saveFailureShot(page, 'web-e2e-subagent-grandchild'))
  407. await page.getByRole('button', { name: '1 subagent' }).hover()
  408. const tree = page.getByRole('tree', { name: 'Subagent sessions' })
  409. const nestedRow = tree.locator('[role="treeitem"]').filter({ hasText: NESTED_LABEL })
  410. await nestedRow.waitFor({ timeout: 15_000 })
  411. const clickArea = nestedRow.locator(':scope > div')
  412. expect(await clickArea.count()).toBe(1)
  413. const [treeBox, clickAreaBox] = await Promise.all([
  414. tree.boundingBox(),
  415. clickArea.boundingBox(),
  416. ])
  417. expect(treeBox).not.toBeNull()
  418. expect(clickAreaBox).not.toBeNull()
  419. expect([
  420. Math.round(clickAreaBox!.x - treeBox!.x),
  421. Math.round(treeBox!.x + treeBox!.width - clickAreaBox!.x - clickAreaBox!.width),
  422. // Menu padding alone insets the rows now that the border is gone.
  423. ]).toEqual([4, 4])
  424. await compareOrRefreshGolden(
  425. BRANCHLESS_EXPECTED,
  426. await captureStableAria(page, '[role="tree"][aria-label="Subagent sessions"]', scaffold.workspaceCwd),
  427. MODE,
  428. )
  429. await nestedRow.click()
  430. await page.getByText('The parent session is offline; reopen it to continue sending messages.').waitFor()
  431. // The offline banner renders from the descriptor alone, so it says nothing
  432. // about the transcript below it. The golden pins that transcript, and
  433. // `captureStableAria` calls two identical polls stable — including two of
  434. // "Loading history…". Wait for the message the golden asserts.
  435. await page.getByText(NESTED_PROMPT).waitFor()
  436. const hierarchy = page.getByRole('navigation', { name: 'Session hierarchy' })
  437. const crumbs = await hierarchy.getByRole('button').allTextContents()
  438. expect(crumbs.slice(-2)).toEqual([LABEL, NESTED_LABEL])
  439. expect(scaffold.ctx.agents.get(childId)).toBeUndefined()
  440. expect(scaffold.ctx.agents.get(grandchildId)).toBeUndefined()
  441. await compareOrRefreshGolden(
  442. UNAVAILABLE_GRANDCHILD_EXPECTED,
  443. await captureStableAria(page, '[class*="centerCol"]', scaffold.workspaceCwd),
  444. MODE,
  445. )
  446. })
  447. it('opens a one-shot child as permanently read-only history', async () => {
  448. onTestFailed(() => saveFailureShot(page, 'web-e2e-subagent-one-shot'))
  449. const parentSession = page.getByRole('tree', { name: 'Sessions' })
  450. .getByRole('treeitem')
  451. .last()
  452. await parentSession.click()
  453. await page.getByRole('button', { name: '3 subagents' }).hover()
  454. await page.getByRole('treeitem', { name: new RegExp(ONE_SHOT_LABEL) }).click()
  455. await page.getByText('One-shot tasks do not accept follow-ups; review the full execution record here.').waitFor()
  456. expect(scaffold.ctx.agents.get(oneShotId)).toBeUndefined()
  457. })
  458. it('places an ordinary fork from a subagent beside its workspace-owning ancestor', async () => {
  459. onTestFailed(() => saveFailureShot(page, 'web-e2e-subagent-fork'))
  460. await page.getByRole('tree', { name: 'Sessions' })
  461. .getByRole('treeitem', { name: /Ask a research subagent to/ })
  462. .click()
  463. await page.getByRole('button', { name: '3 subagents' }).hover()
  464. await page.getByRole('treeitem', { name: new RegExp(LABEL) }).click()
  465. await page.getByRole('textbox', { name: 'Message the agent' }).waitFor()
  466. const forkResponse = page.waitForResponse(response =>
  467. new URL(response.url()).pathname === '/api/session/fork')
  468. await page.getByRole('button', { name: 'Branch into a new conversation' }).last().click()
  469. const forkReceipt = await (await forkResponse).json() as { result: { ok: boolean } }
  470. expect(forkReceipt.result).toMatchObject({ ok: true })
  471. await expect.poll(
  472. () => page.getByRole('tree', { name: 'Sessions' }).getByRole('treeitem').count(),
  473. { timeout: 15_000 },
  474. ).toBe(3)
  475. expect(await page.getByText('Ungrouped', { exact: true }).count()).toBe(0)
  476. const hierarchy = page.getByRole('navigation', { name: 'Session hierarchy' })
  477. await expect.poll(() => hierarchy.getByRole('button').count()).toBe(1)
  478. await compareOrRefreshGolden(
  479. FORK_EXPECTED,
  480. await captureStableAria(page, '[role="tree"][aria-label="Sessions"]', scaffold.workspaceCwd),
  481. MODE,
  482. )
  483. })
  484. it('cold-resumes the original subagent while its ordinary fork stays active', async () => {
  485. onTestFailed(() => saveFailureShot(page, 'web-e2e-subagent-post-fork-followup'))
  486. const sessions = page.getByRole('tree', { name: 'Sessions' })
  487. await sessions.getByRole('treeitem', { name: /Ask a research subagent to/ }).click()
  488. await page.getByRole('button', { name: '3 subagents' }).hover()
  489. await page.getByRole('treeitem', { name: new RegExp(LABEL) }).click()
  490. await page.locator('textarea:enabled').first().waitFor()
  491. expect(scaffold.ctx.agents.get(childId)).toBeUndefined()
  492. const forkResponse = page.waitForResponse(response =>
  493. new URL(response.url()).pathname === '/api/session/fork')
  494. await page.getByRole('button', { name: 'Branch into a new conversation' }).last().click()
  495. const forkReceipt = await (await forkResponse).json() as {
  496. result: { ok: true; value: { sessionId: string } } | { ok: false }
  497. }
  498. expect(forkReceipt.result).toMatchObject({ ok: true })
  499. if (!forkReceipt.result.ok) return
  500. const forkId = sessionId(forkReceipt.result.value.sessionId)
  501. await expect.poll(() => scaffold.ctx.agents.get(forkId)).not.toBeUndefined()
  502. await sessions.getByRole('treeitem', { name: /Ask a research subagent to/ }).click()
  503. await page.getByRole('button', { name: '3 subagents' }).press('ArrowDown')
  504. await page.getByRole('treeitem', { name: new RegExp(LABEL) }).click()
  505. const input = page.locator('textarea:enabled').first()
  506. await input.waitFor()
  507. const promptResponse = page.waitForResponse(response =>
  508. new URL(response.url()).pathname === '/api/subagent.prompt')
  509. await input.fill(POST_FORK_FOLLOWUP)
  510. await input.press('Enter')
  511. const promptReceipt = await (await promptResponse).json() as {
  512. result: { ok: true } | { ok: false; error: { code: string; message: string } }
  513. }
  514. if (!promptReceipt.result.ok) {
  515. throw new Error(`post-fork follow-up rejected: ${JSON.stringify(promptReceipt.result.error)}`)
  516. }
  517. await expect.poll(async () => {
  518. const loaded = await scaffold.ctx.sessionPersistence.load(childId)
  519. const messageIndex = loaded.events.findIndex(event => event.type === 'user/message'
  520. && event.data.content.some(block => block.type === 'text' && block.text === POST_FORK_FOLLOWUP))
  521. return messageIndex >= 0 && loaded.events.slice(messageIndex + 1).some(event => event.type === 'turn/end')
  522. }, { timeout: 30_000 }).toBe(true)
  523. expect(scaffold.ctx.agents.get(forkId)).not.toBeUndefined()
  524. await expect.poll(() => scaffold.ctx.agents.get(childId), { timeout: 10_000 }).toBeUndefined()
  525. })
  526. })