product-projection-open-tools.test.ts 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397
  1. import { describe, expect, it } from "vitest";
  2. import {
  3. SessionEventType,
  4. type EventId,
  5. type SessionEvent,
  6. type SessionEventType as SessionEventTypeUnion,
  7. type SessionId,
  8. type TraceId,
  9. type TurnId,
  10. } from "@zcode/contracts";
  11. import {
  12. applyConversationDeltas,
  13. type ConversationDelta,
  14. type ConversationSnapshot,
  15. type ToolCallRow,
  16. } from "@zcode/shared/zcode-protocol-v4";
  17. import { ProductProjection } from "../src/zcode-protocol-v4/index.js";
  18. const SESSION_ID = "open-tool-index-session";
  19. interface ProductProjectionOpenToolInternals {
  20. snapshot: ConversationSnapshot;
  21. openForegroundToolCallIds: Set<string>;
  22. toolRowIdByCallId: Map<string, number>;
  23. closeOpenToolRows(event: SessionEvent, status: "cancelled" | "error"): ConversationDelta[];
  24. updateToolIndexesAfterDeltas(deltas: readonly ConversationDelta[]): void;
  25. }
  26. class ProjectionHarness {
  27. readonly projection: ProductProjection;
  28. private sequenceNumber = 0;
  29. constructor(epoch: string) {
  30. this.projection = new ProductProjection(SESSION_ID, epoch);
  31. this.apply(SessionEventType.SessionCreated, { mode: "default", contextWindow: 200_000 });
  32. }
  33. get internals(): ProductProjectionOpenToolInternals {
  34. return projectionInternals(this.projection);
  35. }
  36. event(type: SessionEventTypeUnion, payload: unknown, turnId?: string): SessionEvent {
  37. this.sequenceNumber += 1;
  38. return {
  39. id: `open-tool-event-${this.sequenceNumber}` as EventId,
  40. sessionId: SESSION_ID as SessionId,
  41. ...(turnId ? { turnId: turnId as TurnId } : {}),
  42. type,
  43. timestamp: new Date(1_700_000_000_000 + this.sequenceNumber),
  44. traceId: "open-tool-trace" as TraceId,
  45. sequenceNumber: this.sequenceNumber,
  46. payload,
  47. };
  48. }
  49. apply(type: SessionEventTypeUnion, payload: unknown, turnId?: string): SessionEvent {
  50. const event = this.event(type, payload, turnId);
  51. this.projection.applyEvent(event);
  52. return event;
  53. }
  54. startTurn(turnId: string, turnNumber: number, messageId = `user-${turnNumber}`): void {
  55. this.apply(
  56. SessionEventType.TurnStarted,
  57. { turnNumber, input: `turn ${turnNumber}`, messageId },
  58. turnId,
  59. );
  60. }
  61. scheduleTool(turnId: string, toolCallId: string): void {
  62. this.apply(
  63. SessionEventType.ToolCallScheduled,
  64. {
  65. toolCallId,
  66. toolName: "Bash",
  67. input: { command: "pwd" },
  68. schedule: { parallelGroups: [[toolCallId]], executionOrder: [toolCallId] },
  69. },
  70. turnId,
  71. );
  72. }
  73. toolRow(toolCallId: string): ToolCallRow {
  74. const row = this.projection
  75. .getSnapshot()
  76. .rows.window.find(
  77. (candidate): candidate is ToolCallRow =>
  78. candidate.kind === "toolCall" && candidate.toolCallId === toolCallId,
  79. );
  80. if (!row) throw new Error(`missing tool row ${toolCallId}`);
  81. return row;
  82. }
  83. completeTurn(turnId: string, resultType: "success" | "cancelled" = "success"): void {
  84. this.apply(
  85. SessionEventType.TurnComplete,
  86. { response: "", tokenCount: 0, toolCallCount: 1, duration: 1, resultType },
  87. turnId,
  88. );
  89. }
  90. }
  91. function projectionInternals(projection: ProductProjection): ProductProjectionOpenToolInternals {
  92. return projection as unknown as ProductProjectionOpenToolInternals;
  93. }
  94. describe("ProductProjection open foreground tool index", () => {
  95. it("TurnComplete 只遍历 open tracker,不枚举完整 rows 窗口", () => {
  96. const harness = new ProjectionHarness("epoch-scan");
  97. harness.startTurn("turn-scan", 1);
  98. harness.scheduleTool("turn-scan", "tool-scan");
  99. const internals = harness.internals;
  100. expect([...internals.openForegroundToolCallIds]).toEqual(["tool-scan"]);
  101. const originalSnapshot = internals.snapshot;
  102. internals.snapshot = {
  103. ...originalSnapshot,
  104. rows: {
  105. ...originalSnapshot.rows,
  106. window: new Proxy(originalSnapshot.rows.window, {
  107. get(target, property, receiver) {
  108. if (property === Symbol.iterator) {
  109. throw new Error("closeOpenToolRows must not enumerate the rows window");
  110. }
  111. return Reflect.get(target, property, receiver);
  112. },
  113. }),
  114. },
  115. };
  116. try {
  117. const deltas = internals.closeOpenToolRows(
  118. harness.event(
  119. SessionEventType.TurnComplete,
  120. { response: "", tokenCount: 0, toolCallCount: 1, duration: 1, resultType: "success" },
  121. "turn-scan",
  122. ),
  123. "error",
  124. );
  125. expect(deltas).toEqual([
  126. expect.objectContaining({
  127. op: "row.upserted",
  128. row: expect.objectContaining({ toolCallId: "tool-scan", status: "error" }),
  129. }),
  130. ]);
  131. } finally {
  132. internals.snapshot = originalSnapshot;
  133. }
  134. });
  135. it("缺 terminal 的 permission tool 被收口,迟到 allow 重新打开后仍会再次收口", () => {
  136. const harness = new ProjectionHarness("epoch-reopen");
  137. harness.startTurn("turn-1", 1);
  138. harness.scheduleTool("turn-1", "tool-reopen");
  139. harness.apply(
  140. SessionEventType.PermissionRequested,
  141. {
  142. requestId: "permission-reopen",
  143. toolCallId: "tool-reopen",
  144. toolName: "Bash",
  145. riskLevel: "medium",
  146. reason: "Run command",
  147. input: { command: "pwd" },
  148. },
  149. "turn-1",
  150. );
  151. expect(harness.projection.getSnapshot().pendingInteractions).toHaveLength(1);
  152. harness.completeTurn("turn-1");
  153. expect(harness.toolRow("tool-reopen")).toMatchObject({
  154. status: "error",
  155. error: { code: "fault.runtime.toolLifecycleIncomplete" },
  156. });
  157. expect(harness.projection.getSnapshot().pendingInteractions).toEqual([]);
  158. expect(harness.internals.openForegroundToolCallIds.size).toBe(0);
  159. harness.startTurn("turn-2", 2);
  160. harness.apply(
  161. SessionEventType.PermissionResolved,
  162. { requestId: "permission-reopen", toolCallId: "tool-reopen", decision: "allow" },
  163. "turn-1",
  164. );
  165. expect(harness.toolRow("tool-reopen").status).toBe("running");
  166. expect([...harness.internals.openForegroundToolCallIds]).toEqual(["tool-reopen"]);
  167. harness.completeTurn("turn-2");
  168. expect(harness.toolRow("tool-reopen").status).toBe("error");
  169. expect(harness.internals.openForegroundToolCallIds.size).toBe(0);
  170. });
  171. it("多个旧 tool 逆序 reopen 后仍按 snapshot row 顺序下发收口 delta", () => {
  172. const harness = new ProjectionHarness("epoch-reopen-order");
  173. harness.startTurn("turn-order-1", 1);
  174. harness.scheduleTool("turn-order-1", "tool-order-a");
  175. harness.scheduleTool("turn-order-1", "tool-order-b");
  176. harness.completeTurn("turn-order-1");
  177. harness.startTurn("turn-order-2", 2);
  178. for (const toolCallId of ["tool-order-b", "tool-order-a"]) {
  179. harness.apply(
  180. SessionEventType.ToolCallStarted,
  181. { toolCallId, toolName: "Bash", startedAt: new Date() },
  182. "turn-order-1",
  183. );
  184. }
  185. const terminal = harness.event(
  186. SessionEventType.TurnComplete,
  187. { response: "", tokenCount: 0, toolCallCount: 2, duration: 1, resultType: "success" },
  188. "turn-order-2",
  189. );
  190. const closedToolCallIds = harness.projection
  191. .applyEvent(terminal)
  192. .flatMap((delta) =>
  193. delta.op === "row.upserted" && delta.row.kind === "toolCall" ? [delta.row.toolCallId] : [],
  194. );
  195. expect(closedToolCallIds).toEqual(["tool-order-a", "tool-order-b"]);
  196. });
  197. it.each([
  198. { terminal: "cancelled" as const, expectedStatus: "cancelled" as const },
  199. { terminal: "error" as const, expectedStatus: "error" as const },
  200. ])("$terminal turn 正确收口 tracker 中的 foreground tool", ({ terminal, expectedStatus }) => {
  201. const harness = new ProjectionHarness(`epoch-${terminal}`);
  202. harness.startTurn(`turn-${terminal}`, 1);
  203. harness.scheduleTool(`turn-${terminal}`, `tool-${terminal}`);
  204. if (terminal === "cancelled") {
  205. harness.completeTurn(`turn-${terminal}`, "cancelled");
  206. } else {
  207. harness.apply(
  208. SessionEventType.TurnError,
  209. { error: { type: "ProviderError", message: "failed" }, turnPhase: "model" },
  210. `turn-${terminal}`,
  211. );
  212. }
  213. expect(harness.toolRow(`tool-${terminal}`).status).toBe(expectedStatus);
  214. expect(harness.internals.openForegroundToolCallIds.size).toBe(0);
  215. });
  216. it("backgrounded tool 不进入 tracker,也不会被 turn terminal 收口", () => {
  217. const harness = new ProjectionHarness("epoch-background");
  218. harness.startTurn("turn-background", 1);
  219. harness.scheduleTool("turn-background", "tool-background");
  220. const internals = harness.internals;
  221. const backgrounded: ToolCallRow = {
  222. ...harness.toolRow("tool-background"),
  223. backgrounded: true,
  224. workId: "work-background",
  225. };
  226. const delta: ConversationDelta = { op: "row.upserted", row: backgrounded };
  227. internals.snapshot = applyConversationDeltas(internals.snapshot, [delta]);
  228. internals.updateToolIndexesAfterDeltas([delta]);
  229. expect(internals.openForegroundToolCallIds.size).toBe(0);
  230. expect(
  231. internals.closeOpenToolRows(
  232. harness.event(
  233. SessionEventType.TurnComplete,
  234. { response: "", tokenCount: 0, toolCallCount: 1, duration: 1, resultType: "success" },
  235. "turn-background",
  236. ),
  237. "error",
  238. ),
  239. ).toEqual([]);
  240. expect(harness.toolRow("tool-background")).toMatchObject({
  241. status: "inputStreaming",
  242. backgrounded: true,
  243. });
  244. });
  245. it("rewind 清理 open/tool 索引,同 toolCallId 可在新分支重新打开并收口", () => {
  246. const harness = new ProjectionHarness("epoch-rewind");
  247. harness.startTurn("turn-old", 1, "message-old");
  248. harness.apply(
  249. SessionEventType.ModelStreaming,
  250. {
  251. kind: "tool_input_start",
  252. delta: "",
  253. done: false,
  254. toolCallId: "tool-reused",
  255. toolName: "Bash",
  256. },
  257. "turn-old",
  258. );
  259. expect([...harness.internals.openForegroundToolCallIds]).toEqual(["tool-reused"]);
  260. harness.apply(SessionEventType.RewindTriggered, {
  261. targetMessageId: "message-old",
  262. scope: "conversation",
  263. createdMessageId: "rewind-applied",
  264. });
  265. expect(harness.projection.getSnapshot().rows.window).toEqual([]);
  266. expect(harness.internals.openForegroundToolCallIds.size).toBe(0);
  267. expect(harness.internals.toolRowIdByCallId.has("tool-reused")).toBe(false);
  268. harness.startTurn("turn-new", 2, "message-new");
  269. harness.apply(
  270. SessionEventType.ModelStreaming,
  271. {
  272. kind: "tool_input_start",
  273. delta: "",
  274. done: false,
  275. toolCallId: "tool-reused",
  276. toolName: "Bash",
  277. },
  278. "turn-new",
  279. );
  280. expect(harness.toolRow("tool-reused").status).toBe("inputStreaming");
  281. expect([...harness.internals.openForegroundToolCallIds]).toEqual(["tool-reused"]);
  282. harness.completeTurn("turn-new", "cancelled");
  283. expect(harness.toolRow("tool-reused").status).toBe("cancelled");
  284. expect(harness.internals.openForegroundToolCallIds.size).toBe(0);
  285. });
  286. it("atomic reject 不泄漏 tracker,accept 后随候选状态一起 adopt", () => {
  287. const harness = new ProjectionHarness("epoch-atomic");
  288. harness.startTurn("turn-atomic", 1);
  289. harness.scheduleTool("turn-atomic", "tool-atomic");
  290. const before = structuredClone(harness.projection.getSnapshot());
  291. const result = harness.event(
  292. SessionEventType.ToolCallResult,
  293. { toolCallId: "tool-atomic", result: { success: true, content: "ok" }, duration: 1 },
  294. "turn-atomic",
  295. );
  296. expect(harness.projection.applyEventAtomically(result, () => false)).toBeNull();
  297. expect(harness.projection.getSnapshot()).toEqual(before);
  298. expect([...harness.internals.openForegroundToolCallIds]).toEqual(["tool-atomic"]);
  299. expect(harness.projection.applyEventAtomically(result, () => true)).not.toBeNull();
  300. expect(harness.toolRow("tool-atomic").status).toBe("success");
  301. expect(harness.internals.openForegroundToolCallIds.size).toBe(0);
  302. });
  303. it("cold batch 与 strict replay 的 tracker 和最终 snapshot 等价", () => {
  304. const source = new ProjectionHarness("epoch-source");
  305. const history = [
  306. source.event(SessionEventType.SessionCreated, {
  307. mode: "default",
  308. contextWindow: 200_000,
  309. }),
  310. source.event(
  311. SessionEventType.TurnStarted,
  312. { turnNumber: 1, input: "run", messageId: "user-cold" },
  313. "turn-cold",
  314. ),
  315. source.event(
  316. SessionEventType.ToolCallScheduled,
  317. {
  318. toolCallId: "tool-cold",
  319. toolName: "Bash",
  320. input: { command: "pwd" },
  321. schedule: { parallelGroups: [["tool-cold"]], executionOrder: ["tool-cold"] },
  322. },
  323. "turn-cold",
  324. ),
  325. source.event(
  326. SessionEventType.PermissionRequested,
  327. {
  328. requestId: "permission-cold",
  329. toolCallId: "tool-cold",
  330. toolName: "Bash",
  331. riskLevel: "medium",
  332. reason: "Run command",
  333. input: { command: "pwd" },
  334. },
  335. "turn-cold",
  336. ),
  337. ];
  338. const strict = new ProductProjection(SESSION_ID, "epoch-equivalent");
  339. const batch = new ProductProjection(SESSION_ID, "epoch-equivalent");
  340. for (const event of history) strict.applyEvent(event);
  341. batch.beginHydrationReplay();
  342. for (const event of history) batch.applyHydrationEvent(event);
  343. batch.completeHydrationReplay();
  344. expect(batch.getSnapshot()).toEqual(strict.getSnapshot());
  345. expect([...projectionInternals(batch).openForegroundToolCallIds]).toEqual(["tool-cold"]);
  346. expect(projectionInternals(batch).openForegroundToolCallIds).toEqual(
  347. projectionInternals(strict).openForegroundToolCallIds,
  348. );
  349. const terminal = source.event(
  350. SessionEventType.TurnComplete,
  351. { response: "", tokenCount: 0, toolCallCount: 1, duration: 1, resultType: "success" },
  352. "turn-cold",
  353. );
  354. strict.applyEvent(terminal);
  355. batch.applyEvent(terminal);
  356. expect(batch.getSnapshot()).toEqual(strict.getSnapshot());
  357. expect(projectionInternals(batch).openForegroundToolCallIds.size).toBe(0);
  358. });
  359. });