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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334
  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 { TuiAltScreen } from "../../src/tui/engine/tui-alt-screen.js";
  7. import { VirtualTerminal } from "../pi-084-upstream/virtual-terminal.js";
  8. import { visibleWidth } from "../../src/tui/rendering/text.js";
  9. function teamSnapshot(): TuiAgentTeamSnapshot {
  10. return {
  11. rootSessionId: "root",
  12. capturedAtMs: 10_000,
  13. summary: {
  14. total: 1,
  15. running: 1,
  16. waiting: 0,
  17. queued: 0,
  18. done: 0,
  19. failed: 0,
  20. stopped: 0,
  21. },
  22. members: [
  23. {
  24. sessionId: "reviewer",
  25. parentSessionId: "root",
  26. agentName: "reviewer",
  27. task: "Review the implementation",
  28. status: "running",
  29. phase: "tool",
  30. activity: "Reading task-panel.ts",
  31. toolCount: 2,
  32. turnId: "turn-reviewer",
  33. startedAtMs: 1_000,
  34. updatedAtMs: 9_000,
  35. },
  36. ],
  37. };
  38. }
  39. function backgroundTasks(): readonly TuiBackgroundTask[] {
  40. return [
  41. {
  42. taskId: "bg-running",
  43. kind: "bash",
  44. status: "running",
  45. ownerSessionId: "root",
  46. description: "pnpm typecheck",
  47. createdAtMs: 2_000,
  48. updatedAtMs: 9_000,
  49. startedAtMs: 3_000,
  50. },
  51. {
  52. taskId: "bg-failed",
  53. kind: "bash",
  54. status: "failed",
  55. ownerSessionId: "root",
  56. description: "build docs",
  57. createdAtMs: 1_000,
  58. updatedAtMs: 8_000,
  59. startedAtMs: 2_000,
  60. endedAtMs: 8_000,
  61. lastError: "exit code 1\n\u001B]8;;https://example.com\u0007unsafe",
  62. },
  63. {
  64. taskId: "bg-delivered",
  65. kind: "bash",
  66. status: "succeeded",
  67. ownerSessionId: "root",
  68. description: "completed validation",
  69. createdAtMs: 500,
  70. updatedAtMs: 7_000,
  71. startedAtMs: 600,
  72. endedAtMs: 6_000,
  73. deliveredAtMs: 7_000,
  74. },
  75. ];
  76. }
  77. describe("TuiBackgroundWorkPanel", () => {
  78. it("renders one unified list for Agent Team and Runtime background tasks", () => {
  79. const agentTeam = vi.fn(teamSnapshot);
  80. const panel = new TuiBackgroundWorkPanel({
  81. agentTeam,
  82. backgroundTasks,
  83. activeSessionId: () => "root",
  84. onOpenAgent: vi.fn(),
  85. onCancel: vi.fn(),
  86. requestRender: vi.fn(),
  87. });
  88. const rendered = stripVTControlCharacters(panel.render(100).join("\n"));
  89. expect(rendered).toContain("Tasks");
  90. expect(rendered).toContain("4 total · 2 active · 1 failed");
  91. expect(rendered).toContain("[Agent] reviewer");
  92. expect(rendered).toContain("Reading task-panel.ts");
  93. expect(rendered).toContain("[Bash] pnpm typecheck");
  94. expect(rendered).toContain("[Bash] build docs");
  95. expect(rendered).toContain("[Bash] completed validation");
  96. expect(rendered).toContain("Enter open transcript");
  97. expect(agentTeam).toHaveBeenCalledOnce();
  98. });
  99. it("opens Agent transcripts and inspects Runtime task details without mutating them", () => {
  100. const onOpenAgent = vi.fn();
  101. const requestRender = vi.fn();
  102. const panel = new TuiBackgroundWorkPanel({
  103. agentTeam: teamSnapshot,
  104. backgroundTasks,
  105. activeSessionId: () => "root",
  106. onOpenAgent,
  107. onCancel: vi.fn(),
  108. requestRender,
  109. });
  110. panel.handleInput("\r");
  111. expect(onOpenAgent).toHaveBeenCalledWith("reviewer");
  112. panel.handleInput("\u001B[B");
  113. panel.handleInput("\r");
  114. let rendered = stripVTControlCharacters(panel.render(80).join("\n"));
  115. expect(rendered).toContain("Background task · Running");
  116. expect(rendered).toContain("pnpm typecheck");
  117. expect(rendered).toContain("bg-running");
  118. panel.handleInput("\u001B");
  119. rendered = stripVTControlCharacters(panel.render(80).join("\n"));
  120. expect(rendered).toContain("[Agent] reviewer");
  121. expect(rendered).toContain("[Bash] pnpm typecheck");
  122. expect(requestRender).toHaveBeenCalled();
  123. panel.handleInput("\u001B[B");
  124. panel.handleInput("\r");
  125. rendered = stripVTControlCharacters(panel.render(80).join("\n"));
  126. expect(rendered).toContain("Background task · Failed");
  127. expect(rendered).toContain("exit code 1");
  128. expect(rendered).toContain("unsafe");
  129. expect(rendered).not.toContain("https://example.com");
  130. });
  131. it("keeps the full multiline command, task ID and failure reason readable at narrow widths", () => {
  132. const command = `printf "开始"\n${"x".repeat(140)}\n\n echo "command-end"`;
  133. const task = {
  134. ...backgroundTasks()[1]!,
  135. taskId: `bg-${"a".repeat(50)}`,
  136. description: "short summary...",
  137. command: `${command}\u001B]52;c;Y2xpcGJvYXJk\u0007`,
  138. lastError: `exit code 1\n${"e".repeat(130)}\nPermission denied at error-end`,
  139. };
  140. const panel = new TuiBackgroundWorkPanel({
  141. agentTeam: teamSnapshot,
  142. backgroundTasks: () => [task],
  143. activeSessionId: () => "root",
  144. onOpenAgent: vi.fn(),
  145. onCancel: vi.fn(),
  146. requestRender: vi.fn(),
  147. });
  148. panel.handleInput("\u001B[B");
  149. expect(stripVTControlCharacters(panel.render(60).join("\n"))).toContain(
  150. "short summary...",
  151. );
  152. panel.handleInput("\r");
  153. for (const width of [16, 24, 40, 80, 120]) {
  154. const lines = panel.render(width);
  155. expect(lines.every((line) => visibleWidth(line) <= width)).toBe(true);
  156. const body = lines.map((line) =>
  157. stripVTControlCharacters(line)
  158. .replace(/^│ | │$/gu, "")
  159. .trimEnd(),
  160. );
  161. const text = body.join("\n");
  162. expect(text).not.toContain("short summary...");
  163. expect(text).not.toContain("Y2xpcGJvYXJk");
  164. expect(text).not.toContain("…");
  165. expect(text.replace(/\s/gu, "")).toContain(
  166. task.lastError.replace(/\s/gu, ""),
  167. );
  168. expect(text.replace(/\s/gu, "")).toContain(command.replace(/\s/gu, ""));
  169. expect(text.replace(/\s/gu, "")).toContain(task.taskId);
  170. }
  171. const wide = stripVTControlCharacters(panel.render(120).join("\n"));
  172. expect(wide).toContain(' echo "command-end"');
  173. expect(wide.indexOf("Error")).toBeLessThan(wide.indexOf("Command"));
  174. panel.handleInput("\u001B");
  175. expect(stripVTControlCharacters(panel.render(60).join("\n"))).toContain(
  176. "short summary...",
  177. );
  178. });
  179. it("pages through long details and returns to the selected task after resize", async () => {
  180. const terminal = new VirtualTerminal(60, 16);
  181. const tui = new TuiAltScreen(terminal);
  182. const task = {
  183. ...backgroundTasks()[1]!,
  184. command: `${Array.from({ length: 50 }, (_, i) => `echo line-${i}`).join("\n")}\necho command-end`,
  185. };
  186. const panel = new TuiBackgroundWorkPanel({
  187. agentTeam: teamSnapshot,
  188. backgroundTasks: () => [task],
  189. activeSessionId: () => "root",
  190. onOpenAgent: vi.fn(),
  191. onCancel: vi.fn(),
  192. requestRender: () => tui.requestRender(),
  193. });
  194. tui.setLayoutRoot(panel.layoutRoot);
  195. tui.setFocus(panel);
  196. tui.start();
  197. try {
  198. await terminal.waitForRender();
  199. terminal.sendInput("\u001B[B");
  200. terminal.sendInput("\r");
  201. await terminal.waitForRender();
  202. expect(terminal.getViewport().join("\n")).toContain("exit code 1");
  203. for (let i = 0; i < 15; i++) {
  204. terminal.sendInput("\u001B[6~");
  205. await terminal.waitForRender();
  206. }
  207. expect(terminal.getViewport().join("\n")).toContain("command-end");
  208. terminal.resize(40, 12);
  209. await terminal.waitForRender();
  210. for (let i = 0; i < 15; i++) {
  211. terminal.sendInput("\u001B[6~");
  212. await terminal.waitForRender();
  213. }
  214. expect(terminal.getViewport().join("\n")).toContain("command-end");
  215. terminal.sendInput("\u001B[5~");
  216. await terminal.waitForRender();
  217. expect(terminal.getViewport().join("\n")).not.toContain("command-end");
  218. terminal.sendInput("\u001B");
  219. await terminal.waitForRender();
  220. expect(terminal.getViewport().join("\n")).toContain("[Bash] build docs");
  221. terminal.sendInput("\r");
  222. await terminal.waitForRender();
  223. expect(terminal.getViewport().join("\n")).toContain("exit code 1");
  224. } finally {
  225. tui.stop();
  226. }
  227. });
  228. it("labels legacy tasks without a full command as descriptions", () => {
  229. const panel = new TuiBackgroundWorkPanel({
  230. agentTeam: teamSnapshot,
  231. backgroundTasks,
  232. activeSessionId: () => "root",
  233. onOpenAgent: vi.fn(),
  234. onCancel: vi.fn(),
  235. requestRender: vi.fn(),
  236. });
  237. panel.handleInput("\u001B[B");
  238. panel.handleInput("\r");
  239. const text = stripVTControlCharacters(panel.render(80).join("\n"));
  240. expect(text).toContain("Description");
  241. expect(text).toContain("pnpm typecheck");
  242. expect(text).not.toContain("Command");
  243. });
  244. it("closes from the list, keeps detail escape local, and respects narrow widths", () => {
  245. const onCancel = vi.fn();
  246. const panel = new TuiBackgroundWorkPanel({
  247. agentTeam: teamSnapshot,
  248. backgroundTasks,
  249. activeSessionId: () => "root",
  250. onOpenAgent: vi.fn(),
  251. onCancel,
  252. requestRender: vi.fn(),
  253. });
  254. for (const width of [1, 8, 24, 40]) {
  255. expect(
  256. panel.render(width).every((line) => visibleWidth(line) <= width),
  257. ).toBe(true);
  258. }
  259. panel.handleInput("\u001B[B");
  260. panel.handleInput("\r");
  261. panel.handleInput("\u001B");
  262. expect(onCancel).not.toHaveBeenCalled();
  263. panel.handleInput("\u001B");
  264. expect(onCancel).toHaveBeenCalledOnce();
  265. });
  266. it("keeps a selected task visible and stable when Agent rows are inserted ahead of it", () => {
  267. let snapshot = teamSnapshot();
  268. const panel = new TuiBackgroundWorkPanel({
  269. agentTeam: () => snapshot,
  270. backgroundTasks,
  271. activeSessionId: () => "root",
  272. onOpenAgent: vi.fn(),
  273. onCancel: vi.fn(),
  274. requestRender: vi.fn(),
  275. });
  276. const viewport = (
  277. panel as unknown as {
  278. bodyViewport: {
  279. readonly scrollTop: number;
  280. updateLayout(
  281. contentHeight: number,
  282. viewportHeight: number,
  283. requestRender: () => void,
  284. ): void;
  285. };
  286. }
  287. ).bodyViewport;
  288. panel.render(80);
  289. panel.handleInput("\u001B[B");
  290. panel.handleInput("\u001B[B");
  291. viewport.updateLayout(3, 1, vi.fn());
  292. expect(viewport.scrollTop).toBe(2);
  293. snapshot = {
  294. ...snapshot,
  295. summary: { ...snapshot.summary, total: 4, running: 4 },
  296. members: [
  297. ...snapshot.members,
  298. ...["planner", "builder", "verifier"].map((sessionId) => ({
  299. ...snapshot.members[0]!,
  300. sessionId,
  301. agentName: sessionId,
  302. })),
  303. ],
  304. };
  305. panel.render(80);
  306. viewport.updateLayout(6, 1, vi.fn());
  307. expect(viewport.scrollTop).toBe(5);
  308. panel.handleInput("\r");
  309. expect(stripVTControlCharacters(panel.render(80).join("\n"))).toContain(
  310. "Background task · Failed",
  311. );
  312. });
  313. });