1
0

subagent-conversation.e2e.ts 22 KB

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