useRemoteWorkspaceHistoryDirectoryProjection.test.ts 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513
  1. // @vitest-environment jsdom
  2. import { act, renderHook, waitFor } from "@testing-library/react";
  3. import { Emitter, Event, ProxyChannel } from "@zcode/rpc";
  4. import type { IServiceAccessor } from "@zcode/services";
  5. import type {
  6. AppSettings,
  7. IPlatformService,
  8. SourceServerManagementDirectoryDelta,
  9. SourceServerManagementSnapshot,
  10. SourceServerManagementStateDelta,
  11. } from "@zcode/shared";
  12. import { describe, expect, it, vi } from "vitest";
  13. import {
  14. collectStartupRemoteWorkspaceReconnectGroups,
  15. useRemoteWorkspaceHistory,
  16. } from "@/root/useRemoteWorkspaceHistory.js";
  17. import { createTabStore, isWorkspaceTab } from "@/store/tabStore.js";
  18. const PROFILE_ID = "69d675cc-7753-4fa2-a1a1-594281f2c833";
  19. const SOURCE_SERVER_ID = "82d727a5-8e58-4b82-b374-8081e7855666";
  20. const DEFAULT_PATH = "/home/dev/.zcode/workspace/default";
  21. const DEV_PATH = "/home/dev";
  22. const defaultLegacyIdentity = `remote:ssh:localhost:2222:dev:${DEFAULT_PATH}`;
  23. const devLegacyIdentity = `remote:ssh:localhost:2222:dev:${DEV_PATH}`;
  24. const defaultStableIdentity = `remote:server:${SOURCE_SERVER_ID}:${DEFAULT_PATH}`;
  25. const devStableIdentity = `remote:server:${SOURCE_SERVER_ID}:${DEV_PATH}`;
  26. function remoteTarget() {
  27. return {
  28. kind: "ssh" as const,
  29. host: "localhost",
  30. port: 2222,
  31. username: "dev",
  32. sshConfigAlias: "linux-amd64-dev",
  33. };
  34. }
  35. function initialSettings(): AppSettings {
  36. return {
  37. lastWorkspaceSession: [
  38. {
  39. kind: "remote",
  40. workspacePath: DEFAULT_PATH,
  41. workspaceIdentity: defaultLegacyIdentity,
  42. target: remoteTarget(),
  43. lastOpenedAt: Date.now() - 2_000,
  44. lastConnectionStatus: "failed",
  45. lastConnectionError: "远程设备与当前版本不兼容",
  46. },
  47. {
  48. kind: "remote",
  49. workspacePath: DEV_PATH,
  50. workspaceIdentity: devLegacyIdentity,
  51. target: remoteTarget(),
  52. lastOpenedAt: Date.now() - 1_000,
  53. lastConnectionStatus: "connected",
  54. },
  55. ],
  56. sourceServerWorkspaceHistory: [
  57. {
  58. workspacePath: DEV_PATH,
  59. legacyWorkspaceIdentity: devLegacyIdentity,
  60. profileId: PROFILE_ID,
  61. lastOpenedAt: Date.now() - 1_000,
  62. },
  63. ],
  64. sourceServerDirectoryMigrationVersion: 1,
  65. };
  66. }
  67. function managementSnapshot(
  68. generation: number,
  69. identified: boolean,
  70. ): SourceServerManagementSnapshot {
  71. const settings = initialSettings();
  72. return {
  73. generation,
  74. profiles: [
  75. {
  76. profileId: PROFILE_ID,
  77. transport: "ssh",
  78. target: remoteTarget(),
  79. createdAt: 1,
  80. ...(identified ? { sourceServerId: SOURCE_SERVER_ID } : {}),
  81. },
  82. ],
  83. servers: identified
  84. ? [
  85. {
  86. sourceServerId: SOURCE_SERVER_ID,
  87. displayName: "linux-amd64-dev",
  88. declaredWorkspaces: [],
  89. },
  90. ]
  91. : [],
  92. workspaceHistory: settings.sourceServerWorkspaceHistory!.map((entry) =>
  93. identified
  94. ? {
  95. ...entry,
  96. sourceServerId: SOURCE_SERVER_ID,
  97. workspaceIdentity:
  98. entry.workspacePath === DEV_PATH ? devStableIdentity : defaultStableIdentity,
  99. }
  100. : entry,
  101. ),
  102. states: [
  103. {
  104. profileId: PROFILE_ID,
  105. ...(identified ? { sourceServerId: SOURCE_SERVER_ID } : {}),
  106. state: identified ? "updating" : "needs-upgrade",
  107. updatedAt: generation,
  108. },
  109. ],
  110. failedPathCount: 0,
  111. abandonedPathCount: 0,
  112. migrationCounts: [],
  113. };
  114. }
  115. describe("useRemoteWorkspaceHistory Source Directory identity projection", () => {
  116. it("RPC 方法重新取值不使导航回调失稳,服务替换仍更新", () => {
  117. const credential = () =>
  118. ProxyChannel.toService<IServiceAccessor["credentialService"]>({
  119. call: vi.fn(async () => null) as never,
  120. listen: () => Event.None,
  121. });
  122. const services = { credentialService: credential(), settingService: {} } as IServiceAccessor;
  123. const tabStoreApi = createTabStore();
  124. const options = {
  125. intl: { formatMessage: ({ id }: { id: string }) => id } as never,
  126. platform: {
  127. onRemoteConnectionLog: () => () => {},
  128. onRemoteSessionClosed: () => () => {},
  129. onRemoteSessionReconnected: () => () => {},
  130. } as unknown as IPlatformService,
  131. supportsSettings: false,
  132. allowRemoteWorkspace: false,
  133. tabStoreApi,
  134. activateTabByPath: tabStoreApi.getState().activateTabByPath,
  135. addTab: tabStoreApi.getState().addTab,
  136. };
  137. const { result, rerender, unmount } = renderHook(
  138. ({ services }) => useRemoteWorkspaceHistory({ ...options, services }),
  139. { initialProps: { services } },
  140. );
  141. try {
  142. const before = result.current;
  143. rerender({ services });
  144. expect(result.current.remoteWorkspaceController).toBe(before.remoteWorkspaceController);
  145. expect(result.current.handleSelectRemoteProject).toBe(before.handleSelectRemoteProject);
  146. expect(result.current.handleReconnectRemoteWorkspace).toBe(
  147. before.handleReconnectRemoteWorkspace,
  148. );
  149. rerender({ services: { ...services, credentialService: credential() } });
  150. expect(result.current.remoteWorkspaceController).not.toBe(before.remoteWorkspaceController);
  151. } finally {
  152. unmount();
  153. }
  154. });
  155. it("rekeys restored legacy sessions and tabs before the online reconnect gate runs", async () => {
  156. const stateEmitter = new Emitter<SourceServerManagementStateDelta>();
  157. const directoryEmitter = new Emitter<SourceServerManagementDirectoryDelta>();
  158. let snapshot = managementSnapshot(1, false);
  159. const getSnapshot = vi.fn(async () => snapshot);
  160. const connectRemote = vi.fn();
  161. const services = {
  162. sourceServerManagementService: {
  163. getSnapshot,
  164. onDidChangeState: stateEmitter.event,
  165. onDidChangeDirectory: directoryEmitter.event,
  166. },
  167. settingService: {
  168. get: vi.fn(async () => initialSettings()),
  169. update: vi.fn(async () => undefined),
  170. },
  171. credentialService: {
  172. load: vi.fn(async () => null),
  173. save: vi.fn(async () => undefined),
  174. delete: vi.fn(async () => undefined),
  175. },
  176. fileService: {},
  177. modelSelectionService: {},
  178. providerSettingsService: {},
  179. zcodeSessionService: {},
  180. } as unknown as IServiceAccessor;
  181. const platform = {
  182. connectRemote,
  183. disposeRemoteSession: vi.fn(async () => undefined),
  184. onRemoteConnectionLog: vi.fn(() => () => undefined),
  185. onRemoteSessionClosed: vi.fn(() => () => undefined),
  186. onRemoteSessionReconnected: vi.fn(() => () => undefined),
  187. } as unknown as IPlatformService;
  188. const tabStoreApi = createTabStore();
  189. const { result, unmount } = renderHook(() =>
  190. useRemoteWorkspaceHistory({
  191. intl: { formatMessage: ({ id }: { id: string }) => id } as never,
  192. services,
  193. platform,
  194. supportsSettings: false,
  195. isDesktop: true,
  196. tabStoreApi,
  197. activateTabByPath: tabStoreApi.getState().activateTabByPath,
  198. addTab: tabStoreApi.getState().addTab,
  199. }),
  200. );
  201. await act(async () => {
  202. await result.current.restorePersistedSession(initialSettings());
  203. });
  204. await waitFor(() => expect(getSnapshot).toHaveBeenCalled());
  205. snapshot = managementSnapshot(2, true);
  206. act(() => directoryEmitter.fire({ generation: 2 }));
  207. await waitFor(() =>
  208. expect(
  209. result.current.remoteWorkspaceSessions.map((entry) => ({
  210. identity: entry.workspaceIdentity,
  211. status: entry.lastConnectionStatus,
  212. })),
  213. ).toEqual([
  214. { identity: defaultLegacyIdentity, status: "failed" },
  215. { identity: devStableIdentity, status: "connected" },
  216. ]),
  217. );
  218. const workspaceTabs = tabStoreApi.getState().tabs.filter(isWorkspaceTab);
  219. expect(workspaceTabs.map((tab) => tab.workspaceIdentity)).toEqual([
  220. defaultLegacyIdentity,
  221. devStableIdentity,
  222. ]);
  223. expect(tabStoreApi.getState().activeWorkspaceIdentity).toBe(defaultLegacyIdentity);
  224. expect(connectRemote).not.toHaveBeenCalled();
  225. expect(
  226. collectStartupRemoteWorkspaceReconnectGroups({
  227. sessions: result.current.remoteWorkspaceSessions,
  228. tabs: tabStoreApi.getState().tabs,
  229. attemptedWorkspaceKeys: new Set(),
  230. onlineSourceServerIds: new Set([SOURCE_SERVER_ID]),
  231. now: Date.now(),
  232. }),
  233. ).toEqual([
  234. {
  235. sourceServerId: SOURCE_SERVER_ID,
  236. entries: [
  237. expect.objectContaining({
  238. workspacePath: DEV_PATH,
  239. workspaceIdentity: devStableIdentity,
  240. lastConnectionStatus: "connected",
  241. }),
  242. ],
  243. },
  244. ]);
  245. unmount();
  246. });
  247. it("retains a rollback conversation identity as data without restoring its tab", async () => {
  248. const stateEmitter = new Emitter<SourceServerManagementStateDelta>();
  249. const directoryEmitter = new Emitter<SourceServerManagementDirectoryDelta>();
  250. const settings = {
  251. ...initialSettings(),
  252. connectionProfiles: [
  253. {
  254. profileId: PROFILE_ID,
  255. sourceServerId: SOURCE_SERVER_ID,
  256. transport: "ssh" as const,
  257. target: remoteTarget(),
  258. createdAt: 1,
  259. },
  260. ],
  261. remoteConversationWorkspaceBySourceServerId: {
  262. [SOURCE_SERVER_ID]: {
  263. workspacePath: DEFAULT_PATH,
  264. lastResolvedAt: Date.now(),
  265. },
  266. },
  267. } satisfies AppSettings;
  268. const services = {
  269. sourceServerManagementService: {
  270. getSnapshot: vi.fn(async () => managementSnapshot(1, true)),
  271. onDidChangeState: stateEmitter.event,
  272. onDidChangeDirectory: directoryEmitter.event,
  273. ensureConversationWorkspace: vi.fn(async () => ({
  274. path: DEFAULT_PATH,
  275. created: false,
  276. workspacePurpose: "conversation" as const,
  277. })),
  278. },
  279. settingService: {
  280. get: vi.fn(async () => settings),
  281. update: vi.fn(async () => undefined),
  282. },
  283. credentialService: {
  284. load: vi.fn(async () => null),
  285. save: vi.fn(async () => undefined),
  286. delete: vi.fn(async () => undefined),
  287. },
  288. fileService: {},
  289. modelSelectionService: {},
  290. providerSettingsService: {},
  291. zcodeSessionService: {},
  292. } as unknown as IServiceAccessor;
  293. const platform = {
  294. connectRemote: vi.fn(() => new Promise<string>(() => undefined)),
  295. disposeRemoteSession: vi.fn(async () => undefined),
  296. onRemoteConnectionLog: vi.fn(() => () => undefined),
  297. onRemoteSessionClosed: vi.fn(() => () => undefined),
  298. onRemoteSessionReconnected: vi.fn(() => () => undefined),
  299. } as unknown as IPlatformService;
  300. const tabStoreApi = createTabStore();
  301. const { result, unmount } = renderHook(() =>
  302. useRemoteWorkspaceHistory({
  303. intl: { formatMessage: ({ id }: { id: string }) => id } as never,
  304. services,
  305. platform,
  306. supportsSettings: false,
  307. isDesktop: true,
  308. tabStoreApi,
  309. activateTabByPath: tabStoreApi.getState().activateTabByPath,
  310. addTab: tabStoreApi.getState().addTab,
  311. }),
  312. );
  313. await act(async () => {
  314. await result.current.restorePersistedSession(settings);
  315. });
  316. await waitFor(() => {
  317. const tab = tabStoreApi
  318. .getState()
  319. .tabs.filter(isWorkspaceTab)
  320. .find((candidate) => candidate.workspacePath === DEFAULT_PATH);
  321. expect(tab).toBeUndefined();
  322. });
  323. expect(
  324. result.current.remoteWorkspaceSessions.find((entry) => entry.workspacePath === DEFAULT_PATH),
  325. ).toMatchObject({
  326. workspaceIdentity: defaultStableIdentity,
  327. workspacePurpose: "conversation",
  328. });
  329. expect(platform.connectRemote).not.toHaveBeenCalled();
  330. unmount();
  331. });
  332. it("restores all failed open workspaces at startup and after terminal disconnect without stale online retries", async () => {
  333. const stateEmitter = new Emitter<SourceServerManagementStateDelta>();
  334. const directoryEmitter = new Emitter<SourceServerManagementDirectoryDelta>();
  335. const settings = {
  336. ...initialSettings(),
  337. lastWorkspaceSession: [
  338. {
  339. kind: "remote" as const,
  340. workspacePath: DEFAULT_PATH,
  341. workspaceIdentity: defaultStableIdentity,
  342. target: remoteTarget(),
  343. lastOpenedAt: Date.now() - 2_000,
  344. lastConnectionStatus: "failed" as const,
  345. lastConnectionError: "远程连接已断开",
  346. },
  347. {
  348. kind: "remote" as const,
  349. workspacePath: DEV_PATH,
  350. workspaceIdentity: devStableIdentity,
  351. target: remoteTarget(),
  352. lastOpenedAt: Date.now() - 1_000,
  353. lastConnectionStatus: "failed" as const,
  354. lastConnectionError: "远程连接已断开",
  355. },
  356. ],
  357. } satisfies AppSettings;
  358. let snapshot: SourceServerManagementSnapshot = {
  359. ...managementSnapshot(1, true),
  360. states: [
  361. {
  362. profileId: PROFILE_ID,
  363. sourceServerId: SOURCE_SERVER_ID,
  364. state: "online",
  365. updatedAt: 1,
  366. },
  367. ],
  368. };
  369. let onSessionClosed: Parameters<IPlatformService["onRemoteSessionClosed"]>[0] | undefined;
  370. const connectRemote = vi.fn(async () => ({
  371. success: false as const,
  372. error: "stop after observing reconnect admission",
  373. }));
  374. const getSnapshot = vi.fn(async () => snapshot);
  375. const services = {
  376. sourceServerManagementService: {
  377. getSnapshot,
  378. onDidChangeState: stateEmitter.event,
  379. onDidChangeDirectory: directoryEmitter.event,
  380. ensureConversationWorkspace: vi.fn(async () => ({
  381. path: DEFAULT_PATH,
  382. created: false,
  383. workspacePurpose: "conversation" as const,
  384. })),
  385. },
  386. settingService: {
  387. get: vi.fn(async () => settings),
  388. update: vi.fn(async () => undefined),
  389. },
  390. credentialService: {
  391. load: vi.fn(async () => null),
  392. save: vi.fn(async () => undefined),
  393. delete: vi.fn(async () => undefined),
  394. },
  395. fileService: {},
  396. modelSelectionService: {},
  397. providerSettingsService: {},
  398. zcodeSessionService: {},
  399. } as unknown as IServiceAccessor;
  400. const platform = {
  401. connectRemote,
  402. disposeRemoteSession: vi.fn(async () => undefined),
  403. onRemoteConnectionLog: vi.fn(() => () => undefined),
  404. onRemoteSessionClosed: vi.fn((listener) => {
  405. onSessionClosed = listener;
  406. return () => undefined;
  407. }),
  408. onRemoteSessionReconnected: vi.fn(() => () => undefined),
  409. } as unknown as IPlatformService;
  410. const tabStoreApi = createTabStore();
  411. const { result, unmount } = renderHook(() =>
  412. useRemoteWorkspaceHistory({
  413. intl: { formatMessage: ({ id }: { id: string }) => id } as never,
  414. services,
  415. platform,
  416. supportsSettings: false,
  417. isDesktop: true,
  418. tabStoreApi,
  419. activateTabByPath: tabStoreApi.getState().activateTabByPath,
  420. addTab: tabStoreApi.getState().addTab,
  421. }),
  422. );
  423. await act(async () => {
  424. await result.current.restorePersistedSession(settings);
  425. });
  426. await waitFor(() => expect(connectRemote).toHaveBeenCalledTimes(2));
  427. expect(
  428. connectRemote.mock.calls.map(([, , context]) => context?.workspacePath).toSorted(),
  429. ).toEqual([DEFAULT_PATH, DEV_PATH].toSorted());
  430. await act(async () => {
  431. stateEmitter.fire({ generation: 1, state: snapshot.states[0]! });
  432. directoryEmitter.fire({ generation: 1 });
  433. });
  434. expect(connectRemote).toHaveBeenCalledTimes(2);
  435. connectRemote.mockClear();
  436. await waitFor(() => expect(onSessionClosed).toBeDefined());
  437. act(() => {
  438. tabStoreApi.getState().ensureWorkspaceTab(DEFAULT_PATH, {
  439. workspaceIdentity: defaultStableIdentity,
  440. remoteSessionId: "terminal-session",
  441. });
  442. });
  443. await act(async () => {
  444. onSessionClosed?.({
  445. sessionId: "terminal-session",
  446. reason: "host-exit",
  447. exitCode: null,
  448. signal: null,
  449. recoverable: false,
  450. });
  451. });
  452. await waitFor(() => expect(getSnapshot.mock.calls.length).toBeGreaterThan(1));
  453. expect(connectRemote).not.toHaveBeenCalled();
  454. snapshot = {
  455. ...snapshot,
  456. generation: 2,
  457. states: [
  458. {
  459. profileId: PROFILE_ID,
  460. sourceServerId: SOURCE_SERVER_ID,
  461. state: "offline",
  462. updatedAt: 2,
  463. },
  464. ],
  465. };
  466. act(() => {
  467. stateEmitter.fire({ generation: 2, state: snapshot.states[0]! });
  468. });
  469. snapshot = {
  470. ...snapshot,
  471. generation: 3,
  472. states: [
  473. {
  474. profileId: PROFILE_ID,
  475. sourceServerId: SOURCE_SERVER_ID,
  476. state: "online",
  477. updatedAt: 3,
  478. },
  479. ],
  480. };
  481. act(() => {
  482. stateEmitter.fire({ generation: 3, state: snapshot.states[0]! });
  483. });
  484. await waitFor(() => expect(connectRemote).toHaveBeenCalledTimes(2));
  485. expect(
  486. connectRemote.mock.calls.map(([, , context]) => context?.workspacePath).toSorted(),
  487. ).toEqual([DEFAULT_PATH, DEV_PATH].toSorted());
  488. unmount();
  489. });
  490. });