v4-history-first.test.ts 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413
  1. import { SessionLifecycleController } from "../src/session-lifecycle/index.js";
  2. import {
  3. applyConversationDeltas,
  4. type ConversationSnapshot,
  5. } from "@zcode/shared/zcode-protocol-v4";
  6. import { describe, expect, it, vi } from "vitest";
  7. import { ConversationV4Gateway } from "../src/zcode-protocol-v4/v4-gateway.js";
  8. import type { ConversationTopicFrame } from "@zcode/shared/zcode-protocol-v4";
  9. function deferred() {
  10. let resolve!: () => void;
  11. let reject!: (error: Error) => void;
  12. const promise = new Promise<void>((yes, no) => {
  13. resolve = yes;
  14. reject = no;
  15. });
  16. return { promise, resolve, reject };
  17. }
  18. function setup(
  19. lookupTranscriptCommand?: () => {
  20. commandId: string;
  21. status: "accepted";
  22. revisionAtDecision: number;
  23. },
  24. retainSessionRuntime?: () => Promise<() => void>,
  25. ) {
  26. const gate = deferred();
  27. const frames: ConversationTopicFrame[] = [];
  28. let observed: ConversationSnapshot | undefined;
  29. const execute = vi.fn();
  30. const resume = vi.fn(async () => {
  31. await gate.promise;
  32. return { status: "resumed" as const, persistedMessages: [] };
  33. });
  34. const read = vi.fn(async () => []);
  35. const loadPersistedEvents = vi.fn(async () => ({
  36. events: [],
  37. synthesized: true,
  38. sourceEventSeq: 0,
  39. }));
  40. const gateway = new ConversationV4Gateway({
  41. sessionExists: () => false,
  42. executeCommand: execute,
  43. lookupTranscriptCommand,
  44. retainSessionRuntime,
  45. loadPersistedMessages: read,
  46. resumePersistedSession: resume,
  47. loadPersistedEvents,
  48. emitWireFrame: (wire) => {
  49. if (wire.kind === "complete") {
  50. const frame = wire.frame as ConversationTopicFrame;
  51. frames.push(frame);
  52. if (frame.payload.kind === "snapshot") observed = frame.payload.snapshot;
  53. else if (observed)
  54. observed = {
  55. ...applyConversationDeltas(observed, frame.payload.deltas),
  56. seq: frame.toSeq,
  57. };
  58. }
  59. },
  60. });
  61. const params = {
  62. topic: "conversation/history",
  63. connectionId: "desktop",
  64. clientMode: "desktop-continuous",
  65. historyFirst: true,
  66. };
  67. const snapshot = () => observed;
  68. return {
  69. gateway,
  70. gate,
  71. frames,
  72. execute,
  73. resume,
  74. read,
  75. params,
  76. snapshot,
  77. loadPersistedEvents,
  78. seed: (frame: ConversationTopicFrame | null) => {
  79. if (frame?.payload.kind === "snapshot") observed = frame.payload.snapshot;
  80. },
  81. };
  82. }
  83. function setupOwned() {
  84. const fixture = setup();
  85. const activate = vi.fn(
  86. async (_messages: import("@zcode/contracts").MessageWithParts[]) => undefined,
  87. );
  88. let active = false;
  89. const lifecycle = new SessionLifecycleController({
  90. exists: async () => true,
  91. validateActivation: async () => {},
  92. hasRuntime: () => active,
  93. assertCanStop: () => {},
  94. activate: async () => {
  95. const messages = await fixture.gateway.prepareSessionHistory("history");
  96. await activate(messages);
  97. active = true;
  98. },
  99. release: async (_id, failed) => {
  100. active = false;
  101. if (!failed) await fixture.gateway.releaseSessionProjection("history");
  102. },
  103. });
  104. fixture.resume.mockImplementation(async () => {
  105. await lifecycle.ensureReady("history");
  106. return { status: "resumed", persistedMessages: [] };
  107. });
  108. return { ...fixture, lifecycle, activate };
  109. }
  110. describe("history-first cold subscription", () => {
  111. it.each(["desktop-continuous", "web-remote-replayable"])(
  112. "%s reads history while an earlier legacy title handoff is waiting for activation",
  113. async (clientMode) => {
  114. const { gateway, gate, resume, read, execute, params, seed, snapshot } = setup();
  115. const workspace = { workspacePath: "/project", workspaceKey: "/project" };
  116. const rename = gateway.handleCommand({
  117. sessionId: "history",
  118. commandId: "legacy-title",
  119. clientId: "host",
  120. issuedAt: 1,
  121. type: "renameSession",
  122. payload: { title: "Migrated title" },
  123. workspace,
  124. });
  125. try {
  126. await vi.waitFor(() => expect(resume).toHaveBeenCalledTimes(1));
  127. let opened = false;
  128. const history = gateway.subscribe({ ...params, clientMode, workspace }).then((result) => {
  129. seed(result.initialFrame);
  130. opened = true;
  131. });
  132. // 保持激活屏障关闭,证明历史首帧不等待先到的迁移命令。
  133. await vi.waitFor(() => expect(opened).toBe(true));
  134. await history;
  135. expect(snapshot()?.runtimeInitialization?.status).toBe("initializing");
  136. expect(execute).not.toHaveBeenCalled();
  137. let legacyOpened = false;
  138. const legacy = gateway
  139. .subscribe({ ...params, connectionId: "legacy", historyFirst: false })
  140. .then(() => {
  141. legacyOpened = true;
  142. });
  143. await new Promise<void>((resolve) => setImmediate(resolve));
  144. expect(legacyOpened).toBe(false);
  145. gate.resolve();
  146. await rename;
  147. await legacy;
  148. expect(snapshot()?.runtimeInitialization?.status).toBe("ready");
  149. expect(resume).toHaveBeenCalledTimes(1);
  150. expect(read).toHaveBeenCalledTimes(1);
  151. expect(execute).toHaveBeenCalledTimes(1);
  152. } finally {
  153. gate.resolve();
  154. await rename;
  155. gateway.dispose();
  156. }
  157. },
  158. );
  159. it("retries a failed owned activation without waiting on the old failed publisher", async () => {
  160. const { gateway, lifecycle, activate, params, seed, snapshot } = setupOwned();
  161. activate.mockRejectedValueOnce(new Error("startup failed"));
  162. await expect(lifecycle.ensureReady("history")).rejects.toThrow("startup failed");
  163. await lifecycle.ensureReady("history");
  164. expect(activate).toHaveBeenCalledTimes(2);
  165. seed((await gateway.subscribe(params)).initialFrame);
  166. await vi.waitFor(() => expect(snapshot()?.runtimeInitialization?.status).toBe("ready"));
  167. gateway.dispose();
  168. });
  169. it("rejects late subscription and command admission while the session is stopping", async () => {
  170. const executeCommand = vi.fn();
  171. const gateway = new ConversationV4Gateway({
  172. sessionExists: () => true,
  173. isSessionStopping: () => true,
  174. executeCommand,
  175. emitWireFrame: () => {},
  176. });
  177. await expect(
  178. gateway.subscribe({
  179. topic: "conversation/history",
  180. connectionId: "desktop",
  181. clientMode: "desktop-continuous",
  182. }),
  183. ).rejects.toThrow("fault.sessionLifecycle.stopping");
  184. await expect(
  185. gateway.handleCommand({
  186. sessionId: "history",
  187. commandId: "late-rename",
  188. clientId: "desktop",
  189. issuedAt: 1,
  190. type: "renameSession",
  191. payload: { title: "late" },
  192. expectedRevision: 0,
  193. }),
  194. ).resolves.toMatchObject({ status: "failed" });
  195. expect(executeCommand).not.toHaveBeenCalled();
  196. gateway.dispose();
  197. });
  198. it("waits for old final hydration before releasing the publisher", async () => {
  199. const { gateway, lifecycle, loadPersistedEvents } = setupOwned();
  200. const hydrationEntered = deferred();
  201. const hydrationGate = deferred();
  202. loadPersistedEvents
  203. .mockImplementationOnce(async () => ({ events: [], synthesized: true, sourceEventSeq: 0 }))
  204. .mockImplementationOnce(async () => {
  205. hydrationEntered.resolve();
  206. await hydrationGate.promise;
  207. return { events: [], synthesized: true, sourceEventSeq: 0 };
  208. });
  209. await lifecycle.ensureReady("history");
  210. await hydrationEntered.promise;
  211. let released = false;
  212. const release = gateway.releaseSessionProjection("history").then(() => {
  213. released = true;
  214. });
  215. await Promise.resolve();
  216. expect(released).toBe(false);
  217. hydrationGate.resolve();
  218. await release;
  219. expect(released).toBe(true);
  220. gateway.dispose();
  221. });
  222. it("opens fresh history during an externally owned restart without recursively resuming", async () => {
  223. const { gateway, lifecycle, activate, params, read, snapshot, seed } = setupOwned();
  224. const gate = deferred();
  225. activate.mockImplementationOnce(async () => {
  226. await gate.promise;
  227. });
  228. const restarting = lifecycle.restart("history");
  229. await vi.waitFor(() => expect(activate).toHaveBeenCalledTimes(1));
  230. seed((await gateway.subscribe(params)).initialFrame);
  231. expect(snapshot()?.runtimeInitialization?.status).toBe("initializing");
  232. expect(read).toHaveBeenCalledTimes(1);
  233. await vi.waitFor(() => expect(activate).toHaveBeenCalledTimes(1));
  234. gate.resolve();
  235. await restarting;
  236. await vi.waitFor(() => expect(snapshot()?.runtimeInitialization?.status).toBe("ready"));
  237. gateway.dispose();
  238. });
  239. it("completes an externally owned restart without any subscriber", async () => {
  240. const { gateway, lifecycle, activate } = setupOwned();
  241. await lifecycle.restart("history");
  242. expect(activate).toHaveBeenCalledTimes(1);
  243. gateway.dispose();
  244. });
  245. it.each(["desktop-continuous", "web-remote-replayable"])(
  246. "%s preserves project directories alongside the persisted history snapshot",
  247. async (clientMode) => {
  248. const { gateway, gate, resume, params, snapshot, seed } = setup();
  249. const workspace = { workspacePath: "/project", workspaceKey: "/project" };
  250. const additionalDirectories = ["/shared"];
  251. seed(
  252. (await gateway.subscribe({ ...params, clientMode, workspace, additionalDirectories }))
  253. .initialFrame,
  254. );
  255. await vi.waitFor(() => expect(resume).toHaveBeenCalledTimes(1));
  256. expect(resume).toHaveBeenCalledWith(
  257. "history",
  258. undefined,
  259. workspace,
  260. additionalDirectories,
  261. [],
  262. );
  263. gate.resolve();
  264. await vi.waitFor(() => expect(snapshot()?.runtimeInitialization?.status).toBe("ready"));
  265. gateway.dispose();
  266. },
  267. );
  268. it("publishes history before activation and rejects execution while restoring", async () => {
  269. const { gateway, gate, resume, read, execute, params, snapshot, seed } = setup();
  270. const dispatch = await gateway.subscribeReserved(params);
  271. expect(resume).not.toHaveBeenCalled();
  272. expect(dispatch.initialFrame?.payload.kind).toBe("snapshot");
  273. if (dispatch.initialFrame?.payload.kind !== "snapshot") throw new Error("missing history");
  274. expect(dispatch.initialFrame.payload.snapshot.runtimeInitialization?.status).toBe(
  275. "initializing",
  276. );
  277. seed(dispatch.initialFrame);
  278. dispatch.commit();
  279. await vi.waitFor(() => expect(resume).toHaveBeenCalledTimes(1));
  280. const rows = await gateway.rowsRange({ sessionId: "history", limit: 10 });
  281. expect(rows.rows).toEqual([]);
  282. const ack = await gateway.handleCommand({
  283. commandId: "early",
  284. sessionId: "history",
  285. type: "compact",
  286. payload: {},
  287. clientId: "client",
  288. issuedAt: Date.now(),
  289. });
  290. expect(ack.status).toBe("rejected");
  291. expect(ack.reasonCode).toBe("guard.runtimeInitializing");
  292. expect(execute).not.toHaveBeenCalled();
  293. gate.resolve();
  294. await vi.waitFor(() => expect(snapshot()?.runtimeInitialization?.status).toBe("ready"));
  295. expect(read).toHaveBeenCalledTimes(1);
  296. gateway.dispose();
  297. });
  298. it("retains failed history until explicit retry and coalesces repeated retry", async () => {
  299. const { gateway, gate, resume, params, snapshot, seed } = setup();
  300. seed((await gateway.subscribe(params)).initialFrame);
  301. await vi.waitFor(() => expect(resume).toHaveBeenCalledTimes(1));
  302. gate.reject(new Error("hook unavailable"));
  303. await vi.waitFor(() => expect(snapshot()?.runtimeInitialization?.status).toBe("failed"));
  304. const attempt = snapshot()!.runtimeInitialization!.attemptId;
  305. await gateway.subscribe({ ...params, connectionId: "reconnect" });
  306. await expect(
  307. gateway.subscribe({ ...params, historyFirst: false, connectionId: "old-client" }),
  308. ).rejects.toMatchObject({ reasonCode: "fault.subscribe.resumeFailed" });
  309. expect(resume).toHaveBeenCalledTimes(1);
  310. resume.mockImplementationOnce(async () => ({ status: "resumed", persistedMessages: [] }));
  311. await Promise.all([
  312. gateway.subscribe({ ...params, retryInitialization: attempt }),
  313. gateway.subscribe({
  314. ...params,
  315. connectionId: "phone",
  316. clientMode: "web-remote-replayable",
  317. retryInitialization: attempt,
  318. }),
  319. ]);
  320. await vi.waitFor(() => expect(snapshot()?.runtimeInitialization?.status).toBe("ready"));
  321. expect(resume).toHaveBeenCalledTimes(2);
  322. gateway.dispose();
  323. });
  324. it("retains a ready runtime when only final history reconciliation fails", async () => {
  325. const { gateway, params, resume, snapshot, seed, loadPersistedEvents } = setup();
  326. const disposeOnFailure = vi.fn(async () => undefined);
  327. resume.mockImplementationOnce(async () => ({
  328. status: "resumed",
  329. persistedMessages: [],
  330. disposeOnFailure,
  331. }));
  332. seed((await gateway.subscribe(params)).initialFrame);
  333. loadPersistedEvents.mockRejectedValueOnce(new Error("storage unavailable"));
  334. await vi.waitFor(() => expect(snapshot()?.runtimeInitialization?.status).toBe("failed"));
  335. expect(disposeOnFailure).not.toHaveBeenCalled();
  336. gateway.dispose();
  337. });
  338. it("keeps durable command deduplication ahead of initialization guards", async () => {
  339. const { gateway, gate, params, execute } = setup(() => ({
  340. commandId: "settled",
  341. status: "accepted",
  342. revisionAtDecision: 1,
  343. }));
  344. await gateway.subscribe(params);
  345. const ack = await gateway.handleCommand({
  346. commandId: "settled",
  347. sessionId: "history",
  348. type: "compact",
  349. payload: {},
  350. clientId: "client",
  351. issuedAt: Date.now(),
  352. });
  353. expect(ack.status).toBe("duplicate");
  354. expect(execute).not.toHaveBeenCalled();
  355. gateway.dispose();
  356. gate.resolve();
  357. });
  358. it("does not activate a disposed opening when its reserved frame commits late", async () => {
  359. const { gateway, gate, params, resume } = setup();
  360. const dispatch = await gateway.subscribeReserved(params);
  361. gateway.dispose();
  362. dispatch.commit();
  363. await new Promise<void>((resolve) => setImmediate(resolve));
  364. expect(resume).not.toHaveBeenCalled();
  365. gate.resolve();
  366. });
  367. it("keeps legacy subscribers behind runtime readiness", async () => {
  368. const { gateway, gate, params } = setup();
  369. await gateway.subscribe(params);
  370. let returned = false;
  371. const legacy = gateway
  372. .subscribe({ ...params, historyFirst: false, connectionId: "legacy" })
  373. .then(() => {
  374. returned = true;
  375. });
  376. await new Promise<void>((resolve) => setImmediate(resolve));
  377. expect(returned).toBe(false);
  378. gate.resolve();
  379. await legacy;
  380. gateway.dispose();
  381. });
  382. it("releases a delayed residency lease after the opening was disposed", async () => {
  383. const lease = deferred();
  384. const release = vi.fn();
  385. const retain = vi.fn(async () => {
  386. await lease.promise;
  387. return release;
  388. });
  389. const { gateway, params, resume } = setup(undefined, retain);
  390. await gateway.subscribe(params);
  391. await vi.waitFor(() => expect(retain).toHaveBeenCalledTimes(1));
  392. gateway.dispose();
  393. lease.resolve();
  394. await vi.waitFor(() => expect(release).toHaveBeenCalledTimes(1));
  395. expect(resume).not.toHaveBeenCalled();
  396. });
  397. });