tool-execution-component.test.ts 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511
  1. import { join, resolve } from "node:path";
  2. import { Text, type TUI } from "@earendil-works/pi-tui";
  3. import { Type } from "typebox";
  4. import { beforeAll, describe, expect, test } from "vitest";
  5. import { getReadmePath } from "../src/config.ts";
  6. import type { ToolDefinition } from "../src/core/extensions/types.ts";
  7. import { type BashOperations, createBashToolDefinition } from "../src/core/tools/bash.ts";
  8. import { createReadTool, createReadToolDefinition } from "../src/core/tools/read.ts";
  9. import { createWriteToolDefinition } from "../src/core/tools/write.ts";
  10. import { ToolExecutionComponent } from "../src/modes/interactive/components/tool-execution.ts";
  11. import { initTheme } from "../src/modes/interactive/theme/theme.ts";
  12. import { stripAnsi } from "../src/utils/ansi.ts";
  13. function createBaseToolDefinition(name = "custom_tool"): ToolDefinition {
  14. return {
  15. name,
  16. label: name,
  17. description: "custom tool",
  18. parameters: Type.Any(),
  19. execute: async () => ({
  20. content: [{ type: "text", text: "ok" }],
  21. details: {},
  22. }),
  23. };
  24. }
  25. function createFakeTui(): TUI {
  26. return {
  27. requestRender: () => {},
  28. } as unknown as TUI;
  29. }
  30. describe("ToolExecutionComponent parity", () => {
  31. beforeAll(() => {
  32. initTheme("dark");
  33. });
  34. test("stacks custom call and result renderers like the old implementation", () => {
  35. const toolDefinition: ToolDefinition = {
  36. ...createBaseToolDefinition(),
  37. renderCall: () => new Text("custom call", 0, 0),
  38. renderResult: () => new Text("custom result", 0, 0),
  39. };
  40. const component = new ToolExecutionComponent(
  41. "custom_tool",
  42. "tool-1",
  43. {},
  44. {},
  45. toolDefinition,
  46. createFakeTui(),
  47. process.cwd(),
  48. );
  49. expect(stripAnsi(component.render(120).join("\n"))).toContain("custom call");
  50. component.updateResult(
  51. {
  52. content: [{ type: "text", text: "done" }],
  53. details: {},
  54. isError: false,
  55. },
  56. false,
  57. );
  58. const rendered = stripAnsi(component.render(120).join("\n"));
  59. expect(rendered).toContain("custom call");
  60. expect(rendered).toContain("custom result");
  61. });
  62. test("self-rendered empty tool rows take no layout space", () => {
  63. const toolDefinition: ToolDefinition = {
  64. ...createBaseToolDefinition(),
  65. renderShell: "self",
  66. renderCall: () => new Text("", 0, 0),
  67. renderResult: () => new Text("", 0, 0),
  68. };
  69. const component = new ToolExecutionComponent(
  70. "custom_tool",
  71. "tool-empty-self-render",
  72. {},
  73. {},
  74. toolDefinition,
  75. createFakeTui(),
  76. process.cwd(),
  77. );
  78. expect(component.render(120)).toEqual([]);
  79. component.updateResult(
  80. {
  81. content: [],
  82. details: {},
  83. isError: false,
  84. },
  85. false,
  86. );
  87. expect(component.render(120)).toEqual([]);
  88. });
  89. test("uses built-in rendering for built-in overrides without custom renderers", () => {
  90. const overrideDefinition: ToolDefinition = {
  91. ...createBaseToolDefinition("edit"),
  92. };
  93. const component = new ToolExecutionComponent(
  94. "edit",
  95. "tool-2",
  96. { path: "README.md", oldText: "before", newText: "after" },
  97. {},
  98. overrideDefinition,
  99. createFakeTui(),
  100. process.cwd(),
  101. );
  102. component.updateResult({ content: [], details: { diff: "+1 after", firstChangedLine: 1 }, isError: false });
  103. const rendered = stripAnsi(component.render(120).join("\n"));
  104. expect(rendered).toContain("edit");
  105. expect(rendered).toContain("README.md");
  106. expect(rendered).not.toContain(":1");
  107. });
  108. test("preserves legacy file_path rendering compatibility for built-in tools", () => {
  109. const component = new ToolExecutionComponent(
  110. "read",
  111. "tool-3",
  112. { file_path: "README.md" },
  113. {},
  114. undefined,
  115. createFakeTui(),
  116. process.cwd(),
  117. );
  118. const rendered = stripAnsi(component.render(120).join("\n"));
  119. expect(rendered).toContain("read");
  120. expect(rendered).toContain("README.md");
  121. });
  122. test("bash execute emits an initial empty partial update before output arrives", async () => {
  123. const updates: Array<{ content: Array<{ type: string; text?: string }>; details?: unknown }> = [];
  124. const operations: BashOperations = {
  125. exec: async () => {
  126. await new Promise((resolve) => setTimeout(resolve, 10));
  127. return { exitCode: 0 };
  128. },
  129. };
  130. const tool = createBashToolDefinition(process.cwd(), { operations });
  131. const promise = tool.execute(
  132. "tool-bash-1",
  133. { command: "sleep 10" },
  134. undefined,
  135. (update) => updates.push(update as { content: Array<{ type: string; text?: string }>; details?: unknown }),
  136. {} as never,
  137. );
  138. expect(updates).toEqual([{ content: [], details: undefined }]);
  139. await promise;
  140. });
  141. test("bash renderer does not duplicate final full output truncation details", async () => {
  142. const operations: BashOperations = {
  143. exec: async (_command, _cwd, { onData }) => {
  144. for (let i = 1; i <= 4000; i++) {
  145. onData(Buffer.from(`line-${String(i).padStart(4, "0")}\n`));
  146. }
  147. return { exitCode: 0 };
  148. },
  149. };
  150. const tool = createBashToolDefinition(process.cwd(), { operations });
  151. const result = await tool.execute(
  152. "tool-bash-1b",
  153. { command: "generate output" },
  154. undefined,
  155. undefined,
  156. {} as never,
  157. );
  158. const component = new ToolExecutionComponent(
  159. "bash",
  160. "tool-bash-1b",
  161. { command: "generate output" },
  162. {},
  163. tool,
  164. createFakeTui(),
  165. process.cwd(),
  166. );
  167. component.setExpanded(true);
  168. component.updateResult({ ...result, isError: false }, false);
  169. const rendered = stripAnsi(component.render(200).join("\n"));
  170. expect(rendered.match(/Full output:/g)?.length ?? 0).toBe(1);
  171. expect(rendered).toMatch(/line-4000[^\n]*\n[^\S\n]*\n \[Full output:/);
  172. expect(rendered).not.toMatch(/line-4000[^\n]*\n[^\S\n]*\n[^\S\n]*\n \[Full output:/);
  173. expect(rendered).toContain("Truncated: showing 2000 of 4000 lines");
  174. expect(rendered).not.toContain("[Showing lines 2001-4000 of 4000. Full output:");
  175. });
  176. test("does not duplicate built-in headers when passed the active built-in definition", () => {
  177. const component = new ToolExecutionComponent(
  178. "read",
  179. "tool-4",
  180. { path: "README.md" },
  181. {},
  182. createReadToolDefinition(process.cwd()),
  183. createFakeTui(),
  184. process.cwd(),
  185. );
  186. component.updateResult({ content: [{ type: "text", text: "hello" }], details: undefined, isError: false }, false);
  187. const rendered = stripAnsi(component.render(120).join("\n"));
  188. expect(rendered.match(/\bread\b/g)?.length ?? 0).toBe(1);
  189. });
  190. test("inherits missing built-in result renderer slot from the built-in tool", () => {
  191. const overrideDefinition: ToolDefinition = {
  192. ...createBaseToolDefinition("read"),
  193. renderCall: () => new Text("override call", 0, 0),
  194. };
  195. const component = new ToolExecutionComponent(
  196. "read",
  197. "tool-4b",
  198. { path: "notes.txt" },
  199. {},
  200. overrideDefinition,
  201. createFakeTui(),
  202. process.cwd(),
  203. );
  204. component.updateResult({ content: [{ type: "text", text: "hello" }], details: undefined, isError: false }, false);
  205. component.setExpanded(true);
  206. const rendered = stripAnsi(component.render(120).join("\n"));
  207. expect(rendered).toContain("override call");
  208. expect(rendered).toContain("hello");
  209. });
  210. test("inherits missing built-in call renderer slot from the built-in tool", () => {
  211. const overrideDefinition: ToolDefinition = {
  212. ...createBaseToolDefinition("read"),
  213. renderResult: () => new Text("override result", 0, 0),
  214. };
  215. const component = new ToolExecutionComponent(
  216. "read",
  217. "tool-4c",
  218. { path: "README.md" },
  219. {},
  220. overrideDefinition,
  221. createFakeTui(),
  222. process.cwd(),
  223. );
  224. component.updateResult({ content: [{ type: "text", text: "hello" }], details: undefined, isError: false }, false);
  225. const rendered = stripAnsi(component.render(120).join("\n"));
  226. expect(rendered).toContain("read");
  227. expect(rendered).toContain("README.md");
  228. expect(rendered).toContain("override result");
  229. });
  230. test("uses custom renderers for built-in overrides that reuse built-in definition parameters", () => {
  231. const builtInDefinition = createReadToolDefinition(process.cwd());
  232. const component = new ToolExecutionComponent(
  233. "read",
  234. "tool-4d",
  235. { path: "README.md" },
  236. {},
  237. {
  238. ...builtInDefinition,
  239. renderCall: () => new Text("override call", 0, 0),
  240. renderResult: () => new Text("override result", 0, 0),
  241. },
  242. createFakeTui(),
  243. process.cwd(),
  244. );
  245. component.updateResult({ content: [{ type: "text", text: "hello" }], details: undefined, isError: false }, false);
  246. const rendered = stripAnsi(component.render(120).join("\n"));
  247. expect(rendered).toContain("override call");
  248. expect(rendered).toContain("override result");
  249. expect(rendered).not.toContain("read README.md");
  250. });
  251. test("uses custom renderers for built-in overrides that reuse wrapped built-in tool parameters", () => {
  252. const builtInTool = createReadTool(process.cwd());
  253. const component = new ToolExecutionComponent(
  254. "read",
  255. "tool-4e",
  256. { path: "README.md" },
  257. {},
  258. {
  259. ...createBaseToolDefinition("read"),
  260. parameters: builtInTool.parameters,
  261. renderCall: () => new Text("wrapped override call", 0, 0),
  262. renderResult: () => new Text("wrapped override result", 0, 0),
  263. },
  264. createFakeTui(),
  265. process.cwd(),
  266. );
  267. component.updateResult({ content: [{ type: "text", text: "hello" }], details: undefined, isError: false }, false);
  268. const rendered = stripAnsi(component.render(120).join("\n"));
  269. expect(rendered).toContain("wrapped override call");
  270. expect(rendered).toContain("wrapped override result");
  271. });
  272. test("shares renderer state across custom call and result slots", () => {
  273. type RenderState = { token?: string };
  274. const toolDefinition: ToolDefinition<any, unknown, RenderState> = {
  275. ...createBaseToolDefinition(),
  276. renderCall: (_args, _theme, context) => {
  277. context.state.token ??= "shared-token";
  278. return new Text(`custom call ${context.state.token}`, 0, 0);
  279. },
  280. renderResult: (_result, _options, _theme, context) => {
  281. return new Text(`custom result ${context.state.token}`, 0, 0);
  282. },
  283. };
  284. const component = new ToolExecutionComponent(
  285. "custom_tool",
  286. "tool-5",
  287. {},
  288. {},
  289. toolDefinition,
  290. createFakeTui(),
  291. process.cwd(),
  292. );
  293. component.updateResult({ content: [{ type: "text", text: "done" }], details: {}, isError: false }, false);
  294. const rendered = stripAnsi(component.render(120).join("\n"));
  295. expect(rendered).toContain("custom call shared-token");
  296. expect(rendered).toContain("custom result shared-token");
  297. });
  298. test("exposes args in render result context", () => {
  299. const toolDefinition: ToolDefinition = {
  300. ...createBaseToolDefinition(),
  301. renderCall: () => new Text("call", 0, 0),
  302. renderResult: (_result, _options, _theme, context) =>
  303. new Text(`arg:${String((context.args as { foo: string }).foo)}`, 0, 0),
  304. };
  305. const component = new ToolExecutionComponent(
  306. "custom_tool",
  307. "tool-5b",
  308. { foo: "bar" },
  309. {},
  310. toolDefinition,
  311. createFakeTui(),
  312. process.cwd(),
  313. );
  314. component.updateResult({ content: [{ type: "text", text: "done" }], details: {}, isError: false }, false);
  315. const rendered = stripAnsi(component.render(120).join("\n"));
  316. expect(rendered).toContain("arg:bar");
  317. });
  318. test("falls back when custom renderers are absent", () => {
  319. const toolDefinition: ToolDefinition = {
  320. ...createBaseToolDefinition(),
  321. };
  322. const component = new ToolExecutionComponent(
  323. "custom_tool",
  324. "tool-6",
  325. { foo: "bar" },
  326. {},
  327. toolDefinition,
  328. createFakeTui(),
  329. process.cwd(),
  330. );
  331. component.updateResult({ content: [{ type: "text", text: "done" }], details: {}, isError: false }, false);
  332. const rendered = stripAnsi(component.render(120).join("\n"));
  333. expect(rendered).toContain("custom_tool");
  334. expect(rendered).toContain("done");
  335. });
  336. test("trims trailing blank display lines from write previews", () => {
  337. const component = new ToolExecutionComponent(
  338. "write",
  339. "tool-7",
  340. { path: "README.md", content: "one\ntwo\n" },
  341. {},
  342. createWriteToolDefinition(process.cwd()),
  343. createFakeTui(),
  344. process.cwd(),
  345. );
  346. const rendered = stripAnsi(component.render(120).join("\n"));
  347. expect(rendered).toContain("one");
  348. expect(rendered).toContain("two");
  349. expect(rendered).not.toContain("two\n\n");
  350. });
  351. test("trims trailing blank display lines from read results", () => {
  352. const component = new ToolExecutionComponent(
  353. "read",
  354. "tool-8",
  355. { path: "notes.txt" },
  356. {},
  357. createReadToolDefinition(process.cwd()),
  358. createFakeTui(),
  359. process.cwd(),
  360. );
  361. component.updateResult(
  362. { content: [{ type: "text", text: "one\ntwo\n" }], details: undefined, isError: false },
  363. false,
  364. );
  365. component.setExpanded(true);
  366. const rendered = stripAnsi(component.render(120).join("\n"));
  367. expect(rendered).toContain("one");
  368. expect(rendered).toContain("two");
  369. expect(rendered).not.toContain("two\n\n");
  370. });
  371. test("collapses ordinary read results until expanded", () => {
  372. const component = new ToolExecutionComponent(
  373. "read",
  374. "tool-ordinary-read-collapsed",
  375. { path: "notes.txt" },
  376. {},
  377. createReadToolDefinition(process.cwd()),
  378. createFakeTui(),
  379. process.cwd(),
  380. );
  381. component.updateResult(
  382. { content: [{ type: "text", text: "hidden content" }], details: undefined, isError: false },
  383. false,
  384. );
  385. const collapsed = stripAnsi(component.render(120).join("\n"));
  386. expect(collapsed).toContain("read");
  387. expect(collapsed).toContain("notes.txt");
  388. expect(collapsed).not.toContain("hidden content");
  389. component.setExpanded(true);
  390. const expanded = stripAnsi(component.render(120).join("\n"));
  391. expect(expanded).toContain("hidden content");
  392. });
  393. for (const scenario of [
  394. {
  395. title: "SKILL.md",
  396. path: join(process.cwd(), "attio", "SKILL.md"),
  397. content: "---\nname: attio\ndescription: CRM helper\n---\n\n# Hidden skill instructions",
  398. compact: "[skill] attio",
  399. hidden: "Hidden skill instructions",
  400. absent: "read skill attio",
  401. },
  402. {
  403. title: "AGENTS.md",
  404. path: join(process.cwd(), ".pi", "AGENTS.md"),
  405. content: "Hidden resource instructions",
  406. compact: "read resource .pi/AGENTS.md",
  407. hidden: "Hidden resource instructions",
  408. absent: undefined,
  409. },
  410. {
  411. title: "outside AGENTS.md",
  412. path: resolve(process.cwd(), "..", "AGENTS.md"),
  413. content: "Hidden outside resource instructions",
  414. compact: `read resource ${resolve(process.cwd(), "..", "AGENTS.md").replace(/\\/g, "/")}`,
  415. hidden: "Hidden outside resource instructions",
  416. absent: undefined,
  417. },
  418. {
  419. title: "Pi documentation",
  420. path: getReadmePath(),
  421. content: "Hidden docs content",
  422. compact: "read docs README.md",
  423. hidden: "Hidden docs content",
  424. absent: undefined,
  425. },
  426. ] as const) {
  427. test(`renders ${scenario.title} read results compactly until expanded`, () => {
  428. const component = new ToolExecutionComponent(
  429. "read",
  430. `tool-compact-${scenario.title}`,
  431. { path: scenario.path },
  432. {},
  433. createReadToolDefinition(process.cwd()),
  434. createFakeTui(),
  435. process.cwd(),
  436. );
  437. component.updateResult(
  438. { content: [{ type: "text", text: scenario.content }], details: undefined, isError: false },
  439. false,
  440. );
  441. const collapsed = stripAnsi(component.render(120).join("\n"));
  442. expect(collapsed.replace(/\s+/g, "")).toContain(scenario.compact.replace(/\s+/g, ""));
  443. expect(collapsed).not.toContain(scenario.hidden);
  444. if (scenario.absent) {
  445. expect(collapsed).not.toContain(scenario.absent);
  446. }
  447. component.setExpanded(true);
  448. const expanded = stripAnsi(component.render(120).join("\n"));
  449. expect(expanded).toContain(scenario.hidden);
  450. });
  451. }
  452. for (const scenario of [
  453. { title: "SKILL.md", path: join(process.cwd(), "attio", "SKILL.md"), compact: "[skill] attio:120-329" },
  454. { title: "Pi documentation", path: getReadmePath(), compact: "read docs README.md:120-329" },
  455. ] as const) {
  456. test(`shows the read line range in compact ${scenario.title} reads before the expand hint`, () => {
  457. const component = new ToolExecutionComponent(
  458. "read",
  459. `tool-compact-range-${scenario.title}`,
  460. { path: scenario.path, offset: 120, limit: 210 },
  461. {},
  462. createReadToolDefinition(process.cwd()),
  463. createFakeTui(),
  464. process.cwd(),
  465. );
  466. const collapsed = stripAnsi(component.render(120).join("\n"));
  467. expect(collapsed).toContain(scenario.compact);
  468. expect(collapsed.indexOf(":120-329")).toBeLessThan(collapsed.indexOf("to expand"));
  469. });
  470. }
  471. });