v4-history-first.test.ts 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364
  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("retries a failed owned activation without waiting on the old failed publisher", async () => {
  112. const { gateway, lifecycle, activate, params, seed, snapshot } = setupOwned();
  113. activate.mockRejectedValueOnce(new Error("startup failed"));
  114. await expect(lifecycle.ensureReady("history")).rejects.toThrow("startup failed");
  115. await lifecycle.ensureReady("history");
  116. expect(activate).toHaveBeenCalledTimes(2);
  117. seed((await gateway.subscribe(params)).initialFrame);
  118. await vi.waitFor(() => expect(snapshot()?.runtimeInitialization?.status).toBe("ready"));
  119. gateway.dispose();
  120. });
  121. it("rejects late subscription and command admission while the session is stopping", async () => {
  122. const executeCommand = vi.fn();
  123. const gateway = new ConversationV4Gateway({
  124. sessionExists: () => true,
  125. isSessionStopping: () => true,
  126. executeCommand,
  127. emitWireFrame: () => {},
  128. });
  129. await expect(
  130. gateway.subscribe({
  131. topic: "conversation/history",
  132. connectionId: "desktop",
  133. clientMode: "desktop-continuous",
  134. }),
  135. ).rejects.toThrow("fault.sessionLifecycle.stopping");
  136. await expect(
  137. gateway.handleCommand({
  138. sessionId: "history",
  139. commandId: "late-rename",
  140. clientId: "desktop",
  141. issuedAt: 1,
  142. type: "renameSession",
  143. payload: { title: "late" },
  144. expectedRevision: 0,
  145. }),
  146. ).resolves.toMatchObject({ status: "failed" });
  147. expect(executeCommand).not.toHaveBeenCalled();
  148. gateway.dispose();
  149. });
  150. it("waits for old final hydration before releasing the publisher", async () => {
  151. const { gateway, lifecycle, loadPersistedEvents } = setupOwned();
  152. const hydrationEntered = deferred();
  153. const hydrationGate = deferred();
  154. loadPersistedEvents
  155. .mockImplementationOnce(async () => ({ events: [], synthesized: true, sourceEventSeq: 0 }))
  156. .mockImplementationOnce(async () => {
  157. hydrationEntered.resolve();
  158. await hydrationGate.promise;
  159. return { events: [], synthesized: true, sourceEventSeq: 0 };
  160. });
  161. await lifecycle.ensureReady("history");
  162. await hydrationEntered.promise;
  163. let released = false;
  164. const release = gateway.releaseSessionProjection("history").then(() => {
  165. released = true;
  166. });
  167. await Promise.resolve();
  168. expect(released).toBe(false);
  169. hydrationGate.resolve();
  170. await release;
  171. expect(released).toBe(true);
  172. gateway.dispose();
  173. });
  174. it("opens fresh history during an externally owned restart without recursively resuming", async () => {
  175. const { gateway, lifecycle, activate, params, read, snapshot, seed } = setupOwned();
  176. const gate = deferred();
  177. activate.mockImplementationOnce(async () => {
  178. await gate.promise;
  179. });
  180. const restarting = lifecycle.restart("history");
  181. await vi.waitFor(() => expect(activate).toHaveBeenCalledTimes(1));
  182. seed((await gateway.subscribe(params)).initialFrame);
  183. expect(snapshot()?.runtimeInitialization?.status).toBe("initializing");
  184. expect(read).toHaveBeenCalledTimes(1);
  185. await vi.waitFor(() => expect(activate).toHaveBeenCalledTimes(1));
  186. gate.resolve();
  187. await restarting;
  188. await vi.waitFor(() => expect(snapshot()?.runtimeInitialization?.status).toBe("ready"));
  189. gateway.dispose();
  190. });
  191. it("completes an externally owned restart without any subscriber", async () => {
  192. const { gateway, lifecycle, activate } = setupOwned();
  193. await lifecycle.restart("history");
  194. expect(activate).toHaveBeenCalledTimes(1);
  195. gateway.dispose();
  196. });
  197. it.each(["desktop-continuous", "web-remote-replayable"])(
  198. "%s preserves project directories alongside the persisted history snapshot",
  199. async (clientMode) => {
  200. const { gateway, gate, resume, params, snapshot, seed } = setup();
  201. const workspace = { workspacePath: "/project", workspaceKey: "/project" };
  202. const additionalDirectories = ["/shared"];
  203. seed(
  204. (await gateway.subscribe({ ...params, clientMode, workspace, additionalDirectories }))
  205. .initialFrame,
  206. );
  207. await vi.waitFor(() => expect(resume).toHaveBeenCalledTimes(1));
  208. expect(resume).toHaveBeenCalledWith(
  209. "history",
  210. undefined,
  211. workspace,
  212. additionalDirectories,
  213. [],
  214. );
  215. gate.resolve();
  216. await vi.waitFor(() => expect(snapshot()?.runtimeInitialization?.status).toBe("ready"));
  217. gateway.dispose();
  218. },
  219. );
  220. it("publishes history before activation and rejects execution while restoring", async () => {
  221. const { gateway, gate, resume, read, execute, params, snapshot, seed } = setup();
  222. const dispatch = await gateway.subscribeReserved(params);
  223. expect(resume).not.toHaveBeenCalled();
  224. expect(dispatch.initialFrame?.payload.kind).toBe("snapshot");
  225. if (dispatch.initialFrame?.payload.kind !== "snapshot") throw new Error("missing history");
  226. expect(dispatch.initialFrame.payload.snapshot.runtimeInitialization?.status).toBe(
  227. "initializing",
  228. );
  229. seed(dispatch.initialFrame);
  230. dispatch.commit();
  231. await vi.waitFor(() => expect(resume).toHaveBeenCalledTimes(1));
  232. const rows = await gateway.rowsRange({ sessionId: "history", limit: 10 });
  233. expect(rows.rows).toEqual([]);
  234. const ack = await gateway.handleCommand({
  235. commandId: "early",
  236. sessionId: "history",
  237. type: "compact",
  238. payload: {},
  239. clientId: "client",
  240. issuedAt: Date.now(),
  241. });
  242. expect(ack.status).toBe("rejected");
  243. expect(ack.reasonCode).toBe("guard.runtimeInitializing");
  244. expect(execute).not.toHaveBeenCalled();
  245. gate.resolve();
  246. await vi.waitFor(() => expect(snapshot()?.runtimeInitialization?.status).toBe("ready"));
  247. expect(read).toHaveBeenCalledTimes(1);
  248. gateway.dispose();
  249. });
  250. it("retains failed history until explicit retry and coalesces repeated retry", async () => {
  251. const { gateway, gate, resume, params, snapshot, seed } = setup();
  252. seed((await gateway.subscribe(params)).initialFrame);
  253. await vi.waitFor(() => expect(resume).toHaveBeenCalledTimes(1));
  254. gate.reject(new Error("hook unavailable"));
  255. await vi.waitFor(() => expect(snapshot()?.runtimeInitialization?.status).toBe("failed"));
  256. const attempt = snapshot()!.runtimeInitialization!.attemptId;
  257. await gateway.subscribe({ ...params, connectionId: "reconnect" });
  258. await expect(
  259. gateway.subscribe({ ...params, historyFirst: false, connectionId: "old-client" }),
  260. ).rejects.toMatchObject({ reasonCode: "fault.subscribe.resumeFailed" });
  261. expect(resume).toHaveBeenCalledTimes(1);
  262. resume.mockImplementationOnce(async () => ({ status: "resumed", persistedMessages: [] }));
  263. await Promise.all([
  264. gateway.subscribe({ ...params, retryInitialization: attempt }),
  265. gateway.subscribe({
  266. ...params,
  267. connectionId: "phone",
  268. clientMode: "web-remote-replayable",
  269. retryInitialization: attempt,
  270. }),
  271. ]);
  272. await vi.waitFor(() => expect(snapshot()?.runtimeInitialization?.status).toBe("ready"));
  273. expect(resume).toHaveBeenCalledTimes(2);
  274. gateway.dispose();
  275. });
  276. it("retains a ready runtime when only final history reconciliation fails", async () => {
  277. const { gateway, params, resume, snapshot, seed, loadPersistedEvents } = setup();
  278. const disposeOnFailure = vi.fn(async () => undefined);
  279. resume.mockImplementationOnce(async () => ({
  280. status: "resumed",
  281. persistedMessages: [],
  282. disposeOnFailure,
  283. }));
  284. seed((await gateway.subscribe(params)).initialFrame);
  285. loadPersistedEvents.mockRejectedValueOnce(new Error("storage unavailable"));
  286. await vi.waitFor(() => expect(snapshot()?.runtimeInitialization?.status).toBe("failed"));
  287. expect(disposeOnFailure).not.toHaveBeenCalled();
  288. gateway.dispose();
  289. });
  290. it("keeps durable command deduplication ahead of initialization guards", async () => {
  291. const { gateway, gate, params, execute } = setup(() => ({
  292. commandId: "settled",
  293. status: "accepted",
  294. revisionAtDecision: 1,
  295. }));
  296. await gateway.subscribe(params);
  297. const ack = await gateway.handleCommand({
  298. commandId: "settled",
  299. sessionId: "history",
  300. type: "compact",
  301. payload: {},
  302. clientId: "client",
  303. issuedAt: Date.now(),
  304. });
  305. expect(ack.status).toBe("duplicate");
  306. expect(execute).not.toHaveBeenCalled();
  307. gateway.dispose();
  308. gate.resolve();
  309. });
  310. it("does not activate a disposed opening when its reserved frame commits late", async () => {
  311. const { gateway, gate, params, resume } = setup();
  312. const dispatch = await gateway.subscribeReserved(params);
  313. gateway.dispose();
  314. dispatch.commit();
  315. await new Promise<void>((resolve) => setImmediate(resolve));
  316. expect(resume).not.toHaveBeenCalled();
  317. gate.resolve();
  318. });
  319. it("keeps legacy subscribers behind runtime readiness", async () => {
  320. const { gateway, gate, params } = setup();
  321. await gateway.subscribe(params);
  322. let returned = false;
  323. const legacy = gateway
  324. .subscribe({ ...params, historyFirst: false, connectionId: "legacy" })
  325. .then(() => {
  326. returned = true;
  327. });
  328. await new Promise<void>((resolve) => setImmediate(resolve));
  329. expect(returned).toBe(false);
  330. gate.resolve();
  331. await legacy;
  332. gateway.dispose();
  333. });
  334. it("releases a delayed residency lease after the opening was disposed", async () => {
  335. const lease = deferred();
  336. const release = vi.fn();
  337. const retain = vi.fn(async () => {
  338. await lease.promise;
  339. return release;
  340. });
  341. const { gateway, params, resume } = setup(undefined, retain);
  342. await gateway.subscribe(params);
  343. await vi.waitFor(() => expect(retain).toHaveBeenCalledTimes(1));
  344. gateway.dispose();
  345. lease.resolve();
  346. await vi.waitFor(() => expect(release).toHaveBeenCalledTimes(1));
  347. expect(resume).not.toHaveBeenCalled();
  348. });
  349. });