v4PendingCommandRegistry.test.ts 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424
  1. import { describe, expect, it, vi } from "vitest";
  2. import type {
  3. CommandAck,
  4. CommandEnvelope,
  5. ConversationSnapshot,
  6. } from "@zcode/shared/zcode-protocol-v4";
  7. import {
  8. PENDING_COMMAND_TTL_MS,
  9. PendingCommandRegistry,
  10. } from "../src/v4/pendingCommandRegistry.js";
  11. import {
  12. isPendingCommandForWorkspace,
  13. resolvePendingCommandWorkspaceKey,
  14. } from "../src/v4/pendingCommandWorkspace.js";
  15. class MemoryStorage {
  16. readonly values = new Map<string, string>();
  17. getItem(key: string): string | null {
  18. return this.values.get(key) ?? null;
  19. }
  20. setItem(key: string, value: string): void {
  21. this.values.set(key, value);
  22. }
  23. removeItem(key: string): void {
  24. this.values.delete(key);
  25. }
  26. }
  27. function envelope(overrides: Partial<CommandEnvelope> = {}): CommandEnvelope {
  28. return {
  29. commandId: "command-1",
  30. clientId: "client-1",
  31. sessionId: "session-1",
  32. type: "sendText",
  33. payload: { text: "hello", attachments: [{ ref: "attachment-1", kind: "file" }] },
  34. issuedAt: 1_000,
  35. ...overrides,
  36. } as CommandEnvelope;
  37. }
  38. function ack(commandId: string, status: CommandAck["status"], reasonCode?: string): CommandAck {
  39. return {
  40. commandId,
  41. status,
  42. ...(reasonCode ? { reasonCode } : {}),
  43. revisionAtDecision: 1,
  44. };
  45. }
  46. function snapshot(
  47. rows: ConversationSnapshot["rows"]["window"],
  48. queueItems: ConversationSnapshot["queue"]["items"] = [],
  49. ): ConversationSnapshot {
  50. return {
  51. sessionId: "session-1",
  52. logEpoch: "epoch-1",
  53. seq: 1,
  54. revision: 1,
  55. meta: { title: "", titleSource: "default" },
  56. control: {
  57. phase: "running",
  58. sessionEnded: false,
  59. canStop: true,
  60. stopState: "stoppable",
  61. stopTargetKind: "assistant",
  62. activeWorks: [],
  63. lastError: null,
  64. apiRetry: null,
  65. },
  66. availability: {
  67. fork: { allowed: true },
  68. compact: { allowed: false, reasonCode: "running" },
  69. switchModelConfig: { allowed: false, reasonCode: "running" },
  70. setFollowupMode: { allowed: true },
  71. queueEdit: { allowed: true },
  72. sendQueuedNow: { allowed: true },
  73. pauseGoal: { allowed: false, reasonCode: "running" },
  74. resumeGoal: { allowed: false, reasonCode: "running" },
  75. },
  76. inputRouting: { mode: "enqueue" },
  77. config: { provider: "p", model: "m", thought: "medium", followupMode: "queue", mode: "build" },
  78. usage: {
  79. contextWindow: {
  80. usedTokens: 0,
  81. maxTokens: 100,
  82. autoCompactThresholdTokens: null,
  83. },
  84. modelUsage: [],
  85. },
  86. goal: null,
  87. plan: null,
  88. backgroundWorks: [],
  89. pendingInteractions: [],
  90. pendingCommands: [],
  91. queue: { autoDrain: true, items: queueItems },
  92. rows: { firstRowId: rows[0]?.rowId ?? null, totalCount: rows.length, window: rows },
  93. };
  94. }
  95. describe("V4 pending command registry", () => {
  96. it("createSession 重发会保留原始 grouped draft identity 与 placement", () => {
  97. const storage = new MemoryStorage();
  98. const registry = new PendingCommandRegistry({ storage, now: () => 1_000 });
  99. const groupedDraftTask = {
  100. draftId: "grouped-draft-a",
  101. workspacePath: "/repo",
  102. placement: { type: "group" as const, groupId: "group-a" },
  103. createdAt: 900,
  104. };
  105. registry.record(
  106. envelope({
  107. commandId: "create-session-1",
  108. sessionId: null,
  109. type: "createSession",
  110. payload: { workspaceId: "/repo", firstInput: { text: "hello" } },
  111. }),
  112. { workspace: { workspacePath: "/repo" }, groupedDraftTask },
  113. );
  114. const reloaded = new PendingCommandRegistry({ storage, now: () => 1_001 });
  115. expect(
  116. reloaded.consumeReplay({ sessionId: null, commandId: "create-session-1" })?.clientContext,
  117. ).toEqual({ workspace: { workspacePath: "/repo" }, groupedDraftTask });
  118. });
  119. it("createSession workspace key 优先使用 identity 并兼容旧 payload", () => {
  120. const registry = new PendingCommandRegistry({ storage: new MemoryStorage() });
  121. registry.record(
  122. envelope({
  123. commandId: "create-with-identity",
  124. sessionId: null,
  125. type: "createSession",
  126. payload: { workspaceId: "ssh://old/repo", firstInput: { text: "hello" } },
  127. }),
  128. {
  129. workspace: {
  130. workspacePath: "/repo",
  131. workspaceIdentity: "ssh://host/repo",
  132. },
  133. },
  134. );
  135. registry.record(
  136. envelope({
  137. commandId: "legacy-create",
  138. sessionId: null,
  139. type: "createSession",
  140. payload: { workspaceId: "ssh://legacy/repo", firstInput: { text: "hello" } },
  141. }),
  142. );
  143. expect(resolvePendingCommandWorkspaceKey(registry.list(null)[0]!)).toBe("ssh://host/repo");
  144. expect(resolvePendingCommandWorkspaceKey(registry.list(null)[1]!)).toBe("ssh://legacy/repo");
  145. expect(isPendingCommandForWorkspace(registry.list(null)[0]!, "/repo", "ssh://host/repo")).toBe(
  146. true,
  147. );
  148. expect(isPendingCommandForWorkspace(registry.list(null)[0]!, "/repo", "ssh://other/repo")).toBe(
  149. false,
  150. );
  151. });
  152. it("普通输入在首次上行前持久化 24h,reload 不延长 TTL", () => {
  153. const storage = new MemoryStorage();
  154. let now = 1_000;
  155. const registry = new PendingCommandRegistry({ storage, now: () => now });
  156. registry.record(envelope());
  157. expect(registry.list("session-1")).toMatchObject([
  158. {
  159. commandId: "command-1",
  160. expiresAt: 1_000 + PENDING_COMMAND_TTL_MS,
  161. replay: { kind: "input", type: "sendText", payload: { text: "hello" } },
  162. },
  163. ]);
  164. now += 60_000;
  165. const reloaded = new PendingCommandRegistry({ storage, now: () => now });
  166. expect(reloaded.list("session-1")[0]?.expiresAt).toBe(1_000 + PENDING_COMMAND_TTL_MS);
  167. now = 1_000 + PENDING_COMMAND_TTL_MS + 1;
  168. expect(reloaded.list("session-1")).toEqual([]);
  169. });
  170. it("升级前已落盘的 unknown 恢复项不会再进入 UI", () => {
  171. const storage = new MemoryStorage();
  172. const registry = new PendingCommandRegistry({ storage, now: () => 1_000 });
  173. registry.record(envelope({ commandId: "legacy-unknown" }));
  174. const [storageKey, raw] = [...storage.values.entries()][0] ?? [];
  175. expect(storageKey).toBeTruthy();
  176. const persisted = JSON.parse(raw ?? "[]") as Array<Record<string, unknown>>;
  177. persisted[0] = { ...persisted[0], recovery: "unknown" };
  178. storage.setItem(storageKey ?? "", JSON.stringify(persisted));
  179. const reloaded = new PendingCommandRegistry({ storage, now: () => 1_001 });
  180. expect(reloaded.listRecoverable("session-1")).toEqual([]);
  181. });
  182. it("敏感 interaction 只落 digest,不落答案原文", () => {
  183. const storage = new MemoryStorage();
  184. const registry = new PendingCommandRegistry({ storage, now: () => 1_000 });
  185. registry.record(
  186. envelope({
  187. commandId: "interaction-1",
  188. type: "resolveInteraction",
  189. payload: {
  190. interactionId: "permission-1",
  191. answer: { freeText: "secret-answer", content: { token: "secret-token" } },
  192. },
  193. }),
  194. );
  195. const raw = [...storage.values.values()].join("\n");
  196. expect(raw).not.toContain("secret-answer");
  197. expect(raw).not.toContain("secret-token");
  198. expect(registry.list("session-1")[0]?.replay).toMatchObject({
  199. kind: "sensitiveDigest",
  200. });
  201. });
  202. it("Workspace Hook 安全决定只落 digest,ACK 不明时仅供 query 对账", () => {
  203. const storage = new MemoryStorage();
  204. const registry = new PendingCommandRegistry({ storage, now: () => 1_000 });
  205. registry.record(
  206. envelope({
  207. commandId: "workspace-review-1",
  208. type: "respondWorkspaceHookReview",
  209. payload: {
  210. sessionId: "session-1",
  211. taskId: "task-1",
  212. runId: "run-1",
  213. workspaceIdentity: "local:/workspace",
  214. bundleDigest: "a".repeat(64),
  215. reviewFlowId: "flow-1",
  216. generation: 1,
  217. interactionId: "interaction-1",
  218. decision: { action: "trust_selected", reviewItemIds: ["private-item"] },
  219. },
  220. }),
  221. );
  222. const raw = [...storage.values.values()].join("\n");
  223. expect(raw).not.toContain("private-item");
  224. expect(raw).not.toContain("trust_selected");
  225. expect(registry.list("session-1")[0]?.replay).toMatchObject({
  226. kind: "sensitiveDigest",
  227. type: "respondWorkspaceHookReview",
  228. });
  229. });
  230. it("QueueItem 是权威投递证据,立即清除 renderer 持久恢复账本", () => {
  231. const storage = new MemoryStorage();
  232. const registry = new PendingCommandRegistry({
  233. storage,
  234. now: () => 1_000,
  235. });
  236. const command = envelope();
  237. registry.record(command);
  238. registry.applyAck(command, ack("command-1", "accepted"));
  239. registry.reconcileSnapshot(
  240. snapshot(
  241. [],
  242. [
  243. {
  244. sourceCommandId: "command-1",
  245. queueItemId: "queue-1",
  246. clientId: "client-1",
  247. kind: "sendText",
  248. text: "hello",
  249. attachments: [],
  250. delivery: "queued",
  251. admittedAt: 1,
  252. admissionSeq: 1,
  253. dispatch: { state: "queued" },
  254. },
  255. ],
  256. ),
  257. );
  258. expect(registry.list("session-1")).toEqual([]);
  259. expect(new PendingCommandRegistry({ storage, now: () => 2_000 }).list("session-1")).toEqual([]);
  260. });
  261. it("compact accepted 后保留恢复线索,直到 timeline marker 证明已开始执行", () => {
  262. const registry = new PendingCommandRegistry({
  263. storage: new MemoryStorage(),
  264. now: () => 1_000,
  265. });
  266. const command = envelope({ type: "compact", payload: {} });
  267. registry.record(command);
  268. registry.applyAck(command, ack("command-1", "accepted"));
  269. expect(registry.list("session-1")).toMatchObject([
  270. { replay: { kind: "input", type: "compact", payload: {} } },
  271. ]);
  272. registry.reconcileSnapshot(
  273. snapshot([
  274. {
  275. rowId: 1,
  276. turnId: "turn-1",
  277. createdAt: 1,
  278. createdAtSeq: 1,
  279. kind: "timelineMarker",
  280. sourceCommandId: "command-1",
  281. marker: { type: "compact", origin: "manual", status: "running" },
  282. },
  283. ]),
  284. );
  285. expect(registry.list("session-1")).toEqual([]);
  286. });
  287. it("携 firstInput 的 createSession accepted 后把账本迁到真实 session", () => {
  288. const registry = new PendingCommandRegistry({
  289. storage: new MemoryStorage(),
  290. now: () => 1_000,
  291. });
  292. const command = envelope({
  293. commandId: "create-1",
  294. sessionId: null,
  295. type: "createSession",
  296. payload: { workspaceId: "/repo", firstInput: { text: "hello" } },
  297. });
  298. registry.record(command);
  299. registry.applyAck(command, {
  300. ...ack("create-1", "accepted"),
  301. result: { type: "createSession", sessionId: "created-session" },
  302. });
  303. expect(registry.list(null)).toEqual([]);
  304. expect(registry.list("created-session")).toMatchObject([
  305. { commandId: "create-1", sessionId: "created-session" },
  306. ]);
  307. });
  308. it("unknown 静默清账,restart discarded 按 delivery 只保留 startNow 确认", () => {
  309. const registry = new PendingCommandRegistry({
  310. storage: new MemoryStorage(),
  311. now: () => 1_000,
  312. });
  313. for (const commandId of [
  314. "unknown",
  315. "discarded-start",
  316. "discarded-queue",
  317. "discarded-guide",
  318. "unavailable",
  319. ]) {
  320. registry.record(envelope({ commandId }));
  321. }
  322. registry.applyQuery({
  323. results: [
  324. { key: { sessionId: "session-1", commandId: "unknown" }, result: "unknown" },
  325. {
  326. key: { sessionId: "session-1", commandId: "discarded-start" },
  327. result: {
  328. ...ack("discarded-start", "failed", "fault.command.inputDiscardedOnRestart"),
  329. result: { type: "inputDisposition", delivery: "startNow" },
  330. },
  331. },
  332. {
  333. key: { sessionId: "session-1", commandId: "discarded-queue" },
  334. result: {
  335. ...ack("discarded-queue", "failed", "fault.command.inputDiscardedOnRestart"),
  336. result: { type: "inputDisposition", delivery: "queue" },
  337. },
  338. },
  339. {
  340. key: { sessionId: "session-1", commandId: "discarded-guide" },
  341. result: {
  342. ...ack("discarded-guide", "failed", "fault.command.inputDiscardedOnRestart"),
  343. result: { type: "inputDisposition", delivery: "guide" },
  344. },
  345. },
  346. {
  347. key: { sessionId: "session-1", commandId: "unavailable" },
  348. result: ack("unavailable", "failed", "fault.command.queryUnavailable"),
  349. },
  350. ],
  351. });
  352. expect(registry.listRecoverable("session-1").map((entry) => entry.recovery)).toEqual([
  353. "discarded",
  354. ]);
  355. expect(registry.list("session-1").map((entry) => entry.commandId)).not.toContain("unknown");
  356. expect(registry.list("session-1").map((entry) => entry.commandId)).not.toContain(
  357. "discarded-queue",
  358. );
  359. expect(registry.list("session-1").map((entry) => entry.commandId)).not.toContain(
  360. "discarded-guide",
  361. );
  362. expect(registry.list("session-1").map((entry) => entry.commandId)).toContain("unavailable");
  363. });
  364. it("reconnect query 按 64 分批且同 session 单飞,确认重发消费旧记录", async () => {
  365. const registry = new PendingCommandRegistry({
  366. storage: new MemoryStorage(),
  367. now: () => 1_000,
  368. });
  369. for (let index = 0; index < 65; index += 1) {
  370. registry.record(envelope({ commandId: `command-${index}` }));
  371. }
  372. const query = vi.fn(
  373. async (params: { commands: Array<{ sessionId: string | null; commandId: string }> }) => ({
  374. results: params.commands.map((key) => ({
  375. key,
  376. result: {
  377. ...ack(key.commandId, "failed", "fault.command.inputDiscardedOnRestart"),
  378. result: { type: "inputDisposition" as const, delivery: "startNow" as const },
  379. },
  380. })),
  381. }),
  382. );
  383. await Promise.all([
  384. registry.reconcileSession("session-1", query),
  385. registry.reconcileSession("session-1", query),
  386. ]);
  387. expect(query).toHaveBeenCalledTimes(2);
  388. expect(query.mock.calls.map(([params]) => params.commands.length)).toEqual([64, 1]);
  389. const replay = registry.consumeReplay({ sessionId: "session-1", commandId: "command-0" });
  390. expect(replay).toMatchObject({ type: "sendText", payload: { text: "hello" } });
  391. expect(registry.list("session-1").some((entry) => entry.commandId === "command-0")).toBe(false);
  392. });
  393. });