tui-background-work-panel.test.ts 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429
  1. import { stripVTControlCharacters } from "node:util";
  2. import { describe, expect, it, vi } from "vitest";
  3. import { TuiBackgroundWorkPanel } from "../../src/tui/background-work/panel.js";
  4. import type { TuiBackgroundTask } from "../../src/runtime/port.js";
  5. import type { TuiAgentTeamSnapshot } from "../../src/tui/agent-team/model.js";
  6. import { TuiMainScreen } from '../../src/tui/engine/tui-main-screen.js';
  7. import { TuiOverlayRegularFeaturePresenter } from '../../src/tui/shell/regular-feature-presenter.js';
  8. import { TuiAltScreen } from "../../src/tui/engine/tui-alt-screen.js";
  9. import { VirtualTerminal } from "../pi-084-upstream/virtual-terminal.js";
  10. import { visibleWidth } from "../../src/tui/rendering/text.js";
  11. function teamSnapshot(): TuiAgentTeamSnapshot {
  12. return {
  13. rootSessionId: "root",
  14. capturedAtMs: 10_000,
  15. summary: {
  16. total: 1,
  17. running: 1,
  18. waiting: 0,
  19. queued: 0,
  20. done: 0,
  21. failed: 0,
  22. stopped: 0,
  23. },
  24. members: [
  25. {
  26. sessionId: "reviewer",
  27. parentSessionId: "root",
  28. agentName: "reviewer",
  29. task: "Review the implementation",
  30. status: "running",
  31. phase: "tool",
  32. activity: "Reading task-panel.ts",
  33. toolCount: 2,
  34. turnId: "turn-reviewer",
  35. startedAtMs: 1_000,
  36. updatedAtMs: 9_000,
  37. },
  38. ],
  39. };
  40. }
  41. function backgroundTasks(): readonly TuiBackgroundTask[] {
  42. return [
  43. {
  44. taskId: "bg-running",
  45. kind: "bash",
  46. status: "running",
  47. ownerSessionId: "root",
  48. description: "pnpm typecheck",
  49. createdAtMs: 2_000,
  50. updatedAtMs: 9_000,
  51. startedAtMs: 3_000,
  52. },
  53. {
  54. taskId: "bg-failed",
  55. kind: "bash",
  56. status: "failed",
  57. ownerSessionId: "root",
  58. description: "build docs",
  59. createdAtMs: 1_000,
  60. updatedAtMs: 8_000,
  61. startedAtMs: 2_000,
  62. endedAtMs: 8_000,
  63. lastError: "exit code 1\n\u001B]8;;https://example.com\u0007unsafe",
  64. },
  65. {
  66. taskId: "bg-delivered",
  67. kind: "bash",
  68. status: "succeeded",
  69. ownerSessionId: "root",
  70. description: "completed validation",
  71. createdAtMs: 500,
  72. updatedAtMs: 7_000,
  73. startedAtMs: 600,
  74. endedAtMs: 6_000,
  75. deliveredAtMs: 7_000,
  76. },
  77. ];
  78. }
  79. describe("TuiBackgroundWorkPanel", () => {
  80. it("renders one unified list for Agent Team and Runtime background tasks", () => {
  81. const agentTeam = vi.fn(teamSnapshot);
  82. const panel = new TuiBackgroundWorkPanel({
  83. agentTeam,
  84. backgroundTasks,
  85. activeSessionId: () => "root",
  86. onOpenAgent: vi.fn(),
  87. onCancel: vi.fn(),
  88. requestRender: vi.fn(),
  89. });
  90. const rendered = stripVTControlCharacters(panel.render(100).join("\n"));
  91. expect(rendered).toContain("Tasks");
  92. expect(rendered).toContain("4 total · 2 active · 1 failed");
  93. expect(rendered).toContain("[Agent] reviewer");
  94. expect(rendered).toContain("Reading task-panel.ts");
  95. expect(rendered).toContain("[Bash] pnpm typecheck");
  96. expect(rendered).toContain("[Bash] build docs");
  97. expect(rendered).toContain("[Bash] completed validation");
  98. expect(rendered).toContain("Enter open transcript");
  99. expect(agentTeam).toHaveBeenCalledOnce();
  100. });
  101. it("opens Agent transcripts and inspects Runtime task details without mutating them", () => {
  102. const onOpenAgent = vi.fn();
  103. const requestRender = vi.fn();
  104. const panel = new TuiBackgroundWorkPanel({
  105. agentTeam: teamSnapshot,
  106. backgroundTasks,
  107. activeSessionId: () => "root",
  108. onOpenAgent,
  109. onCancel: vi.fn(),
  110. requestRender,
  111. });
  112. panel.handleInput("\r");
  113. expect(onOpenAgent).toHaveBeenCalledWith("reviewer");
  114. panel.handleInput("\u001B[B");
  115. panel.handleInput("\r");
  116. let rendered = stripVTControlCharacters(panel.render(80).join("\n"));
  117. expect(rendered).toContain("Background task · Running");
  118. expect(rendered).toContain("pnpm typecheck");
  119. expect(rendered).toContain("bg-running");
  120. panel.handleInput("\u001B");
  121. rendered = stripVTControlCharacters(panel.render(80).join("\n"));
  122. expect(rendered).toContain("[Agent] reviewer");
  123. expect(rendered).toContain("[Bash] pnpm typecheck");
  124. expect(requestRender).toHaveBeenCalled();
  125. panel.handleInput("\u001B[B");
  126. panel.handleInput("\r");
  127. rendered = stripVTControlCharacters(panel.render(80).join("\n"));
  128. expect(rendered).toContain("Background task · Failed");
  129. expect(rendered).toContain("exit code 1");
  130. expect(rendered).toContain("unsafe");
  131. expect(rendered).not.toContain("https://example.com");
  132. });
  133. it("keeps the full multiline command, task ID and failure reason readable at narrow widths", () => {
  134. const command = `printf "开始"\n${"x".repeat(140)}\n\n echo "command-end"`;
  135. const task = {
  136. ...backgroundTasks()[1]!,
  137. taskId: `bg-${"a".repeat(50)}`,
  138. description: "short summary...",
  139. command: `${command}\u001B]52;c;Y2xpcGJvYXJk\u0007`,
  140. lastError: `exit code 1\n${"e".repeat(130)}\nPermission denied at error-end`,
  141. };
  142. const panel = new TuiBackgroundWorkPanel({
  143. agentTeam: teamSnapshot,
  144. backgroundTasks: () => [task],
  145. activeSessionId: () => "root",
  146. onOpenAgent: vi.fn(),
  147. onCancel: vi.fn(),
  148. requestRender: vi.fn(),
  149. });
  150. panel.handleInput("\u001B[B");
  151. expect(stripVTControlCharacters(panel.render(60).join("\n"))).toContain(
  152. "short summary...",
  153. );
  154. panel.handleInput("\r");
  155. for (const width of [16, 24, 40, 80, 120]) {
  156. const lines = panel.render(width);
  157. expect(lines.every((line) => visibleWidth(line) <= width)).toBe(true);
  158. const body = lines.map((line) =>
  159. stripVTControlCharacters(line)
  160. .replace(/^│ | │$/gu, "")
  161. .trimEnd(),
  162. );
  163. const text = body.join("\n");
  164. expect(text).not.toContain("short summary...");
  165. expect(text).not.toContain("Y2xpcGJvYXJk");
  166. expect(text).not.toContain("…");
  167. expect(text.replace(/\s/gu, "")).toContain(
  168. task.lastError.replace(/\s/gu, ""),
  169. );
  170. expect(text.replace(/\s/gu, "")).toContain(command.replace(/\s/gu, ""));
  171. expect(text.replace(/\s/gu, "")).toContain(task.taskId);
  172. }
  173. const wide = stripVTControlCharacters(panel.render(120).join("\n"));
  174. expect(wide).toContain(' echo "command-end"');
  175. expect(wide.indexOf("Error")).toBeLessThan(wide.indexOf("Command"));
  176. panel.handleInput("\u001B");
  177. expect(stripVTControlCharacters(panel.render(60).join("\n"))).toContain(
  178. "short summary...",
  179. );
  180. });
  181. it("pages through long details and returns to the selected task after resize", async () => {
  182. const terminal = new VirtualTerminal(60, 16);
  183. const tui = new TuiAltScreen(terminal);
  184. const task = {
  185. ...backgroundTasks()[1]!,
  186. command: `${Array.from({ length: 50 }, (_, i) => `echo line-${i}`).join("\n")}\necho command-end`,
  187. };
  188. const panel = new TuiBackgroundWorkPanel({
  189. agentTeam: teamSnapshot,
  190. backgroundTasks: () => [task],
  191. activeSessionId: () => "root",
  192. onOpenAgent: vi.fn(),
  193. onCancel: vi.fn(),
  194. requestRender: () => tui.requestRender(),
  195. });
  196. tui.setLayoutRoot(panel.layoutRoot);
  197. tui.setFocus(panel);
  198. tui.start();
  199. try {
  200. await terminal.waitForRender();
  201. terminal.sendInput("\u001B[B");
  202. terminal.sendInput("\r");
  203. await terminal.waitForRender();
  204. expect(terminal.getViewport().join("\n")).toContain("exit code 1");
  205. for (let i = 0; i < 15; i++) {
  206. terminal.sendInput("\u001B[6~");
  207. await terminal.waitForRender();
  208. }
  209. expect(terminal.getViewport().join("\n")).toContain("command-end");
  210. terminal.resize(40, 12);
  211. await terminal.waitForRender();
  212. for (let i = 0; i < 15; i++) {
  213. terminal.sendInput("\u001B[6~");
  214. await terminal.waitForRender();
  215. }
  216. expect(terminal.getViewport().join("\n")).toContain("command-end");
  217. terminal.sendInput("\u001B[5~");
  218. await terminal.waitForRender();
  219. expect(terminal.getViewport().join("\n")).not.toContain("command-end");
  220. terminal.sendInput("\u001B");
  221. await terminal.waitForRender();
  222. expect(terminal.getViewport().join("\n")).toContain("[Bash] build docs");
  223. terminal.sendInput("\r");
  224. await terminal.waitForRender();
  225. expect(terminal.getViewport().join("\n")).toContain("exit code 1");
  226. } finally {
  227. tui.stop();
  228. }
  229. });
  230. it("labels legacy tasks without a full command as descriptions", () => {
  231. const panel = new TuiBackgroundWorkPanel({
  232. agentTeam: teamSnapshot,
  233. backgroundTasks,
  234. activeSessionId: () => "root",
  235. onOpenAgent: vi.fn(),
  236. onCancel: vi.fn(),
  237. requestRender: vi.fn(),
  238. });
  239. panel.handleInput("\u001B[B");
  240. panel.handleInput("\r");
  241. const text = stripVTControlCharacters(panel.render(80).join("\n"));
  242. expect(text).toContain("Description");
  243. expect(text).toContain("pnpm typecheck");
  244. expect(text).not.toContain("Command");
  245. });
  246. it("closes from the list, keeps detail escape local, and respects narrow widths", () => {
  247. const onCancel = vi.fn();
  248. const panel = new TuiBackgroundWorkPanel({
  249. agentTeam: teamSnapshot,
  250. backgroundTasks,
  251. activeSessionId: () => "root",
  252. onOpenAgent: vi.fn(),
  253. onCancel,
  254. requestRender: vi.fn(),
  255. });
  256. for (const width of [1, 8, 24, 40]) {
  257. expect(
  258. panel.render(width).every((line) => visibleWidth(line) <= width),
  259. ).toBe(true);
  260. }
  261. panel.handleInput("\u001B[B");
  262. panel.handleInput("\r");
  263. panel.handleInput("\u001B");
  264. expect(onCancel).not.toHaveBeenCalled();
  265. panel.handleInput("\u001B");
  266. expect(onCancel).toHaveBeenCalledOnce();
  267. });
  268. it("keeps a selected task visible and stable when Agent rows are inserted ahead of it", () => {
  269. let snapshot = teamSnapshot();
  270. const panel = new TuiBackgroundWorkPanel({
  271. agentTeam: () => snapshot,
  272. backgroundTasks,
  273. activeSessionId: () => "root",
  274. onOpenAgent: vi.fn(),
  275. onCancel: vi.fn(),
  276. requestRender: vi.fn(),
  277. });
  278. const viewport = (
  279. panel as unknown as {
  280. bodyViewport: {
  281. readonly scrollTop: number;
  282. updateLayout(
  283. contentHeight: number,
  284. viewportHeight: number,
  285. requestRender: () => void,
  286. ): void;
  287. };
  288. }
  289. ).bodyViewport;
  290. panel.render(80);
  291. panel.handleInput("\u001B[B");
  292. panel.handleInput("\u001B[B");
  293. viewport.updateLayout(3, 1, vi.fn());
  294. expect(viewport.scrollTop).toBe(2);
  295. snapshot = {
  296. ...snapshot,
  297. summary: { ...snapshot.summary, total: 4, running: 4 },
  298. members: [
  299. ...snapshot.members,
  300. ...["planner", "builder", "verifier"].map((sessionId) => ({
  301. ...snapshot.members[0]!,
  302. sessionId,
  303. agentName: sessionId,
  304. })),
  305. ],
  306. };
  307. panel.render(80);
  308. viewport.updateLayout(6, 1, vi.fn());
  309. expect(viewport.scrollTop).toBe(5);
  310. panel.handleInput("\r");
  311. expect(stripVTControlCharacters(panel.render(80).join("\n"))).toContain(
  312. "Background task · Failed",
  313. );
  314. });
  315. });
  316. describe('Tasks in the regular terminal viewport', () => {
  317. it.each([1, 8, 15])(
  318. 'keeps tasks reachable after shrinking by %i rows without leaking duplicate tasks into scrollback',
  319. async (shrinkRows) => {
  320. const terminal = new VirtualTerminal(80, 16);
  321. const tui = new TuiMainScreen(terminal);
  322. const chatLines = Array.from({ length: 40 }, (_, index) => `chat-line-${index}`);
  323. tui.addChild({ render: () => [...chatLines, 'COMPOSER', 'STATUS'], invalidate() {} });
  324. const tasks = Array.from({ length: 30 }, (_, index) => ({
  325. ...backgroundTasks()[0]!,
  326. taskId: `task-${index}`,
  327. description: `task-row-${String(index).padStart(2, '0')}`,
  328. }));
  329. const panel = new TuiBackgroundWorkPanel({
  330. agentTeam: () => ({ ...teamSnapshot(), members: [] }),
  331. backgroundTasks: () => tasks,
  332. activeSessionId: () => 'root',
  333. onOpenAgent: vi.fn(),
  334. onCancel: vi.fn(),
  335. requestRender: () => tui.requestRender(),
  336. });
  337. tui.start();
  338. try {
  339. await terminal.waitForRender();
  340. chatLines.splice(-shrinkRows);
  341. tui.renderNow();
  342. await terminal.flush();
  343. expect(terminal.getViewport()).toEqual(
  344. [...chatLines, 'COMPOSER', 'STATUS'].slice(-terminal.rows),
  345. );
  346. const presenter = new TuiOverlayRegularFeaturePresenter(terminal, tui, () =>
  347. tui.requestRender(),
  348. );
  349. let handle = presenter.show(panel, panel);
  350. tui.setFocus(handle.focus);
  351. tui.renderNow();
  352. await terminal.flush();
  353. expect(terminal.getViewport().join('\n')).toContain('Tasks');
  354. expect(terminal.getViewport().join('\n')).toContain('task-row-00');
  355. handle.close();
  356. tui.renderNow();
  357. await terminal.flush();
  358. expect(terminal.getViewport()).toEqual(
  359. [...chatLines, 'COMPOSER', 'STATUS'].slice(-terminal.rows),
  360. );
  361. expect(terminal.getScrollBuffer()).toEqual([...chatLines, 'COMPOSER', 'STATUS']);
  362. handle = presenter.show(panel, panel);
  363. tui.setFocus(handle.focus);
  364. tui.renderNow();
  365. await terminal.flush();
  366. const seen = new Set<string>();
  367. for (let index = 0; index < 30; index++) {
  368. chatLines.push(`live-chat-${index}`);
  369. tui.renderNow();
  370. await terminal.flush();
  371. const viewport = terminal.getViewport().join('\n');
  372. for (const match of viewport.matchAll(/task-row-\d+/g)) seen.add(match[0]);
  373. expect(viewport).toContain(`task-row-${String(index).padStart(2, '0')}`);
  374. expect(terminal.getScrollBuffer().slice(0, -terminal.rows).join('\n')).not.toContain(
  375. 'task-row-',
  376. );
  377. terminal.sendInput('\u001B[B');
  378. }
  379. expect(seen.size).toBe(30);
  380. terminal.sendInput('\u001B[6~');
  381. tui.renderNow();
  382. await terminal.flush();
  383. terminal.sendInput('\u001B[5~');
  384. tui.renderNow();
  385. await terminal.flush();
  386. terminal.resize(60, 12);
  387. await terminal.waitForRender();
  388. terminal.sendInput('\u001B[B');
  389. tui.renderNow();
  390. await terminal.flush();
  391. expect(terminal.getViewport().join('\n')).toContain('Tasks');
  392. handle.close();
  393. tui.renderNow();
  394. await terminal.flush();
  395. await vi.waitFor(async () => {
  396. await terminal.flush();
  397. expect(terminal.getScrollBuffer().join('\n')).not.toContain('task-row-');
  398. });
  399. for (const line of chatLines)
  400. expect(terminal.getScrollBuffer().filter((row) => row === line)).toHaveLength(1);
  401. expect(terminal.getViewport().join('\n')).toContain('STATUS');
  402. } finally {
  403. tui.stop();
  404. }
  405. },
  406. );
  407. });