v4-history-first.test.ts 13 KB

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