remoteProjectFirstSubscription.test.ts 5.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154
  1. import { expect, it, vi } from "vitest";
  2. import { Emitter, ProxyChannel, type IServerChannel } from "@zcode/rpc";
  3. import { ServiceChannels } from "@zcode/shared";
  4. import {
  5. ZCODE_AGENT_RUNTIME_UNAVAILABLE_CODE,
  6. type IProjectService,
  7. type IZCodeAgentService,
  8. type ZCodeAgentRuntimeLifecycleEvent,
  9. type ZCodeAgentWorkspaceTarget,
  10. } from "@zcode/services";
  11. import {
  12. sessionsIndexTopic,
  13. type SessionsIndexTopicWireCandidate,
  14. } from "@zcode/shared/zcode-protocol-v4";
  15. import { bindRemoteProjectIdentities } from "../../services/src/project/index.js";
  16. import {
  17. SourceServerWorkspaceIdentityMapper,
  18. SourceServerWorkspaceIdentityChannelServer,
  19. } from "../../services/src/source-server-workspace/sourceServerWorkspaceIdentityChannelServer.js";
  20. import { createWindowHostSessionsIndexObserver } from "../src/host/windowHostSessionsIndexObserver.js";
  21. it.each([false, true])(
  22. "empty remote project receives first permission without restart (runtime already running=%s)",
  23. async (initiallyRunning) => {
  24. const workspacePath = "/repo";
  25. const stable = "remote:server:source:/repo";
  26. const canonical = "remote:ssh:example.test:22:dev:/repo";
  27. const mapper = new SourceServerWorkspaceIdentityMapper();
  28. const lifecycle = new Emitter<ZCodeAgentRuntimeLifecycleEvent>();
  29. const emitters = new Map<string, Emitter<SessionsIndexTopicWireCandidate>>();
  30. const emitter = (identity: string) => {
  31. let value = emitters.get(identity);
  32. if (!value) {
  33. value = new Emitter();
  34. emitters.set(identity, value);
  35. }
  36. return value;
  37. };
  38. let running = initiallyRunning;
  39. const subscribe = vi.fn(async (target: ZCodeAgentWorkspaceTarget) => {
  40. if (!running || target.workspaceIdentity !== canonical)
  41. throw Object.assign(new Error("runtime unavailable"), {
  42. code: ZCODE_AGENT_RUNTIME_UNAVAILABLE_CODE,
  43. });
  44. const key = target.workspaceIdentity ?? target.workspacePath;
  45. const topic = sessionsIndexTopic(key);
  46. emitter(key).fire({
  47. wireVersion: 3,
  48. kind: "complete",
  49. deliveryKind: "initial",
  50. logicalFrameId: "first",
  51. logicalFrameOrdinal: 1,
  52. topic,
  53. subscriptionId: "subscription",
  54. frame: {
  55. topic,
  56. subscriptionId: "subscription",
  57. fromSeq: 0,
  58. toSeq: 1,
  59. sentAt: 1,
  60. payload: {
  61. kind: "snapshot",
  62. snapshot: {
  63. protocolVersion: 1,
  64. workspaceId: key,
  65. logEpoch: "epoch",
  66. sessions: [
  67. {
  68. sessionId: "first-task",
  69. workspaceId: key,
  70. title: "First task",
  71. phase: "running",
  72. sessionEnded: false,
  73. hasBackgroundWork: false,
  74. lastActivityAt: 2,
  75. createdAt: 1,
  76. pendingInteractionSummary: { permissionCount: 1, userInputCount: 0 },
  77. },
  78. ],
  79. },
  80. },
  81. },
  82. });
  83. return {
  84. ack: { subscriptionId: "subscription", mode: "snapshot" as const, logEpoch: "epoch" },
  85. };
  86. });
  87. const inner = {
  88. onDynamicSessionsIndexFrame: (target: ZCodeAgentWorkspaceTarget) =>
  89. emitter(target.workspaceIdentity ?? target.workspacePath).event,
  90. onAgentRuntimeLifecycle: lifecycle.event,
  91. subscribeSessionsIndexV4: subscribe,
  92. unsubscribeSessionsIndexV4: async () => undefined,
  93. resyncSessionsIndexV4: vi.fn(),
  94. };
  95. let channel!: IServerChannel<string>;
  96. new SourceServerWorkspaceIdentityChannelServer(
  97. {
  98. registerChannel: (_name, registered) => {
  99. channel = registered;
  100. },
  101. },
  102. mapper,
  103. ).registerChannel(ServiceChannels.ZCodeAgent, ProxyChannel.fromService(inner));
  104. const agent = ProxyChannel.toService<IZCodeAgentService>({
  105. call: (command, args) => channel.call("controller", command, args),
  106. listen: (event, args) => channel.listen("controller", event, args),
  107. });
  108. // 真实项目树适配器是订阅前的身份准备边界;旧实现忽略没有 task 的 root。
  109. const service = bindRemoteProjectIdentities(
  110. {
  111. readTree: async () => ({ projects: [{ roots: [{ rootPath: workspacePath }] }], tasks: [] }),
  112. } as unknown as IProjectService,
  113. async () => {
  114. mapper.register({ stableIdentity: stable, canonicalIdentity: canonical });
  115. return stable;
  116. },
  117. );
  118. await service.readTree();
  119. const changes = vi.fn();
  120. const observer = createWindowHostSessionsIndexObserver({
  121. agentService: agent,
  122. target: { workspacePath, workspaceIdentity: stable },
  123. onSessionsChange: changes,
  124. });
  125. try {
  126. await observer.start();
  127. // 首次打开仍会调用相同 resolver;该步骤不能挽救已经绑定到错误 emitter 的监听。
  128. mapper.register({ stableIdentity: stable, canonicalIdentity: canonical });
  129. if (!initiallyRunning) {
  130. running = true;
  131. lifecycle.fire({
  132. workspaceKey: canonical,
  133. workspacePath,
  134. workspaceIdentity: canonical,
  135. state: "available",
  136. runtimeIdentity: { workspaceKey: canonical, generation: 1, identity: "runtime" },
  137. });
  138. }
  139. await vi.waitFor(() =>
  140. expect(changes).toHaveBeenCalledWith([
  141. expect.objectContaining({
  142. sessionId: "first-task",
  143. pendingInteractionSummary: { permissionCount: 1, userInputCount: 0 },
  144. }),
  145. ]),
  146. );
  147. } finally {
  148. observer.dispose();
  149. lifecycle.dispose();
  150. for (const value of emitters.values()) value.dispose();
  151. }
  152. },
  153. );