botGroupRuntimeSnapshot.test.ts 8.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259
  1. import { afterEach, describe, expect, it, vi } from "vitest";
  2. import type { ConversationSnapshot, ConversationTopicFrame } from "@zcode/shared/zcode-protocol-v4";
  3. import {
  4. readBotGroupRuntimeSnapshot,
  5. waitBotGroupExecutionEnd,
  6. } from "../src/zcode-agent/groupRuntimeSnapshot.js";
  7. afterEach(() => vi.useRealTimers());
  8. describe("group CLI snapshot read", () => {
  9. it("bounds a hanging subscribe and releases a late subscription", async () => {
  10. vi.useFakeTimers();
  11. const dispose = vi.fn();
  12. let acknowledge!: (result: { ack: { subscriptionId: string } }) => void;
  13. const agent = {
  14. onDynamicConversationFrame: () => () => ({ dispose }),
  15. subscribeConversationV4: () =>
  16. new Promise((resolve) => {
  17. acknowledge = resolve;
  18. }),
  19. unsubscribeConversationV4: vi.fn(async () => undefined),
  20. };
  21. const result = readBotGroupRuntimeSnapshot(agent as never, {
  22. workspacePath: "/work",
  23. sessionId: "task",
  24. }).catch((error) => error);
  25. await vi.advanceTimersByTimeAsync(15000);
  26. expect(await result).toBeInstanceOf(Error);
  27. expect(dispose).toHaveBeenCalledOnce();
  28. acknowledge({ ack: { subscriptionId: "late" } });
  29. await vi.advanceTimersByTimeAsync(0);
  30. expect(agent.unsubscribeConversationV4).toHaveBeenCalledWith(
  31. expect.objectContaining({ subscriptionId: "late" }),
  32. );
  33. }, 1000);
  34. it("registers before subscribe, matches its subscription and always releases it", async () => {
  35. let listener: (value: unknown) => void = () => {};
  36. const dispose = vi.fn();
  37. const frame = makeSnapshotFrame("test");
  38. const snapshot = frame.payload.kind === "snapshot" ? frame.payload.snapshot : undefined;
  39. const agent = {
  40. onDynamicConversationFrame: vi.fn(() => (handler: typeof listener) => {
  41. listener = handler;
  42. return { dispose };
  43. }),
  44. subscribeConversationV4: vi.fn(async () => {
  45. listener({
  46. wireVersion: 1,
  47. kind: "complete",
  48. deliveryKind: "initial",
  49. logicalFrameId: "initial",
  50. logicalFrameOrdinal: 1,
  51. topic: "conversation/task",
  52. subscriptionId: "other",
  53. frame: { ...frame, subscriptionId: "other" },
  54. });
  55. listener({
  56. wireVersion: 1,
  57. kind: "complete",
  58. deliveryKind: "initial",
  59. logicalFrameId: "initial",
  60. logicalFrameOrdinal: 1,
  61. topic: "conversation/task",
  62. subscriptionId: "mine",
  63. frame,
  64. });
  65. return { ack: { subscriptionId: "mine" } };
  66. }),
  67. unsubscribeConversationV4: vi.fn(async () => undefined),
  68. };
  69. expect(
  70. await readBotGroupRuntimeSnapshot(agent as never, {
  71. workspacePath: "/work",
  72. workspaceIdentity: "ssh://host/work",
  73. sessionId: "task",
  74. }),
  75. ).toEqual(snapshot);
  76. expect(agent.unsubscribeConversationV4).toHaveBeenCalledWith(
  77. expect.objectContaining({ subscriptionId: "mine", workspaceIdentity: "ssh://host/work" }),
  78. );
  79. expect(dispose).toHaveBeenCalledOnce();
  80. });
  81. });
  82. describe("topic authoritative stop barrier", () => {
  83. function setup() {
  84. let listener: (value: unknown) => void = () => {};
  85. const frame = makeSnapshotFrame("topic");
  86. if (frame.payload.kind !== "snapshot") throw new Error("fixture");
  87. frame.payload.snapshot.control.activeWorks[0]!.foregroundExecutionId = "old";
  88. let ordinal = 0;
  89. const emit = (value: ConversationTopicFrame) =>
  90. listener({
  91. wireVersion: 1,
  92. kind: "complete",
  93. deliveryKind: ordinal ? "online" : "initial",
  94. logicalFrameId: `frame-${++ordinal}`,
  95. logicalFrameOrdinal: ordinal,
  96. topic: "conversation/task",
  97. subscriptionId: "mine",
  98. frame: value,
  99. });
  100. const agent = {
  101. onDynamicConversationFrame: () => (handler: typeof listener) => {
  102. listener = handler;
  103. return { dispose: vi.fn() };
  104. },
  105. subscribeConversationV4: vi.fn(async () => {
  106. emit(frame);
  107. return { ack: { subscriptionId: "mine" } };
  108. }),
  109. unsubscribeConversationV4: vi.fn(async () => undefined),
  110. };
  111. const terminal = (fromSeq = 11): ConversationTopicFrame => ({
  112. ...frame,
  113. fromSeq,
  114. toSeq: fromSeq + 1,
  115. payload: {
  116. kind: "deltas",
  117. deltas: [
  118. {
  119. op: "state.updated",
  120. patch: {
  121. control: {
  122. ...(frame.payload as { kind: "snapshot"; snapshot: ConversationSnapshot }).snapshot
  123. .control,
  124. phase: "completedInterrupted",
  125. sessionEnded: true,
  126. canStop: false,
  127. stopState: "idle",
  128. activeWorks: [],
  129. },
  130. },
  131. },
  132. ],
  133. },
  134. });
  135. return { agent, emit, terminal };
  136. }
  137. it("waits for terminal control instead of resolving on the initial running snapshot", async () => {
  138. const f = setup();
  139. let done = false;
  140. const waiting = waitBotGroupExecutionEnd(
  141. f.agent as never,
  142. { workspacePath: "/work", sessionId: "task" },
  143. "old",
  144. ).then(() => {
  145. done = true;
  146. });
  147. for (let i = 0; i < 8; i++) await Promise.resolve();
  148. expect(done).toBe(false);
  149. f.emit(f.terminal());
  150. await waiting;
  151. expect(done).toBe(true);
  152. expect(f.agent.unsubscribeConversationV4).toHaveBeenCalledOnce();
  153. });
  154. it("releases its subscription when the stop command fails or is cancelled", async () => {
  155. const f = setup();
  156. const abort = new AbortController();
  157. const waiting = waitBotGroupExecutionEnd(
  158. f.agent as never,
  159. { workspacePath: "/work", sessionId: "task" },
  160. "old",
  161. abort.signal,
  162. );
  163. for (let i = 0; i < 8; i++) await Promise.resolve();
  164. const rejected = expect(waiting).rejects.toThrow();
  165. abort.abort();
  166. for (let i = 0; i < 8; i++) await Promise.resolve();
  167. expect(f.agent.unsubscribeConversationV4).toHaveBeenCalledOnce();
  168. await rejected;
  169. expect(f.agent.unsubscribeConversationV4).toHaveBeenCalledOnce();
  170. });
  171. it("rejects a missing control interval instead of assuming stop completed", async () => {
  172. const f = setup();
  173. const waiting = waitBotGroupExecutionEnd(
  174. f.agent as never,
  175. { workspacePath: "/work", sessionId: "task" },
  176. "old",
  177. );
  178. for (let i = 0; i < 8; i++) await Promise.resolve();
  179. f.emit(f.terminal(50));
  180. await expect(waiting).rejects.toThrow(/gap/i);
  181. });
  182. });
  183. function makeSnapshotFrame(title: string): ConversationTopicFrame {
  184. const snapshot: ConversationSnapshot = {
  185. protocolVersion: 1,
  186. sessionId: "task",
  187. logEpoch: "epoch-wire",
  188. seq: 11,
  189. revision: 1,
  190. control: {
  191. phase: "running",
  192. sessionEnded: false,
  193. canStop: true,
  194. stopState: "stoppable",
  195. stopTargetKind: "assistant",
  196. activeWorks: [{ kind: "primaryTurn", startedAt: 1_000 }],
  197. lastError: null,
  198. apiRetry: null,
  199. },
  200. availability: {
  201. fork: { allowed: true },
  202. compact: { allowed: true },
  203. switchModelConfig: { allowed: true },
  204. setFollowupMode: { allowed: true },
  205. queueEdit: { allowed: true },
  206. sendQueuedNow: { allowed: true },
  207. pauseGoal: { allowed: false, reasonCode: "guard.noGoal" },
  208. resumeGoal: { allowed: false, reasonCode: "guard.noGoal" },
  209. },
  210. inputRouting: { mode: "enqueue" },
  211. meta: { title, titleSource: "custom" },
  212. config: {
  213. provider: "glm",
  214. model: "glm-5",
  215. thought: "medium",
  216. thoughtLevels: [],
  217. followupMode: "queue",
  218. mode: "build",
  219. },
  220. modelTransition: null,
  221. usage: {
  222. contextWindow: {
  223. usedTokens: 0,
  224. maxTokens: 200_000,
  225. autoCompactThresholdTokens: null,
  226. },
  227. cumulative: {
  228. inputTokens: 0,
  229. outputTokens: 0,
  230. cacheReadTokens: 0,
  231. cacheWriteTokens: 0,
  232. },
  233. },
  234. queue: { items: [], autoDrain: true },
  235. pendingInteractions: [],
  236. pendingCommands: [],
  237. backgroundWorks: [],
  238. // 软门禁 additive 字段:归一化形态(带 default(null))
  239. workspaceHookAdmission: null,
  240. goal: null,
  241. plan: null,
  242. rows: { window: [], totalCount: 0, firstRowId: null },
  243. };
  244. return {
  245. topic: "conversation/task",
  246. subscriptionId: "mine",
  247. fromSeq: 0,
  248. toSeq: snapshot.seq,
  249. sentAt: 1_700_000_000_000,
  250. payload: { kind: "snapshot", snapshot },
  251. };
  252. }