hostRemoteWorkspaceServices.test.ts 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353
  1. import { Emitter, ChannelClient, ChannelServer, createQueuePair, ProxyChannel } from "@zcode/rpc";
  2. import { describe, expect, it, vi } from "vitest";
  3. import {
  4. IClientConfigService,
  5. IFileService,
  6. IMediaPreviewService,
  7. ICredentialService,
  8. IOAuthService,
  9. ICodingPlanSubscriptionService,
  10. ISettingService,
  11. IOnboardingRecordService,
  12. ISystemService,
  13. IModelSelectionService,
  14. IProviderSettingsService,
  15. ISourceServerWorkspaceService,
  16. IPluginSyncService,
  17. IPluginsService,
  18. ISubagentsService,
  19. ISettingsSyncService,
  20. IProjectService,
  21. IRemoteProjectService,
  22. ITaskGroupService,
  23. IBroadcastService,
  24. type BroadcastMessage,
  25. type IServiceAccessor,
  26. ServiceCollection,
  27. } from "@zcode/services";
  28. import { REMOTE_WORKSPACE_RPC_CHANNELS } from "../src/host/remoteWorkspaceRpcContract.js";
  29. import {
  30. REMOTE_WORKSPACE_RPC_REGISTRATIONS,
  31. createServerRemoteWorkspaceServiceCollection,
  32. } from "../src/host/remoteWorkspaceServiceCollection.js";
  33. import { getRemoteProviderProvisioningExecutor } from "../src/host/remoteProviderProvisioningService.js";
  34. import {
  35. createSourceSettingsServiceCollection,
  36. shouldDetachSourceSettingsAttachment,
  37. } from "../src/host/sourceSettingsServiceCollection.js";
  38. const clientConfigService = { getSnapshot: vi.fn(async () => ({ pluginStoreOrder: null })) };
  39. function makeServerRemoteServices(): IServiceAccessor {
  40. return {
  41. ...Object.fromEntries(
  42. REMOTE_WORKSPACE_RPC_CHANNELS.map((channel) => [channel, { remote: channel }]),
  43. ),
  44. systemService: { info: vi.fn(async () => ({ platform: "linux", homedir: "/home/remote" })) },
  45. } as unknown as IServiceAccessor;
  46. }
  47. function createOnboardingRecordStub(): IOnboardingRecordService {
  48. return {
  49. appendRecord: vi.fn(async () => {}),
  50. dismissOnboarding: vi.fn(async () => {}),
  51. claimAnonymousRecord: vi.fn(async () => {}),
  52. shouldOnboard: vi.fn(async () => false),
  53. getLatestEntry: vi.fn(async () => null),
  54. syncSettingsFromRecord: vi.fn(async () => null),
  55. updateRecordPreferences: vi.fn(async () => {}),
  56. getRecords: vi.fn(async () => null),
  57. clearRecords: vi.fn(async () => {}),
  58. };
  59. }
  60. describe("server remote workspace host service wiring", () => {
  61. it("keeps registrations equal to the RPC contract", () => {
  62. expect(REMOTE_WORKSPACE_RPC_REGISTRATIONS.map(([key]) => key).sort()).toEqual(
  63. [...REMOTE_WORKSPACE_RPC_CHANNELS].sort(),
  64. );
  65. });
  66. it.each(["ssh", "wsl", "docker", "server"] as const)(
  67. "%s 分组使用控制端服务和广播,执行服务仍归 Source",
  68. async (targetKind) => {
  69. const controllerEvents = new Emitter<BroadcastMessage>();
  70. const sourceEvents = new Emitter<BroadcastMessage>();
  71. const broadcast = (events: Emitter<BroadcastMessage>) => ({
  72. send: vi.fn(async (message: BroadcastMessage) => events.fire(message)),
  73. onMessage: events.event,
  74. acquireClaim: vi.fn(async () => ({ status: "unavailable" as const })),
  75. commitClaim: vi.fn(async () => {}),
  76. releaseClaim: vi.fn(async () => {}),
  77. tryClaim: vi.fn(async () => false),
  78. });
  79. const controllerBroadcast = broadcast(controllerEvents),
  80. sourceBroadcast = broadcast(sourceEvents);
  81. const groups = {
  82. read: vi.fn(async () => ({ groups: [], members: [], order: [] })),
  83. save: vi.fn(),
  84. move: vi.fn(),
  85. ungroup: vi.fn(),
  86. admit: vi.fn(),
  87. };
  88. const remoteServices = { ...makeServerRemoteServices(), broadcastService: sourceBroadcast };
  89. const services = createServerRemoteWorkspaceServiceCollection({
  90. clientConfigService,
  91. targetKind,
  92. connectionServices: remoteServices,
  93. sourceServices: new ServiceCollection()
  94. .register(ITaskGroupService, groups)
  95. .register(IBroadcastService, controllerBroadcast),
  96. });
  97. expect(services.get(ITaskGroupService)).toBe(groups);
  98. expect(services.get(IFileService)).toBe(remoteServices.fileService);
  99. const listener = vi.fn();
  100. const subscription = services.get(IBroadcastService).onMessage(listener);
  101. controllerEvents.fire({ channel: "state:task-groups", payload: {} });
  102. sourceEvents.fire({ channel: "state:task-groups", payload: {} });
  103. sourceEvents.fire({ channel: "state:projects", payload: {} });
  104. expect(listener.mock.calls.map(([event]) => event.channel)).toEqual([
  105. "state:task-groups",
  106. "state:projects",
  107. ]);
  108. subscription.dispose();
  109. controllerEvents.fire({ channel: "state:task-groups", payload: {} });
  110. expect(listener).toHaveBeenCalledTimes(2);
  111. controllerEvents.dispose();
  112. sourceEvents.dispose();
  113. },
  114. );
  115. it("detaches Source settings while updating", () => {
  116. expect(shouldDetachSourceSettingsAttachment("online")).toBe(false);
  117. expect(shouldDetachSourceSettingsAttachment("updating")).toBe(true);
  118. });
  119. it("exposes only non-provider configuration channels for a Source settings attachment", () => {
  120. const remoteServices = makeServerRemoteServices();
  121. const services = createSourceSettingsServiceCollection(remoteServices);
  122. expect(services.get(ICredentialService)).toBe(remoteServices.credentialService);
  123. expect(services.get(IOAuthService)).toBe(remoteServices.oauthService);
  124. expect(services.get(ICodingPlanSubscriptionService)).toBe(
  125. remoteServices.codingPlanSubscriptionService,
  126. );
  127. expect(services.get(ISettingService)).toBe(remoteServices.settingService);
  128. expect(services.get(ISystemService)).toBe(remoteServices.systemService);
  129. expect(services.get(IPluginSyncService)).toBe(remoteServices.pluginSyncService);
  130. expect(services.get(IPluginsService)).toBe(remoteServices.pluginsService);
  131. expect(services.get(ISubagentsService)).toBe(remoteServices.subagentsService);
  132. expect(services.get(ISettingsSyncService)).toBe(remoteServices.settingsSyncService);
  133. // 模型设置页永远绑定本地 Environment,远端 Provider 事实只经 Provisioning 单向下发,
  134. // 不再借 source-settings attachment 暴露给设置页编辑。
  135. expect(services.getOptional(IProviderSettingsService)).toBeUndefined();
  136. expect(services.getOptional(IModelSelectionService)).toBeUndefined();
  137. expect(services.getOptional(IFileService)).toBeUndefined();
  138. });
  139. it("keeps the Source Server runtime authoritative for every forwarded service family", () => {
  140. const remoteServices = makeServerRemoteServices();
  141. const services = createServerRemoteWorkspaceServiceCollection({
  142. clientConfigService,
  143. targetKind: "server",
  144. connectionServices: remoteServices,
  145. });
  146. expect(services.get(IClientConfigService)).toBe(clientConfigService);
  147. expect(services.get(IFileService)).toBe(remoteServices.fileService);
  148. expect(services.get(IMediaPreviewService)).toBe(remoteServices.mediaPreviewService);
  149. expect(services.get(ISettingService)).toBe(remoteServices.settingService);
  150. expect(services.get(IOnboardingRecordService)).toBe(remoteServices.onboardingRecordService);
  151. expect(services.get(IProviderSettingsService)).toBe(remoteServices.providerSettingsService);
  152. expect(services.get(IModelSelectionService)).toBe(remoteServices.modelSelectionService);
  153. expect(services.get(ISourceServerWorkspaceService)).toBe(
  154. remoteServices.sourceServerWorkspaceService,
  155. );
  156. expect(services.get(IPluginSyncService)).toBe(remoteServices.pluginSyncService);
  157. expect(services.get(IPluginsService)).toBe(remoteServices.pluginsService);
  158. expect(services.get(ISubagentsService)).toBe(remoteServices.subagentsService);
  159. expect(services.get(ISettingsSyncService)).toBe(remoteServices.settingsSyncService);
  160. });
  161. it.each(["ssh", "wsl", "docker", "server"] as const)(
  162. "%s 远程 attachment 通过 RPC 访问 Source 自己的引导记录并保留服务错误",
  163. async (targetKind) => {
  164. // R3 下 settings/OAuth 均由 Source 全转发;引导记录必须同源,不能借用本机 Local Host 记录。
  165. const localRecord = createOnboardingRecordStub();
  166. const sourceRecord = createOnboardingRecordStub();
  167. const services = createServerRemoteWorkspaceServiceCollection({
  168. clientConfigService,
  169. targetKind,
  170. connectionServices: {
  171. ...makeServerRemoteServices(),
  172. onboardingRecordService: sourceRecord,
  173. },
  174. sourceServices: new ServiceCollection().register(IOnboardingRecordService, localRecord),
  175. });
  176. const [serverProtocol, clientProtocol] = createQueuePair();
  177. const server = new ChannelServer(serverProtocol, "mobile-onboarding", 50);
  178. const client = new ChannelClient(clientProtocol);
  179. services.exposeOnChannelServer(server);
  180. const record = ProxyChannel.toService<IOnboardingRecordService>(
  181. client.getChannel(IOnboardingRecordService.channelName),
  182. );
  183. try {
  184. // 远程集合曾漏注册通道;即使 owner 已有记录,手机也只能收到 Unknown channel。
  185. await record.claimAnonymousRecord();
  186. await expect(record.shouldOnboard("mobile-device")).resolves.toBe(false);
  187. await record.dismissOnboarding("mobile-device");
  188. const entry = {
  189. occupation: "developer",
  190. interfaceMode: "coding" as const,
  191. memoryEnabled: false,
  192. proactiveSuggestionsEnabled: false,
  193. completedAt: "2026-10-09T00:00:00.000Z",
  194. };
  195. await record.appendRecord("mobile-device", entry);
  196. expect(services.get(IOnboardingRecordService)).toBe(sourceRecord);
  197. expect(sourceRecord.dismissOnboarding).toHaveBeenCalledWith("mobile-device");
  198. expect(sourceRecord.appendRecord).toHaveBeenCalledWith("mobile-device", entry);
  199. expect(localRecord.claimAnonymousRecord).not.toHaveBeenCalled();
  200. expect(localRecord.shouldOnboard).not.toHaveBeenCalled();
  201. expect(localRecord.dismissOnboarding).not.toHaveBeenCalled();
  202. expect(localRecord.appendRecord).not.toHaveBeenCalled();
  203. vi.mocked(sourceRecord.shouldOnboard).mockRejectedValueOnce(
  204. new Error("record read failed"),
  205. );
  206. await expect(record.shouldOnboard("mobile-device")).rejects.toThrow("record read failed");
  207. } finally {
  208. client.dispose();
  209. server.dispose();
  210. }
  211. },
  212. );
  213. it("旧 Server 通过原文件与系统频道浏览目录并保留远端路径规则", async () => {
  214. const remoteServices = makeServerRemoteServices();
  215. const entries = [{ name: "repo", path: "C:\\Users\\remote\\repo", type: "directory" }];
  216. const readdir = vi.fn(async () => entries);
  217. remoteServices.fileService = { readdir } as unknown as IFileService;
  218. remoteServices.systemService = {
  219. info: vi.fn(async () => ({ platform: "win32", homedir: "C:\\Users\\remote" })),
  220. } as unknown as ISystemService;
  221. const services = createServerRemoteWorkspaceServiceCollection({
  222. connectionServices: remoteServices,
  223. serverId: "old",
  224. });
  225. const projectService = services.get(IProjectService);
  226. await expect(projectService.readDirectory()).resolves.toEqual({
  227. path: "C:\\Users\\remote",
  228. entries,
  229. });
  230. await expect(
  231. projectService.readDirectory({ path: "C:/repo/../work", includeHidden: true }),
  232. ).resolves.toEqual({ path: "C:\\work", entries });
  233. expect(readdir).toHaveBeenLastCalledWith({ path: "C:\\work", includeHidden: true });
  234. await expect(projectService.readDirectory({ path: "C:relative" })).rejects.toThrow(
  235. "project.absolute-path-required",
  236. );
  237. await expect(projectService.saveProject({ roots: ["C:\\work"] })).rejects.toThrow(
  238. "project.legacy-read-only",
  239. );
  240. });
  241. it("旧 Server 没有目录历史时仍可按本机保留入口寻址,刷新不会创建新入口", async () => {
  242. const remoteServices = makeServerRemoteServices();
  243. remoteServices.settingService = {
  244. get: vi.fn(async () => ({ lastWorkspaceSession: [], recentProjects: [] })),
  245. } as unknown as typeof remoteServices.settingService;
  246. let entries = [
  247. { hostId: "remote:server:old", roots: [{ rootPath: "/retained" }], legacyWorkspace: null },
  248. ];
  249. const sourceServices = new ServiceCollection().register(IRemoteProjectService, {
  250. readDirectory: vi.fn(async () => ({ hosts: [], entries })),
  251. } as unknown as IRemoteProjectService);
  252. const services = createServerRemoteWorkspaceServiceCollection({
  253. connectionServices: remoteServices,
  254. serverId: "old",
  255. sourceServices,
  256. });
  257. expect((await services.get(IProjectService).readProjects())[0]?.roots[0]?.rootPath).toBe(
  258. "/retained",
  259. );
  260. entries = [];
  261. expect(await services.get(IProjectService).readProjects()).toEqual([]);
  262. });
  263. it("缺少握手能力时忽略未知频道 proxy,通过旧 API 提供单 root 项目", async () => {
  264. const remoteServices = makeServerRemoteServices();
  265. const unsupportedRead = vi.fn(async () => {
  266. throw new Error("Unknown channel");
  267. });
  268. remoteServices.projectService = { readProjects: unsupportedRead } as unknown as IProjectService;
  269. remoteServices.settingService = {
  270. get: vi.fn(async () => ({
  271. lastWorkspaceSession: [{ kind: "local", workspacePath: "/remote/root" }],
  272. recentProjects: [],
  273. })),
  274. } as unknown as typeof remoteServices.settingService;
  275. const services = createServerRemoteWorkspaceServiceCollection({
  276. connectionServices: remoteServices,
  277. serverId: "old",
  278. });
  279. expect(await services.get(IProjectService).readProjects()).toEqual([
  280. expect.objectContaining({
  281. hostId: "remote:server:old",
  282. legacySingleRoot: true,
  283. roots: [{ rootPath: "/remote/root", position: 0, isPrimary: true }],
  284. }),
  285. ]);
  286. expect(unsupportedRead).not.toHaveBeenCalled();
  287. await expect(services.get(IRemoteProjectService).readDirectory()).resolves.toEqual({
  288. hosts: [],
  289. entries: [],
  290. });
  291. });
  292. it("forwards declared virtual-project channels without adding them to the v1 requirement", () => {
  293. const remoteServices = Object.assign(makeServerRemoteServices(), {
  294. projectService: { readTree: vi.fn() },
  295. remoteProjectService: { readDirectory: vi.fn() },
  296. });
  297. const modern = createServerRemoteWorkspaceServiceCollection({
  298. connectionServices: remoteServices as unknown as IServiceAccessor,
  299. virtualProjects: true,
  300. });
  301. expect(modern.get(IProjectService)).toBe(remoteServices.projectService);
  302. expect(modern.get(IRemoteProjectService)).toBe(remoteServices.remoteProjectService);
  303. const legacy = createServerRemoteWorkspaceServiceCollection({
  304. connectionServices: remoteServices as unknown as IServiceAccessor,
  305. });
  306. expect(legacy.getOptional(IProjectService)).toBeUndefined();
  307. expect(REMOTE_WORKSPACE_RPC_CHANNELS).not.toContain("projectService");
  308. });
  309. it("reuses URL registry services for configuration without exposing task/runtime channels", () => {
  310. const remoteServices = makeServerRemoteServices();
  311. const registry = createServerRemoteWorkspaceServiceCollection({
  312. connectionServices: remoteServices,
  313. });
  314. const settings = createSourceSettingsServiceCollection(registry);
  315. expect(settings.get(ISubagentsService)).toBe(remoteServices.subagentsService);
  316. expect(settings.getOptional(IProjectService)).toBeUndefined();
  317. expect(settings.getOptional(IFileService)).toBeUndefined();
  318. });
  319. it("registers a host-private provider provisioning executor for every Source connection", async () => {
  320. const remoteTargetApply = vi.fn();
  321. const remoteServices = Object.assign(makeServerRemoteServices(), {
  322. providerProvisioningTargetService: { apply: remoteTargetApply },
  323. });
  324. const services = createServerRemoteWorkspaceServiceCollection({
  325. clientConfigService,
  326. targetKind: "server",
  327. connectionServices: remoteServices,
  328. });
  329. const executor = getRemoteProviderProvisioningExecutor(services);
  330. expect(executor).toBeDefined();
  331. // 没有本机 Provisioning Source 时必须 fail-closed 为 unsupported,不能向远端发送半份快照。
  332. await expect(executor!.syncLocalToRemote()).resolves.toMatchObject({
  333. status: "unsupported",
  334. rolledBack: false,
  335. });
  336. expect(remoteTargetApply).not.toHaveBeenCalled();
  337. });
  338. });