v4-history-first.test.ts 8.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236
  1. import {
  2. applyConversationDeltas,
  3. type ConversationSnapshot,
  4. } from "@zcode/shared/zcode-protocol-v4";
  5. import { describe, expect, it, vi } from "vitest";
  6. import { ConversationV4Gateway } from "../src/zcode-protocol-v4/v4-gateway.js";
  7. import type { ConversationTopicFrame } from "@zcode/shared/zcode-protocol-v4";
  8. function deferred() {
  9. let resolve!: () => void;
  10. let reject!: (error: Error) => void;
  11. const promise = new Promise<void>((yes, no) => {
  12. resolve = yes;
  13. reject = no;
  14. });
  15. return { promise, resolve, reject };
  16. }
  17. function setup(
  18. lookupTranscriptCommand?: () => {
  19. commandId: string;
  20. status: "accepted";
  21. revisionAtDecision: number;
  22. },
  23. retainSessionRuntime?: () => Promise<() => void>,
  24. ) {
  25. const gate = deferred();
  26. const frames: ConversationTopicFrame[] = [];
  27. let observed: ConversationSnapshot | undefined;
  28. const execute = vi.fn();
  29. const resume = vi.fn(async () => {
  30. await gate.promise;
  31. return { status: "resumed" as const, persistedMessages: [] };
  32. });
  33. const read = vi.fn(async () => []);
  34. const loadPersistedEvents = vi.fn(async () => ({
  35. events: [],
  36. synthesized: true,
  37. sourceEventSeq: 0,
  38. }));
  39. const gateway = new ConversationV4Gateway({
  40. sessionExists: () => false,
  41. executeCommand: execute,
  42. lookupTranscriptCommand,
  43. retainSessionRuntime,
  44. loadPersistedMessages: read,
  45. resumePersistedSession: resume,
  46. loadPersistedEvents,
  47. emitWireFrame: (wire) => {
  48. if (wire.kind === "complete") {
  49. const frame = wire.frame as ConversationTopicFrame;
  50. frames.push(frame);
  51. if (frame.payload.kind === "snapshot") observed = frame.payload.snapshot;
  52. else if (observed)
  53. observed = {
  54. ...applyConversationDeltas(observed, frame.payload.deltas),
  55. seq: frame.toSeq,
  56. };
  57. }
  58. },
  59. });
  60. const params = {
  61. topic: "conversation/history",
  62. connectionId: "desktop",
  63. clientMode: "desktop-continuous",
  64. historyFirst: true,
  65. };
  66. const snapshot = () => observed;
  67. return {
  68. gateway,
  69. gate,
  70. frames,
  71. execute,
  72. resume,
  73. read,
  74. params,
  75. snapshot,
  76. loadPersistedEvents,
  77. seed: (frame: ConversationTopicFrame | null) => {
  78. if (frame?.payload.kind === "snapshot") observed = frame.payload.snapshot;
  79. },
  80. };
  81. }
  82. describe("history-first cold subscription", () => {
  83. it.each(["desktop-continuous", "web-remote-replayable"])(
  84. "%s preserves project directories alongside the persisted history snapshot",
  85. async (clientMode) => {
  86. const { gateway, gate, resume, params, snapshot, seed } = setup();
  87. const workspace = { workspacePath: "/project", workspaceKey: "/project" };
  88. const additionalDirectories = ["/shared"];
  89. seed((await gateway.subscribe({ ...params, clientMode, workspace, additionalDirectories })).initialFrame);
  90. await vi.waitFor(() => expect(resume).toHaveBeenCalledTimes(1));
  91. expect(resume).toHaveBeenCalledWith("history", undefined, workspace, additionalDirectories, []);
  92. gate.resolve();
  93. await vi.waitFor(() => expect(snapshot()?.runtimeInitialization?.status).toBe("ready"));
  94. gateway.dispose();
  95. },
  96. );
  97. it("publishes history before activation and rejects execution while restoring", async () => {
  98. const { gateway, gate, resume, read, execute, params, snapshot, seed } = setup();
  99. const dispatch = await gateway.subscribeReserved(params);
  100. expect(resume).not.toHaveBeenCalled();
  101. expect(dispatch.initialFrame?.payload.kind).toBe("snapshot");
  102. if (dispatch.initialFrame?.payload.kind !== "snapshot") throw new Error("missing history");
  103. expect(dispatch.initialFrame.payload.snapshot.runtimeInitialization?.status).toBe(
  104. "initializing",
  105. );
  106. seed(dispatch.initialFrame);
  107. dispatch.commit();
  108. await vi.waitFor(() => expect(resume).toHaveBeenCalledTimes(1));
  109. const rows = await gateway.rowsRange({ sessionId: "history", limit: 10 });
  110. expect(rows.rows).toEqual([]);
  111. const ack = await gateway.handleCommand({
  112. commandId: "early",
  113. sessionId: "history",
  114. type: "compact",
  115. payload: {},
  116. clientId: "client",
  117. issuedAt: Date.now(),
  118. });
  119. expect(ack.status).toBe("rejected");
  120. expect(ack.reasonCode).toBe("guard.runtimeInitializing");
  121. expect(execute).not.toHaveBeenCalled();
  122. gate.resolve();
  123. await vi.waitFor(() => expect(snapshot()?.runtimeInitialization?.status).toBe("ready"));
  124. expect(read).toHaveBeenCalledTimes(1);
  125. gateway.dispose();
  126. });
  127. it("retains failed history until explicit retry and coalesces repeated retry", async () => {
  128. const { gateway, gate, resume, params, snapshot, seed } = setup();
  129. seed((await gateway.subscribe(params)).initialFrame);
  130. await vi.waitFor(() => expect(resume).toHaveBeenCalledTimes(1));
  131. gate.reject(new Error("hook unavailable"));
  132. await vi.waitFor(() => expect(snapshot()?.runtimeInitialization?.status).toBe("failed"));
  133. const attempt = snapshot()!.runtimeInitialization!.attemptId;
  134. await gateway.subscribe({ ...params, connectionId: "reconnect" });
  135. await expect(
  136. gateway.subscribe({ ...params, historyFirst: false, connectionId: "old-client" }),
  137. ).rejects.toMatchObject({ reasonCode: "fault.subscribe.resumeFailed" });
  138. expect(resume).toHaveBeenCalledTimes(1);
  139. resume.mockImplementationOnce(async () => ({ status: "resumed", persistedMessages: [] }));
  140. await Promise.all([
  141. gateway.subscribe({ ...params, retryInitialization: attempt }),
  142. gateway.subscribe({
  143. ...params,
  144. connectionId: "phone",
  145. clientMode: "web-remote-replayable",
  146. retryInitialization: attempt,
  147. }),
  148. ]);
  149. await vi.waitFor(() => expect(snapshot()?.runtimeInitialization?.status).toBe("ready"));
  150. expect(resume).toHaveBeenCalledTimes(2);
  151. gateway.dispose();
  152. });
  153. it("cleans the activated runtime when final history reconciliation fails", async () => {
  154. const { gateway, params, resume, snapshot, seed, loadPersistedEvents } = setup();
  155. const disposeOnFailure = vi.fn(async () => undefined);
  156. resume.mockImplementationOnce(async () => ({
  157. status: "resumed",
  158. persistedMessages: [],
  159. disposeOnFailure,
  160. }));
  161. seed((await gateway.subscribe(params)).initialFrame);
  162. loadPersistedEvents.mockRejectedValueOnce(new Error("storage unavailable"));
  163. await vi.waitFor(() => expect(snapshot()?.runtimeInitialization?.status).toBe("failed"));
  164. expect(disposeOnFailure).toHaveBeenCalledTimes(1);
  165. gateway.dispose();
  166. });
  167. it("keeps durable command deduplication ahead of initialization guards", async () => {
  168. const { gateway, gate, params, execute } = setup(() => ({
  169. commandId: "settled",
  170. status: "accepted",
  171. revisionAtDecision: 1,
  172. }));
  173. await gateway.subscribe(params);
  174. const ack = await gateway.handleCommand({
  175. commandId: "settled",
  176. sessionId: "history",
  177. type: "compact",
  178. payload: {},
  179. clientId: "client",
  180. issuedAt: Date.now(),
  181. });
  182. expect(ack.status).toBe("duplicate");
  183. expect(execute).not.toHaveBeenCalled();
  184. gateway.dispose();
  185. gate.resolve();
  186. });
  187. it("does not activate a disposed opening when its reserved frame commits late", async () => {
  188. const { gateway, gate, params, resume } = setup();
  189. const dispatch = await gateway.subscribeReserved(params);
  190. gateway.dispose();
  191. dispatch.commit();
  192. await new Promise<void>((resolve) => setImmediate(resolve));
  193. expect(resume).not.toHaveBeenCalled();
  194. gate.resolve();
  195. });
  196. it("keeps legacy subscribers behind runtime readiness", async () => {
  197. const { gateway, gate, params } = setup();
  198. await gateway.subscribe(params);
  199. let returned = false;
  200. const legacy = gateway
  201. .subscribe({ ...params, historyFirst: false, connectionId: "legacy" })
  202. .then(() => {
  203. returned = true;
  204. });
  205. await new Promise<void>((resolve) => setImmediate(resolve));
  206. expect(returned).toBe(false);
  207. gate.resolve();
  208. await legacy;
  209. gateway.dispose();
  210. });
  211. it("releases a delayed residency lease after the opening was disposed", async () => {
  212. const lease = deferred();
  213. const release = vi.fn();
  214. const retain = vi.fn(async () => {
  215. await lease.promise;
  216. return release;
  217. });
  218. const { gateway, params, resume } = setup(undefined, retain);
  219. await gateway.subscribe(params);
  220. await vi.waitFor(() => expect(retain).toHaveBeenCalledTimes(1));
  221. gateway.dispose();
  222. lease.resolve();
  223. await vi.waitFor(() => expect(release).toHaveBeenCalledTimes(1));
  224. expect(resume).not.toHaveBeenCalled();
  225. });
  226. });