connectDesktopSourceServer.test.ts 6.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162
  1. import { describe, expect, it, vi } from "vitest";
  2. import type { DynamicWorkflowMode, WindowHostAttachmentScope } from "@zcode/shared";
  3. import type { IServerChannel } from "@zcode/rpc";
  4. import { ServiceCollection, IZCodeAgentService, type IBotsService } from "@zcode/services";
  5. import type {
  6. ServerRemoteConnection,
  7. ServerRemoteDuplexConnectionOptions,
  8. } from "../src/host/serverRemoteConnection.js";
  9. import { connectDesktopSourceServer } from "../src/host/connectDesktopSourceServer.js";
  10. function setup() {
  11. const sync = vi.fn(async (): Promise<void> => undefined);
  12. const agent = { syncDynamicWorkflowUserMode: sync } as unknown as IZCodeAgentService;
  13. const logicalA = new ServiceCollection().register(IZCodeAgentService, agent);
  14. const logicalB = new ServiceCollection().register(IZCodeAgentService, agent);
  15. const scopes = new Map([
  16. ["a", logicalA],
  17. ["b", logicalB],
  18. ]);
  19. const validate = vi.fn(async () => undefined);
  20. const dispose = vi.fn();
  21. let captured: ServerRemoteDuplexConnectionOptions | undefined;
  22. const connection = {
  23. services: { zcodeAgentService: agent },
  24. dispose,
  25. } as unknown as ServerRemoteConnection;
  26. const connectServer = vi.fn(async (options: ServerRemoteDuplexConnectionOptions) => {
  27. captured = options;
  28. return connection;
  29. });
  30. const onClose = vi.fn();
  31. const dependencies = {
  32. connectServer,
  33. resolveServices: (scope: WindowHostAttachmentScope) => {
  34. if (scope.kind !== "remote") throw new Error("Expected remote");
  35. return scopes.get(scope.remoteSessionId)!;
  36. },
  37. getBots: vi.fn(
  38. () =>
  39. ({
  40. validateTopicResource: validate,
  41. readTopicResource: vi.fn(),
  42. }) as unknown as IBotsService,
  43. ),
  44. readDynamicWorkflowMode: vi.fn(
  45. async (): Promise<DynamicWorkflowMode | undefined> => "alwaysOn",
  46. ),
  47. onModeSyncError: vi.fn(),
  48. };
  49. const options = { ingressToken: "test", createConnection: vi.fn(), onClose };
  50. return {
  51. sync,
  52. scopes,
  53. validate,
  54. dispose,
  55. onClose,
  56. dependencies,
  57. options,
  58. channel: () => captured!.topicResourceChannel as IServerChannel,
  59. close: () => captured!.onClose!({ code: 1006, reason: "closed" }),
  60. };
  61. }
  62. function request(remoteSessionId: string) {
  63. return {
  64. requestId: "r",
  65. taskId: "t",
  66. inputId: "i",
  67. authorizationId: "a",
  68. messageId: "m",
  69. resourceIndex: 0,
  70. workspacePath: "/work",
  71. workspaceIdentity: "source:host:/work",
  72. remoteSessionId,
  73. };
  74. }
  75. describe("Desktop Source physical connection capabilities", () => {
  76. it("uses one reverse channel for all logical wrappers of the same physical Agent", async () => {
  77. const state = setup();
  78. const connection = await connectDesktopSourceServer(state.options, state.dependencies);
  79. expect(state.dependencies.connectServer).toHaveBeenCalledOnce();
  80. expect(await state.channel().call("host", "validate", request("a"))).toEqual({ valid: true });
  81. expect(await state.channel().call("host", "validate", request("b"))).toEqual({ valid: true });
  82. state.scopes.set("b", new ServiceCollection().register(IZCodeAgentService, {} as never));
  83. await expect(state.channel().call("host", "validate", request("b"))).rejects.toThrow(
  84. "connection mismatch",
  85. );
  86. expect(state.validate).toHaveBeenCalledTimes(2);
  87. connection.dispose();
  88. });
  89. it("closes the old reverse channel before reconnecting with a new mode", async () => {
  90. const first = setup();
  91. const oldConnection = await connectDesktopSourceServer(first.options, first.dependencies);
  92. first.close();
  93. expect(first.onClose).toHaveBeenCalledOnce();
  94. await expect(first.channel().call("host", "validate", request("a"))).rejects.toThrow("closed");
  95. const second = setup();
  96. second.dependencies.readDynamicWorkflowMode.mockResolvedValue("disabled");
  97. const newConnection = await connectDesktopSourceServer(second.options, second.dependencies);
  98. expect(second.sync).toHaveBeenCalledWith({ mode: "disabled" });
  99. expect(await second.channel().call("host", "validate", request("a"))).toEqual({ valid: true });
  100. oldConnection.dispose();
  101. newConnection.dispose();
  102. await expect(second.channel().call("host", "validate", request("a"))).rejects.toThrow("closed");
  103. });
  104. it("aborts an in-flight resource read when its physical connection closes", async () => {
  105. const state = setup();
  106. let readingSignal: AbortSignal | undefined;
  107. state.dependencies.getBots.mockReturnValue({
  108. validateTopicResource: state.validate,
  109. readTopicResource: async (value: { signal: AbortSignal }) => {
  110. readingSignal = value.signal;
  111. await new Promise<void>((_resolve, reject) => {
  112. value.signal.addEventListener("abort", () => reject(value.signal.reason), { once: true });
  113. });
  114. throw new Error("Unreachable after cancellation");
  115. },
  116. } as unknown as IBotsService);
  117. const connection = await connectDesktopSourceServer(state.options, state.dependencies);
  118. const pending = state.channel().call("host", "begin", request("a"));
  119. const rejected = expect(pending).rejects.toThrow("closed");
  120. await vi.waitFor(() => expect(readingSignal).toBeDefined());
  121. state.close();
  122. expect(readingSignal!.aborted).toBe(true);
  123. await rejected;
  124. connection.dispose();
  125. });
  126. it("publishes the connection only after the Desktop mode reaches the Source", async () => {
  127. const state = setup();
  128. let finish: () => void = () => undefined;
  129. state.sync.mockImplementation(
  130. () =>
  131. new Promise<void>((resolve) => {
  132. finish = resolve;
  133. }),
  134. );
  135. let published = false;
  136. const pending = connectDesktopSourceServer(state.options, state.dependencies).then(
  137. (connection) => {
  138. published = true;
  139. return connection;
  140. },
  141. );
  142. await vi.waitFor(() => expect(state.sync).toHaveBeenCalledWith({ mode: "alwaysOn" }));
  143. expect(published).toBe(false);
  144. finish();
  145. (await pending).dispose();
  146. });
  147. it("keeps old Sources usable when they do not support mode sync", async () => {
  148. const state = setup();
  149. state.sync.mockRejectedValue(new Error("Unknown method"));
  150. const connection = await connectDesktopSourceServer(state.options, state.dependencies);
  151. expect(state.dependencies.onModeSyncError).toHaveBeenCalledOnce();
  152. expect(await state.channel().call("host", "validate", request("a"))).toEqual({ valid: true });
  153. connection.dispose();
  154. });
  155. });