subagent-conversation.e2e.ts 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516
  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 api-session/added event. 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.hover()
  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' }).hover()
  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' }).hover()
  293. const catalogTree = page.getByRole('tree', { name: 'Subagent sessions' })
  294. expect(await catalogTree.evaluate((element) => {
  295. const rect = element.getBoundingClientRect()
  296. const hit = document.elementFromPoint(rect.left + 8, rect.top + 8)
  297. return hit !== null && element.contains(hit)
  298. })).toBe(true)
  299. expect(await page.getByRole('button', {
  300. name: `Expand ${ONE_SHOT_LABEL} descendants`,
  301. }).count()).toBe(0)
  302. const oneShotRow = page.getByRole('treeitem', { name: new RegExp(ONE_SHOT_LABEL) })
  303. expect(await oneShotRow.getByText('~6mo 12d', { exact: true }).count()).toBe(1)
  304. expect(await oneShotRow.getAttribute('aria-label')).toContain('192d 00h 00m 00s')
  305. await page.getByRole('button', { name: `Expand ${LABEL} descendants` }).click()
  306. const childRow = page.getByRole('treeitem', { name: new RegExp(LABEL) })
  307. const childLabel = await childRow.getAttribute('aria-label')
  308. await page.waitForTimeout(1_100)
  309. expect(await childRow.getAttribute('aria-label')).toBe(childLabel)
  310. await page.getByRole('treeitem', { name: new RegExp(NESTED_LABEL) }).waitFor({ timeout: 15_000 })
  311. expect(scaffold.ctx.agents.get(childId)).toBeUndefined()
  312. expect(scaffold.ctx.agents.get(grandchildId)).toBeUndefined()
  313. const snapshot = await captureStableAria(
  314. page,
  315. '[role="tree"][aria-label="Subagent sessions"]',
  316. scaffold.workspaceCwd,
  317. )
  318. await compareOrRefreshGolden(TREE_EXPECTED, snapshot, MODE)
  319. await page.getByRole('tree', { name: 'Subagent sessions' }).press('Escape')
  320. })
  321. it('opens the completed child from persistence without activating it', async () => {
  322. onTestFailed(() => saveFailureShot(page, 'web-e2e-subagent-open'))
  323. await page.getByRole('button', { name: '3 subagents' }).hover()
  324. await page.getByRole('treeitem', { name: new RegExp(LABEL) }).click()
  325. await expect.poll(
  326. () => page.getByText(INITIAL_PROMPT, { exact: true }).count(),
  327. { timeout: 15_000 },
  328. ).toBe(1)
  329. if (scaffold.ctx.agents.get(childId) !== undefined) {
  330. throw new Error(`viewing the child activated it; API calls: ${apiCalls.join(', ')}`)
  331. }
  332. const hierarchy = page.getByRole('navigation', { name: 'Session hierarchy' })
  333. await hierarchy.getByRole('button', { name: `Switch subagent: ${LABEL}` }).waitFor()
  334. const sidebar = await captureStableAria(
  335. page,
  336. '[role="tree"][aria-label="Sessions"]',
  337. scaffold.workspaceCwd,
  338. )
  339. await compareOrRefreshGolden(SIDEBAR_EXPECTED, sidebar, MODE)
  340. })
  341. it('continues through FIFO follow-up admission and receives the child follow events', async () => {
  342. onTestFailed(() => saveFailureShot(page, 'web-e2e-subagent-followup'))
  343. const ended = new Promise<void>((resolveEnded, reject) => {
  344. const timer = setTimeout(() => {
  345. off()
  346. reject(new Error('subagent follow-up did not reach turn/end'))
  347. }, 30_000)
  348. const off = scaffold.ctx.on('session/event', (session: { id: SessionId }, event: SessionEvent) => {
  349. if (session.id !== childId || event.type !== 'turn/end') return
  350. clearTimeout(timer)
  351. off()
  352. resolveEnded()
  353. })
  354. })
  355. const input = page.getByRole('textbox', { name: 'Message the agent' })
  356. await input.fill(FOLLOWUP)
  357. await input.press('Enter')
  358. await expect.poll(
  359. () => scaffold.ctx.agents.get(childId)?.status,
  360. { timeout: 10_000 },
  361. ).toBe('running')
  362. await ended
  363. await expect.poll(() => page.getByText(FOLLOWUP, { exact: true }).count(), { timeout: 10_000 }).toBe(1)
  364. await expect.poll(() => scaffold.ctx.agents.get(childId), { timeout: 10_000 }).toBeUndefined()
  365. expect(await page.getByRole('button', { name: 'Stop generating' }).count()).toBe(0)
  366. })
  367. it('matches the settled addressed-conversation aria golden and stays clean', async () => {
  368. onTestFailed(() => saveFailureShot(page, 'web-e2e-subagent-aria'))
  369. const snapshot = await captureStableAria(page, '[class*="centerCol"]', scaffold.workspaceCwd)
  370. await compareOrRefreshGolden(AVAILABLE_CHILD_EXPECTED, snapshot, MODE)
  371. expect(tripwire.pageErrors).toEqual([])
  372. expect(tripwire.warnings).toEqual([])
  373. })
  374. it('opens an unavailable persisted grandchild after recording the available child', async () => {
  375. onTestFailed(() => saveFailureShot(page, 'web-e2e-subagent-grandchild'))
  376. await page.getByRole('button', { name: '1 subagent' }).hover()
  377. const tree = page.getByRole('tree', { name: 'Subagent sessions' })
  378. const nestedRow = tree.locator('[role="treeitem"]').filter({ hasText: NESTED_LABEL })
  379. await nestedRow.waitFor({ timeout: 15_000 })
  380. const clickArea = nestedRow.locator(':scope > div')
  381. expect(await clickArea.count()).toBe(1)
  382. const [treeBox, clickAreaBox] = await Promise.all([
  383. tree.boundingBox(),
  384. clickArea.boundingBox(),
  385. ])
  386. expect(treeBox).not.toBeNull()
  387. expect(clickAreaBox).not.toBeNull()
  388. expect([
  389. Math.round(clickAreaBox!.x - treeBox!.x),
  390. Math.round(treeBox!.x + treeBox!.width - clickAreaBox!.x - clickAreaBox!.width),
  391. // Menu padding alone insets the rows now that the border is gone.
  392. ]).toEqual([4, 4])
  393. await compareOrRefreshGolden(
  394. BRANCHLESS_EXPECTED,
  395. await captureStableAria(page, '[role="tree"][aria-label="Subagent sessions"]', scaffold.workspaceCwd),
  396. MODE,
  397. )
  398. await nestedRow.click()
  399. await page.getByText('The parent session is offline; reopen it to continue sending messages.').waitFor()
  400. // The offline banner renders from the descriptor alone, so it says nothing
  401. // about the transcript below it. The golden pins that transcript, and
  402. // `captureStableAria` calls two identical polls stable — including two of
  403. // "Loading history…". Wait for the message the golden asserts.
  404. await page.getByText(NESTED_PROMPT).waitFor()
  405. const hierarchy = page.getByRole('navigation', { name: 'Session hierarchy' })
  406. const crumbs = await hierarchy.getByRole('button').allTextContents()
  407. expect(crumbs.slice(-2)).toEqual([LABEL, NESTED_LABEL])
  408. expect(scaffold.ctx.agents.get(childId)).toBeUndefined()
  409. expect(scaffold.ctx.agents.get(grandchildId)).toBeUndefined()
  410. await compareOrRefreshGolden(
  411. UNAVAILABLE_GRANDCHILD_EXPECTED,
  412. await captureStableAria(page, '[class*="centerCol"]', scaffold.workspaceCwd),
  413. MODE,
  414. )
  415. })
  416. it('opens a one-shot child as permanently read-only history', async () => {
  417. onTestFailed(() => saveFailureShot(page, 'web-e2e-subagent-one-shot'))
  418. const parentSession = page.getByRole('tree', { name: 'Sessions' })
  419. .getByRole('treeitem')
  420. .last()
  421. await parentSession.click()
  422. await page.getByRole('button', { name: '3 subagents' }).hover()
  423. await page.getByRole('treeitem', { name: new RegExp(ONE_SHOT_LABEL) }).click()
  424. await page.getByText('One-shot tasks do not accept follow-ups; review the full execution record here.').waitFor()
  425. expect(scaffold.ctx.agents.get(oneShotId)).toBeUndefined()
  426. })
  427. it('places an ordinary fork from a subagent beside its workspace-owning ancestor', async () => {
  428. onTestFailed(() => saveFailureShot(page, 'web-e2e-subagent-fork'))
  429. await page.getByRole('tree', { name: 'Sessions' })
  430. .getByRole('treeitem', { name: /Ask a research subagent to/ })
  431. .click()
  432. await page.getByRole('button', { name: '3 subagents' }).hover()
  433. await page.getByRole('treeitem', { name: new RegExp(LABEL) }).click()
  434. await page.getByRole('textbox', { name: 'Message the agent' }).waitFor()
  435. const forkResponse = page.waitForResponse(response =>
  436. new URL(response.url()).pathname === '/api/session/fork')
  437. await page.getByRole('button', { name: 'Branch into a new conversation' }).last().click()
  438. const forkReceipt = await (await forkResponse).json() as { result: { ok: boolean } }
  439. expect(forkReceipt.result).toMatchObject({ ok: true })
  440. await expect.poll(
  441. () => page.getByRole('tree', { name: 'Sessions' }).getByRole('treeitem').count(),
  442. { timeout: 15_000 },
  443. ).toBe(3)
  444. expect(await page.getByText('Ungrouped', { exact: true }).count()).toBe(0)
  445. const hierarchy = page.getByRole('navigation', { name: 'Session hierarchy' })
  446. await expect.poll(() => hierarchy.getByRole('button').count()).toBe(1)
  447. await compareOrRefreshGolden(
  448. FORK_EXPECTED,
  449. await captureStableAria(page, '[role="tree"][aria-label="Sessions"]', scaffold.workspaceCwd),
  450. MODE,
  451. )
  452. })
  453. it('cold-resumes the original subagent while its ordinary fork stays active', async () => {
  454. onTestFailed(() => saveFailureShot(page, 'web-e2e-subagent-post-fork-followup'))
  455. const sessions = page.getByRole('tree', { name: 'Sessions' })
  456. await sessions.getByRole('treeitem', { name: /Ask a research subagent to/ }).click()
  457. await page.getByRole('button', { name: '3 subagents' }).hover()
  458. await page.getByRole('treeitem', { name: new RegExp(LABEL) }).click()
  459. await page.locator('textarea:enabled').first().waitFor()
  460. expect(scaffold.ctx.agents.get(childId)).toBeUndefined()
  461. const forkResponse = page.waitForResponse(response =>
  462. new URL(response.url()).pathname === '/api/session/fork')
  463. await page.getByRole('button', { name: 'Branch into a new conversation' }).last().click()
  464. const forkReceipt = await (await forkResponse).json() as {
  465. result: { ok: true; value: { sessionId: string } } | { ok: false }
  466. }
  467. expect(forkReceipt.result).toMatchObject({ ok: true })
  468. if (!forkReceipt.result.ok) return
  469. const forkId = sessionId(forkReceipt.result.value.sessionId)
  470. await expect.poll(() => scaffold.ctx.agents.get(forkId)).not.toBeUndefined()
  471. await sessions.getByRole('treeitem', { name: /Ask a research subagent to/ }).click()
  472. await page.getByRole('button', { name: '3 subagents' }).press('ArrowDown')
  473. await page.getByRole('treeitem', { name: new RegExp(LABEL) }).click()
  474. const input = page.locator('textarea:enabled').first()
  475. await input.waitFor()
  476. const promptResponse = page.waitForResponse(response =>
  477. new URL(response.url()).pathname === '/api/subagent.prompt')
  478. await input.fill(POST_FORK_FOLLOWUP)
  479. await input.press('Enter')
  480. const promptReceipt = await (await promptResponse).json() as {
  481. result: { ok: true } | { ok: false; error: { code: string; message: string } }
  482. }
  483. if (!promptReceipt.result.ok) {
  484. throw new Error(`post-fork follow-up rejected: ${JSON.stringify(promptReceipt.result.error)}`)
  485. }
  486. await expect.poll(async () => {
  487. const loaded = await scaffold.ctx.sessionPersistence.load(childId)
  488. const messageIndex = loaded.events.findIndex(event => event.type === 'user/message'
  489. && event.data.content.some(block => block.type === 'text' && block.text === POST_FORK_FOLLOWUP))
  490. return messageIndex >= 0 && loaded.events.slice(messageIndex + 1).some(event => event.type === 'turn/end')
  491. }, { timeout: 30_000 }).toBe(true)
  492. expect(scaffold.ctx.agents.get(forkId)).not.toBeUndefined()
  493. await expect.poll(() => scaffold.ctx.agents.get(childId), { timeout: 10_000 }).toBeUndefined()
  494. })
  495. })