subagent-conversation.e2e.ts 26 KB

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