tui-subagents.test.ts 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444
  1. import assert from "node:assert/strict";
  2. import { test } from "node:test";
  3. import React from "react";
  4. import { createTestRenderer } from "@mbears/opentui-core/testing";
  5. import type { ScrollBoxRenderable } from "@mbears/opentui-core";
  6. import {
  7. createSessionEvent,
  8. createSessionId,
  9. SessionEventType,
  10. type SessionEvent,
  11. } from "@zcode/contracts";
  12. import type { ZCodeSessionSubagentsResult } from "@zcode/shared";
  13. import { getZCodeCopy } from "@zcode/i18n";
  14. import { runTuiWithRenderer } from "../../tui/src/tui.js";
  15. import {
  16. applyMainSessionEvent,
  17. isMainSessionEvent,
  18. } from "../../tui/src/app-session-event-handler.js";
  19. import {
  20. applySubagentTranscriptEvent,
  21. hydrateSubagentTranscript,
  22. } from "../../tui/src/app-subagent-transcript.js";
  23. import type { TuiOptions, TuiSubagentTranscriptSnapshot } from "../../tui/src/types.js";
  24. const parent = createSessionId("parent");
  25. const child = createSessionId("child");
  26. const child2 = createSessionId("child2");
  27. const event = (
  28. type: SessionEvent["type"],
  29. sessionId = child,
  30. payload: Record<string, unknown> = {},
  31. sequenceNumber = 1,
  32. ) => createSessionEvent(type, sessionId, payload, { sequenceNumber });
  33. const stream = (delta: string, sequenceNumber: number, sessionId = child) =>
  34. event(
  35. SessionEventType.ModelStreaming,
  36. sessionId,
  37. { kind: "text_delta", assistantMessageId: "answer", delta },
  38. sequenceNumber,
  39. );
  40. const directory: ZCodeSessionSubagentsResult = {
  41. revision: 1,
  42. childSessionIds: [child, child2],
  43. running: [child, child2].map((id, index) => ({
  44. childSessionId: id,
  45. title: index ? "Review tests" : "Inspect auth",
  46. status: "running",
  47. subagentType: "Explore",
  48. })),
  49. ended: { total: 0, items: [] },
  50. };
  51. const snapshot = (sessionId = child): TuiSubagentTranscriptSnapshot => ({
  52. sessionId,
  53. sequenceNumber: 2,
  54. messages: [],
  55. replayMessageIds: ["answer"],
  56. events: [
  57. event(SessionEventType.ModelStreaming, sessionId, {
  58. kind: "start",
  59. assistantMessageId: "answer",
  60. }),
  61. stream("Child answer", 2, sessionId),
  62. ],
  63. });
  64. test("main admission rejects raw child events and parent-ID tool mirrors before any state changes", () => {
  65. let mutations = 0;
  66. const handlers = new Proxy(
  67. { copy: getZCodeCopy("en-US").tui, getMainSessionId: () => parent },
  68. {
  69. get(target, property) {
  70. return property in target
  71. ? Reflect.get(target, property)
  72. : () => {
  73. mutations++;
  74. };
  75. },
  76. },
  77. );
  78. for (const type of [
  79. SessionEventType.ToolCallScheduled,
  80. SessionEventType.ToolCallStarted,
  81. SessionEventType.ToolCallProgress,
  82. SessionEventType.ToolCallResult,
  83. SessionEventType.ToolCallError,
  84. ]) {
  85. const mirror = event(type, parent, {
  86. source: "subagent",
  87. childSessionId: child,
  88. toolCallId: "mirrored",
  89. toolName: "Bash",
  90. });
  91. assert.equal(isMainSessionEvent(mirror, parent), false);
  92. assert.equal(
  93. applyMainSessionEvent(
  94. mirror,
  95. new Set(),
  96. handlers as Parameters<typeof applyMainSessionEvent>[2],
  97. ),
  98. false,
  99. );
  100. assert.equal(isMainSessionEvent(event(type, child), parent), false);
  101. }
  102. assert.equal(mutations, 0);
  103. assert.equal(
  104. isMainSessionEvent(
  105. event(SessionEventType.ToolCallScheduled, parent, { toolName: "Agent" }),
  106. parent,
  107. ),
  108. true,
  109. );
  110. assert.equal(
  111. isMainSessionEvent(
  112. event(SessionEventType.SubagentSpawned, parent, { childSessionId: child }),
  113. parent,
  114. ),
  115. true,
  116. );
  117. });
  118. test("child history/live handoff deduplicates events and keeps other sessions isolated", () => {
  119. let state = hydrateSubagentTranscript(snapshot());
  120. state = applySubagentTranscriptEvent(state, stream("Child answer", 2));
  121. state = applySubagentTranscriptEvent(state, stream(" FOREIGN", 3, child2));
  122. state = applySubagentTranscriptEvent(state, stream(" live", 3));
  123. const text = state.messages
  124. .flatMap((message) => message.parts ?? [])
  125. .filter((part) => part.type === "text")
  126. .map((part) => part.text)
  127. .join("");
  128. assert.equal(text, "Child answer live");
  129. assert.equal(state.sequenceNumber, 3);
  130. });
  131. async function fixture(overrides: Partial<TuiOptions> = {}) {
  132. const environment = globalThis as typeof globalThis & { IS_REACT_ACT_ENVIRONMENT?: boolean };
  133. environment.IS_REACT_ACT_ENVIRONMENT = true;
  134. const terminal = await createTestRenderer({
  135. width: 145,
  136. height: 40,
  137. screenMode: "alternate-screen",
  138. useThread: false,
  139. });
  140. terminal.renderer.waitForThemeMode = async () => "dark";
  141. let sink: ((event: SessionEvent) => void) | undefined;
  142. let submitted = 0;
  143. let outcome!: Promise<number>;
  144. await React.act(async () => {
  145. outcome = runTuiWithRenderer(
  146. {
  147. noColor: true,
  148. locale: "en-US",
  149. stdin: process.stdin,
  150. stdout: process.stdout,
  151. stderr: process.stderr,
  152. getMainSessionId: () => parent,
  153. initialResult: { response: "Main answer" },
  154. readSubagents: async () => directory,
  155. readSubagentTranscript: async (id) => snapshot(id as typeof child),
  156. subscribeSessionEvents: (callback) => {
  157. sink = callback;
  158. return () => {
  159. sink = undefined;
  160. };
  161. },
  162. submitPrompt: async () => {
  163. submitted++;
  164. return { response: "unexpected submission" };
  165. },
  166. ...overrides,
  167. },
  168. terminal.renderer,
  169. );
  170. });
  171. const action = async (work: () => unknown) => {
  172. await React.act(async () => {
  173. await work();
  174. });
  175. await React.act(async () => {
  176. await terminal.flush();
  177. });
  178. await React.act(async () => {
  179. await terminal.flush();
  180. });
  181. };
  182. await action(() => terminal.renderOnce());
  183. return {
  184. ...terminal,
  185. action,
  186. emit: (e: SessionEvent) => sink?.(e),
  187. async expectText(pattern: RegExp) {
  188. // Markdown parsing runs in OpenTUI's worker. Wait for the visible result,
  189. // rather than assuming it finishes within a fixed number of paint frames.
  190. for (let attempt = 0; attempt < 100; attempt++) {
  191. const frame = terminal.captureCharFrame();
  192. if (pattern.test(frame)) return frame;
  193. await action(() => new Promise((resolve) => setTimeout(resolve, 10)));
  194. }
  195. const frame = terminal.captureCharFrame();
  196. assert.match(frame, pattern);
  197. return frame;
  198. },
  199. submitted: () => submitted,
  200. async click(id: string) {
  201. const target = terminal.renderer.root.findDescendantById(id);
  202. assert.ok(target, `Missing ${id}`);
  203. await action(() => terminal.mockMouse.click(target.x + 2, target.y));
  204. },
  205. async close() {
  206. await React.act(async () => {
  207. terminal.renderer.destroy();
  208. });
  209. await outcome;
  210. environment.IS_REACT_ACT_ENVIRONMENT = false;
  211. },
  212. };
  213. }
  214. test("native click opens read-only child output, streams independently and Escape restores the draft", async () => {
  215. const tui = await fixture();
  216. try {
  217. await tui.action(() => tui.mockInput.typeText("keep my draft"));
  218. await tui.action(() => {
  219. tui.emit(stream("leaked child text", 3));
  220. tui.emit(
  221. event(SessionEventType.ToolCallScheduled, parent, {
  222. source: "subagent",
  223. toolCallId: "mirror",
  224. toolName: "Bash",
  225. input: { command: "child-private-command" },
  226. }),
  227. );
  228. });
  229. assert.doesNotMatch(tui.captureCharFrame(), /leaked child|child-private-command/);
  230. await tui.click(`subagent-${child}`);
  231. await tui.expectText(/Child answer/);
  232. await tui.expectText(/Read-only/);
  233. assert.doesNotMatch(tui.captureCharFrame(), /keep my draft|Main answer/);
  234. await tui.action(() => {
  235. tui.emit(stream(" live update", 3));
  236. tui.emit(
  237. event(SessionEventType.AssistantMessage, parent, { content: "Main kept running" }, 5),
  238. );
  239. });
  240. await tui.expectText(/Child answer live update/);
  241. assert.doesNotMatch(tui.captureCharFrame(), /Main kept running/);
  242. await tui.action(() => tui.mockInput.typeText("should not edit"));
  243. await tui.action(() => tui.mockInput.pressEnter());
  244. assert.equal(tui.submitted(), 0);
  245. await tui.action(async () => {
  246. tui.mockInput.pressEscape();
  247. await new Promise((resolve) => setTimeout(resolve, 40));
  248. });
  249. await tui.expectText(/keep my draft/);
  250. await tui.expectText(/Main kept running/);
  251. assert.doesNotMatch(tui.captureCharFrame(), /should not edit|Child answer/);
  252. await tui.click(`subagent-${child2}`);
  253. await tui.click("subagent-back");
  254. await tui.expectText(/keep my draft/);
  255. } finally {
  256. await tui.close();
  257. }
  258. });
  259. test("late child loads cannot replace a different selected child or reopen after Back", async () => {
  260. let resolve!: (value: TuiSubagentTranscriptSnapshot) => void;
  261. const slow = new Promise<TuiSubagentTranscriptSnapshot>((r) => {
  262. resolve = r;
  263. });
  264. const tui = await fixture({
  265. readSubagentTranscript: async (id) =>
  266. id === child
  267. ? slow
  268. : {
  269. ...snapshot(child2),
  270. messages: [{ role: "agent", content: "Second child" }],
  271. events: [],
  272. replayMessageIds: [],
  273. },
  274. });
  275. try {
  276. await tui.click(`subagent-${child}`);
  277. await tui.click(`subagent-${child2}`);
  278. await tui.action(() => resolve(snapshot()));
  279. await tui.expectText(/Second child/);
  280. assert.doesNotMatch(tui.captureCharFrame(), /Child answer/);
  281. await tui.action(async () => {
  282. tui.mockInput.pressEscape();
  283. await new Promise((resolve) => setTimeout(resolve, 40));
  284. });
  285. await tui.expectText(/Main answer/);
  286. } finally {
  287. await tui.close();
  288. }
  289. });
  290. test("main scroll position survives child viewing while new main output arrives", async () => {
  291. const tui = await fixture({
  292. initialResult: {
  293. response: "",
  294. restoredMessages: Array.from({ length: 40 }, (_, i) => ({
  295. role: "user",
  296. content: `History entry ${i}`,
  297. })),
  298. },
  299. });
  300. try {
  301. const scroll = tui.renderer.root.findDescendantById("main-transcript") as ScrollBoxRenderable;
  302. await tui.action(() => scroll.scrollTo(12));
  303. const position = scroll.scrollTop;
  304. assert.ok(position > 0);
  305. await tui.click(`subagent-${child}`);
  306. await tui.action(() =>
  307. tui.emit(event(SessionEventType.AssistantMessage, parent, { content: "New main output" }, 8)),
  308. );
  309. await tui.click("subagent-back");
  310. assert.equal(scroll.scrollTop, position);
  311. } finally {
  312. await tui.close();
  313. }
  314. });
  315. test("events arriving during hydration are applied once above the snapshot watermark", async () => {
  316. let resolve!: (value: TuiSubagentTranscriptSnapshot) => void;
  317. const pending = new Promise<TuiSubagentTranscriptSnapshot>((r) => {
  318. resolve = r;
  319. });
  320. const tui = await fixture({ readSubagentTranscript: async () => pending });
  321. try {
  322. await tui.click(`subagent-${child}`);
  323. await tui.action(() => {
  324. tui.emit(stream("Child answer", 2));
  325. tui.emit(stream(" buffered", 3));
  326. });
  327. await tui.action(() => resolve(snapshot()));
  328. const frame = await tui.expectText(/Child answer buffered/);
  329. assert.equal(frame.split("Child answer").length - 1, 1);
  330. } finally {
  331. await tui.close();
  332. }
  333. });
  334. test("narrow sidebar overlay closes on selection and Back returns to the main view", async () => {
  335. const tui = await fixture();
  336. try {
  337. await tui.action(() => tui.resize(100, 30));
  338. assert.equal(tui.renderer.root.findDescendantById(`subagent-${child}`), undefined);
  339. await tui.action(() => tui.mockInput.pressKey("x", { ctrl: true }));
  340. await tui.action(() => tui.mockInput.pressKey("b"));
  341. await tui.click(`subagent-${child}`);
  342. await tui.expectText(/Child answer/);
  343. assert.equal(tui.renderer.root.findDescendantById(`subagent-${child}`), undefined);
  344. await tui.click("subagent-back");
  345. await tui.expectText(/Main answer/);
  346. } finally {
  347. await tui.close();
  348. }
  349. });
  350. test("switching main sessions clears selection and ignores the previous child's late snapshot", async () => {
  351. let current = parent;
  352. let resolve!: (value: TuiSubagentTranscriptSnapshot) => void;
  353. const pending = new Promise<TuiSubagentTranscriptSnapshot>((r) => {
  354. resolve = r;
  355. });
  356. const tui = await fixture({
  357. getMainSessionId: () => current,
  358. readSubagents: async () =>
  359. current === parent
  360. ? directory
  361. : { revision: 1, childSessionIds: [], running: [], ended: { total: 0, items: [] } },
  362. readSubagentTranscript: async () => pending,
  363. });
  364. try {
  365. await tui.click(`subagent-${child}`);
  366. await tui.action(() => {
  367. current = createSessionId("new-parent");
  368. tui.emit(event(SessionEventType.SessionCreated, current, { mode: "build" }));
  369. });
  370. await tui.action(() => resolve(snapshot()));
  371. assert.equal(tui.renderer.root.findDescendantById("subagent-view"), undefined);
  372. assert.doesNotMatch(tui.captureCharFrame(), /Inspect auth|Child answer/);
  373. } finally {
  374. await tui.close();
  375. }
  376. });
  377. test("child tools and final fallback output appear only in the child transcript", () => {
  378. let state = hydrateSubagentTranscript({
  379. sessionId: child,
  380. sequenceNumber: 0,
  381. messages: [],
  382. events: [],
  383. replayMessageIds: [],
  384. });
  385. state = applySubagentTranscriptEvent(
  386. state,
  387. event(
  388. SessionEventType.ToolCallScheduled,
  389. child,
  390. { toolCallId: "read", toolName: "Read", input: { file_path: "auth.ts" } },
  391. 1,
  392. ),
  393. );
  394. state = applySubagentTranscriptEvent(
  395. state,
  396. event(
  397. SessionEventType.ToolCallResult,
  398. child,
  399. { toolCallId: "read", result: { content: "private child tool output" } },
  400. 2,
  401. ),
  402. );
  403. state = applySubagentTranscriptEvent(
  404. state,
  405. event(SessionEventType.TurnComplete, child, { response: "Final child response" }, 3),
  406. );
  407. assert.equal(
  408. state.messages.flatMap((message) => message.parts ?? []).find((part) => part.type === "tool")
  409. ?.output,
  410. "private child tool output",
  411. );
  412. assert.equal(state.messages.at(-1)?.content, "Final child response");
  413. });
  414. test("cold multi-turn history does not replay old final replies", () => {
  415. const restored = hydrateSubagentTranscript({
  416. sessionId: child,
  417. sequenceNumber: 2,
  418. replayMessageIds: [],
  419. messages: [
  420. { id: "first", role: "agent", content: "First response" },
  421. { id: "second", role: "agent", content: "Second response" },
  422. ],
  423. events: [
  424. event(SessionEventType.TurnComplete, child, { response: "First response" }, 1),
  425. event(SessionEventType.TurnComplete, child, { response: "Second response" }, 2),
  426. ],
  427. });
  428. assert.deepEqual(
  429. restored.messages.map((message) => message.content),
  430. ["First response", "Second response"],
  431. );
  432. });