hostRemoteWorkspaceServices.test.ts 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793
  1. import { mkdtempSync, rmSync } from "node:fs";
  2. import { tmpdir } from "node:os";
  3. import { join } from "node:path";
  4. import { afterEach, describe, expect, it, vi } from "vitest";
  5. import { ChannelClient, ChannelServer, createQueuePair, Emitter, ProxyChannel } from "@zcode/rpc";
  6. import {
  7. ServiceCollection,
  8. IFileService,
  9. IGitService,
  10. IGitCheckpointService,
  11. ISystemService,
  12. ITerminalService,
  13. ISettingService,
  14. IOnboardingRecordService,
  15. ICredentialService,
  16. IBroadcastService,
  17. IZCodeAgentService,
  18. IZCodeSessionService,
  19. IZCodeTaskService,
  20. IBotsService,
  21. IFileWatcherService,
  22. IOAuthService,
  23. IModelSelectionService,
  24. IProviderSettingsService,
  25. IUsageStatsService,
  26. ICodingPlanSubscriptionService,
  27. IClientConfigService,
  28. ISkillsService,
  29. ISkillSyncService,
  30. IMcpSyncService,
  31. IPluginSyncService,
  32. IPluginsService,
  33. ISubagentsService,
  34. ICommandsService,
  35. ISettingsSyncService,
  36. type ZCodeAgentSessionRuntimePreferencesRequest,
  37. } from "@zcode/services";
  38. import {
  39. BUILTIN_MODEL_PROVIDER_IDS,
  40. projectAccessTokenFingerprint,
  41. type ApiClient,
  42. } from "@zcode/shared";
  43. import { createRemoteConnectionServiceCollection } from "../src/host/remoteConnectionServiceCollection.js";
  44. import { createRemotePromptAttachmentTaskService } from "../src/host/remotePromptAttachments.js";
  45. import { setDataBaseDir } from "@zcode/services/node";
  46. import * as nodeServices from "@zcode/services/node";
  47. import {
  48. createRemoteWorkspaceServiceCollection,
  49. createServerRemoteWorkspaceServiceCollection,
  50. } from "../src/host/remoteWorkspaceServiceCollection.js";
  51. const originalHome = process.env.HOME;
  52. const clientConfigService = {
  53. getSnapshot: vi.fn(async () => ({ pluginStoreOrder: null })),
  54. };
  55. function createTempHome(): string {
  56. const home = mkdtempSync(join(tmpdir(), "zcode-remote-workspace-services-"));
  57. // Bug 根因:模型供应商存储的默认 data base dir 在模块加载时已经固定;只改 HOME
  58. // 会继续读取真实 ~/.zcode/v2,并让 getAll 的后台权益请求污染下一个测试。
  59. setDataBaseDir(home);
  60. // Bug 根因:设置服务按 process.env.HOME 实时定位 ~/.zcode/v2/setting.json。只改 data base dir
  61. // 时会读到开发机真实设置;配置了 httpProxy 的机器上 Host API 改走 undici 代理 dispatcher,
  62. // 绕过 globalThis.fetch mock 直连线上并 401。HOME 由 afterEach 统一还原。
  63. process.env.HOME = home;
  64. return home;
  65. }
  66. function createPresetFetchMock(modelContextBudgetStrategy: "legacy" | "preflight-v1" = "legacy") {
  67. return vi.fn(async (input: RequestInfo | URL) => {
  68. const url = String(input);
  69. if (url.includes("192.168.100.166") || url.includes("/v1/models")) {
  70. throw new Error(`Retired preset endpoints must not be requested remotely: ${url}`);
  71. }
  72. if (url.includes("/api/v2/releases/latest")) {
  73. return new Response(
  74. JSON.stringify({
  75. version: "0.25.1",
  76. config_version: "0.0.13",
  77. }),
  78. { status: 200, headers: { "content-type": "application/json" } },
  79. );
  80. }
  81. if (url.includes("/api/v1/client/configs")) {
  82. return new Response(
  83. JSON.stringify({
  84. code: 0,
  85. msg: "",
  86. data: {
  87. configs: {
  88. modelContextBudget: {
  89. strategy: modelContextBudgetStrategy,
  90. },
  91. },
  92. },
  93. }),
  94. { status: 200, headers: { "content-type": "application/json" } },
  95. );
  96. }
  97. return new Response(JSON.stringify({}), {
  98. status: 200,
  99. headers: { "content-type": "application/json" },
  100. });
  101. });
  102. }
  103. function makeRemoteServices() {
  104. const runtimePreferencesEmitter = new Emitter<ZCodeAgentSessionRuntimePreferencesRequest>();
  105. return {
  106. fileService: { remote: "file" },
  107. gitService: { remote: "git" },
  108. gitCheckpointService: { remote: "git-checkpoint" },
  109. systemService: { remote: "system" },
  110. terminalService: { remote: "terminal" },
  111. zcodeAgentService: {
  112. onDynamicSessionRuntimePreferencesRequest: vi.fn(() => runtimePreferencesEmitter.event),
  113. respondSessionRuntimePreferences: vi.fn(async () => undefined),
  114. },
  115. runtimePreferencesEmitter,
  116. zcodeTaskService: { sendPrompt: vi.fn() },
  117. zcodeSessionService: { remote: "zcode-session" },
  118. fileWatcherService: { remote: "file-watcher" },
  119. skillsService: { remote: "skills" },
  120. skillSyncService: { remote: "skill-sync" },
  121. mcpSyncService: { remote: "mcp-sync" },
  122. pluginSyncService: { remote: "plugin-sync" },
  123. pluginsService: { remote: "plugins" },
  124. pluginManagementService: { remote: "plugin-management" },
  125. commandsService: { remote: "commands" },
  126. hooksService: { remote: "hooks" },
  127. modelSelectionService: {
  128. getView: vi.fn(async () => ({ revision: 0, providers: [] })),
  129. },
  130. providerSettingsService: { remote: "provider-settings" },
  131. } as never;
  132. }
  133. function remoteWorkspaceHostOptions(onError = vi.fn()) {
  134. return {
  135. localOnboardingRecordService: createOnboardingRecordStub(),
  136. promptAttachmentTransferService: {} as never,
  137. runtimePreferencesBridge: {
  138. onError,
  139. },
  140. };
  141. }
  142. function createOnboardingRecordStub(): IOnboardingRecordService {
  143. return {
  144. appendRecord: vi.fn(async () => {}),
  145. dismissOnboarding: vi.fn(async () => {}),
  146. claimAnonymousRecord: vi.fn(async () => {}),
  147. shouldOnboard: vi.fn(async () => false),
  148. getLatestEntry: vi.fn(async () => null),
  149. syncSettingsFromRecord: vi.fn(async () => null),
  150. updateRecordPreferences: vi.fn(async () => {}),
  151. getRecords: vi.fn(async () => null),
  152. clearRecords: vi.fn(async () => {}),
  153. };
  154. }
  155. function passthroughService<T extends object>(service: T): T {
  156. return service;
  157. }
  158. describe("remote workspace host service wiring", () => {
  159. afterEach(() => {
  160. process.env.HOME = originalHome;
  161. setDataBaseDir(null);
  162. vi.restoreAllMocks();
  163. });
  164. it("keeps workspace services remote and exposes local global services for Web remote control", () => {
  165. const remoteServices = makeRemoteServices();
  166. const services = createRemoteWorkspaceServiceCollection({
  167. clientConfigService,
  168. connectionServices: remoteServices,
  169. ...remoteWorkspaceHostOptions(),
  170. parentPort: null,
  171. createRemotePromptAttachmentTaskService: passthroughService,
  172. createRemotePromptAttachmentSessionService: passthroughService,
  173. createReportingRemoteZCodeTaskService: (service) => ({ wrapped: service }) as never,
  174. });
  175. expect(services.get(IFileService)).toBe(remoteServices.fileService);
  176. expect(services.get(IGitService)).toBe(remoteServices.gitService);
  177. expect(services.get(IGitCheckpointService)).toBe(remoteServices.gitCheckpointService);
  178. expect(services.get(ISystemService)).toBe(remoteServices.systemService);
  179. expect(services.get(ITerminalService)).toBe(remoteServices.terminalService);
  180. expect(services.get(IFileWatcherService)).toBe(remoteServices.fileWatcherService);
  181. expect(services.get(IZCodeTaskService)).toEqual({
  182. wrapped: remoteServices.zcodeTaskService,
  183. });
  184. expect(services.get(IZCodeAgentService)).toBe(remoteServices.zcodeAgentService);
  185. expect(services.get(IZCodeSessionService)).toBe(remoteServices.zcodeSessionService);
  186. expect(services.get(IClientConfigService)).toBe(clientConfigService);
  187. expect(services.get(ISettingService)).toBeTruthy();
  188. expect(services.get(ICredentialService)).toBeTruthy();
  189. expect(services.get(IBroadcastService)).toBeTruthy();
  190. expect(services.get(IBotsService)).toBeTruthy();
  191. expect(services.get(IOAuthService)).toBeTruthy();
  192. expect(services.get(IModelSelectionService)).toBe(remoteServices.modelSelectionService);
  193. expect(services.get(IProviderSettingsService)).toBe(remoteServices.providerSettingsService);
  194. expect(services.get(IUsageStatsService)).toBeTruthy();
  195. expect(services.get(IClientConfigService)).toBe(clientConfigService);
  196. expect(services.get(ISkillsService)).toBe(remoteServices.skillsService);
  197. expect(services.get(ISkillSyncService)).toBe(remoteServices.skillSyncService);
  198. expect(services.get(IMcpSyncService)).toBe(remoteServices.mcpSyncService);
  199. expect(services.get(IPluginSyncService)).toBe(remoteServices.pluginSyncService);
  200. expect(services.get(IPluginsService)).toBe(remoteServices.pluginsService);
  201. expect(services.get(ICommandsService)).toBe(remoteServices.commandsService);
  202. expect(services.get(ISubagentsService)).toBeTruthy();
  203. expect(services.get(ISettingsSyncService)).toBeTruthy();
  204. });
  205. it.each(["desktop-attached", "server"] as const)(
  206. "%s 远程 attachment 通过 RPC 访问同源引导记录并保留服务错误",
  207. async (kind) => {
  208. const localRecord = createOnboardingRecordStub();
  209. const serverRecord = createOnboardingRecordStub();
  210. const owner = kind === "server" ? serverRecord : localRecord;
  211. const other = kind === "server" ? localRecord : serverRecord;
  212. const connectionServices = {
  213. ...makeRemoteServices(),
  214. onboardingRecordService: serverRecord,
  215. };
  216. const sourceServices = new ServiceCollection().register(
  217. IOnboardingRecordService,
  218. localRecord,
  219. );
  220. const services =
  221. kind === "server"
  222. ? createServerRemoteWorkspaceServiceCollection({
  223. clientConfigService,
  224. connectionServices,
  225. sourceServices,
  226. })
  227. : createRemoteWorkspaceServiceCollection({
  228. clientConfigService,
  229. connectionServices,
  230. sourceServices,
  231. ...remoteWorkspaceHostOptions(),
  232. localOnboardingRecordService: localRecord,
  233. parentPort: null,
  234. createRemotePromptAttachmentTaskService: passthroughService,
  235. createRemotePromptAttachmentSessionService: passthroughService,
  236. createReportingRemoteZCodeTaskService: passthroughService,
  237. });
  238. const [serverProtocol, clientProtocol] = createQueuePair();
  239. const server = new ChannelServer(serverProtocol, "mobile-onboarding", 50);
  240. const client = new ChannelClient(clientProtocol);
  241. services.exposeOnChannelServer(server);
  242. const record = ProxyChannel.toService<IOnboardingRecordService>(
  243. client.getChannel(IOnboardingRecordService.channelName),
  244. );
  245. try {
  246. // 远程集合曾漏注册通道;即使 owner 已有记录,手机也只能收到 Unknown channel。
  247. await record.claimAnonymousRecord();
  248. await expect(record.shouldOnboard("mobile-device")).resolves.toBe(false);
  249. await record.dismissOnboarding("mobile-device");
  250. const entry = {
  251. occupation: "developer",
  252. interfaceMode: "coding" as const,
  253. memoryEnabled: false,
  254. proactiveSuggestionsEnabled: false,
  255. completedAt: "2026-10-09T00:00:00.000Z",
  256. };
  257. await record.appendRecord("mobile-device", entry);
  258. expect(services.get(IOnboardingRecordService)).toBe(owner);
  259. expect(owner.dismissOnboarding).toHaveBeenCalledWith("mobile-device");
  260. expect(owner.appendRecord).toHaveBeenCalledWith("mobile-device", entry);
  261. expect(other.claimAnonymousRecord).not.toHaveBeenCalled();
  262. expect(other.shouldOnboard).not.toHaveBeenCalled();
  263. expect(other.dismissOnboarding).not.toHaveBeenCalled();
  264. expect(other.appendRecord).not.toHaveBeenCalled();
  265. vi.mocked(owner.shouldOnboard).mockRejectedValueOnce(new Error("record read failed"));
  266. await expect(record.shouldOnboard("mobile-device")).rejects.toThrow("record read failed");
  267. } finally {
  268. client.dispose();
  269. server.dispose();
  270. }
  271. },
  272. );
  273. it.each([
  274. { sharedOwner: false, team: false },
  275. { sharedOwner: true, team: false },
  276. { sharedOwner: false, team: true },
  277. ])(
  278. "远程用量使用 Token,已有 Local Host owner=$sharedOwner,team=$team,不依赖旧 Key",
  279. async ({ sharedOwner, team }) => {
  280. const home = createTempHome();
  281. const owner = {
  282. resolveAccessCurrent: vi.fn(async () => null),
  283. resolveCurrent: vi.fn(async () => ({ apiKey: "project-token" })),
  284. assertCurrent: vi.fn(async () => undefined),
  285. };
  286. if (sharedOwner)
  287. vi.spyOn(nodeServices, "getAccountRequestAuthService").mockReturnValue(owner);
  288. const urls: string[] = [];
  289. vi.spyOn(globalThis, "fetch").mockImplementation(async (input, init) => {
  290. const url = String(input);
  291. urls.push(url);
  292. let data: unknown;
  293. if (url.endsWith("/getCustomerInfo"))
  294. data = {
  295. organizations: [{ organizationId: "org", projects: [{ projectId: "project" }] }],
  296. };
  297. else if (url.includes("/api_keys") && !url.endsWith("/access_tokens"))
  298. data = [
  299. {
  300. name: team ? "zcode-team-api-key" : "zcode-api-key",
  301. apiKey: "key",
  302. keyType: 2,
  303. },
  304. ];
  305. else if (url.endsWith("/access_tokens"))
  306. data = {
  307. accessToken: "project-token",
  308. tokenType: "Bearer",
  309. expiresIn: 600,
  310. expiresAt: Date.now() / 1000 + 600,
  311. };
  312. else if (url.includes("/querySubscribeDetail"))
  313. data = { hasSubscription: true, status: "EFFECTIVE", memberGrantStatus: "VALID" };
  314. else if (url.includes("/quota/limit")) {
  315. expect(new Headers(init?.headers).get("authorization")).toBe("project-token");
  316. data = { level: "pro", limits: [] };
  317. } else data = [];
  318. return new Response(JSON.stringify({ code: 200, data }), {
  319. headers: { "content-type": "application/json" },
  320. });
  321. });
  322. const services = createRemoteWorkspaceServiceCollection({
  323. clientConfigService,
  324. connectionServices: makeRemoteServices(),
  325. ...(sharedOwner ? { sourceServices: new ServiceCollection() } : {}),
  326. ...remoteWorkspaceHostOptions(),
  327. parentPort: null,
  328. createRemotePromptAttachmentTaskService: passthroughService,
  329. createRemotePromptAttachmentSessionService: passthroughService,
  330. createReportingRemoteZCodeTaskService: passthroughService,
  331. });
  332. try {
  333. const credentials = services.get(ICredentialService);
  334. await credentials.save("oauth:bigmodel:access_token", "login-token");
  335. await credentials.save(
  336. "oauth:bigmodel:user_info",
  337. JSON.stringify({ id: "user", username: "user", displayName: "User" }),
  338. );
  339. await expect(
  340. services.get(IUsageStatsService).getEntitlementSnapshot({
  341. includeSubscription: false,
  342. preferredProviderId: team
  343. ? BUILTIN_MODEL_PROVIDER_IDS.bigmodelTeamCodingPlan
  344. : BUILTIN_MODEL_PROVIDER_IDS.bigmodelIndividualCodingPlan,
  345. accountAccess: {
  346. type: "zhipu-account",
  347. family: "bigmodel",
  348. ...(team
  349. ? {
  350. planKind: "team-coding-plan" as const,
  351. organizationId: "org",
  352. projectId: "project",
  353. }
  354. : { planKind: "individual-coding-plan" as const }),
  355. },
  356. requirePreferredProvider: true,
  357. allowEnvApiKey: false,
  358. }),
  359. ).resolves.toMatchObject({
  360. authenticated: true,
  361. quota: { level: "pro" },
  362. });
  363. expect(urls.some((url) => url.includes("/copy/"))).toBe(false);
  364. expect(urls.filter((url) => url.endsWith("/access_tokens"))).toHaveLength(
  365. sharedOwner ? 0 : 1,
  366. );
  367. expect(owner.resolveCurrent).toHaveBeenCalledTimes(sharedOwner ? 1 : 0);
  368. } finally {
  369. rmSync(home, { recursive: true, force: true });
  370. }
  371. },
  372. );
  373. it.each([
  374. { family: "bigmodel" as const, team: false },
  375. { family: "bigmodel" as const, team: true },
  376. { family: "zai" as const, team: false },
  377. { family: "zai" as const, team: true },
  378. ])(
  379. "fallback $family team=$team 的 401 指纹到达 PAT owner 并只刷新一次",
  380. async ({ family, team }) => {
  381. const home = createTempHome();
  382. const authFactory = vi.spyOn(nodeServices, "createAccountRequestAuthService");
  383. let issued = 0;
  384. vi.spyOn(globalThis, "fetch").mockImplementation(async (input, init) => {
  385. const url = String(input);
  386. const authorization = new Headers(init?.headers).get("authorization");
  387. // 桌面存储的是业务 JWT;这里不应再次调用 /api/auth/z/login。
  388. expect(url).not.toContain("/api/auth/z/login");
  389. let data: unknown;
  390. if (url.endsWith("/getCustomerInfo")) {
  391. expect(authorization).toBe(family === "zai" ? "Bearer business-jwt" : "business-jwt");
  392. data = {
  393. organizations: [{ organizationId: "org", projects: [{ projectId: "project" }] }],
  394. };
  395. } else if (url.endsWith("/access_tokens")) {
  396. expect(authorization).toBe("Bearer business-jwt");
  397. data = {
  398. accessToken: `pat-${++issued}`,
  399. tokenType: "Bearer",
  400. expiresIn: 600,
  401. expiresAt: Date.now() / 1000 + 600,
  402. };
  403. } else if (url.includes("/api_keys")) {
  404. expect(authorization).toBe(
  405. !team && family === "zai" ? "Bearer business-jwt" : "business-jwt",
  406. );
  407. data = [
  408. {
  409. name: team ? "zcode-team-api-key" : "zcode-api-key",
  410. apiKey: "key",
  411. keyType: 2,
  412. },
  413. ];
  414. } else throw new Error("Unexpected endpoint");
  415. return new Response(JSON.stringify({ code: 200, data }), {
  416. headers: { "content-type": "application/json" },
  417. });
  418. });
  419. const services = createRemoteWorkspaceServiceCollection({
  420. clientConfigService,
  421. connectionServices: makeRemoteServices(),
  422. ...remoteWorkspaceHostOptions(),
  423. parentPort: null,
  424. createRemotePromptAttachmentTaskService: passthroughService,
  425. createRemotePromptAttachmentSessionService: passthroughService,
  426. createReportingRemoteZCodeTaskService: passthroughService,
  427. });
  428. try {
  429. const credentials = services.get(ICredentialService);
  430. await credentials.save(`oauth:${family}:access_token`, "business-jwt");
  431. await credentials.save(
  432. `oauth:${family}:user_info`,
  433. JSON.stringify({ id: "user", username: "user", displayName: "User" }),
  434. );
  435. const auth = authFactory.mock.results.at(-1)!.value as ReturnType<
  436. typeof nodeServices.createAccountRequestAuthService
  437. >;
  438. const input = {
  439. providerId: `account:${family}-${team ? "team" : "individual"}-coding-plan`,
  440. reason: "model-request" as const,
  441. accountAccess: {
  442. type: "zhipu-account" as const,
  443. family,
  444. ...(team
  445. ? {
  446. planKind: "team-coding-plan" as const,
  447. organizationId: "org",
  448. projectId: "project",
  449. }
  450. : { planKind: "individual-coding-plan" as const }),
  451. },
  452. };
  453. const first = await auth.resolveCurrent(input);
  454. expect(first.apiKey).toBe("pat-1");
  455. const retry = {
  456. ...input,
  457. expectedAccountScope: first.accountScope,
  458. rejectedProjectTokenFingerprint: await projectAccessTokenFingerprint(first.apiKey!),
  459. };
  460. const recovered = await Promise.all([
  461. auth.resolveCurrent(retry),
  462. auth.resolveCurrent(retry),
  463. ]);
  464. expect(recovered.map((value) => value.apiKey)).toEqual(["pat-2", "pat-2"]);
  465. expect((await auth.resolveCurrent(retry)).apiKey).toBe("pat-2");
  466. expect(issued).toBe(2);
  467. await credentials.save(`oauth:${family}:access_token`, "other-login");
  468. await expect(auth.resolveCurrent(retry)).rejects.toThrow("project_token_scope_invalidated");
  469. expect(issued).toBe(2);
  470. } finally {
  471. rmSync(home, { recursive: true, force: true });
  472. }
  473. },
  474. );
  475. it("bridges app-global runtime preferences without a workspace-scoped subscription", async () => {
  476. const home = createTempHome();
  477. vi.spyOn(globalThis, "fetch").mockImplementation(createPresetFetchMock("preflight-v1"));
  478. const remoteServices = makeRemoteServices();
  479. const services = createRemoteWorkspaceServiceCollection({
  480. clientConfigService,
  481. connectionServices: remoteServices,
  482. ...remoteWorkspaceHostOptions(),
  483. parentPort: null,
  484. createRemotePromptAttachmentTaskService: passthroughService,
  485. createRemotePromptAttachmentSessionService: passthroughService,
  486. createReportingRemoteZCodeTaskService: (service) => service,
  487. });
  488. const strategyResolver = vi.spyOn(
  489. services.get(ICodingPlanSubscriptionService),
  490. "getModelContextBudgetStrategy",
  491. );
  492. strategyResolver.mockImplementation(() => new Promise(() => {}));
  493. try {
  494. await services.get(ISettingService).update({
  495. askUserQuestionAutoResolutionEnabled: false,
  496. nativeSearchEnhancementsEnabled: false,
  497. integratedTerminalShell: {
  498. mode: "shell",
  499. dialect: "git-bash",
  500. id: "git-bash:C:/Program Files/Git/bin/bash.exe",
  501. label: "Git Bash",
  502. path: "C:/Program Files/Git/bin/bash.exe",
  503. },
  504. });
  505. remoteServices.runtimePreferencesEmitter.fire({
  506. requestId: "request-runtime-preferences",
  507. sessionId: "session-remote",
  508. scope: "runtime-materialization",
  509. });
  510. await vi.waitFor(() => {
  511. expect(
  512. remoteServices.zcodeAgentService.onDynamicSessionRuntimePreferencesRequest,
  513. ).toHaveBeenCalledWith();
  514. expect(
  515. remoteServices.zcodeAgentService.respondSessionRuntimePreferences,
  516. ).toHaveBeenCalledWith({
  517. requestId: "request-runtime-preferences",
  518. resolution: {
  519. status: "resolved",
  520. preferences: {
  521. askUserQuestionAutoResolutionEnabled: false,
  522. nativeSearchEnhancementsEnabled: false,
  523. memoryEnabled: false,
  524. modelContextBudgetStrategy: "preflight-v1",
  525. },
  526. },
  527. });
  528. });
  529. expect(strategyResolver).not.toHaveBeenCalled();
  530. strategyResolver.mockImplementation(() => new Promise(() => {}));
  531. remoteServices.runtimePreferencesEmitter.fire({
  532. requestId: "request-user-execution-preferences",
  533. sessionId: "session-remote",
  534. scope: "user-execution",
  535. });
  536. await vi.waitFor(() => {
  537. expect(
  538. remoteServices.zcodeAgentService.respondSessionRuntimePreferences,
  539. ).toHaveBeenCalledWith({
  540. requestId: "request-user-execution-preferences",
  541. resolution: {
  542. status: "resolved",
  543. preferences: {
  544. askUserQuestionAutoResolutionEnabled: false,
  545. nativeSearchEnhancementsEnabled: false,
  546. memoryEnabled: false,
  547. modelContextBudgetStrategy: "preflight-v1",
  548. integratedTerminalShell: {
  549. mode: "shell",
  550. dialect: "git-bash",
  551. id: "git-bash:C:/Program Files/Git/bin/bash.exe",
  552. label: "Git Bash",
  553. path: "C:/Program Files/Git/bin/bash.exe",
  554. },
  555. },
  556. },
  557. });
  558. });
  559. // 第二个 scope 只读取 Shell;即使 strategy 永不返回也不能新增调用或阻塞响应。
  560. expect(strategyResolver).not.toHaveBeenCalled();
  561. } finally {
  562. rmSync(home, { recursive: true, force: true });
  563. }
  564. });
  565. it("reports a runtime preference response transport failure without retrying", async () => {
  566. const home = createTempHome();
  567. vi.spyOn(globalThis, "fetch").mockImplementation(createPresetFetchMock());
  568. const remoteServices = makeRemoteServices();
  569. const transportError = new Error("transport closed");
  570. const onError = vi.fn();
  571. remoteServices.zcodeAgentService.respondSessionRuntimePreferences.mockRejectedValueOnce(
  572. transportError,
  573. );
  574. const services = createRemoteWorkspaceServiceCollection({
  575. clientConfigService,
  576. connectionServices: remoteServices,
  577. ...remoteWorkspaceHostOptions(onError),
  578. parentPort: null,
  579. createRemotePromptAttachmentTaskService: passthroughService,
  580. createRemotePromptAttachmentSessionService: passthroughService,
  581. createReportingRemoteZCodeTaskService: (service) => service,
  582. });
  583. try {
  584. await services.get(ISettingService).update({
  585. askUserQuestionAutoResolutionEnabled: false,
  586. nativeSearchEnhancementsEnabled: false,
  587. memoryEnabled: false,
  588. });
  589. remoteServices.runtimePreferencesEmitter.fire({
  590. requestId: "request-closed-transport",
  591. sessionId: "session-remote",
  592. scope: "runtime-materialization",
  593. });
  594. await vi.waitFor(() => {
  595. expect(onError).toHaveBeenCalledOnce();
  596. });
  597. expect(onError).toHaveBeenCalledWith(transportError);
  598. expect(
  599. remoteServices.zcodeAgentService.respondSessionRuntimePreferences,
  600. ).toHaveBeenCalledOnce();
  601. expect(
  602. remoteServices.zcodeAgentService.respondSessionRuntimePreferences,
  603. ).toHaveBeenCalledWith({
  604. requestId: "request-closed-transport",
  605. resolution: {
  606. status: "resolved",
  607. preferences: {
  608. askUserQuestionAutoResolutionEnabled: false,
  609. nativeSearchEnhancementsEnabled: false,
  610. memoryEnabled: false,
  611. modelContextBudgetStrategy: "preflight-v1",
  612. },
  613. },
  614. });
  615. } finally {
  616. rmSync(home, { recursive: true, force: true });
  617. }
  618. });
  619. it("does not warm legacy model provider presets when constructing remote workspace services", async () => {
  620. const home = createTempHome();
  621. const fetchImpl = createPresetFetchMock();
  622. vi.spyOn(globalThis, "fetch").mockImplementation(fetchImpl);
  623. const remoteServices = makeRemoteServices();
  624. createRemoteWorkspaceServiceCollection({
  625. clientConfigService,
  626. connectionServices: remoteServices,
  627. ...remoteWorkspaceHostOptions(),
  628. parentPort: null,
  629. createRemotePromptAttachmentTaskService: passthroughService,
  630. createRemotePromptAttachmentSessionService: passthroughService,
  631. createReportingRemoteZCodeTaskService: (service) => service,
  632. });
  633. try {
  634. await new Promise((resolve) => setTimeout(resolve, 50));
  635. expect(fetchImpl).not.toHaveBeenCalled();
  636. } finally {
  637. rmSync(home, { recursive: true, force: true });
  638. }
  639. });
  640. it("exposes remote skill sync service in the remote connection host", () => {
  641. const remoteServices = makeRemoteServices();
  642. const credentialService = {
  643. load: vi.fn(),
  644. save: vi.fn(),
  645. delete: vi.fn(),
  646. };
  647. const services = createRemoteConnectionServiceCollection({
  648. clientConfigService,
  649. connectionServices: remoteServices,
  650. parentPort: null,
  651. credentialService,
  652. apiClient: { request: vi.fn() } as unknown as ApiClient,
  653. remoteZCodeTaskService: { remote: "wrapped-task" } as never,
  654. remoteZCodeSessionService: { remote: "wrapped-session" } as never,
  655. });
  656. expect(services.get(IClientConfigService)).toBe(clientConfigService);
  657. expect(services.get(ISkillsService)).toBe(remoteServices.skillsService);
  658. expect(services.get(ISkillSyncService)).toBe(remoteServices.skillSyncService);
  659. expect(services.get(IMcpSyncService)).toBe(remoteServices.mcpSyncService);
  660. expect(services.get(IPluginSyncService)).toBe(remoteServices.pluginSyncService);
  661. expect(services.get(IPluginsService)).toBe(remoteServices.pluginsService);
  662. expect(services.get(ICommandsService)).toBe(remoteServices.commandsService);
  663. });
  664. it("keeps server remote workspace runtime services server-authoritative", () => {
  665. const remoteServices = {
  666. ...makeRemoteServices(),
  667. settingService: { remote: "setting" },
  668. onboardingRecordService: createOnboardingRecordStub(),
  669. credentialService: { remote: "credential" },
  670. broadcastService: { remote: "broadcast" },
  671. botsService: { remote: "bots" },
  672. oauthService: { remote: "oauth" },
  673. usageStatsService: { remote: "usage-stats" },
  674. codingPlanSubscriptionService: { remote: "coding-plan" },
  675. pluginManagementService: { remote: "plugin-management" },
  676. subagentsService: { remote: "subagents" },
  677. hooksService: { remote: "hooks" },
  678. memoryService: { remote: "memory" },
  679. outputStyleService: { remote: "output-style" },
  680. settingsSyncService: { remote: "settings-sync" },
  681. } as never;
  682. const services = createServerRemoteWorkspaceServiceCollection({
  683. clientConfigService,
  684. connectionServices: remoteServices,
  685. });
  686. expect(services.get(IClientConfigService)).toBe(clientConfigService);
  687. expect(services.get(ISettingService)).toBe(remoteServices.settingService);
  688. expect(services.get(IOnboardingRecordService)).toBe(remoteServices.onboardingRecordService);
  689. expect(services.get(ICredentialService)).toBe(remoteServices.credentialService);
  690. expect(services.get(IBroadcastService)).toBe(remoteServices.broadcastService);
  691. expect(services.get(IBotsService)).toBe(remoteServices.botsService);
  692. expect(services.get(IOAuthService)).toBe(remoteServices.oauthService);
  693. expect(services.get(IModelSelectionService)).toBe(remoteServices.modelSelectionService);
  694. expect(services.get(IProviderSettingsService)).toBe(remoteServices.providerSettingsService);
  695. expect(services.get(IUsageStatsService)).toBe(remoteServices.usageStatsService);
  696. expect(services.get(ISubagentsService)).toBe(remoteServices.subagentsService);
  697. expect(services.get(ISettingsSyncService)).toBe(remoteServices.settingsSyncService);
  698. });
  699. it("materializes web remote task prompts before the reporting wrapper observes them", async () => {
  700. const hostAttachment = {
  701. kind: "file",
  702. filename: "pasted.txt",
  703. localPath: "/tmp/host-paste.txt",
  704. mimeType: "text/plain",
  705. sizeBytes: 5,
  706. sourceKind: "clipboard-text",
  707. } as const;
  708. const remoteAttachment = {
  709. ...hostAttachment,
  710. localPath: "/home/tester/.zcode/tmp/prompt-attachments/input-1/01-pasted.txt",
  711. };
  712. const rawSendPrompt = vi.fn(async () => undefined);
  713. const observedByReporting: unknown[] = [];
  714. const remoteServices = {
  715. ...makeRemoteServices(),
  716. zcodeTaskService: { sendPrompt: rawSendPrompt },
  717. } as never;
  718. const services = createRemoteWorkspaceServiceCollection({
  719. clientConfigService,
  720. connectionServices: remoteServices,
  721. ...remoteWorkspaceHostOptions(),
  722. parentPort: null,
  723. createRemotePromptAttachmentTaskService: (service) =>
  724. createRemotePromptAttachmentTaskService(service, {
  725. materializePromptAttachments: async (params) => ({
  726. content: params.content.replace("/tmp/host-paste.txt", remoteAttachment.localPath),
  727. attachments: [remoteAttachment],
  728. }),
  729. }),
  730. createRemotePromptAttachmentSessionService: passthroughService,
  731. createReportingRemoteZCodeTaskService: (service) =>
  732. new Proxy(service, {
  733. get(target, property, receiver) {
  734. const value = Reflect.get(target, property, receiver);
  735. if (property !== "sendPrompt" || typeof value !== "function") {
  736. return value;
  737. }
  738. return async (...args: unknown[]) => {
  739. observedByReporting.push(args[0]);
  740. return value.apply(target, args);
  741. };
  742. },
  743. }) as never,
  744. });
  745. await services.get(IZCodeTaskService).sendPrompt({
  746. taskId: "task-1",
  747. traceId: "input-1",
  748. content: "read /tmp/host-paste.txt",
  749. attachments: [hostAttachment],
  750. });
  751. const expectedParams = {
  752. taskId: "task-1",
  753. traceId: "input-1",
  754. content: "read /home/tester/.zcode/tmp/prompt-attachments/input-1/01-pasted.txt",
  755. attachments: [remoteAttachment],
  756. };
  757. expect(observedByReporting).toEqual([expectedParams]);
  758. expect(rawSendPrompt).toHaveBeenCalledWith(expectedParams);
  759. });
  760. });