sessionsIndexRegistry.test.ts 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469
  1. import { describe, expect, it, vi } from "vitest";
  2. import { Emitter } from "@zcode/rpc";
  3. import type { IServiceAccessor } from "@zcode/services";
  4. import type {
  5. SessionSummary,
  6. SessionsIndexTopicFrame,
  7. SessionsIndexTopicWireFrame,
  8. } from "@zcode/shared/zcode-protocol-v4";
  9. import {
  10. acquireSessionsIndex,
  11. buildSessionsIndexEntryKey,
  12. releaseSessionsIndex,
  13. sessionsIndexRegistrySize,
  14. type SessionsIndexAgentService,
  15. } from "@/v4/sessionsIndexRegistry.js";
  16. import { SessionsIndexStore } from "@/v4/sessionsIndexStore.js";
  17. import {
  18. registerRemoteWorkspaceSession,
  19. unregisterRemoteWorkspaceSession,
  20. } from "@/store/remoteWorkspaceSessionStore.js";
  21. function mockAgentService(): SessionsIndexAgentService {
  22. const runtimeRestarts = new Emitter<{ workspaceKey: string }>();
  23. return {
  24. helloConversationV4: vi.fn(async () => ({
  25. kind: "hello" as const,
  26. protocolVersion: 3 as const,
  27. connectionId: "test-connection",
  28. clientMode: "desktop-continuous" as const,
  29. deliveryProfile: "continuous" as const,
  30. serverTime: 1,
  31. capabilities: {
  32. nativeDialogs: true,
  33. localTerminal: true,
  34. binaryFrames: false,
  35. compression: "none" as const,
  36. },
  37. auth: {},
  38. })),
  39. initializeConversationV4: vi.fn(async () => {}),
  40. subscribeSessionsIndexV4: vi.fn(async () => ({
  41. ack: {
  42. subscriptionId: "sub-1",
  43. mode: "snapshot" as const,
  44. logEpoch: "e1",
  45. },
  46. })),
  47. unsubscribeSessionsIndexV4: vi.fn(async () => {}),
  48. resyncSessionsIndexV4: vi.fn(async (params) => ({
  49. ack: {
  50. subscriptionId: params.subscriptionId,
  51. mode: "snapshot" as const,
  52. logEpoch: "e1",
  53. },
  54. })),
  55. onDynamicSessionsIndexFrame: vi.fn(() => () => ({ dispose: () => {} })),
  56. onAgentRuntimeRestarted: runtimeRestarts.event,
  57. } as unknown as SessionsIndexAgentService;
  58. }
  59. function createReplacingRemoteServices(
  60. workspaceKey: string,
  61. clientMode: "desktop-continuous" | "web-remote-replayable",
  62. ) {
  63. let nextSubscription = 1;
  64. let nextLogicalFrame = 1;
  65. let currentSeq = 1;
  66. let active: { serviceKey: string; subscriptionId: string } | null = null;
  67. const listenersByService = new Map<string, Set<(frame: SessionsIndexTopicWireFrame) => void>>();
  68. const physicalFrame = (
  69. frame: SessionsIndexTopicFrame,
  70. deliveryKind: "initial" | "online",
  71. ): SessionsIndexTopicWireFrame => ({
  72. wireVersion: 3,
  73. kind: "complete",
  74. deliveryKind,
  75. logicalFrameId: `logical-${nextLogicalFrame}`,
  76. logicalFrameOrdinal: nextLogicalFrame++,
  77. topic: frame.topic,
  78. subscriptionId: frame.subscriptionId,
  79. frame,
  80. });
  81. const snapshotFrame = (subscriptionId: string): SessionsIndexTopicFrame => ({
  82. topic: `sessions-index/${workspaceKey}`,
  83. subscriptionId,
  84. fromSeq: 0,
  85. toSeq: 1,
  86. sentAt: 1,
  87. payload: {
  88. kind: "snapshot",
  89. snapshot: {
  90. protocolVersion: 1,
  91. workspaceId: workspaceKey,
  92. logEpoch: "epoch-1",
  93. sessions: [],
  94. },
  95. },
  96. });
  97. const createService = (serviceKey: string): SessionsIndexAgentService => {
  98. const runtimeRestarts = new Emitter<{ workspaceKey: string }>();
  99. const listeners = new Set<(frame: SessionsIndexTopicWireFrame) => void>();
  100. listenersByService.set(serviceKey, listeners);
  101. return {
  102. helloConversationV4: vi.fn(async () => ({
  103. kind: "hello" as const,
  104. protocolVersion: 3 as const,
  105. connectionId: "shared-remote-connection",
  106. clientMode,
  107. deliveryProfile: clientMode === "desktop-continuous" ? "continuous" : "replayable",
  108. serverTime: 1,
  109. capabilities: {
  110. nativeDialogs: true,
  111. localTerminal: true,
  112. binaryFrames: false,
  113. compression: "none" as const,
  114. },
  115. auth: {},
  116. })),
  117. initializeConversationV4: vi.fn(async () => {}),
  118. subscribeSessionsIndexV4: vi.fn(async () => {
  119. const subscriptionId = `sub-${nextSubscription++}`;
  120. // 真实 CLI 语义:同 connection/topic 的后订阅替换前订阅。
  121. active = { serviceKey, subscriptionId };
  122. const initial = physicalFrame(snapshotFrame(subscriptionId), "initial");
  123. for (const listener of listeners) listener(initial);
  124. return {
  125. ack: {
  126. subscriptionId,
  127. mode: "snapshot" as const,
  128. logEpoch: "epoch-1",
  129. },
  130. };
  131. }),
  132. unsubscribeSessionsIndexV4: vi.fn(async (params) => {
  133. if (active?.subscriptionId === params.subscriptionId) active = null;
  134. }),
  135. resyncSessionsIndexV4: vi.fn(async (params) => ({
  136. ack: {
  137. subscriptionId: params.subscriptionId,
  138. mode: "snapshot" as const,
  139. logEpoch: "epoch-1",
  140. },
  141. })),
  142. onDynamicSessionsIndexFrame: vi.fn(
  143. () => (listener: (frame: SessionsIndexTopicWireFrame) => void) => {
  144. listeners.add(listener);
  145. return { dispose: () => listeners.delete(listener) };
  146. },
  147. ),
  148. onAgentRuntimeRestarted: runtimeRestarts.event,
  149. } as unknown as SessionsIndexAgentService;
  150. };
  151. return {
  152. oldService: createService("old"),
  153. newService: createService("new"),
  154. emitUpsert(session: SessionSummary) {
  155. if (!active) return;
  156. const frame: SessionsIndexTopicFrame = {
  157. topic: `sessions-index/${workspaceKey}`,
  158. subscriptionId: active.subscriptionId,
  159. fromSeq: currentSeq,
  160. toSeq: currentSeq + 1,
  161. sentAt: 2,
  162. payload: {
  163. kind: "deltas",
  164. deltas: [{ op: "session.upserted", session }],
  165. },
  166. };
  167. for (const listener of listenersByService.get(active.serviceKey) ?? []) {
  168. listener(physicalFrame(frame, "online"));
  169. }
  170. currentSeq += 1;
  171. },
  172. };
  173. }
  174. describe("sessionsIndexRegistry", () => {
  175. it("引用计数:同 endpoint 同 workspaceKey 复用 store,归零才移除", async () => {
  176. const service = mockAgentService();
  177. const scope = { workspaceKey: "ws-1", workspacePath: "/ws" };
  178. const a = acquireSessionsIndex(scope, service);
  179. const b = acquireSessionsIndex(scope, service);
  180. // 同一 store 复用(一条订阅)
  181. expect(a).toBe(b);
  182. expect(sessionsIndexRegistrySize()).toBe(1);
  183. await vi.waitFor(() => expect(service.subscribeSessionsIndexV4).toHaveBeenCalledTimes(1));
  184. releaseSessionsIndex(scope, a);
  185. // 还有一个引用 → 不移除
  186. expect(sessionsIndexRegistrySize()).toBe(1);
  187. releaseSessionsIndex(scope, b);
  188. // 归零 → 移除
  189. expect(sessionsIndexRegistrySize()).toBe(0);
  190. });
  191. it("不同 workspace 各自独立 store", async () => {
  192. const service = mockAgentService();
  193. const s1 = acquireSessionsIndex({ workspaceKey: "ws-a", workspacePath: "/a" }, service);
  194. const s2 = acquireSessionsIndex({ workspaceKey: "ws-b", workspacePath: "/b" }, service);
  195. expect(s1).not.toBe(s2);
  196. expect(sessionsIndexRegistrySize()).toBe(2);
  197. await vi.waitFor(() => expect(service.subscribeSessionsIndexV4).toHaveBeenCalledTimes(2));
  198. releaseSessionsIndex({ workspaceKey: "ws-a" }, s1);
  199. releaseSessionsIndex({ workspaceKey: "ws-b" }, s2);
  200. expect(sessionsIndexRegistrySize()).toBe(0);
  201. });
  202. it("M5 ③:同 workspaceKey 不同 endpoint 不共用 store,各走各的 agentService 订阅", async () => {
  203. const localService = mockAgentService();
  204. const remoteService = mockAgentService();
  205. const localScope = { workspaceKey: "ws-1", workspacePath: "/ws" };
  206. const remoteScope = {
  207. workspaceKey: "ws-1",
  208. workspacePath: "/ws",
  209. endpointKey: "remote-session-1",
  210. };
  211. const localStore = acquireSessionsIndex(localScope, localService);
  212. const remoteStore = acquireSessionsIndex(remoteScope, remoteService);
  213. expect(localStore).not.toBe(remoteStore);
  214. expect(sessionsIndexRegistrySize()).toBe(2);
  215. // 订阅落在各自 endpoint 的 agentService(remote 经 rpc proxy)
  216. await vi.waitFor(() => {
  217. expect(localService.subscribeSessionsIndexV4).toHaveBeenCalledTimes(1);
  218. expect(remoteService.subscribeSessionsIndexV4).toHaveBeenCalledTimes(1);
  219. });
  220. // 同 endpoint 再次 acquire → 复用,不再发订阅
  221. const remoteStoreAgain = acquireSessionsIndex(remoteScope, remoteService);
  222. expect(remoteStoreAgain).toBe(remoteStore);
  223. expect(remoteService.subscribeSessionsIndexV4).toHaveBeenCalledTimes(1);
  224. releaseSessionsIndex(localScope, localStore);
  225. releaseSessionsIndex(remoteScope, remoteStore);
  226. releaseSessionsIndex(remoteScope, remoteStoreAgain);
  227. expect(sessionsIndexRegistrySize()).toBe(0);
  228. });
  229. it.each(["desktop-continuous", "web-remote-replayable"] as const)(
  230. "远程 agentService 换代时旧消费者继续从同一 store 收到后续任务(%s)",
  231. async (clientMode) => {
  232. const scope = {
  233. workspaceKey: "ssh:repo",
  234. workspacePath: "/repo",
  235. workspaceIdentity: "ssh:repo",
  236. endpointKey: "remote-1",
  237. };
  238. const { oldService, newService, emitUpsert } = createReplacingRemoteServices(
  239. scope.workspaceKey,
  240. clientMode,
  241. );
  242. const oldStore = acquireSessionsIndex(scope, oldService);
  243. await vi.waitFor(() => expect(oldStore.getState().workspaceId).toBe(scope.workspaceKey));
  244. const newStore = acquireSessionsIndex(scope, newService);
  245. await vi.waitFor(() => expect(newService.subscribeSessionsIndexV4).toHaveBeenCalledTimes(1));
  246. expect(
  247. vi.mocked(oldService.unsubscribeSessionsIndexV4).mock.invocationCallOrder[0],
  248. ).toBeLessThan(vi.mocked(newService.subscribeSessionsIndexV4).mock.invocationCallOrder[0]!);
  249. // 旧 React consumer 的迟到 acquire 只能增加引用,不能把 transport 切回已退休 proxy。
  250. const staleOldStore = acquireSessionsIndex(scope, oldService);
  251. expect(staleOldStore).toBe(oldStore);
  252. expect(oldService.subscribeSessionsIndexV4).toHaveBeenCalledTimes(1);
  253. expect(newService.subscribeSessionsIndexV4).toHaveBeenCalledTimes(1);
  254. emitUpsert({
  255. sessionId: "root-task",
  256. workspaceId: scope.workspaceKey,
  257. title: "root task",
  258. phase: "completedSuccess",
  259. sessionEnded: true,
  260. hasBackgroundWork: false,
  261. lastActivityAt: 2,
  262. createdAt: 1,
  263. });
  264. expect(newStore).toBe(oldStore);
  265. await vi.waitFor(() =>
  266. expect(oldStore.getSessions().map((session) => session.sessionId)).toEqual(["root-task"]),
  267. );
  268. expect(sessionsIndexRegistrySize()).toBe(1);
  269. // 新 consumer 先 cleanup 后,旧 consumer 仍持有同一有效订阅,不会退化成空的僵尸 store。
  270. releaseSessionsIndex(scope, newStore);
  271. expect(sessionsIndexRegistrySize()).toBe(1);
  272. expect(newService.unsubscribeSessionsIndexV4).not.toHaveBeenCalled();
  273. emitUpsert({
  274. sessionId: "root-task-after-cleanup",
  275. workspaceId: scope.workspaceKey,
  276. title: "root task after cleanup",
  277. phase: "completedSuccess",
  278. sessionEnded: true,
  279. hasBackgroundWork: false,
  280. lastActivityAt: 3,
  281. createdAt: 1,
  282. });
  283. await vi.waitFor(() =>
  284. expect(oldStore.getSessions().map((session) => session.sessionId)).toEqual([
  285. "root-task-after-cleanup",
  286. "root-task",
  287. ]),
  288. );
  289. releaseSessionsIndex(scope, staleOldStore);
  290. releaseSessionsIndex(scope, oldStore);
  291. expect(sessionsIndexRegistrySize()).toBe(0);
  292. },
  293. );
  294. it("远程旧订阅一直未完成时,新 service 仍可立即接管 transport", async () => {
  295. const oldService = mockAgentService();
  296. const newService = mockAgentService();
  297. const scope = {
  298. workspaceKey: "ssh:repo",
  299. workspacePath: "/repo",
  300. workspaceIdentity: "ssh:repo",
  301. endpointKey: "remote-1",
  302. };
  303. vi.mocked(oldService.subscribeSessionsIndexV4).mockImplementation(() => new Promise(() => {}));
  304. const oldStore = acquireSessionsIndex(scope, oldService);
  305. const newStore = acquireSessionsIndex(scope, newService);
  306. try {
  307. expect(newStore).toBe(oldStore);
  308. await vi.waitFor(() => expect(newService.subscribeSessionsIndexV4).toHaveBeenCalledTimes(1));
  309. } finally {
  310. releaseSessionsIndex(scope, newStore);
  311. releaseSessionsIndex(scope, oldStore);
  312. }
  313. });
  314. it("远程旧退订一直未完成时,新 service 仍可立即接管 transport", async () => {
  315. const oldService = mockAgentService();
  316. const newService = mockAgentService();
  317. const scope = {
  318. workspaceKey: "ssh:repo",
  319. workspacePath: "/repo",
  320. workspaceIdentity: "ssh:repo",
  321. endpointKey: "remote-1",
  322. };
  323. vi.mocked(oldService.unsubscribeSessionsIndexV4).mockImplementation(
  324. () => new Promise(() => {}),
  325. );
  326. const oldStore = acquireSessionsIndex(scope, oldService);
  327. await vi.waitFor(() => expect(oldService.subscribeSessionsIndexV4).toHaveBeenCalledTimes(1));
  328. const newStore = acquireSessionsIndex(scope, newService);
  329. try {
  330. expect(newStore).toBe(oldStore);
  331. await vi.waitFor(() => expect(newService.subscribeSessionsIndexV4).toHaveBeenCalledTimes(1));
  332. } finally {
  333. releaseSessionsIndex(scope, newStore);
  334. releaseSessionsIndex(scope, oldStore);
  335. }
  336. });
  337. it("远程中间代际订阅一直未完成时,更新 service 仍可立即接管 transport", async () => {
  338. const firstService = mockAgentService();
  339. const pendingMiddleService = mockAgentService();
  340. const latestService = mockAgentService();
  341. const scope = {
  342. workspaceKey: "ssh:repo",
  343. workspacePath: "/repo",
  344. workspaceIdentity: "ssh:repo",
  345. endpointKey: "remote-1",
  346. };
  347. vi.mocked(pendingMiddleService.subscribeSessionsIndexV4).mockImplementation(
  348. () => new Promise(() => {}),
  349. );
  350. const firstStore = acquireSessionsIndex(scope, firstService);
  351. await vi.waitFor(() => expect(firstService.subscribeSessionsIndexV4).toHaveBeenCalledTimes(1));
  352. const pendingStore = acquireSessionsIndex(scope, pendingMiddleService);
  353. await vi.waitFor(() =>
  354. expect(pendingMiddleService.subscribeSessionsIndexV4).toHaveBeenCalledTimes(1),
  355. );
  356. const latestStore = acquireSessionsIndex(scope, latestService);
  357. try {
  358. expect(pendingStore).toBe(firstStore);
  359. expect(latestStore).toBe(firstStore);
  360. await vi.waitFor(() =>
  361. expect(latestService.subscribeSessionsIndexV4).toHaveBeenCalledTimes(1),
  362. );
  363. } finally {
  364. releaseSessionsIndex(scope, latestStore);
  365. releaseSessionsIndex(scope, pendingStore);
  366. releaseSessionsIndex(scope, firstStore);
  367. }
  368. });
  369. it("远程 service 连续换代时,迟到的中间代际不能把 transport 切回去", async () => {
  370. const firstService = mockAgentService();
  371. const staleMiddleService = mockAgentService();
  372. const latestService = mockAgentService();
  373. const scope = {
  374. workspaceKey: "ssh:repo",
  375. workspacePath: "/repo",
  376. workspaceIdentity: "ssh:repo",
  377. endpointKey: "remote-1",
  378. };
  379. const register = (agentService: SessionsIndexAgentService) =>
  380. registerRemoteWorkspaceSession({
  381. sessionId: scope.endpointKey,
  382. services: { zcodeAgentService: agentService } as unknown as IServiceAccessor,
  383. });
  384. register(firstService);
  385. register(staleMiddleService);
  386. register(latestService);
  387. const firstStore = acquireSessionsIndex(scope, firstService);
  388. const latestStore = acquireSessionsIndex(scope, latestService);
  389. await vi.waitFor(() => expect(latestService.subscribeSessionsIndexV4).toHaveBeenCalledTimes(1));
  390. const staleStore = acquireSessionsIndex(scope, staleMiddleService);
  391. try {
  392. expect(latestStore).toBe(firstStore);
  393. expect(staleStore).toBe(firstStore);
  394. await new Promise((resolve) => setTimeout(resolve, 0));
  395. expect(staleMiddleService.subscribeSessionsIndexV4).not.toHaveBeenCalled();
  396. } finally {
  397. releaseSessionsIndex(scope, staleStore);
  398. releaseSessionsIndex(scope, latestStore);
  399. releaseSessionsIndex(scope, firstStore);
  400. unregisterRemoteWorkspaceSession(scope.endpointKey);
  401. }
  402. });
  403. it("本地 __base__ 的 service 换代仍创建独立 store,不改变原有生命周期", async () => {
  404. const oldService = mockAgentService();
  405. const newService = mockAgentService();
  406. const scope = { workspaceKey: "/repo", workspacePath: "/repo" };
  407. const oldStore = acquireSessionsIndex(scope, oldService);
  408. const newStore = acquireSessionsIndex(scope, newService);
  409. expect(newStore).not.toBe(oldStore);
  410. expect(sessionsIndexRegistrySize()).toBe(1);
  411. releaseSessionsIndex(scope, oldStore);
  412. expect(sessionsIndexRegistrySize()).toBe(1);
  413. expect(newService.unsubscribeSessionsIndexV4).not.toHaveBeenCalled();
  414. releaseSessionsIndex(scope, newStore);
  415. expect(sessionsIndexRegistrySize()).toBe(0);
  416. });
  417. it("hook signature 使用的 entry key 对 service generation 敏感且同引用稳定", () => {
  418. const scope = { workspaceKey: "ws-1", endpointKey: "remote-1" };
  419. const first = mockAgentService();
  420. const second = mockAgentService();
  421. const signatureFor = (service: SessionsIndexAgentService) =>
  422. Reflect.apply(buildSessionsIndexEntryKey, undefined, [scope, service]) as string;
  423. expect(signatureFor(first)).toBe(signatureFor(first));
  424. expect(signatureFor(first)).not.toBe(signatureFor(second));
  425. });
  426. it("release 未注册 key 为 no-op", () => {
  427. releaseSessionsIndex({ workspaceKey: "ws-unknown" }, new SessionsIndexStore());
  428. expect(sessionsIndexRegistrySize()).toBe(0);
  429. });
  430. });