rootSettingsSessionsIndexSubscription.test.ts 7.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208
  1. import { describe, expect, it, vi } from "vitest";
  2. import { Emitter } from "@zcode/rpc";
  3. import type {
  4. SessionSummary,
  5. SessionsIndexTopicFrame,
  6. SessionsIndexTopicWireFrame,
  7. } from "@zcode/shared/zcode-protocol-v4";
  8. import { resolveRootWorkspaceShellTarget } from "@/root/rootWorkspaceShellTarget.js";
  9. import {
  10. acquireSessionsIndex,
  11. releaseSessionsIndex,
  12. sessionsIndexRegistrySize,
  13. type SessionsIndexAgentService,
  14. type SessionsIndexScope,
  15. } from "@/v4/sessionsIndexRegistry.js";
  16. const workspacePath = "/root/src/plancov";
  17. const workspaceIdentity = "remote:wsl:default:root:/root/src/plancov";
  18. const remoteSessionId = "df0312a2-2628-4215-8556-2f5e4c33b394";
  19. /**
  20. * 模拟一条远程 attachment 连接上的 CLI sessions-index publisher:
  21. * 同 connection/topic 的后一次 subscribe 会静默替换前一次(`SessionsIndexPublisher.subscribeReserved`),
  22. * 被替换的订阅再也收不到帧,也不会收到任何信号。
  23. */
  24. function createSingleConnectionRemoteService(): {
  25. service: SessionsIndexAgentService;
  26. emitUpsert(session: SessionSummary): void;
  27. } {
  28. let nextSubscription = 1;
  29. let nextLogicalFrame = 1;
  30. let currentSeq = 1;
  31. let activeSubscriptionId: string | null = null;
  32. const listeners = new Set<(frame: SessionsIndexTopicWireFrame) => void>();
  33. const runtimeRestarts = new Emitter<{ workspaceKey: string }>();
  34. const topic = `sessions-index/${workspaceIdentity}`;
  35. const physicalFrame = (
  36. frame: SessionsIndexTopicFrame,
  37. deliveryKind: "initial" | "online",
  38. ): SessionsIndexTopicWireFrame => ({
  39. wireVersion: 3,
  40. kind: "complete",
  41. deliveryKind,
  42. logicalFrameId: `logical-${nextLogicalFrame}`,
  43. logicalFrameOrdinal: nextLogicalFrame++,
  44. topic: frame.topic,
  45. subscriptionId: frame.subscriptionId,
  46. frame,
  47. });
  48. const service = {
  49. helloConversationV4: vi.fn(async () => ({
  50. kind: "hello" as const,
  51. protocolVersion: 3 as const,
  52. connectionId: "host-rpc-plancov-attachment",
  53. clientMode: "desktop-continuous" as const,
  54. deliveryProfile: "continuous" as const,
  55. serverTime: 1,
  56. capabilities: {
  57. nativeDialogs: true,
  58. localTerminal: true,
  59. binaryFrames: false,
  60. compression: "none" as const,
  61. },
  62. auth: {},
  63. })),
  64. initializeConversationV4: vi.fn(async () => {}),
  65. subscribeSessionsIndexV4: vi.fn(async () => {
  66. const subscriptionId = `six-${nextSubscription++}`;
  67. activeSubscriptionId = subscriptionId;
  68. const initial = physicalFrame(
  69. {
  70. topic,
  71. subscriptionId,
  72. fromSeq: 0,
  73. toSeq: currentSeq,
  74. sentAt: 1,
  75. payload: {
  76. kind: "snapshot",
  77. snapshot: {
  78. protocolVersion: 1,
  79. workspaceId: workspaceIdentity,
  80. logEpoch: "epoch-1",
  81. sessions: [],
  82. },
  83. },
  84. },
  85. "initial",
  86. );
  87. for (const listener of listeners) listener(initial);
  88. return { ack: { subscriptionId, mode: "snapshot" as const, logEpoch: "epoch-1" } };
  89. }),
  90. unsubscribeSessionsIndexV4: vi.fn(async (params: { subscriptionId: string }) => {
  91. if (activeSubscriptionId === params.subscriptionId) activeSubscriptionId = null;
  92. }),
  93. resyncSessionsIndexV4: vi.fn(async (params: { subscriptionId: string }) => ({
  94. ack: {
  95. subscriptionId: params.subscriptionId,
  96. mode: "snapshot" as const,
  97. logEpoch: "epoch-1",
  98. },
  99. })),
  100. onDynamicSessionsIndexFrame: vi.fn(
  101. () => (listener: (frame: SessionsIndexTopicWireFrame) => void) => {
  102. listeners.add(listener);
  103. return { dispose: () => listeners.delete(listener) };
  104. },
  105. ),
  106. onAgentRuntimeRestarted: runtimeRestarts.event,
  107. } as unknown as SessionsIndexAgentService;
  108. return {
  109. service,
  110. emitUpsert(session) {
  111. if (!activeSubscriptionId) return;
  112. const frame: SessionsIndexTopicFrame = {
  113. topic,
  114. subscriptionId: activeSubscriptionId,
  115. fromSeq: currentSeq,
  116. toSeq: currentSeq + 1,
  117. sentAt: 2,
  118. payload: { kind: "deltas", deltas: [{ op: "session.upserted", session }] },
  119. };
  120. currentSeq += 1;
  121. for (const listener of listeners) listener(physicalFrame(frame, "online"));
  122. },
  123. };
  124. }
  125. function summary(phase: SessionSummary["phase"], lastActivityAt: number): SessionSummary {
  126. return {
  127. sessionId: "sess_b8d3c760",
  128. workspaceId: workspaceIdentity,
  129. title: "EDGES视图覆盖情况可视化方案",
  130. phase,
  131. sessionEnded: phase === "completedSuccess",
  132. hasBackgroundWork: false,
  133. lastActivityAt,
  134. createdAt: 1,
  135. };
  136. }
  137. /** 与 App.useWorkspaceTerminalTaskNotifications 同口径:Root 的外壳目标 → 注册表 scope。 */
  138. function notificationScopeFromShellTarget(target: {
  139. workspaceShellPath: string | null;
  140. workspaceIdentity?: string;
  141. workspaceRemoteSessionId?: string;
  142. }): SessionsIndexScope {
  143. const path = target.workspaceShellPath ?? "";
  144. return {
  145. workspaceKey: target.workspaceIdentity ?? path,
  146. workspacePath: path,
  147. ...(target.workspaceIdentity ? { workspaceIdentity: target.workspaceIdentity } : {}),
  148. ...(target.workspaceRemoteSessionId ? { endpointKey: target.workspaceRemoteSessionId } : {}),
  149. };
  150. }
  151. describe("Settings 覆盖远程 workspace 时的 sessions-index 单订阅不变量", () => {
  152. it("通知 hook 复用侧栏订阅;关闭 Settings 后侧栏仍能收到任务完成", async () => {
  153. const { service, emitUpsert } = createSingleConnectionRemoteService();
  154. const remoteTab = { workspacePath, workspaceIdentity, remoteSessionId };
  155. // 侧栏 useWorkspaceTaskLists 的远程 shard scope(endpointKey = remoteSessionId)。
  156. const sidebarScope: SessionsIndexScope = {
  157. workspaceKey: workspaceIdentity,
  158. workspacePath,
  159. workspaceIdentity,
  160. endpointKey: remoteSessionId,
  161. };
  162. const sidebarStore = acquireSessionsIndex(sidebarScope, service);
  163. await vi.waitFor(() => expect(sidebarStore.getState().workspaceId).toBe(workspaceIdentity));
  164. emitUpsert(summary("running", 100));
  165. await vi.waitFor(() => expect(sidebarStore.getSessions()[0]?.phase).toBe("running"));
  166. // 用户打开 Settings:active tab 不再是 workspace tab,Root 按 fallback 解析外壳目标。
  167. const shellTarget = resolveRootWorkspaceShellTarget({
  168. activeWorkspaceTab: null,
  169. activeWorkspacePath: workspacePath,
  170. activeWorkspaceIdentity: workspaceIdentity,
  171. workspaceTabs: [remoteTab],
  172. });
  173. const notificationStore = acquireSessionsIndex(
  174. notificationScopeFromShellTarget(shellTarget),
  175. service,
  176. );
  177. // 不变量:同一远程 workspace 在这条 attachment 上只能有一条 sessions-index 订阅。
  178. expect(notificationStore).toBe(sidebarStore);
  179. expect(sessionsIndexRegistrySize()).toBe(1);
  180. expect(service.subscribeSessionsIndexV4).toHaveBeenCalledTimes(1);
  181. // 用户关闭 Settings:通知 hook 释放引用,不能让 CLI 侧该 topic 归零。
  182. releaseSessionsIndex(notificationScopeFromShellTarget(shellTarget), notificationStore);
  183. expect(service.unsubscribeSessionsIndexV4).not.toHaveBeenCalled();
  184. // 任务完成:侧栏必须收敛,而不是停留在冻结的 running/lastActivityAt。
  185. emitUpsert(summary("completedSuccess", 200));
  186. await vi.waitFor(() => {
  187. const [session] = sidebarStore.getSessions();
  188. expect(session?.phase).toBe("completedSuccess");
  189. expect(session?.lastActivityAt).toBe(200);
  190. });
  191. releaseSessionsIndex(sidebarScope, sidebarStore);
  192. expect(sessionsIndexRegistrySize()).toBe(0);
  193. });
  194. });