sourceServerManagementService.test.ts 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737
  1. import { SourceServerConnectionManager } from "../src/host/sourceServerConnectionManager.js";
  2. import type { SourceServerTransportAdapter } from "@zcode/server/source-server";
  3. import { describe, expect, it, vi } from "vitest";
  4. import { Emitter } from "@zcode/rpc";
  5. import type { SourceServerConnectionStateSnapshot } from "@zcode/shared";
  6. import { createSourceServerManagementService } from "../src/host/sourceServerManagementService.js";
  7. const profileId = "17ef20b3-622d-4a53-98c1-0cdff29f3e6d";
  8. const sourceServerId = "3cd4f9da-cd79-426c-9d70-75f36e9f6a87";
  9. describe("SourceServerManagementService", () => {
  10. it("routes a retained-member reconnect without saving a new membership", async () => {
  11. const emitter = new Emitter<SourceServerConnectionStateSnapshot>();
  12. const target = { kind: "docker" as const, container: "dev" };
  13. const profile = {
  14. profileId,
  15. sourceServerId,
  16. transport: "docker" as const,
  17. target,
  18. createdAt: 1,
  19. };
  20. const onConnectionLog = vi.fn();
  21. const connect = vi.fn(async (input) => {
  22. input.context?.onLog?.({ phase: "probe", message: "connected transport" });
  23. return {};
  24. });
  25. const service = createSourceServerManagementService({
  26. directory: {
  27. snapshot: async () => ({
  28. profiles: [profile],
  29. servers: [{ sourceServerId, displayName: "dev" }],
  30. workspaceHistory: [],
  31. }),
  32. resolveProfileTarget: async () => target,
  33. } as never,
  34. manager: {
  35. listStates: () => [],
  36. onDidChangeState: emitter.event,
  37. connect,
  38. getOnlineConnection: () => undefined,
  39. } as never,
  40. onConnectionLog,
  41. });
  42. await service.connectProfile(profileId, { retainedOnly: true });
  43. expect(connect).toHaveBeenCalledWith({
  44. profile,
  45. target,
  46. membershipIntent: "retain",
  47. context: { onLog: onConnectionLog },
  48. });
  49. expect(onConnectionLog).toHaveBeenCalledWith({
  50. phase: "probe",
  51. message: "connected transport",
  52. });
  53. service.dispose();
  54. });
  55. it("管理服务查询并转发更新阶段、真实进度和失败日志", async () => {
  56. const manager = new SourceServerConnectionManager({
  57. directory: { recordHandshake: vi.fn() },
  58. createAdapter: () =>
  59. ({
  60. kind: "docker",
  61. probe: async () => ({ platform: "linux", arch: "x64", installed: false }),
  62. installOrUpdate: async (_target, _release, context) => {
  63. context.onLog?.({
  64. phase: "upload",
  65. message: "archive /Users/private/file token=hidden",
  66. progress: 0.5,
  67. });
  68. throw new Error("upload failed");
  69. },
  70. }) as SourceServerTransportAdapter,
  71. now: () => 10,
  72. });
  73. const service = createSourceServerManagementService({
  74. directory: {
  75. snapshot: vi.fn(async () => ({
  76. profiles: [
  77. {
  78. profileId,
  79. transport: "docker" as const,
  80. target: { kind: "docker" as const, container: "dev" },
  81. sourceServerId,
  82. createdAt: 1,
  83. },
  84. ],
  85. servers: [{ sourceServerId, displayName: "dev", declaredWorkspaces: [] }],
  86. workspaceHistory: [],
  87. })),
  88. resolveProfileTarget: vi.fn(async () => ({
  89. kind: "docker" as const,
  90. container: "dev",
  91. })),
  92. renameSource: vi.fn(),
  93. renameProfile: vi.fn(),
  94. setPreferredProfile: vi.fn(),
  95. removeProfile: vi.fn(),
  96. },
  97. manager,
  98. resolveRelease: async () => ({
  99. target: "linux-x64",
  100. version: "3.8.0",
  101. sha256: "a".repeat(64),
  102. sizeBytes: 1,
  103. urls: [],
  104. }),
  105. now: () => 10,
  106. });
  107. const logs: unknown[] = [];
  108. service.onDidAppendOperationLog?.((entry) => logs.push(entry));
  109. await expect(service.updateSource({ profileId, force: false })).rejects.toThrow(
  110. "upload failed",
  111. );
  112. expect(logs).toEqual([
  113. expect.objectContaining({ phase: "probe", timestamp: 10 }),
  114. expect.objectContaining({
  115. phase: "upload",
  116. progress: 0.5,
  117. timestamp: 10,
  118. }),
  119. expect.objectContaining({
  120. phase: "upload",
  121. level: "error",
  122. timestamp: 10,
  123. }),
  124. ]);
  125. expect(await service.getRecentOperationLogs(profileId)).toEqual(logs);
  126. expect(JSON.stringify(logs)).not.toContain("hidden");
  127. expect(JSON.stringify(logs)).not.toContain("/Users/");
  128. service.dispose();
  129. manager.dispose();
  130. });
  131. it("prepares distinct unclassified conversation directories on the existing online Host", async () => {
  132. const stateEmitter = new Emitter<SourceServerConnectionStateSnapshot>();
  133. const recordConversationWorkspace = vi.fn(async () => undefined);
  134. let nextDirectory = 0;
  135. const prepareSession = vi.fn(async () => ({
  136. workspacePath: `/home/dev/.zcode/workspace/task-${++nextDirectory}`,
  137. projectId: null,
  138. additionalDirectories: [],
  139. }));
  140. const service = createSourceServerManagementService({
  141. directory: {
  142. snapshot: vi.fn(async () => ({
  143. profiles: [],
  144. servers: [],
  145. workspaceHistory: [],
  146. })),
  147. resolveProfileTarget: vi.fn(),
  148. renameSource: vi.fn(),
  149. renameProfile: vi.fn(),
  150. setPreferredProfile: vi.fn(),
  151. removeProfile: vi.fn(),
  152. recordConversationWorkspace,
  153. },
  154. manager: {
  155. listStates: () => [],
  156. onDidChangeState: stateEmitter.event,
  157. getOnlineConnection: () => ({
  158. sourceServerId,
  159. profileId,
  160. serverInfo: {} as never,
  161. services: { projectService: { prepareSession } } as never,
  162. }),
  163. connect: vi.fn(),
  164. updateServer: vi.fn(),
  165. disconnect: vi.fn(),
  166. },
  167. });
  168. await expect(service.ensureConversationWorkspace(sourceServerId)).resolves.toEqual({
  169. path: "/home/dev/.zcode/workspace/task-1",
  170. created: true,
  171. workspacePurpose: "conversation",
  172. });
  173. expect(recordConversationWorkspace).toHaveBeenCalledWith(
  174. sourceServerId,
  175. "/home/dev/.zcode/workspace/task-1",
  176. );
  177. await expect(service.ensureConversationWorkspace(sourceServerId)).resolves.toMatchObject({
  178. path: "/home/dev/.zcode/workspace/task-2",
  179. });
  180. expect(prepareSession).toHaveBeenCalledWith();
  181. service.dispose();
  182. });
  183. it("returns an initial snapshot and monotonic Host state deltas", async () => {
  184. const stateEmitter = new Emitter<SourceServerConnectionStateSnapshot>();
  185. const state: SourceServerConnectionStateSnapshot = {
  186. profileId,
  187. sourceServerId,
  188. state: "online",
  189. updateAvailability: "none",
  190. currentVersion: "3.8.0",
  191. availableVersion: "3.8.0",
  192. minimumVersion: "3.8.0",
  193. updatedAt: 10,
  194. };
  195. const sourceServerWorkspaceService = {
  196. getFailedPathCount: vi.fn(async () => 2),
  197. getAbandonedPathCount: vi.fn(async () => 1),
  198. };
  199. const connection = {
  200. sourceServerId,
  201. profileId,
  202. serverInfo: {} as never,
  203. services: { sourceServerWorkspaceService } as never,
  204. };
  205. const service = createSourceServerManagementService({
  206. directory: {
  207. snapshot: vi.fn(async () => ({
  208. profiles: [
  209. {
  210. profileId,
  211. transport: "docker" as const,
  212. target: { kind: "docker" as const, container: "dev" },
  213. sourceServerId,
  214. createdAt: 1,
  215. },
  216. ],
  217. servers: [{ sourceServerId, displayName: "devbox", declaredWorkspaces: [] }],
  218. workspaceHistory: [],
  219. })),
  220. resolveProfileTarget: vi.fn(),
  221. renameSource: vi.fn(),
  222. renameProfile: vi.fn(),
  223. setPreferredProfile: vi.fn(),
  224. removeProfile: vi.fn(),
  225. },
  226. manager: {
  227. listStates: () => [state],
  228. onDidChangeState: stateEmitter.event,
  229. getOnlineConnection: () => connection,
  230. connect: vi.fn(),
  231. updateServer: vi.fn(),
  232. disconnect: vi.fn(),
  233. },
  234. });
  235. const deltas: unknown[] = [];
  236. const subscription = service.onDidChangeState((delta) => deltas.push(delta));
  237. await expect(service.getSnapshot()).resolves.toEqual({
  238. generation: 0,
  239. profiles: expect.arrayContaining([expect.objectContaining({ profileId })]),
  240. servers: [
  241. {
  242. sourceServerId,
  243. displayName: "devbox",
  244. installState: "installed",
  245. declaredWorkspaces: [],
  246. },
  247. ],
  248. workspaceHistory: [],
  249. states: [state],
  250. failedPathCount: 0,
  251. abandonedPathCount: 0,
  252. migrationCounts: [{ sourceServerId, status: "loading" }],
  253. });
  254. await vi.waitFor(async () => {
  255. expect(await service.getSnapshot()).toMatchObject({
  256. generation: 1,
  257. failedPathCount: 2,
  258. abandonedPathCount: 1,
  259. migrationCounts: [
  260. { sourceServerId, status: "available", failedPathCount: 2, abandonedPathCount: 1 },
  261. ],
  262. });
  263. });
  264. const retrying = { ...state, state: "retrying" as const, updatedAt: 11 };
  265. stateEmitter.fire(retrying);
  266. expect(deltas).toEqual([{ generation: 2, state: retrying }]);
  267. subscription.dispose();
  268. service.dispose();
  269. });
  270. it("reports offline migration counts as requiring a connection instead of zero", async () => {
  271. const stateEmitter = new Emitter<SourceServerConnectionStateSnapshot>();
  272. const service = createSourceServerManagementService({
  273. directory: {
  274. snapshot: vi.fn(async () => ({
  275. profiles: [],
  276. servers: [{ sourceServerId, displayName: "offline", declaredWorkspaces: [] }],
  277. workspaceHistory: [],
  278. })),
  279. resolveProfileTarget: vi.fn(),
  280. renameSource: vi.fn(),
  281. renameProfile: vi.fn(),
  282. setPreferredProfile: vi.fn(),
  283. removeProfile: vi.fn(),
  284. },
  285. manager: {
  286. listStates: () => [],
  287. onDidChangeState: stateEmitter.event,
  288. getOnlineConnection: () => undefined,
  289. connect: vi.fn(),
  290. updateServer: vi.fn(),
  291. disconnect: vi.fn(),
  292. },
  293. });
  294. await expect(service.getSnapshot()).resolves.toMatchObject({
  295. failedPathCount: 0,
  296. abandonedPathCount: 0,
  297. migrationCounts: [{ sourceServerId, status: "requires-connection" }],
  298. });
  299. service.dispose();
  300. });
  301. it("renames a connection profile through the directory authority", async () => {
  302. const stateEmitter = new Emitter<SourceServerConnectionStateSnapshot>();
  303. const renameProfile = vi.fn(async () => undefined);
  304. const service = createSourceServerManagementService({
  305. directory: {
  306. snapshot: vi.fn(async () => ({
  307. profiles: [],
  308. servers: [{ sourceServerId, displayName: "server", declaredWorkspaces: [] }],
  309. workspaceHistory: [],
  310. })),
  311. resolveProfileTarget: vi.fn(),
  312. renameSource: vi.fn(),
  313. renameProfile,
  314. setPreferredProfile: vi.fn(),
  315. removeProfile: vi.fn(),
  316. },
  317. manager: {
  318. listStates: () => [],
  319. onDidChangeState: stateEmitter.event,
  320. getOnlineConnection: () => undefined,
  321. connect: vi.fn(),
  322. updateServer: vi.fn(),
  323. disconnect: vi.fn(),
  324. },
  325. });
  326. await service.renameProfile(profileId, "backup line");
  327. expect(renameProfile).toHaveBeenCalledWith(profileId, "backup line");
  328. service.dispose();
  329. });
  330. it("updates a connection profile through the directory authority", async () => {
  331. const stateEmitter = new Emitter<SourceServerConnectionStateSnapshot>();
  332. const updateProfile = vi.fn(async () => undefined);
  333. const service = createSourceServerManagementService({
  334. directory: {
  335. snapshot: vi.fn(async () => ({
  336. profiles: [],
  337. servers: [],
  338. workspaceHistory: [],
  339. })),
  340. resolveProfileTarget: vi.fn(),
  341. renameSource: vi.fn(),
  342. renameProfile: vi.fn(),
  343. updateProfile,
  344. setPreferredProfile: vi.fn(),
  345. removeProfile: vi.fn(),
  346. removeSourceServer: vi.fn(),
  347. },
  348. manager: {
  349. listStates: () => [],
  350. onDidChangeState: stateEmitter.event,
  351. getOnlineConnection: () => undefined,
  352. connect: vi.fn(),
  353. updateServer: vi.fn(),
  354. removeProfile: vi.fn(),
  355. disconnect: vi.fn(),
  356. },
  357. onBeforeSourceServerRemoved: vi.fn(),
  358. });
  359. const input = {
  360. profileId,
  361. profileDisplayName: "primary",
  362. sourceDisplayName: "Build server",
  363. sshAuthMethod: "password" as const,
  364. target: {
  365. kind: "ssh" as const,
  366. host: "example.com",
  367. port: 2222,
  368. username: "dev",
  369. password: "secret",
  370. },
  371. };
  372. await service.updateProfile(input);
  373. expect(updateProfile).toHaveBeenCalledWith(input);
  374. service.dispose();
  375. });
  376. it("removes the persisted Profile before terminalizing its Manager lifecycle", async () => {
  377. const stateEmitter = new Emitter<SourceServerConnectionStateSnapshot>();
  378. const removeDirectoryProfile = vi.fn(async () => undefined);
  379. const removeManagerProfile = vi.fn();
  380. const service = createSourceServerManagementService({
  381. directory: {
  382. snapshot: vi.fn(async () => ({
  383. profiles: [],
  384. servers: [],
  385. workspaceHistory: [],
  386. })),
  387. resolveProfileTarget: vi.fn(),
  388. renameSource: vi.fn(),
  389. renameProfile: vi.fn(),
  390. updateProfile: vi.fn(),
  391. setPreferredProfile: vi.fn(),
  392. removeProfile: removeDirectoryProfile,
  393. removeSourceServer: vi.fn(),
  394. },
  395. manager: {
  396. listStates: () => [],
  397. onDidChangeState: stateEmitter.event,
  398. getOnlineConnection: () => undefined,
  399. connect: vi.fn(),
  400. updateServer: vi.fn(),
  401. disconnect: vi.fn(),
  402. removeProfile: removeManagerProfile,
  403. },
  404. onBeforeSourceServerRemoved: vi.fn(),
  405. });
  406. await service.removeProfile(profileId);
  407. expect(removeDirectoryProfile).toHaveBeenCalledWith(profileId);
  408. expect(removeManagerProfile).toHaveBeenCalledWith(profileId);
  409. expect(removeDirectoryProfile.mock.invocationCallOrder[0]).toBeLessThan(
  410. removeManagerProfile.mock.invocationCallOrder[0]!,
  411. );
  412. service.dispose();
  413. });
  414. it("keeps the Manager lifecycle unchanged when Profile persistence fails", async () => {
  415. const stateEmitter = new Emitter<SourceServerConnectionStateSnapshot>();
  416. const removeManagerProfile = vi.fn();
  417. const service = createSourceServerManagementService({
  418. directory: {
  419. snapshot: vi.fn(async () => ({
  420. profiles: [],
  421. servers: [],
  422. workspaceHistory: [],
  423. })),
  424. resolveProfileTarget: vi.fn(),
  425. renameSource: vi.fn(),
  426. renameProfile: vi.fn(),
  427. updateProfile: vi.fn(),
  428. setPreferredProfile: vi.fn(),
  429. removeProfile: vi.fn(async () => {
  430. throw new Error("settings write failed");
  431. }),
  432. removeSourceServer: vi.fn(),
  433. },
  434. manager: {
  435. listStates: () => [],
  436. onDidChangeState: stateEmitter.event,
  437. getOnlineConnection: () => undefined,
  438. connect: vi.fn(),
  439. updateServer: vi.fn(),
  440. disconnect: vi.fn(),
  441. removeProfile: removeManagerProfile,
  442. },
  443. onBeforeSourceServerRemoved: vi.fn(),
  444. });
  445. await expect(service.removeProfile(profileId)).rejects.toThrow("settings write failed");
  446. expect(removeManagerProfile).not.toHaveBeenCalled();
  447. service.dispose();
  448. });
  449. it("publishes directory deltas with the same monotonic generation as state deltas", async () => {
  450. const stateEmitter = new Emitter<SourceServerConnectionStateSnapshot>();
  451. const directoryEmitter = new Emitter<void>();
  452. const directory = {
  453. snapshot: vi.fn(async () => ({
  454. profiles: [],
  455. servers: [],
  456. workspaceHistory: [],
  457. })),
  458. onDidChange: directoryEmitter.event,
  459. resolveProfileTarget: vi.fn(),
  460. renameSource: vi.fn(),
  461. renameProfile: vi.fn(),
  462. setPreferredProfile: vi.fn(),
  463. removeProfile: vi.fn(),
  464. removeSourceServer: vi.fn(),
  465. };
  466. const service = createSourceServerManagementService({
  467. directory,
  468. manager: {
  469. listStates: () => [],
  470. onDidChangeState: stateEmitter.event,
  471. getOnlineConnection: () => undefined,
  472. connect: vi.fn(),
  473. updateServer: vi.fn(),
  474. removeProfile: vi.fn(),
  475. disconnect: vi.fn(),
  476. },
  477. onBeforeSourceServerRemoved: vi.fn(),
  478. });
  479. const directoryDeltas: unknown[] = [];
  480. const stateDeltas: unknown[] = [];
  481. service.onDidChangeDirectory((delta) => directoryDeltas.push(delta));
  482. service.onDidChangeState((delta) => stateDeltas.push(delta));
  483. directoryEmitter.fire();
  484. stateEmitter.fire({ profileId, state: "online", updatedAt: 1 });
  485. expect(directoryDeltas).toEqual([{ generation: 1 }]);
  486. expect(stateDeltas).toEqual([
  487. { generation: 2, state: { profileId, state: "online", updatedAt: 1 } },
  488. ]);
  489. service.dispose();
  490. });
  491. it("removes a complete device through the Host callback before persistence", async () => {
  492. const stateEmitter = new Emitter<SourceServerConnectionStateSnapshot>();
  493. const removeSourceServer = vi.fn(async () => undefined);
  494. const disconnect = vi.fn();
  495. const onBeforeSourceServerRemoved = vi.fn(async () => undefined);
  496. const service = createSourceServerManagementService({
  497. directory: {
  498. snapshot: vi.fn(async () => ({
  499. profiles: [],
  500. servers: [{ sourceServerId, displayName: "server", declaredWorkspaces: [] }],
  501. workspaceHistory: [],
  502. })),
  503. onDidChange: new Emitter<void>().event,
  504. resolveProfileTarget: vi.fn(),
  505. renameSource: vi.fn(),
  506. renameProfile: vi.fn(),
  507. setPreferredProfile: vi.fn(),
  508. removeProfile: vi.fn(),
  509. removeSourceServer,
  510. },
  511. manager: {
  512. listStates: () => [],
  513. onDidChangeState: stateEmitter.event,
  514. getOnlineConnection: () => undefined,
  515. connect: vi.fn(),
  516. updateServer: vi.fn(),
  517. removeProfile: vi.fn(),
  518. disconnect,
  519. },
  520. onBeforeSourceServerRemoved,
  521. });
  522. await service.removeSourceServer(sourceServerId);
  523. expect(disconnect).toHaveBeenCalledWith(sourceServerId);
  524. expect(onBeforeSourceServerRemoved).toHaveBeenCalledWith(sourceServerId);
  525. expect(removeSourceServer).toHaveBeenCalledWith(sourceServerId);
  526. expect(disconnect.mock.invocationCallOrder[0]).toBeLessThan(
  527. onBeforeSourceServerRemoved.mock.invocationCallOrder[0]!,
  528. );
  529. expect(onBeforeSourceServerRemoved.mock.invocationCallOrder[0]).toBeLessThan(
  530. removeSourceServer.mock.invocationCallOrder[0]!,
  531. );
  532. service.dispose();
  533. });
  534. it("rejects removal without attachment cleanup and preserves callback failures as codes", async () => {
  535. const stateEmitter = new Emitter<SourceServerConnectionStateSnapshot>();
  536. const snapshot = {
  537. profiles: [],
  538. servers: [{ sourceServerId, displayName: "server", declaredWorkspaces: [] }],
  539. workspaceHistory: [],
  540. };
  541. const directoryRemove = vi.fn(async () => undefined);
  542. const makeService = (onBeforeSourceServerRemoved?: () => Promise<void>) =>
  543. createSourceServerManagementService({
  544. directory: {
  545. snapshot: vi.fn(async () => snapshot),
  546. onDidChange: new Emitter<void>().event,
  547. resolveProfileTarget: vi.fn(),
  548. renameSource: vi.fn(),
  549. renameProfile: vi.fn(),
  550. setPreferredProfile: vi.fn(),
  551. removeProfile: vi.fn(),
  552. removeSourceServer: directoryRemove,
  553. },
  554. manager: {
  555. listStates: () => [],
  556. onDidChangeState: stateEmitter.event,
  557. getOnlineConnection: () => undefined,
  558. connect: vi.fn(),
  559. updateServer: vi.fn(),
  560. disconnect: vi.fn(),
  561. removeProfile: vi.fn(),
  562. },
  563. ...(onBeforeSourceServerRemoved ? { onBeforeSourceServerRemoved } : {}),
  564. });
  565. const missing = makeService();
  566. await expect(missing.removeSourceServer(sourceServerId)).rejects.toMatchObject({
  567. code: "source-server-remove-callback-missing",
  568. });
  569. missing.dispose();
  570. const callbackFailed = makeService(async () => {
  571. throw new Error("attachment failure");
  572. });
  573. await expect(callbackFailed.removeSourceServer(sourceServerId)).rejects.toMatchObject({
  574. code: "source-server-remove-callback-failed",
  575. });
  576. callbackFailed.dispose();
  577. // 合同 §8.1.3:缺回调拒绝与回调失败中止都不得触碰持久化记录。
  578. expect(directoryRemove).not.toHaveBeenCalled();
  579. });
  580. it("maps persistence failures to the persist-failed code and keeps the device in the snapshot", async () => {
  581. const stateEmitter = new Emitter<SourceServerConnectionStateSnapshot>();
  582. const snapshot = {
  583. profiles: [],
  584. servers: [{ sourceServerId, displayName: "server", declaredWorkspaces: [] }],
  585. workspaceHistory: [],
  586. };
  587. const service = createSourceServerManagementService({
  588. directory: {
  589. snapshot: vi.fn(async () => snapshot),
  590. onDidChange: new Emitter<void>().event,
  591. resolveProfileTarget: vi.fn(),
  592. renameSource: vi.fn(),
  593. renameProfile: vi.fn(),
  594. setPreferredProfile: vi.fn(),
  595. removeProfile: vi.fn(),
  596. removeSourceServer: vi.fn(async () => {
  597. throw new Error("disk full");
  598. }),
  599. },
  600. manager: {
  601. listStates: () => [],
  602. onDidChangeState: stateEmitter.event,
  603. getOnlineConnection: () => undefined,
  604. connect: vi.fn(),
  605. updateServer: vi.fn(),
  606. disconnect: vi.fn(),
  607. removeProfile: vi.fn(),
  608. },
  609. onBeforeSourceServerRemoved: vi.fn(async () => undefined),
  610. });
  611. await expect(service.removeSourceServer(sourceServerId)).rejects.toMatchObject({
  612. code: "source-server-remove-persist-failed",
  613. });
  614. // 恢复态:设备记录保留在权威快照中,且无任何在线状态(连接已在删除流程前断开)。
  615. const recovered = await service.getSnapshot();
  616. expect(recovered.servers).toEqual([expect.objectContaining({ sourceServerId })]);
  617. expect(recovered.states).toEqual([]);
  618. service.dispose();
  619. });
  620. it("returns a successful snapshot without side effects when removing an unknown device", async () => {
  621. const stateEmitter = new Emitter<SourceServerConnectionStateSnapshot>();
  622. const directoryRemove = vi.fn(async () => undefined);
  623. const onBeforeSourceServerRemoved = vi.fn(async () => undefined);
  624. const disconnect = vi.fn();
  625. const service = createSourceServerManagementService({
  626. directory: {
  627. snapshot: vi.fn(async () => ({
  628. profiles: [],
  629. servers: [],
  630. workspaceHistory: [],
  631. })),
  632. onDidChange: new Emitter<void>().event,
  633. resolveProfileTarget: vi.fn(),
  634. renameSource: vi.fn(),
  635. renameProfile: vi.fn(),
  636. setPreferredProfile: vi.fn(),
  637. removeProfile: vi.fn(),
  638. removeSourceServer: directoryRemove,
  639. },
  640. manager: {
  641. listStates: () => [],
  642. onDidChangeState: stateEmitter.event,
  643. getOnlineConnection: () => undefined,
  644. connect: vi.fn(),
  645. updateServer: vi.fn(),
  646. disconnect,
  647. removeProfile: vi.fn(),
  648. },
  649. onBeforeSourceServerRemoved,
  650. });
  651. // 幂等:设备不存在返回成功空操作,不走断连/回调/持久化,也不占用错误码。
  652. await expect(service.removeSourceServer(sourceServerId)).resolves.toMatchObject({
  653. servers: [],
  654. });
  655. expect(disconnect).not.toHaveBeenCalled();
  656. expect(onBeforeSourceServerRemoved).not.toHaveBeenCalled();
  657. expect(directoryRemove).not.toHaveBeenCalled();
  658. service.dispose();
  659. });
  660. it("retries the snapshot read when a concurrent write bumps the generation", async () => {
  661. const stateEmitter = new Emitter<SourceServerConnectionStateSnapshot>();
  662. const directoryChange = new Emitter<void>();
  663. const staleServers = [{ sourceServerId, displayName: "stale-name", declaredWorkspaces: [] }];
  664. const freshServers = [{ sourceServerId, displayName: "fresh-name", declaredWorkspaces: [] }];
  665. const snapshot = vi.fn(async () => {
  666. if (snapshot.mock.calls.length === 1) {
  667. // 读取进行中注入并发目录写入:generation 递增,本轮读到的是旧内容。
  668. directoryChange.fire();
  669. return { profiles: [], servers: staleServers, workspaceHistory: [] };
  670. }
  671. return { profiles: [], servers: freshServers, workspaceHistory: [] };
  672. });
  673. const service = createSourceServerManagementService({
  674. directory: {
  675. snapshot,
  676. onDidChange: directoryChange.event,
  677. resolveProfileTarget: vi.fn(),
  678. renameSource: vi.fn(),
  679. renameProfile: vi.fn(),
  680. setPreferredProfile: vi.fn(),
  681. removeProfile: vi.fn(),
  682. removeSourceServer: vi.fn(),
  683. },
  684. manager: {
  685. listStates: () => [],
  686. onDidChangeState: stateEmitter.event,
  687. getOnlineConnection: () => undefined,
  688. connect: vi.fn(),
  689. updateServer: vi.fn(),
  690. disconnect: vi.fn(),
  691. removeProfile: vi.fn(),
  692. },
  693. });
  694. // 合同 §8.1.4 稳定读取:start/end generation 双检查,不一致必须整体重读,
  695. // 不得产出「旧内容 + 新版本号」。
  696. const result = await service.getSnapshot();
  697. expect(snapshot).toHaveBeenCalledTimes(2);
  698. expect(result.generation).toBe(1);
  699. expect(result.servers).toEqual([expect.objectContaining({ displayName: "fresh-name" })]);
  700. service.dispose();
  701. });
  702. });