workspaceSessionsIndexSubscriptionSet.test.ts 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302
  1. import { describe, expect, it, vi } from "vitest";
  2. import { Emitter } from "@zcode/rpc";
  3. import type { SessionSummary, SessionsIndexTopicFrame } from "@zcode/shared/zcode-protocol-v4";
  4. import {
  5. sessionsIndexRegistrySize,
  6. type SessionsIndexAgentService,
  7. type SessionsIndexScope,
  8. } from "@/v4/sessionsIndexRegistry.js";
  9. import {
  10. WorkspaceSessionsIndexSubscriptionSet,
  11. type WorkspaceSessionsIndexBinding,
  12. } from "@/v4/workspaceSessionsIndexSubscriptionSet.js";
  13. vi.mock("@/logger.js", () => ({
  14. logger: {
  15. debug: vi.fn(),
  16. info: vi.fn(),
  17. warn: vi.fn(),
  18. error: vi.fn(),
  19. trace: vi.fn(),
  20. },
  21. }));
  22. function mockAgentService(): SessionsIndexAgentService {
  23. const runtimeRestarts = new Emitter<{ workspaceKey: string }>();
  24. let nextSubscription = 1;
  25. return {
  26. helloConversationV4: vi.fn(async () => ({
  27. kind: "hello" as const,
  28. protocolVersion: 3 as const,
  29. connectionId: "test-connection",
  30. clientMode: "desktop-continuous" as const,
  31. deliveryProfile: "continuous" as const,
  32. serverTime: 1,
  33. capabilities: {
  34. nativeDialogs: true,
  35. localTerminal: true,
  36. binaryFrames: false,
  37. compression: "none" as const,
  38. },
  39. auth: {},
  40. })),
  41. initializeConversationV4: vi.fn(async () => {}),
  42. subscribeSessionsIndexV4: vi.fn(async () => ({
  43. ack: {
  44. subscriptionId: `sub-${nextSubscription++}`,
  45. mode: "snapshot" as const,
  46. logEpoch: "e1",
  47. },
  48. })),
  49. unsubscribeSessionsIndexV4: vi.fn(async () => {}),
  50. resyncSessionsIndexV4: vi.fn(async (params) => ({
  51. ack: {
  52. subscriptionId: params.subscriptionId,
  53. mode: "snapshot" as const,
  54. logEpoch: "e1",
  55. },
  56. })),
  57. onDynamicSessionsIndexFrame: vi.fn(() => () => ({ dispose: () => {} })),
  58. onAgentRuntimeRestarted: runtimeRestarts.event,
  59. } as unknown as SessionsIndexAgentService;
  60. }
  61. function binding(
  62. scope: SessionsIndexScope,
  63. agentService: SessionsIndexAgentService,
  64. ): WorkspaceSessionsIndexBinding {
  65. return { scope, agentService };
  66. }
  67. function summary(workspaceId: string, sessionId: string): SessionSummary {
  68. return {
  69. sessionId,
  70. workspaceId,
  71. title: sessionId,
  72. phase: "completedSuccess",
  73. sessionEnded: true,
  74. hasBackgroundWork: false,
  75. lastActivityAt: 100,
  76. createdAt: 1,
  77. };
  78. }
  79. function snapshotFrame(
  80. workspaceId: string,
  81. sessions: SessionSummary[],
  82. toSeq: number,
  83. ): SessionsIndexTopicFrame {
  84. return {
  85. topic: `sessions-index/${workspaceId}`,
  86. subscriptionId: "test-direct-apply",
  87. fromSeq: 0,
  88. toSeq,
  89. sentAt: 1,
  90. payload: {
  91. kind: "snapshot",
  92. snapshot: {
  93. protocolVersion: 1,
  94. workspaceId,
  95. logEpoch: `epoch-${workspaceId}`,
  96. sessions,
  97. },
  98. },
  99. };
  100. }
  101. describe("WorkspaceSessionsIndexSubscriptionSet", () => {
  102. it("TSL11:删除 A 只释放 A,B/C 的 store、水位和任务快照保持原引用", async () => {
  103. const service = mockAgentService();
  104. const subscriptions = new WorkspaceSessionsIndexSubscriptionSet(vi.fn());
  105. const a = binding({ workspaceKey: "a", workspacePath: "/a" }, service);
  106. const b = binding({ workspaceKey: "b", workspacePath: "/b" }, service);
  107. const c = binding({ workspaceKey: "c", workspacePath: "/c" }, service);
  108. try {
  109. expect(subscriptions.reconcile([a, b, c])).toBe(true);
  110. await vi.waitFor(() => expect(service.subscribeSessionsIndexV4).toHaveBeenCalledTimes(3));
  111. const bStore = subscriptions.getStore(b.scope)!;
  112. const cStore = subscriptions.getStore(c.scope)!;
  113. bStore.applyFrame(snapshotFrame("b", [summary("b", "b-task")], 5));
  114. cStore.applyFrame(snapshotFrame("c", [summary("c", "c-task")], 7));
  115. const bState = bStore.getState();
  116. const cState = cStore.getState();
  117. const bItems = bStore.getSessions();
  118. const cItems = cStore.getSessions();
  119. expect(subscriptions.reconcile([b, c])).toBe(true);
  120. expect(subscriptions.size()).toBe(2);
  121. expect(subscriptions.getStore(b.scope)).toBe(bStore);
  122. expect(subscriptions.getStore(c.scope)).toBe(cStore);
  123. expect(bStore.getState()).toBe(bState);
  124. expect(cStore.getState()).toBe(cState);
  125. expect(bStore.getSessions()).toBe(bItems);
  126. expect(cStore.getSessions()).toBe(cItems);
  127. expect(service.subscribeSessionsIndexV4).toHaveBeenCalledTimes(3);
  128. await vi.waitFor(() => expect(service.unsubscribeSessionsIndexV4).toHaveBeenCalledTimes(1));
  129. expect(sessionsIndexRegistrySize()).toBe(2);
  130. } finally {
  131. subscriptions.dispose();
  132. }
  133. expect(sessionsIndexRegistrySize()).toBe(0);
  134. });
  135. it("TSL12:重排无副作用,新增和 service 换代只变更目标 scope", async () => {
  136. const localService = mockAgentService();
  137. const nextRemoteService = mockAgentService();
  138. const subscriptions = new WorkspaceSessionsIndexSubscriptionSet(vi.fn());
  139. const a = binding({ workspaceKey: "a", workspacePath: "/a" }, localService);
  140. const b = binding(
  141. {
  142. workspaceKey: "remote:ssh:host:/repo",
  143. workspacePath: "/repo",
  144. workspaceIdentity: "remote:ssh:host:/repo",
  145. endpointKey: "remote-1",
  146. },
  147. localService,
  148. );
  149. const c = binding({ workspaceKey: "c", workspacePath: "/c" }, localService);
  150. try {
  151. subscriptions.reconcile([a, b]);
  152. await vi.waitFor(() =>
  153. expect(localService.subscribeSessionsIndexV4).toHaveBeenCalledTimes(2),
  154. );
  155. const aStore = subscriptions.getStore(a.scope)!;
  156. const bStore = subscriptions.getStore(b.scope)!;
  157. expect(subscriptions.reconcile([b, a])).toBe(false);
  158. expect(subscriptions.getStore(a.scope)).toBe(aStore);
  159. expect(subscriptions.getStore(b.scope)).toBe(bStore);
  160. expect(localService.subscribeSessionsIndexV4).toHaveBeenCalledTimes(2);
  161. expect(localService.unsubscribeSessionsIndexV4).not.toHaveBeenCalled();
  162. expect(subscriptions.reconcile([a, b, c])).toBe(true);
  163. await vi.waitFor(() =>
  164. expect(localService.subscribeSessionsIndexV4).toHaveBeenCalledTimes(3),
  165. );
  166. const cStore = subscriptions.getStore(c.scope)!;
  167. expect(subscriptions.getStore(a.scope)).toBe(aStore);
  168. expect(subscriptions.getStore(b.scope)).toBe(bStore);
  169. bStore.applyFrame(
  170. snapshotFrame("remote:ssh:host:/repo", [summary("remote:ssh:host:/repo", "b-task")], 5),
  171. );
  172. const bState = bStore.getState();
  173. const nextB = binding(b.scope, nextRemoteService);
  174. expect(subscriptions.reconcile([a, nextB, c])).toBe(true);
  175. expect(subscriptions.getStore(a.scope)).toBe(aStore);
  176. expect(subscriptions.getStore(c.scope)).toBe(cStore);
  177. expect(subscriptions.getStore(b.scope)).toBe(bStore);
  178. expect(bStore.getState()).toBe(bState);
  179. expect(bStore.getSessions().map((session) => session.sessionId)).toEqual(["b-task"]);
  180. await vi.waitFor(() => {
  181. expect(localService.unsubscribeSessionsIndexV4).toHaveBeenCalledTimes(1);
  182. expect(nextRemoteService.subscribeSessionsIndexV4).toHaveBeenCalledTimes(1);
  183. });
  184. } finally {
  185. subscriptions.dispose();
  186. }
  187. expect(sessionsIndexRegistrySize()).toBe(0);
  188. });
  189. it("相同 workspacePath 的不同 identity/remoteSessionId 各自持有订阅", async () => {
  190. const firstService = mockAgentService();
  191. const secondService = mockAgentService();
  192. const subscriptions = new WorkspaceSessionsIndexSubscriptionSet(vi.fn());
  193. const first = binding(
  194. {
  195. workspaceKey: "remote:ssh:first:/repo",
  196. workspacePath: "/repo",
  197. workspaceIdentity: "remote:ssh:first:/repo",
  198. endpointKey: "remote-session-first",
  199. },
  200. firstService,
  201. );
  202. const second = binding(
  203. {
  204. workspaceKey: "remote:ssh:second:/repo",
  205. workspacePath: "/repo",
  206. workspaceIdentity: "remote:ssh:second:/repo",
  207. endpointKey: "remote-session-second",
  208. },
  209. secondService,
  210. );
  211. try {
  212. subscriptions.reconcile([first, second]);
  213. await vi.waitFor(() => {
  214. expect(firstService.subscribeSessionsIndexV4).toHaveBeenCalledTimes(1);
  215. expect(secondService.subscribeSessionsIndexV4).toHaveBeenCalledTimes(1);
  216. });
  217. const secondStore = subscriptions.getStore(second.scope)!;
  218. subscriptions.reconcile([second]);
  219. expect(subscriptions.getStore(second.scope)).toBe(secondStore);
  220. expect(secondService.subscribeSessionsIndexV4).toHaveBeenCalledTimes(1);
  221. expect(secondService.unsubscribeSessionsIndexV4).not.toHaveBeenCalled();
  222. await vi.waitFor(() =>
  223. expect(firstService.unsubscribeSessionsIndexV4).toHaveBeenCalledTimes(1),
  224. );
  225. } finally {
  226. subscriptions.dispose();
  227. }
  228. expect(sessionsIndexRegistrySize()).toBe(0);
  229. });
  230. it("远程 service 未换代但 scope 路径变化时重建 transport", async () => {
  231. const service = mockAgentService();
  232. const subscriptions = new WorkspaceSessionsIndexSubscriptionSet(vi.fn());
  233. const original = binding(
  234. {
  235. workspaceKey: "remote:ssh:host:/repo",
  236. workspacePath: "/repo-old",
  237. workspaceIdentity: "remote:ssh:host:/repo",
  238. endpointKey: "remote-1",
  239. },
  240. service,
  241. );
  242. const moved = binding(
  243. {
  244. ...original.scope,
  245. workspacePath: "/repo-new",
  246. },
  247. service,
  248. );
  249. try {
  250. subscriptions.reconcile([original]);
  251. await vi.waitFor(() => expect(service.subscribeSessionsIndexV4).toHaveBeenCalledTimes(1));
  252. const originalStore = subscriptions.getStore(original.scope)!;
  253. expect(subscriptions.reconcile([moved])).toBe(true);
  254. expect(subscriptions.getStore(moved.scope)).not.toBe(originalStore);
  255. await vi.waitFor(() => {
  256. expect(service.unsubscribeSessionsIndexV4).toHaveBeenCalledTimes(1);
  257. expect(service.subscribeSessionsIndexV4).toHaveBeenCalledTimes(2);
  258. });
  259. } finally {
  260. subscriptions.dispose();
  261. }
  262. expect(sessionsIndexRegistrySize()).toBe(0);
  263. });
  264. it("StrictMode cleanup 后同一 subscription set 可以重新 reconcile,且不泄漏 registry", async () => {
  265. const service = mockAgentService();
  266. const subscriptions = new WorkspaceSessionsIndexSubscriptionSet(vi.fn());
  267. const a = binding({ workspaceKey: "a", workspacePath: "/a" }, service);
  268. subscriptions.reconcile([a]);
  269. await vi.waitFor(() => expect(service.subscribeSessionsIndexV4).toHaveBeenCalledTimes(1));
  270. subscriptions.dispose();
  271. expect(sessionsIndexRegistrySize()).toBe(0);
  272. subscriptions.reconcile([a]);
  273. await vi.waitFor(() => expect(service.subscribeSessionsIndexV4).toHaveBeenCalledTimes(2));
  274. expect(subscriptions.size()).toBe(1);
  275. subscriptions.dispose();
  276. expect(sessionsIndexRegistrySize()).toBe(0);
  277. });
  278. });