v4PendingCommandRegistry.test.ts 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545
  1. import { describe, expect, it, vi } from "vitest";
  2. import {
  3. ensurePendingTaskDraft,
  4. readPendingTaskDraft,
  5. bindPendingTaskDraft,
  6. persistV4ComposerDraft,
  7. readV4ComposerDraft,
  8. V4_DRAFT_SCOPE_ROOT,
  9. } from "@/v4/composer/composerDraftStore.js";
  10. import { prepareComposerRecentReceipt, readComposerRecent } from "@/lib/composerRecent.js";
  11. it.each(["next input", " submitted draft "])(
  12. "PD06/07 首发未知跨 TTL 保留,重载后 duplicate 交接:%s",
  13. (restoredText) => {
  14. const storage = new MemoryStorage();
  15. vi.stubGlobal("window", { localStorage: storage });
  16. const scope = { clientNamespace: "desktop", hostId: "local", projectId: null };
  17. try {
  18. const pending = ensurePendingTaskDraft(scope);
  19. bindPendingTaskDraft(scope, pending.draftId, "/task-a");
  20. const command = envelope();
  21. const receipt = prepareComposerRecentReceipt(scope, {
  22. modelSelection: { providerId: "p", modelId: "m", options: { reasoningLevel: "high" } },
  23. mode: "yolo",
  24. });
  25. const registry = new PendingCommandRegistry({ storage, now: () => 1000 });
  26. registry.record(command, {
  27. workspace: { workspacePath: "/task-a" },
  28. composer: { ...receipt, draftId: pending.draftId, submittedText: " submitted draft " },
  29. });
  30. registry.applyQuery({
  31. results: [
  32. {
  33. key: { sessionId: command.sessionId, commandId: command.commandId },
  34. result: "unknown",
  35. },
  36. ],
  37. });
  38. persistV4ComposerDraft(
  39. "/task-a",
  40. undefined,
  41. V4_DRAFT_SCOPE_ROOT,
  42. { text: restoredText },
  43. scope,
  44. );
  45. const restored = new PendingCommandRegistry({
  46. storage,
  47. now: () => PENDING_COMMAND_TTL_MS * 2,
  48. });
  49. expect(restored.list(command.sessionId)).toHaveLength(1);
  50. expect(readPendingTaskDraft(scope)?.commandId).toBe(command.commandId);
  51. restored.applyAck(command, ack(command.commandId, "duplicate"));
  52. expect(readPendingTaskDraft(scope)).toBeNull();
  53. expect(readV4ComposerDraft("/task-a", undefined, command.sessionId!)?.text).toBe(
  54. restoredText === "next input" ? "next input" : undefined,
  55. );
  56. expect(readV4ComposerDraft("/task-b", undefined, V4_DRAFT_SCOPE_ROOT, scope)).toBeNull();
  57. expect(readComposerRecent("/task-b", undefined, storage, scope)?.mode).toBe("yolo");
  58. const next = ensurePendingTaskDraft(scope);
  59. restored.applyAck(command, ack(command.commandId, "accepted"));
  60. expect(readPendingTaskDraft(scope)?.draftId).toBe(next.draftId);
  61. } finally {
  62. vi.unstubAllGlobals();
  63. }
  64. },
  65. );
  66. it("PD06 首发账本写入失败时不能允许上行或留下不可恢复的锁定", () => {
  67. const storage = new MemoryStorage();
  68. vi.stubGlobal("window", { localStorage: storage });
  69. try {
  70. const scope = { clientNamespace: "desktop", hostId: "local", projectId: null };
  71. const pending = ensurePendingTaskDraft(scope);
  72. const registry = new PendingCommandRegistry({ storage });
  73. const original = storage.setItem.bind(storage);
  74. storage.setItem = (key, value) => {
  75. if (key === "zcode-v4-pending-commands:v1") throw new Error("quota");
  76. original(key, value);
  77. };
  78. const composer = {
  79. ...prepareComposerRecentReceipt(scope, {
  80. modelSelection: { providerId: "p", modelId: "m" },
  81. mode: "build",
  82. }),
  83. draftId: pending.draftId,
  84. };
  85. expect(() => registry.record(envelope(), { composer })).toThrow();
  86. expect(readPendingTaskDraft(scope)?.commandId).toBeUndefined();
  87. expect(registry.findCommand("command-1")).toBeUndefined();
  88. } finally {
  89. vi.unstubAllGlobals();
  90. }
  91. });
  92. import type {
  93. CommandAck,
  94. CommandEnvelope,
  95. ConversationSnapshot,
  96. } from "@zcode/shared/zcode-protocol-v4";
  97. import {
  98. PENDING_COMMAND_TTL_MS,
  99. PendingCommandRegistry,
  100. } from "../src/v4/pendingCommandRegistry.js";
  101. import {
  102. isPendingCommandForWorkspace,
  103. resolvePendingCommandWorkspaceKey,
  104. } from "../src/v4/pendingCommandWorkspace.js";
  105. class MemoryStorage {
  106. readonly values = new Map<string, string>();
  107. getItem(key: string): string | null {
  108. return this.values.get(key) ?? null;
  109. }
  110. setItem(key: string, value: string): void {
  111. this.values.set(key, value);
  112. }
  113. removeItem(key: string): void {
  114. this.values.delete(key);
  115. }
  116. }
  117. it("PD10 不把另一工作区的全局创建命令交给当前 Agent 查询", async () => {
  118. const registry = new PendingCommandRegistry({ storage: new MemoryStorage() });
  119. for (const path of ["/a", "/b"])
  120. registry.record(envelope({ commandId: path, sessionId: null }), {
  121. workspace: { workspacePath: path },
  122. });
  123. const query = vi.fn(async () => ({ results: [] }));
  124. await registry.reconcileSession(null, query, "/a");
  125. expect(query).toHaveBeenCalledWith({ commands: [{ sessionId: null, commandId: "/a" }] });
  126. });
  127. function envelope(overrides: Partial<CommandEnvelope> = {}): CommandEnvelope {
  128. return {
  129. commandId: "command-1",
  130. clientId: "client-1",
  131. sessionId: "session-1",
  132. type: "sendText",
  133. payload: { text: "hello", attachments: [{ ref: "attachment-1", kind: "file" }] },
  134. issuedAt: 1_000,
  135. ...overrides,
  136. } as CommandEnvelope;
  137. }
  138. function ack(commandId: string, status: CommandAck["status"], reasonCode?: string): CommandAck {
  139. return {
  140. commandId,
  141. status,
  142. ...(reasonCode ? { reasonCode } : {}),
  143. revisionAtDecision: 1,
  144. };
  145. }
  146. function snapshot(
  147. rows: ConversationSnapshot["rows"]["window"],
  148. queueItems: ConversationSnapshot["queue"]["items"] = [],
  149. ): ConversationSnapshot {
  150. return {
  151. sessionId: "session-1",
  152. logEpoch: "epoch-1",
  153. seq: 1,
  154. revision: 1,
  155. meta: { title: "", titleSource: "default" },
  156. control: {
  157. phase: "running",
  158. sessionEnded: false,
  159. canStop: true,
  160. stopState: "stoppable",
  161. stopTargetKind: "assistant",
  162. activeWorks: [],
  163. lastError: null,
  164. apiRetry: null,
  165. },
  166. availability: {
  167. fork: { allowed: true },
  168. compact: { allowed: false, reasonCode: "running" },
  169. switchModelConfig: { allowed: false, reasonCode: "running" },
  170. setFollowupMode: { allowed: true },
  171. queueEdit: { allowed: true },
  172. sendQueuedNow: { allowed: true },
  173. pauseGoal: { allowed: false, reasonCode: "running" },
  174. resumeGoal: { allowed: false, reasonCode: "running" },
  175. },
  176. inputRouting: { mode: "enqueue" },
  177. config: { provider: "p", model: "m", thought: "medium", followupMode: "queue", mode: "build" },
  178. usage: {
  179. contextWindow: {
  180. usedTokens: 0,
  181. maxTokens: 100,
  182. autoCompactThresholdTokens: null,
  183. },
  184. modelUsage: [],
  185. },
  186. goal: null,
  187. plan: null,
  188. backgroundWorks: [],
  189. pendingInteractions: [],
  190. pendingCommands: [],
  191. queue: { autoDrain: true, items: queueItems },
  192. rows: { firstRowId: rows[0]?.rowId ?? null, totalCount: rows.length, window: rows },
  193. };
  194. }
  195. describe("V4 pending command registry", () => {
  196. it("createSession 重发会保留原始项目选择与 workspace identity", () => {
  197. const storage = new MemoryStorage();
  198. const registry = new PendingCommandRegistry({ storage, now: () => 1_000 });
  199. const projectId = "project-a";
  200. registry.record(
  201. envelope({
  202. commandId: "create-session-1",
  203. sessionId: null,
  204. type: "createSession",
  205. payload: { workspaceId: "/repo", firstInput: { text: "hello" } },
  206. }),
  207. { workspace: { workspacePath: "/repo" }, projectId },
  208. );
  209. const reloaded = new PendingCommandRegistry({ storage, now: () => 1_001 });
  210. expect(
  211. reloaded.consumeReplay({ sessionId: null, commandId: "create-session-1" })?.clientContext,
  212. ).toEqual({ workspace: { workspacePath: "/repo" }, projectId });
  213. });
  214. it("createSession workspace key 优先使用 identity 并兼容旧 payload", () => {
  215. const registry = new PendingCommandRegistry({ storage: new MemoryStorage() });
  216. registry.record(
  217. envelope({
  218. commandId: "create-with-identity",
  219. sessionId: null,
  220. type: "createSession",
  221. payload: { workspaceId: "ssh://old/repo", firstInput: { text: "hello" } },
  222. }),
  223. {
  224. workspace: {
  225. workspacePath: "/repo",
  226. workspaceIdentity: "ssh://host/repo",
  227. },
  228. },
  229. );
  230. registry.record(
  231. envelope({
  232. commandId: "legacy-create",
  233. sessionId: null,
  234. type: "createSession",
  235. payload: { workspaceId: "ssh://legacy/repo", firstInput: { text: "hello" } },
  236. }),
  237. );
  238. expect(resolvePendingCommandWorkspaceKey(registry.list(null)[0]!)).toBe("ssh://host/repo");
  239. expect(resolvePendingCommandWorkspaceKey(registry.list(null)[1]!)).toBe("ssh://legacy/repo");
  240. expect(isPendingCommandForWorkspace(registry.list(null)[0]!, "/repo", "ssh://host/repo")).toBe(
  241. true,
  242. );
  243. expect(isPendingCommandForWorkspace(registry.list(null)[0]!, "/repo", "ssh://other/repo")).toBe(
  244. false,
  245. );
  246. });
  247. it("普通输入在首次上行前持久化 24h,reload 不延长 TTL", () => {
  248. const storage = new MemoryStorage();
  249. let now = 1_000;
  250. const registry = new PendingCommandRegistry({ storage, now: () => now });
  251. registry.record(envelope());
  252. expect(registry.list("session-1")).toMatchObject([
  253. {
  254. commandId: "command-1",
  255. expiresAt: 1_000 + PENDING_COMMAND_TTL_MS,
  256. replay: { kind: "input", type: "sendText", payload: { text: "hello" } },
  257. },
  258. ]);
  259. now += 60_000;
  260. const reloaded = new PendingCommandRegistry({ storage, now: () => now });
  261. expect(reloaded.list("session-1")[0]?.expiresAt).toBe(1_000 + PENDING_COMMAND_TTL_MS);
  262. now = 1_000 + PENDING_COMMAND_TTL_MS + 1;
  263. expect(reloaded.list("session-1")).toEqual([]);
  264. });
  265. it("升级前已落盘的 unknown 恢复项不会再进入 UI", () => {
  266. const storage = new MemoryStorage();
  267. const registry = new PendingCommandRegistry({ storage, now: () => 1_000 });
  268. registry.record(envelope({ commandId: "legacy-unknown" }));
  269. const [storageKey, raw] = [...storage.values.entries()][0] ?? [];
  270. expect(storageKey).toBeTruthy();
  271. const persisted = JSON.parse(raw ?? "[]") as Array<Record<string, unknown>>;
  272. persisted[0] = { ...persisted[0], recovery: "unknown" };
  273. storage.setItem(storageKey ?? "", JSON.stringify(persisted));
  274. const reloaded = new PendingCommandRegistry({ storage, now: () => 1_001 });
  275. expect(reloaded.listRecoverable("session-1")).toEqual([]);
  276. });
  277. it("敏感 interaction 只落 digest,不落答案原文", () => {
  278. const storage = new MemoryStorage();
  279. const registry = new PendingCommandRegistry({ storage, now: () => 1_000 });
  280. registry.record(
  281. envelope({
  282. commandId: "interaction-1",
  283. type: "resolveInteraction",
  284. payload: {
  285. interactionId: "permission-1",
  286. answer: { freeText: "secret-answer", content: { token: "secret-token" } },
  287. },
  288. }),
  289. );
  290. const raw = [...storage.values.values()].join("\n");
  291. expect(raw).not.toContain("secret-answer");
  292. expect(raw).not.toContain("secret-token");
  293. expect(registry.list("session-1")[0]?.replay).toMatchObject({
  294. kind: "sensitiveDigest",
  295. });
  296. });
  297. it("Workspace Hook 安全决定只落 digest,ACK 不明时仅供 query 对账", () => {
  298. const storage = new MemoryStorage();
  299. const registry = new PendingCommandRegistry({ storage, now: () => 1_000 });
  300. registry.record(
  301. envelope({
  302. commandId: "workspace-review-1",
  303. type: "respondWorkspaceHookReview",
  304. payload: {
  305. sessionId: "session-1",
  306. taskId: "task-1",
  307. runId: "run-1",
  308. workspaceIdentity: "local:/workspace",
  309. bundleDigest: "a".repeat(64),
  310. reviewFlowId: "flow-1",
  311. generation: 1,
  312. interactionId: "interaction-1",
  313. decision: { action: "trust_selected", reviewItemIds: ["private-item"] },
  314. },
  315. }),
  316. );
  317. const raw = [...storage.values.values()].join("\n");
  318. expect(raw).not.toContain("private-item");
  319. expect(raw).not.toContain("trust_selected");
  320. expect(registry.list("session-1")[0]?.replay).toMatchObject({
  321. kind: "sensitiveDigest",
  322. type: "respondWorkspaceHookReview",
  323. });
  324. });
  325. it("QueueItem 是权威投递证据,立即清除 renderer 持久恢复账本", () => {
  326. const storage = new MemoryStorage();
  327. const registry = new PendingCommandRegistry({
  328. storage,
  329. now: () => 1_000,
  330. });
  331. const command = envelope();
  332. registry.record(command);
  333. registry.applyAck(command, ack("command-1", "accepted"));
  334. registry.reconcileSnapshot(
  335. snapshot(
  336. [],
  337. [
  338. {
  339. sourceCommandId: "command-1",
  340. queueItemId: "queue-1",
  341. clientId: "client-1",
  342. kind: "sendText",
  343. text: "hello",
  344. attachments: [],
  345. delivery: "queued",
  346. admittedAt: 1,
  347. admissionSeq: 1,
  348. dispatch: { state: "queued" },
  349. },
  350. ],
  351. ),
  352. );
  353. expect(registry.list("session-1")).toEqual([]);
  354. expect(new PendingCommandRegistry({ storage, now: () => 2_000 }).list("session-1")).toEqual([]);
  355. });
  356. it("权威投影结算时通知同 commandId 的提交方", () => {
  357. const registry = new PendingCommandRegistry({ storage: new MemoryStorage() });
  358. const resolutions: string[] = [];
  359. const unsubscribe = registry.subscribeResolution("command-1", (resolution) => {
  360. resolutions.push(resolution);
  361. });
  362. registry.record(envelope());
  363. registry.reconcileSnapshot(
  364. snapshot([
  365. {
  366. rowId: 2,
  367. kind: "userInput",
  368. origin: "realUser",
  369. sourceCommandId: "command-1",
  370. text: "hello",
  371. } as ConversationSnapshot["rows"]["window"][number],
  372. ]),
  373. );
  374. unsubscribe();
  375. expect(resolutions).toEqual(["authoritative"]);
  376. expect(registry.list("session-1")).toEqual([]);
  377. });
  378. it("compact accepted 后保留恢复线索,直到 timeline marker 证明已开始执行", () => {
  379. const registry = new PendingCommandRegistry({
  380. storage: new MemoryStorage(),
  381. now: () => 1_000,
  382. });
  383. const command = envelope({ type: "compact", payload: {} });
  384. registry.record(command);
  385. registry.applyAck(command, ack("command-1", "accepted"));
  386. expect(registry.list("session-1")).toMatchObject([
  387. { replay: { kind: "input", type: "compact", payload: {} } },
  388. ]);
  389. registry.reconcileSnapshot(
  390. snapshot([
  391. {
  392. rowId: 1,
  393. turnId: "turn-1",
  394. createdAt: 1,
  395. createdAtSeq: 1,
  396. kind: "timelineMarker",
  397. sourceCommandId: "command-1",
  398. marker: { type: "compact", origin: "manual", status: "running" },
  399. },
  400. ]),
  401. );
  402. expect(registry.list("session-1")).toEqual([]);
  403. });
  404. it("携 firstInput 的 createSession accepted 后把账本迁到真实 session", () => {
  405. const registry = new PendingCommandRegistry({
  406. storage: new MemoryStorage(),
  407. now: () => 1_000,
  408. });
  409. const command = envelope({
  410. commandId: "create-1",
  411. sessionId: null,
  412. type: "createSession",
  413. payload: { workspaceId: "/repo", firstInput: { text: "hello" } },
  414. });
  415. registry.record(command);
  416. registry.applyAck(command, {
  417. ...ack("create-1", "accepted"),
  418. result: { type: "createSession", sessionId: "created-session" },
  419. });
  420. expect(registry.list(null)).toEqual([]);
  421. expect(registry.list("created-session")).toMatchObject([
  422. { commandId: "create-1", sessionId: "created-session" },
  423. ]);
  424. });
  425. it("unknown 静默清账,restart discarded 按 delivery 只保留 startNow 确认", () => {
  426. const registry = new PendingCommandRegistry({
  427. storage: new MemoryStorage(),
  428. now: () => 1_000,
  429. });
  430. for (const commandId of [
  431. "unknown",
  432. "discarded-start",
  433. "discarded-queue",
  434. "discarded-guide",
  435. "unavailable",
  436. ]) {
  437. registry.record(envelope({ commandId }));
  438. }
  439. registry.applyQuery({
  440. results: [
  441. { key: { sessionId: "session-1", commandId: "unknown" }, result: "unknown" },
  442. {
  443. key: { sessionId: "session-1", commandId: "discarded-start" },
  444. result: {
  445. ...ack("discarded-start", "failed", "fault.command.inputDiscardedOnRestart"),
  446. result: { type: "inputDisposition", delivery: "startNow" },
  447. },
  448. },
  449. {
  450. key: { sessionId: "session-1", commandId: "discarded-queue" },
  451. result: {
  452. ...ack("discarded-queue", "failed", "fault.command.inputDiscardedOnRestart"),
  453. result: { type: "inputDisposition", delivery: "queue" },
  454. },
  455. },
  456. {
  457. key: { sessionId: "session-1", commandId: "discarded-guide" },
  458. result: {
  459. ...ack("discarded-guide", "failed", "fault.command.inputDiscardedOnRestart"),
  460. result: { type: "inputDisposition", delivery: "guide" },
  461. },
  462. },
  463. {
  464. key: { sessionId: "session-1", commandId: "unavailable" },
  465. result: ack("unavailable", "failed", "fault.command.queryUnavailable"),
  466. },
  467. ],
  468. });
  469. expect(registry.listRecoverable("session-1").map((entry) => entry.recovery)).toEqual([
  470. "discarded",
  471. ]);
  472. expect(registry.list("session-1").map((entry) => entry.commandId)).not.toContain("unknown");
  473. expect(registry.list("session-1").map((entry) => entry.commandId)).not.toContain(
  474. "discarded-queue",
  475. );
  476. expect(registry.list("session-1").map((entry) => entry.commandId)).not.toContain(
  477. "discarded-guide",
  478. );
  479. expect(registry.list("session-1").map((entry) => entry.commandId)).toContain("unavailable");
  480. });
  481. it("reconnect query 按 64 分批且同 session 单飞,确认重发消费旧记录", async () => {
  482. const registry = new PendingCommandRegistry({
  483. storage: new MemoryStorage(),
  484. now: () => 1_000,
  485. });
  486. for (let index = 0; index < 65; index += 1) {
  487. registry.record(envelope({ commandId: `command-${index}` }));
  488. }
  489. const query = vi.fn(
  490. async (params: { commands: Array<{ sessionId: string | null; commandId: string }> }) => ({
  491. results: params.commands.map((key) => ({
  492. key,
  493. result: {
  494. ...ack(key.commandId, "failed", "fault.command.inputDiscardedOnRestart"),
  495. result: { type: "inputDisposition" as const, delivery: "startNow" as const },
  496. },
  497. })),
  498. }),
  499. );
  500. await Promise.all([
  501. registry.reconcileSession("session-1", query),
  502. registry.reconcileSession("session-1", query),
  503. ]);
  504. expect(query).toHaveBeenCalledTimes(2);
  505. expect(query.mock.calls.map(([params]) => params.commands.length)).toEqual([64, 1]);
  506. const replay = registry.consumeReplay({ sessionId: "session-1", commandId: "command-0" });
  507. expect(replay).toMatchObject({ type: "sendText", payload: { text: "hello" } });
  508. expect(registry.list("session-1").some((entry) => entry.commandId === "command-0")).toBe(false);
  509. });
  510. });