toolsearch-terminal.ts 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. import { writeFile } from "node:fs/promises";
  2. import { createRequire } from "node:module";
  3. import { join } from "node:path";
  4. import { stripVTControlCharacters } from "node:util";
  5. import { pathToFileURL } from "node:url";
  6. import { spawn } from "node-pty";
  7. import type { createToolSearchCliFixture } from "./toolsearch-cli-process.js";
  8. /** 真实终端输入,不替换 TUI renderer、submit handler 或 runtime。 */
  9. export function startToolSearchTerminal(
  10. fixture: Awaited<ReturnType<typeof createToolSearchCliFixture>>,
  11. args: string[],
  12. ) {
  13. // 仓库中的 TUI 是外置 workspace 模块,依赖共享包的 TS 入口;沿用 tsx 解析源码导入。
  14. const tsx = pathToFileURL(createRequire(join(process.cwd(), "package.json")).resolve("tsx")).href;
  15. const terminal = spawn(
  16. process.execPath,
  17. ["--import", tsx, fixture.cliPath, "tui", ...args, "--no-browser", "--locale", "en-US"],
  18. {
  19. name: "xterm-256color",
  20. // 系统 ConPTY 会先关输出管道再回传退出码;使用 node-pty 自带版本保证退出事件完整。
  21. useConptyDll: process.platform === "win32",
  22. cols: 140,
  23. rows: 40,
  24. cwd: fixture.workspace,
  25. env: { ...fixture.env, TERM: "xterm-256color" },
  26. },
  27. );
  28. let output = "";
  29. let exited = false;
  30. terminal.onData((data) => {
  31. output += data;
  32. });
  33. const done = new Promise<number>((resolve) =>
  34. terminal.onExit(({ exitCode }) => {
  35. exited = true;
  36. resolve(exitCode);
  37. }),
  38. );
  39. return {
  40. done,
  41. output: () => stripVTControlCharacters(output),
  42. // ConPTY 的能力探测也会输出同步帧结束序列;只有输入框占位符才证明 TUI 已可输入。
  43. ready: () => stripVTControlCharacters(output).includes("Type a prompt"),
  44. frameCount: () => output.split("\x1b[?2026l").length - 1,
  45. write: (text: string) => terminal.write(text),
  46. async close() {
  47. if (!exited) terminal.kill();
  48. await done;
  49. const capture = process.env.E2E_PROVIDER_CAPTURE_PATH;
  50. if (capture) await writeFile(`${capture}.pty-${terminal.pid}.txt`, output);
  51. },
  52. };
  53. }