subagent-conversation.e2e.ts 23 KB

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