conversation-session-toolsearch-tui.test.ts 6.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166
  1. import { DatabaseSync } from "node:sqlite";
  2. import { join } from "node:path";
  3. import { mkdir, writeFile } from "node:fs/promises";
  4. import { createToolSearchCliFixture } from "#e2e/helpers/toolsearch-cli-process";
  5. import {
  6. ensureToolSearchTuiBuild,
  7. startToolSearchTerminal,
  8. } from "#e2e/helpers/toolsearch-terminal";
  9. import {
  10. TOOLSEARCH_NOTICE,
  11. TOOLSEARCH_DONE,
  12. toolSearchResponseStage,
  13. type ToolSearchRequest,
  14. } from "#e2e/helpers/toolsearch-provider";
  15. // 修复原因:wdio 的 Mocha 单 case 上限固定 120s,用例内 this.timeout 不生效(实测 this.timeout(300s) 仍在 120s 被截断)。
  16. // 本例要启动 3 次真实 TUI,Windows 上每次冷启动 20-80s(tsx 编译 TUI 源码约 10s + 启动数据加载约 10s,
  17. // 负载高时翻倍),三轮串在一个 it 里必然超过 120s。拆成共享同一 fixture/会话、顺序执行的三个 it,
  18. // 每轮独占一份 120s 预算,断言与原用例一致。
  19. describe("ToolSearch TUI 真实终端", () => {
  20. let fixture: Awaited<ReturnType<typeof createToolSearchCliFixture>>;
  21. let terminal: ReturnType<typeof startToolSearchTerminal> | undefined;
  22. let sessionId: string;
  23. const typeAndPaint = async (keys: string) => {
  24. const before = terminal!.frameCount();
  25. terminal!.write(keys);
  26. await browser.waitUntil(async () => terminal!.frameCount() > before, {
  27. timeout: 10_000,
  28. timeoutMsg: "TUI 按键后没有绘制新帧",
  29. });
  30. };
  31. const submit = async (value: string) => {
  32. // 动画也会触发重绘;仅等帧数会在输入状态尚未提交时按 Enter,导致旧文本回写。
  33. // 使用终端粘贴协议,并等待本次输入实际绘制,保持输入与提交的真实顺序。
  34. const before = terminal!.output().length;
  35. terminal!.write(`\x1b[200~${value}\x1b[201~`);
  36. await browser.waitUntil(async () => terminal!.output().slice(before).includes(value), {
  37. timeout: 10_000,
  38. timeoutMsg: "TUI 本次输入尚未绘制",
  39. });
  40. terminal!.write("\r");
  41. };
  42. const turn = async (args: string[], marker: string) => {
  43. const before = fixture.requests.length;
  44. const completed = `${TOOLSEARCH_DONE}_${marker}`;
  45. fixture.setResponse((body, response) => {
  46. const stage = toolSearchResponseStage(body);
  47. fixture.reply(
  48. body,
  49. response,
  50. stage === "done" ? `done-${marker.split("_").at(-1)!.toLowerCase()}` : stage,
  51. );
  52. });
  53. terminal = startToolSearchTerminal(fixture, args);
  54. await browser.waitUntil(async () => terminal!.ready(), {
  55. // 修复原因:全新 HOME 冷启动 TUI 实测 20-80s(见文件头说明),原 30s 不够。
  56. timeout: 100_000,
  57. timeoutMsg: "TUI 未完成首帧终端绘制",
  58. });
  59. const beforeModel = terminal.output().length;
  60. await submit("/model toolsearch-process/test-toolsearch");
  61. await browser.waitUntil(
  62. async () => {
  63. const rendered = terminal!.output().slice(beforeModel);
  64. // 终端增量绘制只会重画变化后缀;完整占位文字不一定再次出现在 PTY 流中。
  65. return rendered.includes("Model switched to toolsearch-process/test-toolsearch");
  66. },
  67. {
  68. timeout: 15_000,
  69. timeoutMsg: "TUI 未切换到隔离的普通 Anthropic provider",
  70. },
  71. );
  72. const beforeEffort = terminal.output().length;
  73. await submit("/effort disabled");
  74. await browser.waitUntil(
  75. async () => {
  76. const rendered = terminal!.output().slice(beforeEffort);
  77. return rendered.includes("Reasoning effort switched to disabled");
  78. },
  79. { timeout: 15_000, timeoutMsg: "TUI 未确认测试模型的思考档位" },
  80. );
  81. await submit(marker);
  82. await browser.waitUntil(async () => terminal!.output().includes(completed), {
  83. timeout: 30_000,
  84. timeoutMsg: "TUI 没有显示模型完成文本",
  85. });
  86. // 增量重绘只输出变化的字符,原始 PTY 文本不保证含完整退出提示;等新帧后确认退出。
  87. await typeAndPaint("\x03");
  88. terminal.write("\x03");
  89. expect(await terminal.done).toBe(0);
  90. await terminal.close();
  91. terminal = undefined;
  92. return fixture.requests
  93. .slice(before)
  94. .filter(({ body }) => body.tools?.length)
  95. .map(({ body }) => body);
  96. };
  97. const loaded = (body: ToolSearchRequest) => {
  98. expect(body.tools?.find((tool) => tool.name === "TodoRead")?.defer_loading).toBe(true);
  99. expect(JSON.stringify(body.messages)).toContain(
  100. '"type":"tool_reference","tool_name":"TodoRead"',
  101. );
  102. expect(JSON.stringify(body.messages).split(TOOLSEARCH_NOTICE)).toHaveLength(2);
  103. };
  104. // TUI 构建单独占一个 hook,不挤占 fixture 准备和首轮 TUI 冷启动的 120s 预算。
  105. before(async () => {
  106. await ensureToolSearchTuiBuild();
  107. });
  108. before(async () => {
  109. fixture = await createToolSearchCliFixture("conversation-session-toolsearch-tui");
  110. // TUI 现有登录门槛要求一个有效计划连接;请求仍选择隔离的普通测试 Provider。
  111. // 只在隔离 HOME 中写虚构身份,不读取或复用本机登录凭据。
  112. await mkdir(join(fixture.root, ".zcode", "v2"), { recursive: true });
  113. await writeFile(
  114. join(fixture.root, ".zcode", "v2", "credentials.json"),
  115. JSON.stringify({
  116. "account-provider:account:zai-individual-coding-plan:identity": "toolsearch-e2e",
  117. "account-provider:coding-plan:account:zai-individual-coding-plan:account:toolsearch-e2e:api-key":
  118. "test-only",
  119. }),
  120. );
  121. });
  122. afterEach(async () => {
  123. await terminal?.close();
  124. terminal = undefined;
  125. });
  126. after(async () => {
  127. await fixture?.close();
  128. });
  129. it("TS02-TUI: 强开搜索首轮,工具延迟加载并写入真实引用", async () => {
  130. const initial = await turn(["--toolsearch-mode", "native"], "E2E_TOOLSEARCH_INITIAL");
  131. expect(initial).toHaveLength(3);
  132. expect(initial[0]!.tools?.some((tool) => tool.name === "TodoRead")).toBe(false);
  133. loaded(initial[1]!);
  134. const db = new DatabaseSync(join(fixture.root, "session.sqlite"), { readOnly: true });
  135. try {
  136. sessionId = (
  137. db.prepare("SELECT id FROM session ORDER BY time_created DESC LIMIT 1").get() as {
  138. id: string;
  139. }
  140. ).id;
  141. } finally {
  142. db.close();
  143. }
  144. });
  145. it("TS02-TUI: resume 不带 flag 默认关闭并降级", async () => {
  146. const off = await turn(["--resume", sessionId], "E2E_TOOLSEARCH_OFF");
  147. expect(off).toHaveLength(1);
  148. expect(off[0]!.tools?.some((tool) => tool.name === "TodoRead")).toBe(true);
  149. expect(off[0]!.tools?.some((tool) => tool.name === "ToolSearch" || tool.defer_loading)).toBe(
  150. false,
  151. );
  152. expect(JSON.stringify(off[0]!.messages)).not.toContain("tool_reference");
  153. expect(JSON.stringify(off[0]!.messages)).not.toContain(TOOLSEARCH_NOTICE);
  154. });
  155. it("TS02-TUI: continue 再开启并恢复真实引用", async () => {
  156. const on = await turn(["--toolsearch-mode", "native", "--continue"], "E2E_TOOLSEARCH_ON");
  157. expect(on).toHaveLength(1);
  158. loaded(on[0]!);
  159. });
  160. });