conversation-session-toolsearch-recording.test.ts 7.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177
  1. import { resolve } from "node:path";
  2. import { createToolSearchCliFixture } from "#e2e/helpers/toolsearch-cli-process";
  3. import { startToolSearchRuntimeDriver } from "#e2e/helpers/toolsearch-runtime-driver";
  4. import { isToolSearchCompact, type ToolSearchRequest } from "#e2e/helpers/toolsearch-provider";
  5. import {
  6. contentText,
  7. loadedCount,
  8. recordingCase,
  9. replyStage,
  10. saveSearchEvidence,
  11. } from "#e2e/helpers/toolsearch-feedback";
  12. type Block = {
  13. type: string;
  14. text?: string;
  15. toolName?: string;
  16. tool_name?: string;
  17. id?: string;
  18. name?: string;
  19. input?: unknown;
  20. tool_use_id?: string;
  21. content?: unknown;
  22. };
  23. type Message = {
  24. role: string;
  25. content: unknown;
  26. toolCallId?: string;
  27. toolCalls?: { id: string; name: string; input: unknown }[];
  28. };
  29. type RecordRequest = { querySource?: string; messages: Message[] };
  30. const continuePrefix = "Output token limit hit. Resume directly";
  31. function normalizedContent(content: unknown): unknown {
  32. if (typeof content === "string") return [{ type: "text", text: content }];
  33. if (!Array.isArray(content)) return content;
  34. return content.map((block: Block) =>
  35. block.type === "tool_reference"
  36. ? { type: "tool_reference", tool_name: block.toolName ?? block.tool_name }
  37. : { type: block.type, text: block.text },
  38. );
  39. }
  40. // 比较 ToolSearch 相关有序片段,不把 adapter 的相邻 user 合并或 cache_control 当作差异。
  41. function searchTrace(messages: readonly Message[]): unknown[] {
  42. const trace: unknown[] = [];
  43. for (const message of messages) {
  44. if (message.role === "tool") {
  45. trace.push({ result: message.toolCallId, content: normalizedContent(message.content) });
  46. continue;
  47. }
  48. const blocks: Block[] =
  49. typeof message.content === "string"
  50. ? [{ type: "text", text: message.content }]
  51. : (message.content as Block[]);
  52. for (const block of blocks) {
  53. if (block.type === "tool_result")
  54. trace.push({ result: block.tool_use_id, content: normalizedContent(block.content) });
  55. if (block.type === "tool_use")
  56. trace.push({ call: block.id, name: block.name, input: block.input });
  57. if (block.type === "text" && block.text === "Tool loaded.")
  58. trace.push({ loaded: message.role });
  59. if (block.type === "text" && block.text?.startsWith(continuePrefix))
  60. trace.push({ continuation: true });
  61. }
  62. for (const call of message.toolCalls ?? [])
  63. trace.push({ call: call.id, name: call.name, input: call.input });
  64. }
  65. return trace;
  66. }
  67. describe("ToolSearch Continue 与 compact 请求记录(Runtime / HTTP 集成)", () => {
  68. for (const mode of ["native", "local"] as const) {
  69. for (const streaming of ["on", "off"] as const) {
  70. for (const trigger of ["none", "auto", "reactive"] as const) {
  71. it(`TS12-RECORD: ${mode}/${streaming}/${trigger}`, async function () {
  72. this.timeout(120_000);
  73. const fixture = await createToolSearchCliFixture(recordingCase, { modelIo: true });
  74. await fixture.configure({
  75. features: { memory: false, skill: false, subagent: false, mcp: true },
  76. mcp: {
  77. servers: {
  78. catalog: {
  79. type: "stdio",
  80. command: process.execPath,
  81. args: [resolve("test/e2e/fixtures/mcp/toolsearch-server.mjs")],
  82. },
  83. },
  84. },
  85. });
  86. const driver = await startToolSearchRuntimeDriver(fixture, streaming, {
  87. mode,
  88. recording: true,
  89. autoCompact: trigger === "auto",
  90. });
  91. let records: unknown;
  92. let history: unknown;
  93. try {
  94. let calls = 0;
  95. fixture.setResponse((body, response) => {
  96. let stage = "done";
  97. if (isToolSearchCompact(body)) stage = "summary";
  98. else {
  99. calls++;
  100. if (calls === 1) stage = "search";
  101. else if (trigger === "none" && calls <= 4) stage = "partial";
  102. else if (trigger !== "none" && calls === 4) stage = "partial";
  103. else if (trigger !== "none" && calls === 5)
  104. stage = trigger === "auto" ? "pressure" : "partial";
  105. else if (trigger === "reactive" && calls === 6) {
  106. fixture.reply(body, response, "context-error");
  107. return;
  108. }
  109. }
  110. replyStage(fixture, body, response, stage);
  111. });
  112. await driver.turn("E2E_TOOLSEARCH_RECORD_SEARCH");
  113. if (trigger !== "none") await driver.turn("E2E_TOOLSEARCH_RECORD_WARMUP");
  114. await driver.turn("E2E_TOOLSEARCH_RECORD_CONTINUE");
  115. records = await driver.records();
  116. history = await driver.history();
  117. const actual = fixture.requests.map(({ body }) => body);
  118. const stored = records as RecordRequest[];
  119. expect(
  120. actual
  121. .filter((request) => !isToolSearchCompact(request))
  122. .every((request) => (request.stream === true) === (streaming === "on")),
  123. ).toBe(true);
  124. expect(stored).toHaveLength(actual.length);
  125. for (const [index, request] of actual.entries()) {
  126. // 记录与实际请求是同一份消息(续写提示也写进记录)。
  127. expect(searchTrace(stored[index]!.messages)).toEqual(searchTrace(request.messages));
  128. }
  129. if (trigger === "none") {
  130. expect(actual.map(loadedCount)).toEqual(
  131. mode === "native" ? [0, 1, 1, 1, 1, 1] : [0, 0, 0, 0, 0, 0],
  132. );
  133. // 续写提示按隐藏记录写入历史:下一轮第一个请求仍带着本轮的三条。
  134. expect(actual.map(continueCount)).toEqual([0, 0, 1, 2, 3, 3]);
  135. expect(JSON.stringify(history).split(continuePrefix).length - 1).toBe(3);
  136. } else {
  137. const compact = actual.filter(isToolSearchCompact);
  138. expect(compact).toHaveLength(1);
  139. expect(continueCount(compact[0]!)).toBeGreaterThan(0);
  140. expect(loadedCount(compact[0]!)).toBe(mode === "native" ? 1 : 0);
  141. const record = stored.filter((item) => item.querySource === "compact");
  142. expect(record).toHaveLength(1);
  143. expect(
  144. searchTrace(record[0]!.messages).filter(
  145. (item) => item !== null && typeof item === "object" && "loaded" in item,
  146. ),
  147. ).toEqual(mode === "native" ? [{ loaded: "user" }] : []);
  148. }
  149. expect(JSON.stringify(history)).not.toContain("Tool loaded.");
  150. expect(JSON.stringify(records)).not.toContain("loadedToolCallIds");
  151. } finally {
  152. try {
  153. await saveSearchEvidence(`record-${mode}-${streaming}-${trigger}`, fixture, {
  154. records,
  155. history,
  156. });
  157. } finally {
  158. await driver.close();
  159. await fixture.close();
  160. }
  161. }
  162. });
  163. }
  164. }
  165. }
  166. });
  167. function continueCount(body: ToolSearchRequest): number {
  168. return body.messages.reduce(
  169. (total, message) => total + contentText(message.content).split(continuePrefix).length - 1,
  170. 0,
  171. );
  172. }