input-prediction-sidecar.test.ts 7.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208
  1. // 输入预测 sidecar 纯函数与编排壳(docs/web-remote-control/mobile-input-prediction.md)。
  2. import { describe, expect, it, vi } from "vitest";
  3. import { v4ConversationInputPredictionResultSchema } from "@zcode/shared/zcode-protocol-v4";
  4. import {
  5. INPUT_PREDICTION_QUERY_SOURCE,
  6. buildInputPredictionContext,
  7. buildInputPredictionMessages,
  8. decideInputPrediction,
  9. generateInputPredictionCandidates,
  10. inputPredictionMinTurns,
  11. normalizeInputPredictionDraft,
  12. parseInputPredictionResponse,
  13. toInputPredictionSuffix,
  14. type InputPredictionModelCall,
  15. type InputPredictionTurnContext,
  16. } from "../src/runtime/methods/input-prediction-sidecar.js";
  17. const turns: InputPredictionTurnContext[] = [
  18. { userText: "帮我看下 lint 报错", assistantText: "已修复 3 处" },
  19. { userText: "再跑一遍单测", assistantText: "全部通过" },
  20. ];
  21. describe("parseInputPredictionResponse", () => {
  22. it("解析纯 JSON", () => {
  23. expect(
  24. parseInputPredictionResponse('{"candidates":[{"text":"提交吧","confidence":0.9}]}'),
  25. ).toEqual([{ text: "提交吧", confidence: 0.9 }]);
  26. });
  27. it("容忍 think 段、code fence、尾逗号与前后说明", () => {
  28. const raw =
  29. '<think>想一想</think>\n```json\n{"candidates":[{"text":"提交吧","confidence":0.9},]}\n```';
  30. expect(parseInputPredictionResponse(raw)).toEqual([{ text: "提交吧", confidence: 0.9 }]);
  31. expect(
  32. parseInputPredictionResponse('结果如下:{"candidates":[{"text":"好","confidence":0.5}]} 完'),
  33. ).toEqual([{ text: "好", confidence: 0.5 }]);
  34. });
  35. it("结构不对或没有有效候选时返回 null", () => {
  36. expect(parseInputPredictionResponse("不是 JSON")).toBeNull();
  37. expect(parseInputPredictionResponse('{"candidates":[]}')).toBeNull();
  38. expect(parseInputPredictionResponse('{"candidates":[{"text":1,"confidence":0.9}]}')).toBeNull();
  39. expect(parseInputPredictionResponse("[]")).toBeNull();
  40. });
  41. });
  42. describe("toInputPredictionSuffix", () => {
  43. it("无草稿时单行化并两端 trim", () => {
  44. expect(toInputPredictionSuffix(" 提交\n代码 ", "")).toBe("提交 代码");
  45. });
  46. it("有草稿时剥掉模型重复的草稿前缀,保留续写开头的空格", () => {
  47. expect(toInputPredictionSuffix("run the tests", "run the")).toBe(" tests");
  48. expect(toInputPredictionSuffix(" tests ", "run the")).toBe(" tests");
  49. });
  50. it("草稿以空白结尾时续写不再以空白开头", () => {
  51. expect(toInputPredictionSuffix("run the tests", "run the ")).toBe("tests");
  52. expect(toInputPredictionSuffix(" tests", "run the ")).toBe("tests");
  53. });
  54. it("按 UTF-16 长度截断到 40,不劈开代理对", () => {
  55. const long = "好".repeat(50);
  56. expect(toInputPredictionSuffix(long, "")).toHaveLength(40);
  57. const emoji = "😀".repeat(30);
  58. const bounded = toInputPredictionSuffix(emoji, "");
  59. expect(bounded.length).toBeLessThanOrEqual(40);
  60. expect(bounded).toBe("😀".repeat(20));
  61. });
  62. });
  63. describe("decideInputPrediction", () => {
  64. it("轮数不够时 suppress_no_context", () => {
  65. expect(
  66. decideInputPrediction({
  67. rawCandidates: [{ text: "好", confidence: 1 }],
  68. draft: "",
  69. recentUserInputs: ["a"],
  70. turnCount: 1,
  71. }),
  72. ).toEqual({ decision: "suppress_no_context", candidates: [], topConfidence: 0 });
  73. // 草稿模式只要 1 轮。
  74. expect(inputPredictionMinTurns("草稿")).toBe(1);
  75. expect(inputPredictionMinTurns("")).toBe(2);
  76. });
  77. it("去掉与最近用户输入重复的、候选间重复的,按置信度降序取前 3", () => {
  78. const outcome = decideInputPrediction({
  79. rawCandidates: [
  80. { text: "再跑一遍 单测", confidence: 0.99 },
  81. { text: "提交代码", confidence: 0.7 },
  82. { text: "提交 代码", confidence: 0.85 },
  83. { text: "推送", confidence: 0.6 },
  84. { text: "看下覆盖率", confidence: 0.5 },
  85. { text: "合并", confidence: 0.4 },
  86. { text: " ", confidence: 0.95 },
  87. ],
  88. draft: "",
  89. recentUserInputs: turns.map((turn) => turn.userText),
  90. turnCount: 2,
  91. });
  92. expect(outcome).toEqual({
  93. decision: "show",
  94. candidates: [
  95. { text: "提交 代码", confidence: 0.85 },
  96. { text: "推送", confidence: 0.6 },
  97. { text: "看下覆盖率", confidence: 0.5 },
  98. ],
  99. topConfidence: 0.85,
  100. });
  101. expect(
  102. v4ConversationInputPredictionResultSchema.safeParse({ ...outcome, requestId: "r" }).success,
  103. ).toBe(true);
  104. });
  105. it("top 置信度不到门槛时 suppress_below_threshold;置信度被夹到 0..1", () => {
  106. expect(
  107. decideInputPrediction({
  108. rawCandidates: [{ text: "提交", confidence: 0.79 }],
  109. draft: "",
  110. recentUserInputs: [],
  111. turnCount: 3,
  112. }).decision,
  113. ).toBe("suppress_below_threshold");
  114. expect(
  115. decideInputPrediction({
  116. rawCandidates: [{ text: "提交", confidence: 3 }],
  117. draft: "",
  118. recentUserInputs: [],
  119. turnCount: 3,
  120. }),
  121. ).toMatchObject({ decision: "show", topConfidence: 1 });
  122. });
  123. it("草稿模式按「草稿 + 续写」与最近输入去重", () => {
  124. expect(
  125. decideInputPrediction({
  126. rawCandidates: [{ text: "单测", confidence: 0.9 }],
  127. draft: "再跑一遍",
  128. recentUserInputs: ["再跑一遍单测"],
  129. turnCount: 1,
  130. }).candidates,
  131. ).toEqual([]);
  132. });
  133. });
  134. describe("上下文与提示词", () => {
  135. it("只取最近 6 轮,助手回复截断,总预算从最旧处截断", () => {
  136. const many = Array.from({ length: 8 }, (_, index) => ({
  137. userText: `问题${index}`,
  138. assistantText: index === 7 ? "长".repeat(900) : null,
  139. }));
  140. const context = buildInputPredictionContext(many);
  141. expect(context).not.toContain("问题1");
  142. expect(context).toContain("问题2");
  143. expect(context).toContain("(无回复)");
  144. expect(context).toContain(`${"长".repeat(800)}…`);
  145. expect(buildInputPredictionContext(many, { totalMaxChars: 20 })).toHaveLength(20);
  146. });
  147. it("草稿模式换提示词并附草稿;纯空白草稿视为无草稿", () => {
  148. expect(normalizeInputPredictionDraft(" ")).toBe("");
  149. expect(normalizeInputPredictionDraft(undefined)).toBe("");
  150. const [system, user] = buildInputPredictionMessages(turns, "帮我");
  151. expect(system!.content).toContain("输入补全器");
  152. expect(user!.content).toContain("【用户正在输入的草稿】\n帮我");
  153. expect(buildInputPredictionMessages(turns, "")[0]!.content).toContain("输入预测器");
  154. });
  155. });
  156. describe("generateInputPredictionCandidates", () => {
  157. it("用 input_prediction querySource 调模型并解析", async () => {
  158. const callModel = vi.fn<InputPredictionModelCall>(async () => ({
  159. text: '{"candidates":[{"text":"提交","confidence":0.9}]}',
  160. }));
  161. await expect(generateInputPredictionCandidates({ turns, draft: "", callModel })).resolves.toEqual(
  162. [{ text: "提交", confidence: 0.9 }],
  163. );
  164. expect(callModel.mock.calls[0]![1].querySource).toBe(INPUT_PREDICTION_QUERY_SOURCE);
  165. });
  166. it("外部取消时立即放弃等待,即使模型执行面不响应 signal", async () => {
  167. const controller = new AbortController();
  168. const pending = generateInputPredictionCandidates({
  169. turns,
  170. draft: "",
  171. callModel: () => new Promise(() => undefined),
  172. abortSignal: controller.signal,
  173. });
  174. controller.abort(new Error("superseded"));
  175. await expect(pending).rejects.toThrow("superseded");
  176. });
  177. it("超时后拒绝,并把合并后的 signal 交给模型执行面", async () => {
  178. let seen: AbortSignal | undefined;
  179. const pending = generateInputPredictionCandidates({
  180. turns,
  181. draft: "",
  182. timeoutMs: 10,
  183. callModel: (_messages, options) => {
  184. seen = options.abortSignal;
  185. return new Promise(() => undefined);
  186. },
  187. });
  188. await expect(pending).rejects.toBeDefined();
  189. expect(seen?.aborted).toBe(true);
  190. });
  191. });