tui-delegation-flow.test.ts 45 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541
  1. import { stripVTControlCharacters } from "node:util";
  2. import { afterEach, describe, expect, it, vi } from "vitest";
  3. import { TuiDelegationFlow } from "../../src/tui/controller/delegation-flow.js";
  4. import { createTranscriptCell } from "../../src/tui/transcript/model.js";
  5. import { TranscriptStore } from "../../src/tui/transcript/store.js";
  6. function runtime(overrides: Record<string, unknown> = {}) {
  7. return {
  8. getDelegationSnapshot: vi.fn(async () => ({
  9. schemaVersion: 1 as const,
  10. rootSessionId: "root",
  11. members: [],
  12. })),
  13. stopDelegation: vi.fn(),
  14. getActiveRun: vi.fn(async (sessionId: string) => ({
  15. schemaVersion: 1 as const,
  16. sessionId,
  17. state: "idle" as const,
  18. actions: { steer: false },
  19. })),
  20. getMessages: vi.fn(async () => []),
  21. getSession: vi.fn(async (sessionId: string) => ({ sessionId })),
  22. watchSessionTurn: vi.fn(async function* watchSessionTurn() {}),
  23. ...overrides,
  24. };
  25. }
  26. describe("TuiDelegationFlow", () => {
  27. afterEach(() => vi.useRealTimers());
  28. it("recovers delegated agents into an explicit live projection without writing Transcript", async () => {
  29. const transcript = new TranscriptStore();
  30. const runtimePort = runtime({
  31. getDelegationSnapshot: vi.fn(async () => ({
  32. schemaVersion: 1 as const,
  33. rootSessionId: "root",
  34. members: [
  35. {
  36. sessionId: "child-1",
  37. parentSessionId: "root",
  38. agentName: "verifier",
  39. task: "Review recent CLI changes",
  40. status: "running" as const,
  41. createdAtMs: 100,
  42. updatedAtMs: 200,
  43. },
  44. ],
  45. })),
  46. getActiveRun: vi.fn(async () => ({
  47. schemaVersion: 1 as const,
  48. sessionId: "child-1",
  49. state: "running" as const,
  50. turnId: "turn-1",
  51. actions: { steer: false },
  52. })),
  53. });
  54. const flow = new TuiDelegationFlow({
  55. runtime: runtimePort,
  56. currentSession: () => ({ sessionId: "root" }),
  57. onChanged: vi.fn(),
  58. });
  59. await flow.refresh();
  60. expect(flow.snapshot()).toMatchObject({
  61. summary: { total: 1, running: 1 },
  62. members: [
  63. {
  64. sessionId: "child-1",
  65. agentName: "verifier",
  66. task: "Review recent CLI changes",
  67. activity: "Starting",
  68. },
  69. ],
  70. });
  71. expect(transcript.snapshot()).toEqual([]);
  72. expect(flow.agentCounts()).toEqual({ active: 1, total: 1 });
  73. const permissionResolvers = flow.permissionResolvers(() => "root-turn");
  74. expect(permissionResolvers.permissionOwnerTurnId("root")).toBe("root-turn");
  75. expect(permissionResolvers.permissionOwnerTurnId("child-1")).toBe("turn-1");
  76. expect(
  77. permissionResolvers.permissionOwnerTurnId("missing-child"),
  78. ).toBeUndefined();
  79. flow.stop();
  80. });
  81. it("keeps mixed failed and running state in the live projection", async () => {
  82. const transcript = new TranscriptStore();
  83. const flow = new TuiDelegationFlow({
  84. runtime: runtime({
  85. getDelegationSnapshot: vi.fn(async () => ({
  86. schemaVersion: 1 as const,
  87. rootSessionId: "root",
  88. members: [
  89. {
  90. sessionId: "failed-child",
  91. parentSessionId: "root",
  92. agentName: "reviewer",
  93. task: "Review changes",
  94. status: "failed" as const,
  95. },
  96. {
  97. sessionId: "running-child",
  98. parentSessionId: "root",
  99. agentName: "verifier",
  100. task: "Run focused tests",
  101. status: "running" as const,
  102. },
  103. ],
  104. })),
  105. getActiveRun: vi.fn(async (sessionId: string) => ({
  106. schemaVersion: 1 as const,
  107. sessionId,
  108. state:
  109. sessionId === "running-child"
  110. ? ("running" as const)
  111. : ("idle" as const),
  112. ...(sessionId === "running-child" ? { turnId: "turn-running" } : {}),
  113. actions: { steer: false },
  114. })),
  115. }),
  116. currentSession: () => ({ sessionId: "root" }),
  117. onChanged: vi.fn(),
  118. });
  119. await flow.refresh();
  120. expect(flow.snapshot().summary).toMatchObject({ failed: 1, running: 1 });
  121. expect(transcript.snapshot()).toEqual([]);
  122. expect(flow.agentCounts()).toEqual({ active: 1, total: 2 });
  123. flow.stop();
  124. });
  125. it("settles a successful child from the terminal active Run after authoritative refresh", async () => {
  126. const transcript = new TranscriptStore();
  127. const flow = new TuiDelegationFlow({
  128. runtime: runtime({
  129. getDelegationSnapshot: vi.fn(async () => ({
  130. schemaVersion: 1 as const,
  131. rootSessionId: "root",
  132. members: [
  133. {
  134. sessionId: "child-1",
  135. parentSessionId: "root",
  136. agentName: "verifier",
  137. task: "Verify changes",
  138. status: "queued" as const,
  139. },
  140. ],
  141. })),
  142. getActiveRun: vi.fn(async () => ({
  143. schemaVersion: 1 as const,
  144. sessionId: "child-1",
  145. state: "terminal" as const,
  146. turnId: "turn-1",
  147. actions: { steer: false },
  148. })),
  149. }),
  150. currentSession: () => ({ sessionId: "root" }),
  151. onChanged: vi.fn(),
  152. });
  153. await flow.refresh();
  154. expect(flow.snapshot().summary).toMatchObject({ done: 1, queued: 0 });
  155. expect(transcript.snapshot()).toEqual([]);
  156. expect(flow.agentCounts()).toEqual({ active: 0, total: 1 });
  157. flow.stop();
  158. });
  159. it("settles a successful idle child from durable history after a cold refresh", async () => {
  160. const transcript = new TranscriptStore();
  161. const flow = new TuiDelegationFlow({
  162. runtime: runtime({
  163. getDelegationSnapshot: vi.fn(async () => ({
  164. schemaVersion: 1 as const,
  165. rootSessionId: "root",
  166. members: [
  167. {
  168. sessionId: "child-1",
  169. parentSessionId: "root",
  170. agentName: "verifier",
  171. task: "Verify changes",
  172. status: "queued" as const,
  173. },
  174. ],
  175. })),
  176. getMessages: vi.fn(async (sessionId: string) =>
  177. sessionId === "child-1"
  178. ? [
  179. {
  180. id: "child-answer",
  181. turnId: "turn-1",
  182. role: "assistant" as const,
  183. content: "Verified",
  184. finishReason: "stop",
  185. },
  186. ]
  187. : [],
  188. ),
  189. }),
  190. currentSession: () => ({ sessionId: "root" }),
  191. onChanged: vi.fn(),
  192. });
  193. await flow.refresh();
  194. expect(flow.snapshot().summary).toMatchObject({ done: 1, queued: 0 });
  195. expect(transcript.snapshot()).toEqual([]);
  196. expect(flow.agentCounts()).toEqual({ active: 0, total: 1 });
  197. flow.stop();
  198. });
  199. it("keeps an idle child queued when durable history has no successful terminal message", async () => {
  200. const flow = new TuiDelegationFlow({
  201. runtime: runtime({
  202. getDelegationSnapshot: vi.fn(async () => ({
  203. schemaVersion: 1 as const,
  204. rootSessionId: "root",
  205. members: [
  206. {
  207. sessionId: "child-1",
  208. parentSessionId: "root",
  209. status: "queued" as const,
  210. },
  211. ],
  212. })),
  213. getMessages: vi.fn(async (sessionId: string) =>
  214. sessionId === "child-1"
  215. ? [
  216. {
  217. id: "old-answer",
  218. turnId: "turn-old",
  219. role: "assistant" as const,
  220. finishReason: "stop",
  221. },
  222. {
  223. id: "tool-request",
  224. turnId: "turn-new",
  225. role: "assistant" as const,
  226. finishReason: "toolUse",
  227. },
  228. ]
  229. : [],
  230. ),
  231. }),
  232. currentSession: () => ({ sessionId: "root" }),
  233. onChanged: vi.fn(),
  234. });
  235. await flow.refresh();
  236. expect(flow.agentCounts()).toEqual({ active: 1, total: 1 });
  237. flow.stop();
  238. });
  239. it("keeps background members active until every root delivery Turn is settled", async () => {
  240. const onChanged = vi.fn();
  241. const flow = new TuiDelegationFlow({
  242. runtime: runtime({
  243. getDelegationSnapshot: vi.fn(async () => ({
  244. schemaVersion: 1 as const,
  245. rootSessionId: "root",
  246. members: [
  247. {
  248. sessionId: "child-a",
  249. parentSessionId: "root",
  250. status: "completed" as const,
  251. backgroundTaskId: "task-a",
  252. },
  253. {
  254. sessionId: "child-b",
  255. parentSessionId: "root",
  256. status: "completed" as const,
  257. backgroundTaskId: "task-b",
  258. },
  259. ],
  260. })),
  261. }),
  262. currentSession: () => ({ sessionId: "root" }),
  263. onChanged,
  264. });
  265. await flow.refresh();
  266. const firstDelivery = {
  267. type: "session.finish" as const,
  268. timestampMs: 500,
  269. source: "runtime",
  270. sessionId: "root",
  271. turnId: "delivery-a",
  272. taskId: "task-a",
  273. runSource: "background-task-delivery",
  274. queueItemIds: [],
  275. };
  276. expect(flow.agentCounts()).toEqual({ active: 2, total: 2 });
  277. await flow.handleRuntimeEvent(firstDelivery);
  278. expect(flow.agentCounts()).toEqual({ active: 2, total: 2 });
  279. flow.handleSettledRuntimeEvent(firstDelivery);
  280. expect(flow.agentCounts()).toEqual({ active: 1, total: 2 });
  281. flow.handleSettledRuntimeEvent({
  282. ...firstDelivery,
  283. timestampMs: 600,
  284. turnId: "delivery-b",
  285. taskId: "task-b",
  286. });
  287. expect(flow.agentCounts()).toEqual({ active: 0, total: 2 });
  288. expect(onChanged).toHaveBeenCalledTimes(3);
  289. flow.stop();
  290. });
  291. it("settles every background Task steered into one owner Turn without reopening on replay", async () => {
  292. const onChanged = vi.fn();
  293. const flow = new TuiDelegationFlow({
  294. runtime: runtime({
  295. getDelegationSnapshot: vi.fn(async () => ({
  296. schemaVersion: 1 as const,
  297. rootSessionId: "root",
  298. members: [
  299. {
  300. sessionId: "child-a",
  301. parentSessionId: "root",
  302. status: "completed" as const,
  303. backgroundTaskId: "task-a",
  304. },
  305. {
  306. sessionId: "child-b",
  307. parentSessionId: "root",
  308. status: "completed" as const,
  309. backgroundTaskId: "task-b",
  310. },
  311. {
  312. sessionId: "child-c",
  313. parentSessionId: "root",
  314. status: "completed" as const,
  315. backgroundTaskId: "task-c",
  316. },
  317. ],
  318. })),
  319. }),
  320. currentSession: () => ({ sessionId: "root" }),
  321. onChanged,
  322. });
  323. await flow.refresh();
  324. const steeredStart = {
  325. type: "session.start" as const,
  326. timestampMs: 500,
  327. source: "runtime",
  328. sessionId: "root",
  329. turnId: "turn-owner",
  330. taskId: "task-a",
  331. runSource: "background-task-delivery",
  332. queueItemIds: [],
  333. };
  334. await flow.handleRuntimeEvent(steeredStart);
  335. await flow.handleRuntimeEvent({ ...steeredStart, taskId: "task-b" });
  336. flow.handleAutomationResultPublished({
  337. sessionId: "root",
  338. turnId: "turn-unrelated",
  339. });
  340. expect(flow.agentCounts()).toEqual({ active: 3, total: 3 });
  341. flow.handleAutomationResultPublished({
  342. sessionId: "root",
  343. turnId: "turn-owner",
  344. });
  345. expect(flow.agentCounts()).toEqual({ active: 1, total: 3 });
  346. flow.handleAutomationResultPublished({
  347. sessionId: "root",
  348. turnId: "turn-late-event",
  349. });
  350. await flow.handleRuntimeEvent({
  351. ...steeredStart,
  352. timestampMs: 550,
  353. turnId: "turn-late-event",
  354. taskId: "task-c",
  355. });
  356. expect(flow.agentCounts()).toEqual({ active: 0, total: 3 });
  357. await flow.handleRuntimeEvent({ ...steeredStart, timestampMs: 600 });
  358. expect(flow.agentCounts()).toEqual({ active: 0, total: 3 });
  359. expect(onChanged).toHaveBeenCalledTimes(3);
  360. flow.stop();
  361. });
  362. it("does not settle a background member from an unrelated delivery task", async () => {
  363. const flow = new TuiDelegationFlow({
  364. runtime: runtime({
  365. getDelegationSnapshot: vi.fn(async () => ({
  366. schemaVersion: 1 as const,
  367. rootSessionId: "root",
  368. members: [
  369. {
  370. sessionId: "child",
  371. parentSessionId: "root",
  372. status: "completed" as const,
  373. backgroundTaskId: "expected-task",
  374. },
  375. ],
  376. })),
  377. }),
  378. currentSession: () => ({ sessionId: "root" }),
  379. onChanged: vi.fn(),
  380. });
  381. await flow.refresh();
  382. flow.handleSettledRuntimeEvent({
  383. type: "session.finish",
  384. timestampMs: 500,
  385. source: "runtime",
  386. sessionId: "root",
  387. turnId: "other-delivery",
  388. taskId: "other-task",
  389. runSource: "background-task-delivery",
  390. queueItemIds: [],
  391. });
  392. expect(flow.agentCounts()).toEqual({ active: 1, total: 1 });
  393. flow.stop();
  394. });
  395. it("keeps durable task turns unchanged while publishing the recovered team", async () => {
  396. const transcript = new TranscriptStore([
  397. createTranscriptCell({
  398. id: "turn-task-answer",
  399. kind: "assistant",
  400. status: "succeeded",
  401. content: "Launching two agents",
  402. turnId: "turn-task",
  403. createdAtMs: 100,
  404. }),
  405. createTranscriptCell({
  406. id: "turn-later-answer",
  407. kind: "assistant",
  408. status: "succeeded",
  409. content: "Later answer",
  410. turnId: "turn-later",
  411. createdAtMs: 500,
  412. }),
  413. ]);
  414. const taskMessages = [
  415. {
  416. id: "message-task",
  417. turnId: "turn-task",
  418. role: "assistant" as const,
  419. timestamp: 100,
  420. toolCalls: [
  421. { id: "call-a", name: "task", input: { description: "Task A" } },
  422. { id: "call-b", name: "task", input: { description: "Task B" } },
  423. ],
  424. },
  425. {
  426. id: "result-a",
  427. turnId: "turn-task",
  428. role: "unknown" as const,
  429. toolResult: {
  430. toolCallId: "call-a",
  431. toolName: "task",
  432. details: { subSessionId: "child-a" },
  433. },
  434. },
  435. {
  436. id: "result-b",
  437. turnId: "turn-task",
  438. role: "unknown" as const,
  439. toolResult: {
  440. toolCallId: "call-b",
  441. toolName: "task",
  442. details: { subSessionId: "child-b" },
  443. },
  444. },
  445. ];
  446. const flow = new TuiDelegationFlow({
  447. runtime: runtime({
  448. getDelegationSnapshot: vi.fn(async () => ({
  449. schemaVersion: 1 as const,
  450. rootSessionId: "root",
  451. members: [
  452. {
  453. sessionId: "child-a",
  454. parentSessionId: "root",
  455. task: "Task A",
  456. status: "completed" as const,
  457. createdAtMs: 110,
  458. },
  459. {
  460. sessionId: "child-b",
  461. parentSessionId: "root",
  462. task: "Task B",
  463. status: "completed" as const,
  464. createdAtMs: 120,
  465. },
  466. ],
  467. })),
  468. getMessages: vi.fn(async (sessionId: string) =>
  469. sessionId === "root" ? taskMessages : [],
  470. ),
  471. }),
  472. currentSession: () => ({ sessionId: "root" }),
  473. onChanged: vi.fn(),
  474. });
  475. await flow.refresh();
  476. expect(flow.snapshot()).toMatchObject({
  477. summary: { total: 2 },
  478. members: [{ sessionId: "child-a" }, { sessionId: "child-b" }],
  479. });
  480. expect(transcript.snapshot().map((cell) => cell.id)).toEqual([
  481. "turn-task-answer",
  482. "turn-later-answer",
  483. ]);
  484. });
  485. it("keeps sequential task waves out of Transcript and in one live team projection", async () => {
  486. const transcript = new TranscriptStore([
  487. createTranscriptCell({
  488. id: "tool:turn-shared:call-a",
  489. kind: "tool",
  490. status: "succeeded",
  491. content: "Task A",
  492. turnId: "turn-shared",
  493. createdAtMs: 100,
  494. }),
  495. createTranscriptCell({
  496. id: "assistant-between-waves",
  497. kind: "assistant-preamble",
  498. status: "succeeded",
  499. content: "The first agent finished; starting another.",
  500. turnId: "turn-shared",
  501. createdAtMs: 200,
  502. }),
  503. createTranscriptCell({
  504. id: "tool:turn-shared:call-b",
  505. kind: "tool",
  506. status: "failed",
  507. content: "Task B",
  508. turnId: "turn-shared",
  509. createdAtMs: 300,
  510. }),
  511. createTranscriptCell({
  512. id: "later-turn",
  513. kind: "assistant",
  514. status: "succeeded",
  515. content: "Later output",
  516. turnId: "turn-later",
  517. createdAtMs: 500,
  518. }),
  519. ]);
  520. const flow = new TuiDelegationFlow({
  521. runtime: runtime({
  522. getDelegationSnapshot: vi.fn(async () => ({
  523. schemaVersion: 1 as const,
  524. rootSessionId: "root",
  525. members: [
  526. {
  527. sessionId: "child-a",
  528. parentSessionId: "root",
  529. status: "completed" as const,
  530. },
  531. {
  532. sessionId: "nested-a",
  533. parentSessionId: "child-a",
  534. status: "completed" as const,
  535. },
  536. {
  537. sessionId: "child-b",
  538. parentSessionId: "root",
  539. status: "failed" as const,
  540. },
  541. ],
  542. })),
  543. getMessages: vi.fn(async (sessionId: string) =>
  544. sessionId === "root"
  545. ? [
  546. {
  547. id: "call-message-a",
  548. turnId: "turn-shared",
  549. role: "assistant" as const,
  550. timestamp: 100,
  551. toolCalls: [{ id: "call-a", name: "task" }],
  552. },
  553. {
  554. turnId: "turn-shared",
  555. role: "unknown" as const,
  556. toolResult: {
  557. toolCallId: "call-a",
  558. toolName: "task",
  559. details: { subSessionId: "child-a" },
  560. },
  561. },
  562. {
  563. id: "call-message-b",
  564. turnId: "turn-shared",
  565. role: "assistant" as const,
  566. timestamp: 300,
  567. toolCalls: [{ id: "call-b", name: "task" }],
  568. },
  569. {
  570. turnId: "turn-shared",
  571. role: "unknown" as const,
  572. toolResult: {
  573. toolCallId: "call-b",
  574. toolName: "task",
  575. details: { subSessionId: "child-b" },
  576. },
  577. },
  578. ]
  579. : [],
  580. ),
  581. }),
  582. currentSession: () => ({ sessionId: "root" }),
  583. onChanged: vi.fn(),
  584. });
  585. await flow.refresh();
  586. expect(
  587. flow
  588. .snapshot()
  589. .members.map((member) => member.sessionId)
  590. .sort(),
  591. ).toEqual(["child-a", "child-b", "nested-a"]);
  592. expect(flow.snapshot().summary).toMatchObject({ done: 2, failed: 1 });
  593. expect(transcript.snapshot().map((cell) => cell.id)).toEqual([
  594. "tool:turn-shared:call-a",
  595. "assistant-between-waves",
  596. "tool:turn-shared:call-b",
  597. "later-turn",
  598. ]);
  599. });
  600. it("preserves an all-stopped team in the live snapshot", async () => {
  601. const transcript = new TranscriptStore();
  602. const flow = new TuiDelegationFlow({
  603. runtime: runtime({
  604. getDelegationSnapshot: vi.fn(async () => ({
  605. schemaVersion: 1 as const,
  606. rootSessionId: "root",
  607. members: [
  608. {
  609. sessionId: "child",
  610. parentSessionId: "root",
  611. status: "stopped" as const,
  612. },
  613. ],
  614. })),
  615. }),
  616. currentSession: () => ({ sessionId: "root" }),
  617. onChanged: vi.fn(),
  618. });
  619. await flow.refresh();
  620. expect(flow.snapshot().summary).toMatchObject({ total: 1, stopped: 1 });
  621. expect(transcript.snapshot()).toEqual([]);
  622. });
  623. it("updates a live team without touching later Transcript rows", async () => {
  624. const transcript = new TranscriptStore();
  625. const flow = new TuiDelegationFlow({
  626. runtime: runtime({
  627. getDelegationSnapshot: vi.fn(async () => ({
  628. schemaVersion: 1 as const,
  629. rootSessionId: "root",
  630. members: [
  631. {
  632. sessionId: "child-1",
  633. parentSessionId: "root",
  634. status: "running" as const,
  635. },
  636. ],
  637. })),
  638. getActiveRun: vi.fn(async () => ({
  639. schemaVersion: 1 as const,
  640. sessionId: "child-1",
  641. state: "running" as const,
  642. turnId: "turn-1",
  643. actions: { steer: false },
  644. })),
  645. }),
  646. currentSession: () => ({ sessionId: "root" }),
  647. onChanged: vi.fn(),
  648. });
  649. await flow.refresh();
  650. transcript.upsert(
  651. createTranscriptCell({
  652. id: "later-turn",
  653. kind: "assistant",
  654. status: "succeeded",
  655. content: "Later output",
  656. createdAtMs: 500,
  657. }),
  658. );
  659. await flow.handleRuntimeEvent({
  660. type: "permission.ask",
  661. timestampMs: 600,
  662. source: "runtime",
  663. sessionId: "child-1",
  664. request: {
  665. requestId: "permission-tail",
  666. sessionId: "child-1",
  667. toolName: "write",
  668. description: "Write a file",
  669. },
  670. });
  671. expect(flow.snapshot().members[0]).toMatchObject({
  672. status: "waiting",
  673. activity: "Waiting for approval",
  674. });
  675. expect(transcript.snapshot().map((cell) => cell.id)).toEqual([
  676. "later-turn",
  677. ]);
  678. flow.stop();
  679. });
  680. it("refreshes when a Runtime V2 visible task child is created under the active root", async () => {
  681. const runtimePort = runtime({
  682. getDelegationSnapshot: vi.fn(async () => ({
  683. schemaVersion: 1 as const,
  684. rootSessionId: "root",
  685. members: [],
  686. })),
  687. });
  688. const flow = new TuiDelegationFlow({
  689. runtime: runtimePort,
  690. currentSession: () => ({ sessionId: "root" }),
  691. onChanged: vi.fn(),
  692. });
  693. await flow.handleRuntimeEvent({
  694. type: "session.created",
  695. timestampMs: 100,
  696. source: "runtime",
  697. sessionId: "child-1",
  698. agentName: "verifier",
  699. sessionType: "branch",
  700. sessionKind: "task",
  701. visibility: "visible",
  702. parentSessionId: "root",
  703. });
  704. expect(runtimePort.getDelegationSnapshot).toHaveBeenCalledWith("root");
  705. });
  706. it("refreshes when a delegated agent creates a nested task child", async () => {
  707. const runtimePort = runtime({
  708. getDelegationSnapshot: vi
  709. .fn()
  710. .mockResolvedValueOnce({
  711. schemaVersion: 1,
  712. rootSessionId: "root",
  713. members: [
  714. {
  715. sessionId: "child-a",
  716. parentSessionId: "root",
  717. status: "running",
  718. },
  719. ],
  720. })
  721. .mockResolvedValueOnce({
  722. schemaVersion: 1,
  723. rootSessionId: "root",
  724. members: [],
  725. }),
  726. });
  727. const flow = new TuiDelegationFlow({
  728. runtime: runtimePort,
  729. currentSession: () => ({ sessionId: "root" }),
  730. onChanged: vi.fn(),
  731. });
  732. await flow.refresh();
  733. await flow.handleRuntimeEvent({
  734. type: "session.created",
  735. sessionId: "child-b",
  736. parentSessionId: "child-a",
  737. sessionType: "branch",
  738. sessionKind: "task",
  739. visibility: "visible",
  740. });
  741. expect(runtimePort.getDelegationSnapshot).toHaveBeenCalledTimes(2);
  742. });
  743. it("does not let a projection refresh failure break the Runtime event loop", async () => {
  744. const error = new Error("catalog unavailable");
  745. const onError = vi.fn();
  746. const flow = new TuiDelegationFlow({
  747. runtime: runtime({
  748. getDelegationSnapshot: vi.fn(async () => Promise.reject(error)),
  749. }),
  750. currentSession: () => ({ sessionId: "root" }),
  751. onChanged: vi.fn(),
  752. onError,
  753. });
  754. await expect(flow.refresh()).resolves.toBeUndefined();
  755. await expect(flow.refresh()).resolves.toBeUndefined();
  756. expect(onError).toHaveBeenCalledOnce();
  757. expect(onError).toHaveBeenCalledWith(error);
  758. });
  759. it("hydrates durable child activity after overflow and resumes without the stale anchor", async () => {
  760. const watchSessionTurn = vi.fn(async function* watchSessionTurn(
  761. _sessionId: string,
  762. _turnId: string,
  763. _signal: AbortSignal,
  764. options?: { afterMsgId?: string },
  765. ) {
  766. if (options?.afterMsgId) {
  767. yield { type: "resync-required" as const, turnId: "turn-1" };
  768. return;
  769. }
  770. yield {
  771. type: "delta" as const,
  772. turnId: "turn-1",
  773. toolCalls: [
  774. {
  775. id: "tool-1",
  776. name: "read",
  777. status: "started",
  778. input: { path: "packages/tui/src/tui/app.ts" },
  779. },
  780. ],
  781. };
  782. });
  783. const runtimePort = runtime({
  784. getDelegationSnapshot: vi.fn(async () => ({
  785. schemaVersion: 1 as const,
  786. rootSessionId: "root",
  787. members: [
  788. {
  789. sessionId: "child-1",
  790. parentSessionId: "root",
  791. agentName: "verifier",
  792. task: "Verify TUI",
  793. status: "running" as const,
  794. },
  795. ],
  796. })),
  797. getActiveRun: vi.fn(async () => ({
  798. schemaVersion: 1 as const,
  799. sessionId: "child-1",
  800. state: "running" as const,
  801. turnId: "turn-1",
  802. actions: { steer: false },
  803. })),
  804. getMessages: vi.fn(async () => [
  805. { id: "message-anchor", turnId: "turn-1", role: "assistant" as const },
  806. ]),
  807. watchSessionTurn,
  808. });
  809. const flow = new TuiDelegationFlow({
  810. runtime: runtimePort,
  811. currentSession: () => ({ sessionId: "root" }),
  812. onChanged: vi.fn(),
  813. });
  814. await flow.refresh();
  815. await vi.waitFor(() => {
  816. expect(flow.snapshot().members[0]).toMatchObject({
  817. activity: "Reading packages/tui/src/tui/app.ts",
  818. toolCount: 1,
  819. });
  820. });
  821. expect(watchSessionTurn).toHaveBeenNthCalledWith(
  822. 1,
  823. "child-1",
  824. "turn-1",
  825. expect.any(AbortSignal),
  826. { afterMsgId: "message-anchor" },
  827. );
  828. expect(watchSessionTurn).toHaveBeenNthCalledWith(
  829. 2,
  830. "child-1",
  831. "turn-1",
  832. expect.any(AbortSignal),
  833. );
  834. flow.stop();
  835. });
  836. it("restarts a child watcher when a same-turn stream closes before the Run is terminal", async () => {
  837. vi.useFakeTimers();
  838. const watchSessionTurn = vi.fn(async function* watchSessionTurn() {});
  839. const runtimePort = runtime({
  840. getDelegationSnapshot: vi.fn(async () => ({
  841. schemaVersion: 1 as const,
  842. rootSessionId: "root",
  843. members: [
  844. {
  845. sessionId: "child-1",
  846. parentSessionId: "root",
  847. status: "running" as const,
  848. },
  849. ],
  850. })),
  851. getActiveRun: vi.fn(async () => ({
  852. schemaVersion: 1 as const,
  853. sessionId: "child-1",
  854. state: "running" as const,
  855. turnId: "turn-1",
  856. actions: { steer: false },
  857. })),
  858. watchSessionTurn,
  859. });
  860. const flow = new TuiDelegationFlow({
  861. runtime: runtimePort,
  862. currentSession: () => ({ sessionId: "root" }),
  863. onChanged: vi.fn(),
  864. });
  865. await flow.refresh();
  866. await vi.waitFor(() => expect(watchSessionTurn).toHaveBeenCalledOnce());
  867. await vi.advanceTimersByTimeAsync(300);
  868. await vi.waitFor(() =>
  869. expect(watchSessionTurn.mock.calls.length).toBeGreaterThan(1),
  870. );
  871. flow.stop();
  872. });
  873. it("retries after stream and active Run inspection fail together", async () => {
  874. vi.useFakeTimers();
  875. const watchSessionTurn = vi.fn(async function* watchSessionTurn() {});
  876. const running = {
  877. schemaVersion: 1 as const,
  878. sessionId: "child-1",
  879. state: "running" as const,
  880. turnId: "turn-1",
  881. actions: { steer: false },
  882. };
  883. const getActiveRun = vi
  884. .fn()
  885. .mockResolvedValueOnce(running)
  886. .mockRejectedValueOnce(new Error("inspection unavailable"))
  887. .mockResolvedValue(running);
  888. const flow = new TuiDelegationFlow({
  889. runtime: runtime({
  890. getDelegationSnapshot: vi.fn(async () => ({
  891. schemaVersion: 1 as const,
  892. rootSessionId: "root",
  893. members: [
  894. {
  895. sessionId: "child-1",
  896. parentSessionId: "root",
  897. status: "running" as const,
  898. },
  899. ],
  900. })),
  901. getActiveRun,
  902. watchSessionTurn,
  903. }),
  904. currentSession: () => ({ sessionId: "root" }),
  905. onChanged: vi.fn(),
  906. });
  907. await flow.refresh();
  908. await vi.waitFor(() => expect(watchSessionTurn).toHaveBeenCalledOnce());
  909. await vi.advanceTimersByTimeAsync(300);
  910. await vi.waitFor(() =>
  911. expect(watchSessionTurn.mock.calls.length).toBeGreaterThan(1),
  912. );
  913. expect(getActiveRun.mock.calls.length).toBeGreaterThanOrEqual(3);
  914. flow.stop();
  915. });
  916. it("coalesces simultaneous child watcher retries into one team refresh", async () => {
  917. vi.useFakeTimers();
  918. const watchSessionTurn = vi.fn(async function* watchSessionTurn() {});
  919. const getDelegationSnapshot = vi.fn(async () => ({
  920. schemaVersion: 1 as const,
  921. rootSessionId: "root",
  922. members: ["child-1", "child-2"].map((sessionId) => ({
  923. sessionId,
  924. parentSessionId: "root",
  925. status: "running" as const,
  926. })),
  927. }));
  928. const flow = new TuiDelegationFlow({
  929. runtime: runtime({
  930. getDelegationSnapshot,
  931. getActiveRun: vi.fn(async (sessionId: string) => ({
  932. schemaVersion: 1 as const,
  933. sessionId,
  934. state: "running" as const,
  935. turnId: `turn-${sessionId}`,
  936. actions: { steer: false },
  937. })),
  938. watchSessionTurn,
  939. }),
  940. currentSession: () => ({ sessionId: "root" }),
  941. onChanged: vi.fn(),
  942. });
  943. await flow.refresh();
  944. await vi.waitFor(() => expect(watchSessionTurn).toHaveBeenCalledTimes(2));
  945. await vi.advanceTimersByTimeAsync(300);
  946. await vi.waitFor(() => expect(watchSessionTurn).toHaveBeenCalledTimes(4));
  947. expect(getDelegationSnapshot).toHaveBeenCalledTimes(2);
  948. flow.stop();
  949. });
  950. it("aborts child watchers when the active Session changes", async () => {
  951. let watcherSignal: AbortSignal | undefined;
  952. const runtimePort = runtime({
  953. getDelegationSnapshot: vi.fn(async () => ({
  954. schemaVersion: 1 as const,
  955. rootSessionId: "root",
  956. members: [
  957. {
  958. sessionId: "child-1",
  959. parentSessionId: "root",
  960. status: "running" as const,
  961. },
  962. ],
  963. })),
  964. getActiveRun: vi.fn(async () => ({
  965. schemaVersion: 1 as const,
  966. sessionId: "child-1",
  967. state: "running" as const,
  968. turnId: "turn-1",
  969. actions: { steer: false },
  970. })),
  971. watchSessionTurn: vi.fn(async function* watchSessionTurn(
  972. _sessionId: string,
  973. _turnId: string,
  974. signal: AbortSignal,
  975. ) {
  976. watcherSignal = signal;
  977. await new Promise<void>((resolve) =>
  978. signal.addEventListener("abort", () => resolve(), { once: true }),
  979. );
  980. yield* [];
  981. }),
  982. });
  983. const flow = new TuiDelegationFlow({
  984. runtime: runtimePort,
  985. currentSession: () => ({ sessionId: "root" }),
  986. onChanged: vi.fn(),
  987. });
  988. await flow.refresh();
  989. await vi.waitFor(() => expect(watcherSignal).toBeDefined());
  990. flow.reset();
  991. expect(watcherSignal?.aborted).toBe(true);
  992. });
  993. it("keeps a same-turn watcher alive across authoritative refreshes", async () => {
  994. let watcherSignal: AbortSignal | undefined;
  995. const runtimePort = runtime({
  996. getDelegationSnapshot: vi.fn(async () => ({
  997. schemaVersion: 1 as const,
  998. rootSessionId: "root",
  999. members: [
  1000. {
  1001. sessionId: "child-1",
  1002. parentSessionId: "root",
  1003. status: "running" as const,
  1004. },
  1005. ],
  1006. })),
  1007. getActiveRun: vi.fn(async () => ({
  1008. schemaVersion: 1 as const,
  1009. sessionId: "child-1",
  1010. state: "running" as const,
  1011. turnId: "turn-1",
  1012. actions: { steer: false },
  1013. })),
  1014. watchSessionTurn: vi.fn(async function* watchSessionTurn(
  1015. _sessionId: string,
  1016. _turnId: string,
  1017. signal: AbortSignal,
  1018. ) {
  1019. watcherSignal = signal;
  1020. await new Promise<void>((resolve) =>
  1021. signal.addEventListener("abort", () => resolve(), { once: true }),
  1022. );
  1023. yield* [];
  1024. }),
  1025. });
  1026. const flow = new TuiDelegationFlow({
  1027. runtime: runtimePort,
  1028. currentSession: () => ({ sessionId: "root" }),
  1029. onChanged: vi.fn(),
  1030. });
  1031. await flow.refresh();
  1032. await vi.waitFor(() => expect(watcherSignal).toBeDefined());
  1033. await flow.refresh();
  1034. expect(watcherSignal?.aborted).toBe(false);
  1035. expect(runtimePort.watchSessionTurn).toHaveBeenCalledOnce();
  1036. flow.stop();
  1037. });
  1038. it("publishes Runtime background work and refreshes changes to the full command", async () => {
  1039. const task = {
  1040. taskId: "bg-1",
  1041. kind: "bash" as const,
  1042. status: "failed" as const,
  1043. ownerSessionId: "root",
  1044. description: "pnpm test",
  1045. createdAtMs: 100,
  1046. updatedAtMs: 200,
  1047. startedAtMs: 110,
  1048. endedAtMs: 190,
  1049. lastError: "exit code 1",
  1050. };
  1051. const onBackgroundTasksChanged = vi.fn();
  1052. const runtimePort = runtime({
  1053. listBackgroundTasks: vi.fn(async () => [task]),
  1054. });
  1055. const flow = new TuiDelegationFlow({
  1056. runtime: runtimePort,
  1057. currentSession: () => ({ sessionId: "root" }),
  1058. onBackgroundTasksChanged,
  1059. onChanged: vi.fn(),
  1060. });
  1061. await flow.refresh();
  1062. expect(runtimePort.listBackgroundTasks).toHaveBeenCalledWith("root");
  1063. expect(onBackgroundTasksChanged).toHaveBeenLastCalledWith([task]);
  1064. const updated = { ...task, command: "pnpm test --filter regression" };
  1065. runtimePort.listBackgroundTasks = vi.fn(async () => [updated]);
  1066. await flow.refresh();
  1067. expect(onBackgroundTasksChanged).toHaveBeenLastCalledWith([updated]);
  1068. flow.stop();
  1069. });
  1070. it("polls background work for a newly created root Session before manual refresh", async () => {
  1071. vi.useFakeTimers();
  1072. const task = {
  1073. taskId: "bg-new-session",
  1074. kind: "bash" as const,
  1075. status: "running" as const,
  1076. ownerSessionId: "root",
  1077. description: "sleep 120",
  1078. createdAtMs: 100,
  1079. updatedAtMs: 200,
  1080. };
  1081. const listBackgroundTasks = vi.fn(async () => [task]);
  1082. const onBackgroundTasksChanged = vi.fn();
  1083. const flow = new TuiDelegationFlow({
  1084. runtime: runtime({ listBackgroundTasks }),
  1085. currentSession: () => ({ sessionId: "root" }),
  1086. onBackgroundTasksChanged,
  1087. onChanged: vi.fn(),
  1088. });
  1089. try {
  1090. await flow.handleRuntimeEvent({
  1091. type: "session.start",
  1092. timestampMs: 100,
  1093. source: "runtime",
  1094. sessionId: "root",
  1095. turnId: "root-turn",
  1096. queueItemIds: [],
  1097. });
  1098. expect(listBackgroundTasks).not.toHaveBeenCalled();
  1099. await vi.advanceTimersByTimeAsync(1_000);
  1100. expect(listBackgroundTasks).toHaveBeenCalledWith("root");
  1101. expect(onBackgroundTasksChanged).toHaveBeenLastCalledWith([task]);
  1102. } finally {
  1103. flow.stop();
  1104. vi.useRealTimers();
  1105. }
  1106. });
  1107. it("does not keep polling when only delivered terminal task history remains", async () => {
  1108. vi.useFakeTimers();
  1109. const listBackgroundTasks = vi.fn(async () => [
  1110. {
  1111. taskId: "bg-delivered",
  1112. kind: "bash" as const,
  1113. status: "succeeded" as const,
  1114. ownerSessionId: "root",
  1115. description: "completed validation",
  1116. createdAtMs: 100,
  1117. updatedAtMs: 300,
  1118. startedAtMs: 120,
  1119. endedAtMs: 250,
  1120. deliveredAtMs: 300,
  1121. },
  1122. ]);
  1123. const flow = new TuiDelegationFlow({
  1124. runtime: runtime({ listBackgroundTasks }),
  1125. currentSession: () => ({ sessionId: "root" }),
  1126. onChanged: vi.fn(),
  1127. });
  1128. try {
  1129. await flow.refresh();
  1130. expect(listBackgroundTasks).toHaveBeenCalledOnce();
  1131. await vi.advanceTimersByTimeAsync(5_000);
  1132. expect(listBackgroundTasks).toHaveBeenCalledOnce();
  1133. } finally {
  1134. flow.stop();
  1135. vi.useRealTimers();
  1136. }
  1137. });
  1138. it("opens one unified feature screen for Agent Team and Runtime background work", async () => {
  1139. const backgroundTask = {
  1140. taskId: "bg-1",
  1141. kind: "bash" as const,
  1142. status: "running" as const,
  1143. ownerSessionId: "root",
  1144. description: "pnpm test",
  1145. createdAtMs: 100,
  1146. updatedAtMs: 200,
  1147. };
  1148. const openSession = vi.fn(async () => undefined);
  1149. const taskClose = vi.fn(() => true);
  1150. const transcriptClose = vi.fn(() => true);
  1151. let screen:
  1152. | {
  1153. readonly id: string;
  1154. render(width: number): string[];
  1155. handleInput(data: string): void;
  1156. }
  1157. | undefined;
  1158. const pushFeature = vi.fn((input: { screen: typeof screen }) => {
  1159. screen = input.screen;
  1160. return {
  1161. id: input.screen?.id ?? "unknown",
  1162. close: input.screen?.id === "transcript" ? transcriptClose : taskClose,
  1163. isActive: () => true,
  1164. };
  1165. });
  1166. const flow = new TuiDelegationFlow({
  1167. runtime: runtime({
  1168. getDelegationSnapshot: vi.fn(async () => ({
  1169. schemaVersion: 1 as const,
  1170. rootSessionId: "root",
  1171. members: [
  1172. {
  1173. sessionId: "child-1",
  1174. parentSessionId: "root",
  1175. agentName: "reviewer",
  1176. task: "Review the implementation",
  1177. status: "running" as const,
  1178. createdAtMs: 100,
  1179. updatedAtMs: 200,
  1180. },
  1181. ],
  1182. })),
  1183. getActiveRun: vi.fn(async (sessionId: string) => ({
  1184. schemaVersion: 1 as const,
  1185. sessionId,
  1186. state: "running" as const,
  1187. turnId: "turn-child",
  1188. actions: { steer: false },
  1189. })),
  1190. getMessages: vi.fn(async () => [
  1191. {
  1192. id: "assistant-1",
  1193. turnId: "turn-child",
  1194. role: "assistant" as const,
  1195. content: "Child transcript response",
  1196. timestamp: 200,
  1197. },
  1198. ]),
  1199. listBackgroundTasks: vi.fn(async () => [backgroundTask]),
  1200. }),
  1201. currentSession: () => ({ sessionId: "root" }),
  1202. surfaceHost: { pushFeature } as never,
  1203. openSession,
  1204. onChanged: vi.fn(),
  1205. });
  1206. await flow.showTasks();
  1207. expect(pushFeature).toHaveBeenCalledOnce();
  1208. expect(screen?.id).toBe("background-work");
  1209. expect(screen?.render(100).join("\n")).toContain("reviewer");
  1210. expect(screen?.render(100).join("\n")).toContain("pnpm test");
  1211. screen?.handleInput("\r");
  1212. await vi.waitFor(() => expect(pushFeature).toHaveBeenCalledTimes(2));
  1213. expect(screen?.id).toBe("transcript");
  1214. screen?.handleInput("\r");
  1215. expect(
  1216. stripVTControlCharacters(screen?.render(100).join("\n") ?? ""),
  1217. ).toContain("Child transcript response");
  1218. expect(openSession).not.toHaveBeenCalled();
  1219. expect(taskClose).not.toHaveBeenCalled();
  1220. flow.stop();
  1221. });
  1222. it("does not open a stale Agent transcript after the task center closes", async () => {
  1223. let resolveMessages: ((messages: readonly []) => void) | undefined;
  1224. const getMessages = vi.fn(
  1225. async () =>
  1226. new Promise<readonly []>((resolve) => {
  1227. resolveMessages = resolve;
  1228. }),
  1229. );
  1230. let taskScreen:
  1231. | {
  1232. readonly id: string;
  1233. render(width: number): string[];
  1234. handleInput(data: string): void;
  1235. }
  1236. | undefined;
  1237. let taskScreenActive = true;
  1238. const pushFeature = vi.fn(
  1239. (input: {
  1240. screen:
  1241. | {
  1242. readonly id: string;
  1243. render(width: number): string[];
  1244. handleInput(data: string): void;
  1245. }
  1246. | undefined;
  1247. }) => {
  1248. taskScreen = input.screen;
  1249. return {
  1250. id: input.screen?.id ?? "unknown",
  1251. close: () => {
  1252. taskScreenActive = false;
  1253. return true;
  1254. },
  1255. isActive: () => taskScreenActive,
  1256. };
  1257. },
  1258. );
  1259. const flow = new TuiDelegationFlow({
  1260. runtime: runtime({
  1261. getDelegationSnapshot: vi.fn(async () => ({
  1262. schemaVersion: 1 as const,
  1263. rootSessionId: "root",
  1264. members: [
  1265. {
  1266. sessionId: "child-1",
  1267. parentSessionId: "root",
  1268. agentName: "reviewer",
  1269. task: "Review the implementation",
  1270. status: "running" as const,
  1271. },
  1272. ],
  1273. })),
  1274. getActiveRun: vi.fn(async (sessionId: string) => ({
  1275. schemaVersion: 1 as const,
  1276. sessionId,
  1277. state: "running" as const,
  1278. turnId: "turn-child",
  1279. actions: { steer: false },
  1280. })),
  1281. getMessages,
  1282. listBackgroundTasks: vi.fn(async () => []),
  1283. }),
  1284. currentSession: () => ({ sessionId: "root" }),
  1285. surfaceHost: { pushFeature } as never,
  1286. onChanged: vi.fn(),
  1287. });
  1288. await flow.showTasks();
  1289. taskScreen?.handleInput("\r");
  1290. await vi.waitFor(() =>
  1291. expect(getMessages).toHaveBeenCalledWith("child-1", 200),
  1292. );
  1293. taskScreen?.handleInput("\u001B");
  1294. resolveMessages?.([]);
  1295. await vi.waitFor(() => expect(taskScreenActive).toBe(false));
  1296. await new Promise((resolve) => setTimeout(resolve, 0));
  1297. expect(pushFeature).toHaveBeenCalledOnce();
  1298. flow.stop();
  1299. });
  1300. it("polls once more when the root Turn finishes during an older background task query", async () => {
  1301. vi.useFakeTimers();
  1302. const task = {
  1303. taskId: "bg-after-finish",
  1304. kind: "bash" as const,
  1305. status: "running" as const,
  1306. ownerSessionId: "root",
  1307. description: "pnpm test",
  1308. createdAtMs: 100,
  1309. updatedAtMs: 200,
  1310. };
  1311. let finishStalePoll:
  1312. | ((tasks: readonly (typeof task)[]) => void)
  1313. | undefined;
  1314. const listBackgroundTasks = vi
  1315. .fn()
  1316. .mockResolvedValueOnce([])
  1317. .mockImplementationOnce(
  1318. () =>
  1319. new Promise<readonly (typeof task)[]>((resolve) => {
  1320. finishStalePoll = resolve;
  1321. }),
  1322. )
  1323. .mockResolvedValueOnce([task]);
  1324. const onBackgroundTasksChanged = vi.fn();
  1325. const flow = new TuiDelegationFlow({
  1326. runtime: runtime({
  1327. getActiveRun: vi.fn(async (sessionId: string) => ({
  1328. schemaVersion: 1 as const,
  1329. sessionId,
  1330. state:
  1331. sessionId === "root" ? ("running" as const) : ("idle" as const),
  1332. actions: { steer: false },
  1333. })),
  1334. listBackgroundTasks,
  1335. }),
  1336. currentSession: () => ({ sessionId: "root" }),
  1337. onBackgroundTasksChanged,
  1338. onChanged: vi.fn(),
  1339. });
  1340. try {
  1341. await flow.refresh();
  1342. await vi.advanceTimersByTimeAsync(1_000);
  1343. expect(finishStalePoll).toBeTypeOf("function");
  1344. await flow.handleRuntimeEvent({
  1345. type: "session.finish",
  1346. timestampMs: 300,
  1347. source: "runtime",
  1348. sessionId: "root",
  1349. turnId: "root-turn",
  1350. queueItemIds: [],
  1351. });
  1352. finishStalePoll?.([]);
  1353. await vi.waitFor(() =>
  1354. expect(listBackgroundTasks).toHaveBeenCalledTimes(2),
  1355. );
  1356. await vi.advanceTimersByTimeAsync(1_000);
  1357. await vi.waitFor(() =>
  1358. expect(listBackgroundTasks).toHaveBeenCalledTimes(3),
  1359. );
  1360. expect(onBackgroundTasksChanged).toHaveBeenLastCalledWith([task]);
  1361. } finally {
  1362. flow.stop();
  1363. vi.useRealTimers();
  1364. }
  1365. });
  1366. it("finds the root team when opened from a nested child Session", async () => {
  1367. const transcript = new TranscriptStore();
  1368. const getSession = vi.fn(async (sessionId: string) => {
  1369. if (sessionId === "child-a") {
  1370. return {
  1371. sessionId,
  1372. parentSessionId: "root",
  1373. sessionType: "branch" as const,
  1374. sessionKind: "task",
  1375. visibility: "visible" as const,
  1376. };
  1377. }
  1378. return {
  1379. sessionId: "root",
  1380. sessionType: "root" as const,
  1381. visibility: "visible" as const,
  1382. };
  1383. });
  1384. const runtimePort = runtime({ getSession });
  1385. const flow = new TuiDelegationFlow({
  1386. runtime: runtimePort,
  1387. currentSession: () => ({
  1388. sessionId: "child-b",
  1389. parentSessionId: "child-a",
  1390. sessionType: "branch",
  1391. sessionKind: "task",
  1392. visibility: "visible",
  1393. }),
  1394. onChanged: vi.fn(),
  1395. });
  1396. await flow.refresh();
  1397. expect(getSession.mock.calls.map(([sessionId]) => sessionId)).toEqual([
  1398. "child-a",
  1399. "root",
  1400. ]);
  1401. expect(runtimePort.getDelegationSnapshot).toHaveBeenCalledWith("root");
  1402. expect(transcript.get("agent-team:root")).toBeUndefined();
  1403. expect(flow.agentCounts()).toEqual({ active: 0, total: 0 });
  1404. });
  1405. it("marks a child as waiting when its Runtime interaction blocks", async () => {
  1406. const runtimePort = runtime({
  1407. getDelegationSnapshot: vi.fn(async () => ({
  1408. schemaVersion: 1 as const,
  1409. rootSessionId: "root",
  1410. members: [
  1411. {
  1412. sessionId: "child-1",
  1413. parentSessionId: "root",
  1414. status: "running" as const,
  1415. },
  1416. ],
  1417. })),
  1418. getActiveRun: vi.fn(async () => ({
  1419. schemaVersion: 1 as const,
  1420. sessionId: "child-1",
  1421. state: "running" as const,
  1422. turnId: "turn-1",
  1423. actions: { steer: false },
  1424. })),
  1425. });
  1426. const flow = new TuiDelegationFlow({
  1427. runtime: runtimePort,
  1428. currentSession: () => ({ sessionId: "root" }),
  1429. onChanged: vi.fn(),
  1430. });
  1431. await flow.refresh();
  1432. await flow.handleRuntimeEvent({
  1433. type: "permission.ask",
  1434. timestampMs: 500,
  1435. source: "runtime",
  1436. sessionId: "child-1",
  1437. request: {
  1438. requestId: "permission-1",
  1439. sessionId: "child-1",
  1440. toolName: "write",
  1441. description: "Write a file",
  1442. },
  1443. });
  1444. expect(flow.snapshot().members[0]).toMatchObject({
  1445. status: "waiting",
  1446. activity: "Waiting for approval",
  1447. });
  1448. flow.stop();
  1449. });
  1450. });