input-prediction-handler.test.ts 9.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242
  1. // v4/conversation/inputPrediction 的 CLI 处理器(docs/web-remote-control/mobile-input-prediction.md)。
  2. import { describe, expect, it, vi } from "vitest";
  3. import type { MessageWithParts } from "@zcode/contracts";
  4. import type { InputPredictionModelCall } from "@zcode/core";
  5. import { V4_METHODS } from "@zcode/shared/zcode-protocol-v4";
  6. import { ZCodeProtocolAgentServer } from "../src/zcode-protocol/server.js";
  7. import {
  8. ConversationInputPredictionHandler,
  9. collectInputPredictionTurns,
  10. type InputPredictionSessionMaterial,
  11. } from "../src/zcode-protocol/input-prediction-handler.js";
  12. const SHOW_RESPONSE = '{"candidates":[{"text":"提交代码","confidence":0.9}]}';
  13. function material(callModel: InputPredictionModelCall | null): InputPredictionSessionMaterial {
  14. return {
  15. turns: [
  16. { userText: "修 lint", assistantText: "好了" },
  17. { userText: "跑单测", assistantText: "通过" },
  18. ],
  19. callModel,
  20. };
  21. }
  22. function deferred<T>() {
  23. let resolve!: (value: T) => void;
  24. const promise = new Promise<T>((done) => {
  25. resolve = done;
  26. });
  27. return { promise, resolve };
  28. }
  29. describe("ConversationInputPredictionHandler", () => {
  30. it("返回 show 并回显 requestId;同 (session, revision, draft) 命中缓存不再调模型", async () => {
  31. const callModel = vi.fn<InputPredictionModelCall>(async () => ({ text: SHOW_RESPONSE }));
  32. const handler = new ConversationInputPredictionHandler({
  33. loadSession: async () => material(callModel),
  34. });
  35. await expect(handler.handle({ sessionId: "s", revision: 1, requestId: "a" })).resolves.toEqual(
  36. {
  37. decision: "show",
  38. candidates: [{ text: "提交代码", confidence: 0.9 }],
  39. topConfidence: 0.9,
  40. requestId: "a",
  41. },
  42. );
  43. await expect(
  44. handler.handle({ sessionId: "s", revision: 1, requestId: "b" }),
  45. ).resolves.toMatchObject({ decision: "show", requestId: "b" });
  46. // 纯空白草稿与无草稿同键。
  47. await handler.handle({ sessionId: "s", revision: 1, draft: " " });
  48. expect(callModel).toHaveBeenCalledTimes(1);
  49. await handler.handle({ sessionId: "s", revision: 2 });
  50. expect(callModel).toHaveBeenCalledTimes(2);
  51. });
  52. it("同会话新请求中止旧请求,旧请求回 cancelled", async () => {
  53. const first = deferred<{ text: string }>();
  54. let firstSignal: AbortSignal | undefined;
  55. const callModel = vi.fn<InputPredictionModelCall>(async (_messages, options) => {
  56. if (!firstSignal) {
  57. firstSignal = options.abortSignal;
  58. return first.promise;
  59. }
  60. return { text: SHOW_RESPONSE };
  61. });
  62. const handler = new ConversationInputPredictionHandler({
  63. loadSession: async () => material(callModel),
  64. });
  65. const stale = handler.handle({ sessionId: "s", revision: 1, draft: "提", requestId: "old" });
  66. await vi.waitFor(() => expect(callModel).toHaveBeenCalledTimes(1));
  67. const fresh = handler.handle({ sessionId: "s", revision: 1, draft: "提交", requestId: "new" });
  68. await expect(stale).resolves.toEqual({
  69. decision: "cancelled",
  70. candidates: [],
  71. topConfidence: 0,
  72. requestId: "old",
  73. });
  74. expect(firstSignal?.aborted).toBe(true);
  75. await expect(fresh).resolves.toMatchObject({ decision: "show", requestId: "new" });
  76. });
  77. it("不同会话互不中止", async () => {
  78. const pending = deferred<{ text: string }>();
  79. const handler = new ConversationInputPredictionHandler({
  80. loadSession: async (sessionId) =>
  81. material(sessionId === "a" ? () => pending.promise : async () => ({ text: SHOW_RESPONSE })),
  82. });
  83. const a = handler.handle({ sessionId: "a", revision: 1 });
  84. await expect(handler.handle({ sessionId: "b", revision: 1 })).resolves.toMatchObject({
  85. decision: "show",
  86. });
  87. pending.resolve({ text: SHOW_RESPONSE });
  88. await expect(a).resolves.toMatchObject({ decision: "show" });
  89. });
  90. it("会话不在内存或轮数不够 → suppress_no_context,不调模型", async () => {
  91. const callModel = vi.fn<InputPredictionModelCall>();
  92. const missing = new ConversationInputPredictionHandler({ loadSession: async () => null });
  93. await expect(missing.handle({ sessionId: "s", revision: 0 })).resolves.toMatchObject({
  94. decision: "suppress_no_context",
  95. });
  96. const short = new ConversationInputPredictionHandler({
  97. loadSession: async () => ({ turns: [{ userText: "hi", assistantText: null }], callModel }),
  98. });
  99. await expect(short.handle({ sessionId: "s", revision: 0 })).resolves.toMatchObject({
  100. decision: "suppress_no_context",
  101. });
  102. // 草稿模式 1 轮就够。
  103. callModel.mockResolvedValue({ text: SHOW_RESPONSE });
  104. await expect(short.handle({ sessionId: "s", revision: 0, draft: "帮我" })).resolves.toMatchObject(
  105. { decision: "show" },
  106. );
  107. });
  108. it("无模型、模型失败、超时、读会话失败 → unavailable;日志不含草稿内容;unavailable 不缓存", async () => {
  109. const warn = vi.fn();
  110. const logger = { warn } as unknown as NonNullable<
  111. ConstructorParameters<typeof ConversationInputPredictionHandler>[0]["logger"]
  112. >;
  113. const noModel = new ConversationInputPredictionHandler({ loadSession: async () => material(null) });
  114. await expect(noModel.handle({ sessionId: "s", revision: 0 })).resolves.toMatchObject({
  115. decision: "unavailable",
  116. });
  117. const failing = vi.fn<InputPredictionModelCall>(async () => {
  118. throw new Error("provider down");
  119. });
  120. const failed = new ConversationInputPredictionHandler({
  121. loadSession: async () => material(failing),
  122. logger,
  123. });
  124. await expect(
  125. failed.handle({ sessionId: "s", revision: 0, draft: "机密草稿" }),
  126. ).resolves.toMatchObject({ decision: "unavailable" });
  127. await failed.handle({ sessionId: "s", revision: 0, draft: "机密草稿" });
  128. expect(failing).toHaveBeenCalledTimes(2);
  129. expect(JSON.stringify(warn.mock.calls)).not.toContain("机密草稿");
  130. const slow = new ConversationInputPredictionHandler({
  131. loadSession: async () => material(() => new Promise(() => undefined)),
  132. timeoutMs: 10,
  133. });
  134. await expect(slow.handle({ sessionId: "s", revision: 0 })).resolves.toMatchObject({
  135. decision: "unavailable",
  136. });
  137. const broken = new ConversationInputPredictionHandler({
  138. loadSession: async () => {
  139. throw new Error("store gone");
  140. },
  141. logger,
  142. });
  143. await expect(broken.handle({ sessionId: "s", revision: 0 })).resolves.toMatchObject({
  144. decision: "unavailable",
  145. });
  146. });
  147. it("模型输出无法解析 → suppress_below_threshold", async () => {
  148. const handler = new ConversationInputPredictionHandler({
  149. loadSession: async () => material(async () => ({ text: "抱歉,我不能" })),
  150. });
  151. await expect(handler.handle({ sessionId: "s", revision: 0 })).resolves.toMatchObject({
  152. decision: "suppress_below_threshold",
  153. candidates: [],
  154. });
  155. });
  156. it("非法参数直接抛错(strict schema)", async () => {
  157. const handler = new ConversationInputPredictionHandler({ loadSession: async () => null });
  158. await expect(handler.handle({ sessionId: "s" })).rejects.toThrow();
  159. await expect(handler.handle({ sessionId: "s", revision: 0, extra: 1 })).rejects.toThrow();
  160. });
  161. it("dispose 中止全部进行中的预测", async () => {
  162. const handler = new ConversationInputPredictionHandler({
  163. loadSession: async () => material(() => new Promise(() => undefined)),
  164. });
  165. const pending = handler.handle({ sessionId: "s", revision: 0, requestId: "r" });
  166. await Promise.resolve();
  167. await Promise.resolve();
  168. handler.dispose(new Error("disconnected"));
  169. await expect(pending).resolves.toMatchObject({ decision: "cancelled", requestId: "r" });
  170. });
  171. });
  172. function message(
  173. id: string,
  174. role: "user" | "assistant",
  175. text: string,
  176. extra: Record<string, unknown> = {},
  177. ): MessageWithParts {
  178. return {
  179. info: { id, sessionID: "s", role, ...extra },
  180. parts: [{ id: `${id}-p`, type: "text", text }],
  181. } as unknown as MessageWithParts;
  182. }
  183. describe("collectInputPredictionTurns", () => {
  184. it("真实用户输入配对到下一条用户消息前最后一条非空助手文本;合成消息不算轮次", () => {
  185. const turns = collectInputPredictionTurns([
  186. message("u1", "user", "修 lint"),
  187. message("a1", "assistant", "先看看"),
  188. message("a2", "assistant", "已修复"),
  189. message("a3", "assistant", ""),
  190. message("u2", "user", "系统注入", { synthetic: true }),
  191. message("u3", "user", "跑单测"),
  192. message("u4", "user", " "),
  193. ]);
  194. expect(turns).toEqual([
  195. { userText: "修 lint", assistantText: "已修复" },
  196. { userText: "跑单测", assistantText: null },
  197. ]);
  198. });
  199. });
  200. describe("server 分发 v4/conversation/inputPrediction", () => {
  201. it("会话不在本进程时回 suppress_no_context 并回显 requestId;非法参数回协议错误", async () => {
  202. const server = new ZCodeProtocolAgentServer({
  203. cwd: process.cwd(),
  204. createZCodeApp: async () => {
  205. throw new Error("不应为预测创建 app");
  206. },
  207. });
  208. await expect(
  209. server.handleMessage({
  210. id: 1,
  211. method: V4_METHODS.conversationInputPrediction,
  212. params: { sessionId: "missing", revision: 0, requestId: "r" },
  213. }),
  214. ).resolves.toMatchObject({
  215. id: 1,
  216. result: { decision: "suppress_no_context", candidates: [], requestId: "r" },
  217. });
  218. const invalid = await server.handleMessage({
  219. id: 2,
  220. method: V4_METHODS.conversationInputPrediction,
  221. params: { sessionId: "missing" },
  222. });
  223. expect(invalid && "error" in invalid).toBe(true);
  224. });
  225. });