useRemoteWorkspaceHistory.test.ts 62 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711
  1. import { describe, expect, it, vi } from "vitest";
  2. import type { RemoteWorkspaceSessionEntry } from "@zcode/shared";
  3. import type { WindowTabState } from "@/store/tabStore.js";
  4. import type { ReconnectRemoteWorkspaceOptions } from "@/root/reconnectRemoteWorkspaceHistoryEntry.js";
  5. import {
  6. bindRemoteWorkspaceContextAndGetSession,
  7. cancelPendingRemoteReconnectsForWorkspaceKeys,
  8. collectSshReconnectGroup,
  9. openRemoteWorkspaceFromHistoryEntry,
  10. reconnectRemoteWorkspaceByKey,
  11. reconnectRemoteWorkspaceHistoryEntry,
  12. reconnectRemoteWorkspaceGroup,
  13. resolveBotRemoteWorkspaceReconnectedIdentity,
  14. shouldPersistRemoteWorkspaceFailure,
  15. selectRemoteWorkspaceProjectFromDialog,
  16. } from "@/root/useRemoteWorkspaceHistory.js";
  17. import {
  18. registerRemoteWorkspaceSession,
  19. unregisterRemoteWorkspaceSession,
  20. } from "@/store/remoteWorkspaceSessionStore.js";
  21. import {
  22. buildRemoteWorkspaceIdentity,
  23. buildWorkspaceSessionKey,
  24. } from "@/lib/remoteWorkspaceHistory.js";
  25. function createRemoteWorkspaceSessionEntry(
  26. overrides: Partial<RemoteWorkspaceSessionEntry> = {},
  27. ): RemoteWorkspaceSessionEntry {
  28. return {
  29. kind: "remote",
  30. workspacePath: "/workspace/demo",
  31. workspaceIdentity: "remote:docker:demo:/workspace/demo",
  32. target: {
  33. kind: "docker",
  34. container: "demo",
  35. },
  36. lastOpenedAt: 10,
  37. lastConnectionStatus: "failed",
  38. ...overrides,
  39. };
  40. }
  41. function createWorkspaceTab(
  42. overrides: {
  43. id?: string;
  44. workspacePath?: string;
  45. workspaceIdentity?: string;
  46. remoteSessionId?: string;
  47. } = {},
  48. ): WindowTabState {
  49. return {
  50. id: overrides.id ?? "tab-1",
  51. kind: "workspace",
  52. label: "demo",
  53. workspacePath: overrides.workspacePath ?? "/workspace/demo",
  54. workspaceIdentity: overrides.workspaceIdentity,
  55. remoteSessionId: overrides.remoteSessionId,
  56. };
  57. }
  58. describe("bindRemoteWorkspaceContextAndGetSession", () => {
  59. it("bind 完成后重新读取同一 session 的新 attachment services", async () => {
  60. const firstServices = { zcodeSessionService: { attachment: "A" } } as never;
  61. const secondServices = { zcodeSessionService: { attachment: "B" } } as never;
  62. registerRemoteWorkspaceSession({
  63. sessionId: "remote-session-1",
  64. services: firstServices,
  65. });
  66. const bindRemoteWorkspaceSessionContext = vi.fn(async () => {
  67. registerRemoteWorkspaceSession({
  68. sessionId: "remote-session-1",
  69. services: secondServices,
  70. });
  71. });
  72. try {
  73. const session = await bindRemoteWorkspaceContextAndGetSession({
  74. platform: { bindRemoteWorkspaceSessionContext } as never,
  75. sessionId: "remote-session-1",
  76. workspacePath: "/workspace/demo",
  77. workspaceIdentity: "remote:ssh:dev.internal:22:developer:/workspace/demo",
  78. });
  79. expect(bindRemoteWorkspaceSessionContext).toHaveBeenCalledOnce();
  80. expect(session.services).toBe(secondServices);
  81. expect(session.services).not.toBe(firstServices);
  82. } finally {
  83. unregisterRemoteWorkspaceSession("remote-session-1");
  84. }
  85. });
  86. });
  87. function createOpenRemoteWorkspaceContext(options?: {
  88. sessionEntry?: RemoteWorkspaceSessionEntry;
  89. tabs?: WindowTabState[];
  90. }) {
  91. const sessionEntry = options?.sessionEntry ?? createRemoteWorkspaceSessionEntry();
  92. const workspaceKey = buildWorkspaceSessionKey(sessionEntry);
  93. let tabs = options?.tabs ?? [];
  94. const tabStoreApi = {
  95. getState: () => ({
  96. tabs,
  97. }),
  98. };
  99. const activateTabByPath = vi.fn(() => false);
  100. const setReconnectingRemoteWorkspaceKeys = vi.fn((updater: (current: string[]) => string[]) =>
  101. updater([]),
  102. );
  103. const resetLogsForWorkspaceKey = vi.fn();
  104. const onWorkspaceActivated = vi.fn();
  105. const reconnectImpl = vi.fn(async () => undefined);
  106. const inflightReconnectWorkspaceKeys = new Set<string>();
  107. const params: Parameters<typeof openRemoteWorkspaceFromHistoryEntry>[0] = {
  108. workspaceKey,
  109. tabStoreApi,
  110. getRemoteSessions: () => [sessionEntry],
  111. inflightReconnectWorkspaceKeys,
  112. activateTabByPath,
  113. setReconnectingRemoteWorkspaceKeys,
  114. loadCredential: vi.fn(async () => null),
  115. connectRemoteWorkspaceTarget: vi.fn(async () => "session-1"),
  116. resolveRemoteWorkspaceCanonicalPath: vi.fn(async (_sessionId, workspacePath) => workspacePath),
  117. disposeRemoteWorkspaceSession: vi.fn(async () => undefined),
  118. bindRemoteWorkspaceSessionContext: vi.fn(async () => undefined),
  119. addTab: vi.fn(),
  120. commitRemoteWorkspaceSessionMutation: vi.fn(async (mutation) => mutation.entry),
  121. resetLogsForWorkspaceKey,
  122. onWorkspaceActivated,
  123. reconnectImpl,
  124. };
  125. return {
  126. params,
  127. sessionEntry,
  128. workspaceKey,
  129. activateTabByPath,
  130. resetLogsForWorkspaceKey,
  131. onWorkspaceActivated,
  132. reconnectImpl,
  133. inflightReconnectWorkspaceKeys,
  134. setTabs(nextTabs: WindowTabState[]) {
  135. tabs = nextTabs;
  136. },
  137. };
  138. }
  139. describe("shouldPersistRemoteWorkspaceFailure", () => {
  140. it("keeps non-WSL remote failures persisted immediately", () => {
  141. const sessionEntry = createRemoteWorkspaceSessionEntry();
  142. expect(
  143. shouldPersistRemoteWorkspaceFailure({
  144. pendingReconnectRequestIds: new Map([
  145. [buildWorkspaceSessionKey(sessionEntry), "request-1"],
  146. ]),
  147. sessionEntry,
  148. workspaceKey: buildWorkspaceSessionKey(sessionEntry),
  149. }),
  150. ).toBe(true);
  151. });
  152. it("delays WSL failure persistence while reconnect is pending", () => {
  153. const sessionEntry = createRemoteWorkspaceSessionEntry({
  154. workspaceIdentity: "remote:wsl:default:/workspace/demo",
  155. target: { kind: "wsl" },
  156. });
  157. const workspaceKey = buildWorkspaceSessionKey(sessionEntry);
  158. expect(
  159. shouldPersistRemoteWorkspaceFailure({
  160. pendingReconnectRequestIds: new Map([[workspaceKey, "request-1"]]),
  161. sessionEntry,
  162. workspaceKey,
  163. }),
  164. ).toBe(false);
  165. });
  166. });
  167. describe("reconnectRemoteWorkspaceHistoryEntry", () => {
  168. describe("resolveBotRemoteWorkspaceReconnectedIdentity", () => {
  169. it("keeps the bot event workspace identity when canonical path differs", () => {
  170. const eventWorkspaceIdentity = "remote:docker:demo:/workspace/link";
  171. const canonicalIdentity = buildRemoteWorkspaceIdentity("/workspace/real", {
  172. kind: "docker",
  173. container: "demo",
  174. });
  175. const resolvedIdentity = resolveBotRemoteWorkspaceReconnectedIdentity({
  176. event: {
  177. workspaceIdentity: eventWorkspaceIdentity,
  178. },
  179. resolvedWorkspacePath: "/workspace/real",
  180. target: {
  181. kind: "docker",
  182. container: "demo",
  183. },
  184. });
  185. expect(resolvedIdentity).toBe(eventWorkspaceIdentity);
  186. expect(resolvedIdentity).not.toBe(canonicalIdentity);
  187. });
  188. it("falls back to canonical identity when the bot event identity is blank", () => {
  189. const target = {
  190. kind: "docker" as const,
  191. container: "demo",
  192. };
  193. const expectedIdentity = buildRemoteWorkspaceIdentity("/workspace/real", target);
  194. const resolvedIdentity = resolveBotRemoteWorkspaceReconnectedIdentity({
  195. event: {
  196. workspaceIdentity: " ",
  197. },
  198. resolvedWorkspacePath: "/workspace/real",
  199. target,
  200. });
  201. expect(resolvedIdentity).toBe(expectedIdentity);
  202. });
  203. });
  204. it("keeps the current conversation mounted until reconnect is ready, then activates the remote draft", async () => {
  205. const activateTabByPath = vi.fn(() => true);
  206. const setReconnectingRemoteWorkspaceKeys = vi.fn((updater) => {
  207. updater([]);
  208. updater(["remote:docker:demo:/workspace/demo"]);
  209. });
  210. const loadCredential = vi.fn(async () => null);
  211. let resolveConnect!: (sessionId: string) => void;
  212. const pendingConnect = new Promise<string>((resolve) => {
  213. resolveConnect = resolve;
  214. });
  215. const connectRemoteWorkspaceTarget = vi.fn(() => pendingConnect);
  216. const resolveRemoteWorkspaceCanonicalPath = vi.fn(async () => "/workspace/demo");
  217. const disposeRemoteWorkspaceSession = vi.fn(async () => undefined);
  218. const bindWorkspacePath = vi.fn();
  219. const bindWorkspaceIdentity = vi.fn();
  220. const upsertWorkspaceTab = vi.fn();
  221. const commitRemoteWorkspaceSessionMutation = vi.fn(async (mutation) => mutation.entry);
  222. const warn = vi.fn();
  223. const toast = vi.fn();
  224. const onWorkspaceActivated = vi.fn();
  225. const sessionEntry = {
  226. kind: "remote" as const,
  227. workspacePath: "/workspace/demo",
  228. target: {
  229. kind: "docker" as const,
  230. container: "demo",
  231. },
  232. lastOpenedAt: 10,
  233. lastConnectionStatus: "failed" as const,
  234. };
  235. const reconnect = reconnectRemoteWorkspaceHistoryEntry({
  236. sessionEntry,
  237. activateTabByPath,
  238. setReconnectingRemoteWorkspaceKeys,
  239. loadCredential,
  240. connectRemoteWorkspaceTarget,
  241. resolveRemoteWorkspaceCanonicalPath,
  242. disposeRemoteWorkspaceSession,
  243. bindRemoteWorkspaceSessionContext: vi.fn(async () => undefined),
  244. bindRemoteWorkspacePath: bindWorkspacePath,
  245. bindRemoteWorkspaceIdentity: bindWorkspaceIdentity,
  246. upsertWorkspaceTab,
  247. commitRemoteWorkspaceSessionMutation,
  248. getRemoteSessions: () => [sessionEntry],
  249. logger: { warn },
  250. toast,
  251. onWorkspaceActivated,
  252. });
  253. await vi.waitFor(() => expect(connectRemoteWorkspaceTarget).toHaveBeenCalledTimes(1));
  254. expect(activateTabByPath).not.toHaveBeenCalled();
  255. expect(upsertWorkspaceTab).not.toHaveBeenCalled();
  256. expect(onWorkspaceActivated).not.toHaveBeenCalled();
  257. resolveConnect("session-1");
  258. await reconnect;
  259. const expectedWorkspaceIdentity = buildRemoteWorkspaceIdentity("/workspace/demo", {
  260. kind: "docker",
  261. container: "demo",
  262. });
  263. expect(activateTabByPath).toHaveBeenCalledWith("/workspace/demo", {
  264. workspaceIdentity: expectedWorkspaceIdentity,
  265. });
  266. expect(connectRemoteWorkspaceTarget).toHaveBeenCalledWith(
  267. {
  268. kind: "docker",
  269. container: "demo",
  270. },
  271. undefined,
  272. {
  273. workspacePath: "/workspace/demo",
  274. workspaceIdentity: expectedWorkspaceIdentity,
  275. connectTrigger: "reconnect",
  276. },
  277. );
  278. expect(resolveRemoteWorkspaceCanonicalPath).toHaveBeenCalledWith(
  279. "session-1",
  280. "/workspace/demo",
  281. );
  282. expect(bindWorkspacePath).toHaveBeenCalledWith("/workspace/demo", "session-1");
  283. expect(bindWorkspaceIdentity).toHaveBeenCalledWith(expectedWorkspaceIdentity, "session-1");
  284. expect(upsertWorkspaceTab).toHaveBeenCalledWith("/workspace/demo", {
  285. remoteSessionId: "session-1",
  286. remoteTarget: {
  287. kind: "docker",
  288. container: "demo",
  289. },
  290. workspaceIdentity: expectedWorkspaceIdentity,
  291. });
  292. expect(onWorkspaceActivated).toHaveBeenCalledWith({
  293. workspacePath: "/workspace/demo",
  294. workspaceIdentity: expectedWorkspaceIdentity,
  295. });
  296. expect(upsertWorkspaceTab.mock.invocationCallOrder[0]).toBeLessThan(
  297. activateTabByPath.mock.invocationCallOrder[0]!,
  298. );
  299. expect(activateTabByPath.mock.invocationCallOrder[0]).toBeLessThan(
  300. onWorkspaceActivated.mock.invocationCallOrder[0]!,
  301. );
  302. expect(commitRemoteWorkspaceSessionMutation).toHaveBeenCalledTimes(1);
  303. expect(disposeRemoteWorkspaceSession).not.toHaveBeenCalled();
  304. expect(warn).not.toHaveBeenCalled();
  305. expect(toast).not.toHaveBeenCalled();
  306. });
  307. it("canonical path 与历史记录一致时不再重复绑定 main context", async () => {
  308. // connect 已携带历史记录的 path/identity,descriptor 与 tab 一致,不应再触发一次 attachment 换代。
  309. const bindRemoteWorkspaceSessionContext = vi.fn(async () => undefined);
  310. const sessionEntry = createRemoteWorkspaceSessionEntry();
  311. await reconnectRemoteWorkspaceHistoryEntry({
  312. sessionEntry,
  313. activateTabByPath: vi.fn(() => true),
  314. setReconnectingRemoteWorkspaceKeys: vi.fn((updater) => updater([])),
  315. loadCredential: vi.fn(async () => null),
  316. connectRemoteWorkspaceTarget: vi.fn(async () => "session-1"),
  317. resolveRemoteWorkspaceCanonicalPath: vi.fn(async () => sessionEntry.workspacePath),
  318. disposeRemoteWorkspaceSession: vi.fn(async () => undefined),
  319. bindRemoteWorkspaceSessionContext,
  320. bindRemoteWorkspacePath: vi.fn(),
  321. bindRemoteWorkspaceIdentity: vi.fn(),
  322. upsertWorkspaceTab: vi.fn(),
  323. commitRemoteWorkspaceSessionMutation: vi.fn(async (mutation) => mutation.entry),
  324. getRemoteSessions: () => [sessionEntry],
  325. logger: { warn: vi.fn() },
  326. toast: vi.fn(),
  327. });
  328. expect(bindRemoteWorkspaceSessionContext).not.toHaveBeenCalled();
  329. });
  330. it("canonical path 与历史记录不一致时,先重新绑定 main context 再回填 tab", async () => {
  331. // Bugfix 回归:手机桥接用 tab 上的 canonical path/identity 比对 main descriptor,
  332. // 重连时 descriptor 只有历史记录里的旧路径,realpath 归一化后不同就必须 bind,否则桥接被拒。
  333. const target = { kind: "docker" as const, container: "demo" };
  334. const sessionEntry = createRemoteWorkspaceSessionEntry({
  335. workspacePath: "/dev",
  336. workspaceIdentity: buildRemoteWorkspaceIdentity("/dev", target),
  337. target,
  338. });
  339. const bindRemoteWorkspaceSessionContext = vi.fn(async () => undefined);
  340. const upsertWorkspaceTab = vi.fn();
  341. const disposeRemoteWorkspaceSession = vi.fn(async () => undefined);
  342. await reconnectRemoteWorkspaceHistoryEntry({
  343. sessionEntry,
  344. activateTabByPath: vi.fn(() => true),
  345. setReconnectingRemoteWorkspaceKeys: vi.fn((updater) => updater([])),
  346. loadCredential: vi.fn(async () => null),
  347. connectRemoteWorkspaceTarget: vi.fn(async () => "session-1"),
  348. resolveRemoteWorkspaceCanonicalPath: vi.fn(async () => "/home/dev"),
  349. disposeRemoteWorkspaceSession,
  350. bindRemoteWorkspaceSessionContext,
  351. bindRemoteWorkspacePath: vi.fn(),
  352. bindRemoteWorkspaceIdentity: vi.fn(),
  353. upsertWorkspaceTab,
  354. commitRemoteWorkspaceSessionMutation: vi.fn(async (mutation) => mutation.entry),
  355. getRemoteSessions: () => [sessionEntry],
  356. logger: { warn: vi.fn() },
  357. toast: vi.fn(),
  358. });
  359. const expectedWorkspaceIdentity = buildRemoteWorkspaceIdentity("/home/dev", target);
  360. expect(bindRemoteWorkspaceSessionContext).toHaveBeenCalledWith({
  361. sessionId: "session-1",
  362. workspacePath: "/home/dev",
  363. workspaceIdentity: expectedWorkspaceIdentity,
  364. });
  365. expect(bindRemoteWorkspaceSessionContext.mock.invocationCallOrder[0]).toBeLessThan(
  366. upsertWorkspaceTab.mock.invocationCallOrder[0]!,
  367. );
  368. expect(upsertWorkspaceTab).toHaveBeenCalledWith("/home/dev", {
  369. remoteSessionId: "session-1",
  370. remoteTarget: target,
  371. workspaceIdentity: expectedWorkspaceIdentity,
  372. localWorkspacePath: undefined,
  373. });
  374. expect(disposeRemoteWorkspaceSession).not.toHaveBeenCalled();
  375. });
  376. it("重连时 main 绑定失败会回收 session 并按失败落库,不回填 tab", async () => {
  377. const target = { kind: "docker" as const, container: "demo" };
  378. const sessionEntry = createRemoteWorkspaceSessionEntry({
  379. workspacePath: "/dev",
  380. workspaceIdentity: buildRemoteWorkspaceIdentity("/dev", target),
  381. target,
  382. });
  383. const bindRemoteWorkspaceSessionContext = vi.fn(async () => {
  384. throw new Error("bind failed");
  385. });
  386. const upsertWorkspaceTab = vi.fn();
  387. const disposeRemoteWorkspaceSession = vi.fn(async () => undefined);
  388. const commitRemoteWorkspaceSessionMutation = vi.fn(async (mutation) => mutation.entry);
  389. const toast = vi.fn();
  390. await reconnectRemoteWorkspaceHistoryEntry({
  391. sessionEntry,
  392. activateTabByPath: vi.fn(() => true),
  393. setReconnectingRemoteWorkspaceKeys: vi.fn((updater) => updater([])),
  394. loadCredential: vi.fn(async () => null),
  395. connectRemoteWorkspaceTarget: vi.fn(async () => "session-1"),
  396. resolveRemoteWorkspaceCanonicalPath: vi.fn(async () => "/home/dev"),
  397. disposeRemoteWorkspaceSession,
  398. bindRemoteWorkspaceSessionContext,
  399. bindRemoteWorkspacePath: vi.fn(),
  400. bindRemoteWorkspaceIdentity: vi.fn(),
  401. upsertWorkspaceTab,
  402. commitRemoteWorkspaceSessionMutation,
  403. getRemoteSessions: () => [sessionEntry],
  404. logger: { warn: vi.fn() },
  405. toast,
  406. });
  407. expect(disposeRemoteWorkspaceSession).toHaveBeenCalledWith("session-1");
  408. expect(upsertWorkspaceTab).not.toHaveBeenCalled();
  409. expect(commitRemoteWorkspaceSessionMutation).toHaveBeenCalledTimes(1);
  410. expect(commitRemoteWorkspaceSessionMutation.mock.calls[0]?.[0]?.entry).toMatchObject({
  411. lastConnectionStatus: "failed",
  412. lastConnectionError: "bind failed",
  413. });
  414. expect(toast).toHaveBeenCalledWith("bind failed");
  415. });
  416. it("用户在 bind main context 等待期间移除 tab 时,不回填 tab 并回收 session", async () => {
  417. // 回归锁定:保留校验与 upsertWorkspaceTab 之间不能再有 await,
  418. // 否则校验通过后用户在 bind 等待 ready ACK 期间移除 workspace,仍会被重新加回并落库 connected。
  419. const target = { kind: "docker" as const, container: "demo" };
  420. const sessionEntry = createRemoteWorkspaceSessionEntry({
  421. workspacePath: "/dev",
  422. workspaceIdentity: buildRemoteWorkspaceIdentity("/dev", target),
  423. target,
  424. });
  425. let workspaceTabPresent = true;
  426. const shouldKeepReconnectedWorkspace = vi.fn(() => workspaceTabPresent);
  427. const bindRemoteWorkspaceSessionContext = vi.fn(async () => {
  428. workspaceTabPresent = false;
  429. });
  430. const upsertWorkspaceTab = vi.fn();
  431. const disposeRemoteWorkspaceSession = vi.fn(async () => undefined);
  432. const commitRemoteWorkspaceSessionMutation = vi.fn(async (mutation) => mutation.entry);
  433. await reconnectRemoteWorkspaceHistoryEntry({
  434. sessionEntry,
  435. activateTabByPath: vi.fn(() => true),
  436. setReconnectingRemoteWorkspaceKeys: vi.fn((updater) => updater([])),
  437. loadCredential: vi.fn(async () => null),
  438. connectRemoteWorkspaceTarget: vi.fn(async () => "session-1"),
  439. resolveRemoteWorkspaceCanonicalPath: vi.fn(async () => "/home/dev"),
  440. disposeRemoteWorkspaceSession,
  441. bindRemoteWorkspaceSessionContext,
  442. bindRemoteWorkspacePath: vi.fn(),
  443. bindRemoteWorkspaceIdentity: vi.fn(),
  444. upsertWorkspaceTab,
  445. commitRemoteWorkspaceSessionMutation,
  446. getRemoteSessions: () => [sessionEntry],
  447. logger: { warn: vi.fn() },
  448. toast: vi.fn(),
  449. shouldKeepReconnectedWorkspace,
  450. });
  451. expect(bindRemoteWorkspaceSessionContext).toHaveBeenCalledTimes(1);
  452. expect(shouldKeepReconnectedWorkspace.mock.invocationCallOrder[0]).toBeGreaterThan(
  453. bindRemoteWorkspaceSessionContext.mock.invocationCallOrder[0]!,
  454. );
  455. expect(upsertWorkspaceTab).not.toHaveBeenCalled();
  456. expect(disposeRemoteWorkspaceSession).toHaveBeenCalledWith("session-1");
  457. expect(commitRemoteWorkspaceSessionMutation).not.toHaveBeenCalled();
  458. });
  459. it("reuses initiator credentials and reports Host ready before sibling initialization", async () => {
  460. const activateTabByPath = vi.fn(() => true);
  461. const setReconnectingRemoteWorkspaceKeys = vi.fn((updater) => updater([]));
  462. const loadCredential = vi.fn(async () => {
  463. throw new Error("sibling credential must not be loaded");
  464. });
  465. const connectRemoteWorkspaceTarget = vi.fn(async () => "session-1");
  466. const onSshHostReady = vi.fn();
  467. const resolveRemoteWorkspaceCanonicalPath = vi.fn(async () => {
  468. expect(onSshHostReady).toHaveBeenCalledWith({
  469. password: "initiator-password",
  470. privateKeyPassphrase: null,
  471. });
  472. return "/repo/b";
  473. });
  474. const sessionEntry = createRemoteWorkspaceSessionEntry({
  475. workspacePath: "/repo/b",
  476. workspaceIdentity: "remote:ssh:root@mac-studio:/repo/b",
  477. target: {
  478. kind: "ssh",
  479. host: "mac-studio",
  480. username: "root",
  481. passwordCredentialKey: "credential-b",
  482. },
  483. });
  484. await reconnectRemoteWorkspaceHistoryEntry({
  485. sessionEntry,
  486. activateTabByPath,
  487. setReconnectingRemoteWorkspaceKeys,
  488. loadCredential,
  489. connectRemoteWorkspaceTarget,
  490. resolveRemoteWorkspaceCanonicalPath,
  491. disposeRemoteWorkspaceSession: vi.fn(async () => undefined),
  492. bindRemoteWorkspaceSessionContext: vi.fn(async () => undefined),
  493. bindRemoteWorkspacePath: vi.fn(),
  494. bindRemoteWorkspaceIdentity: vi.fn(),
  495. upsertWorkspaceTab: vi.fn(),
  496. commitRemoteWorkspaceSessionMutation: vi.fn(async (mutation) => mutation.entry),
  497. getRemoteSessions: () => [sessionEntry],
  498. logger: { warn: vi.fn() },
  499. toast: vi.fn(),
  500. options: {
  501. sshCredentialsOverride: {
  502. password: "initiator-password",
  503. privateKeyPassphrase: null,
  504. },
  505. onSshHostReady,
  506. },
  507. });
  508. expect(loadCredential).not.toHaveBeenCalled();
  509. expect(connectRemoteWorkspaceTarget).toHaveBeenCalledWith(
  510. expect.objectContaining({ password: "initiator-password" }),
  511. undefined,
  512. expect.objectContaining({ workspaceIdentity: sessionEntry.workspaceIdentity }),
  513. );
  514. });
  515. it("rejects when mobile reconnect needs an explicit failure result", async () => {
  516. const activateTabByPath = vi.fn(() => true);
  517. const setReconnectingRemoteWorkspaceKeys = vi.fn((updater) => {
  518. updater([]);
  519. updater(["remote:docker:demo:/workspace/demo"]);
  520. });
  521. const loadCredential = vi.fn(async () => null);
  522. const connectRemoteWorkspaceTarget = vi.fn(async () => {
  523. throw new Error("ssh closed");
  524. });
  525. const resolveRemoteWorkspaceCanonicalPath = vi.fn(async () => "/workspace/demo");
  526. const disposeRemoteWorkspaceSession = vi.fn(async () => undefined);
  527. const bindWorkspacePath = vi.fn();
  528. const bindWorkspaceIdentity = vi.fn();
  529. const upsertWorkspaceTab = vi.fn();
  530. const commitRemoteWorkspaceSessionMutation = vi.fn(async (mutation) => mutation.entry);
  531. const warn = vi.fn();
  532. const toast = vi.fn();
  533. const sessionEntry = createRemoteWorkspaceSessionEntry();
  534. await expect(
  535. reconnectRemoteWorkspaceHistoryEntry({
  536. sessionEntry,
  537. activateTabByPath,
  538. setReconnectingRemoteWorkspaceKeys,
  539. loadCredential,
  540. connectRemoteWorkspaceTarget,
  541. resolveRemoteWorkspaceCanonicalPath,
  542. disposeRemoteWorkspaceSession,
  543. bindRemoteWorkspaceSessionContext: vi.fn(async () => undefined),
  544. bindRemoteWorkspacePath: bindWorkspacePath,
  545. bindRemoteWorkspaceIdentity: bindWorkspaceIdentity,
  546. upsertWorkspaceTab,
  547. commitRemoteWorkspaceSessionMutation,
  548. getRemoteSessions: () => [sessionEntry],
  549. logger: { warn },
  550. toast,
  551. options: {
  552. showErrorToast: false,
  553. throwOnFailure: true,
  554. },
  555. }),
  556. ).rejects.toThrow("ssh closed");
  557. expect(commitRemoteWorkspaceSessionMutation).toHaveBeenCalledTimes(1);
  558. expect(toast).not.toHaveBeenCalled();
  559. });
  560. it("passes reconnect request id to the platform connection", async () => {
  561. const activateTabByPath = vi.fn(() => true);
  562. const setReconnectingRemoteWorkspaceKeys = vi.fn((updater) => {
  563. updater([]);
  564. updater(["remote:docker:demo:/workspace/demo"]);
  565. });
  566. const loadCredential = vi.fn(async () => null);
  567. const connectRemoteWorkspaceTarget = vi.fn(async () => "session-1");
  568. const resolveRemoteWorkspaceCanonicalPath = vi.fn(async () => "/workspace/demo");
  569. const disposeRemoteWorkspaceSession = vi.fn(async () => undefined);
  570. const bindWorkspacePath = vi.fn();
  571. const bindWorkspaceIdentity = vi.fn();
  572. const upsertWorkspaceTab = vi.fn();
  573. const commitRemoteWorkspaceSessionMutation = vi.fn(async (mutation) => mutation.entry);
  574. const warn = vi.fn();
  575. const toast = vi.fn();
  576. const sessionEntry = createRemoteWorkspaceSessionEntry();
  577. await reconnectRemoteWorkspaceHistoryEntry({
  578. sessionEntry,
  579. activateTabByPath,
  580. setReconnectingRemoteWorkspaceKeys,
  581. loadCredential,
  582. connectRemoteWorkspaceTarget,
  583. resolveRemoteWorkspaceCanonicalPath,
  584. disposeRemoteWorkspaceSession,
  585. bindRemoteWorkspaceSessionContext: vi.fn(async () => undefined),
  586. bindRemoteWorkspacePath: bindWorkspacePath,
  587. bindRemoteWorkspaceIdentity: bindWorkspaceIdentity,
  588. upsertWorkspaceTab,
  589. commitRemoteWorkspaceSessionMutation,
  590. getRemoteSessions: () => [sessionEntry],
  591. logger: { warn },
  592. toast,
  593. options: {
  594. requestId: "request-1",
  595. },
  596. });
  597. expect(connectRemoteWorkspaceTarget).toHaveBeenCalledWith(
  598. {
  599. kind: "docker",
  600. container: "demo",
  601. },
  602. "request-1",
  603. {
  604. workspacePath: "/workspace/demo",
  605. workspaceIdentity: sessionEntry.workspaceIdentity,
  606. connectTrigger: "reconnect",
  607. },
  608. );
  609. });
  610. it("rehydrates SSH private key passphrase from credential store during reconnect", async () => {
  611. const activateTabByPath = vi.fn(() => true);
  612. const setReconnectingRemoteWorkspaceKeys = vi.fn((updater) => {
  613. updater([]);
  614. updater(["remote:ssh:demo.internal:22:root:/workspace/demo"]);
  615. });
  616. const loadCredential = vi.fn(async (key: string) => {
  617. if (key.endsWith(":password")) {
  618. return null;
  619. }
  620. if (key.endsWith(":private-key-passphrase")) {
  621. return "key-secret";
  622. }
  623. return null;
  624. });
  625. const connectRemoteWorkspaceTarget = vi.fn(async () => "session-1");
  626. const resolveRemoteWorkspaceCanonicalPath = vi.fn(async () => "/workspace/demo");
  627. const disposeRemoteWorkspaceSession = vi.fn(async () => undefined);
  628. const bindWorkspacePath = vi.fn();
  629. const bindWorkspaceIdentity = vi.fn();
  630. const upsertWorkspaceTab = vi.fn();
  631. const commitRemoteWorkspaceSessionMutation = vi.fn(async (mutation) => mutation.entry);
  632. const warn = vi.fn();
  633. const toast = vi.fn();
  634. const sessionEntry = {
  635. kind: "remote" as const,
  636. workspacePath: "/workspace/demo",
  637. workspaceIdentity: "remote:ssh:demo.internal:22:root:/workspace/demo",
  638. target: {
  639. kind: "ssh" as const,
  640. host: "demo.internal",
  641. port: 22,
  642. username: "root",
  643. privateKeyPath: "~/.ssh/id_ed25519",
  644. privateKeyPassphraseCredentialKey:
  645. "remote-workspace:remote:ssh:demo.internal:22:root:/workspace/demo:private-key-passphrase",
  646. },
  647. lastOpenedAt: 10,
  648. lastConnectionStatus: "failed" as const,
  649. };
  650. await reconnectRemoteWorkspaceHistoryEntry({
  651. sessionEntry,
  652. activateTabByPath,
  653. setReconnectingRemoteWorkspaceKeys,
  654. loadCredential,
  655. connectRemoteWorkspaceTarget,
  656. resolveRemoteWorkspaceCanonicalPath,
  657. disposeRemoteWorkspaceSession,
  658. bindRemoteWorkspaceSessionContext: vi.fn(async () => undefined),
  659. bindRemoteWorkspacePath: bindWorkspacePath,
  660. bindRemoteWorkspaceIdentity: bindWorkspaceIdentity,
  661. upsertWorkspaceTab,
  662. commitRemoteWorkspaceSessionMutation,
  663. getRemoteSessions: () => [sessionEntry],
  664. logger: { warn },
  665. toast,
  666. });
  667. expect(connectRemoteWorkspaceTarget).toHaveBeenCalledWith(
  668. {
  669. kind: "ssh",
  670. host: "demo.internal",
  671. port: 22,
  672. username: "root",
  673. privateKeyPath: "~/.ssh/id_ed25519",
  674. privateKeyPassphrase: "key-secret",
  675. },
  676. undefined,
  677. {
  678. workspacePath: "/workspace/demo",
  679. workspaceIdentity: "remote:ssh:demo.internal:22:root:/workspace/demo",
  680. connectTrigger: "reconnect",
  681. },
  682. );
  683. expect(upsertWorkspaceTab).toHaveBeenCalledWith("/workspace/demo", {
  684. remoteSessionId: "session-1",
  685. remoteTarget: {
  686. kind: "ssh",
  687. host: "demo.internal",
  688. port: 22,
  689. username: "root",
  690. privateKeyPath: "~/.ssh/id_ed25519",
  691. },
  692. workspaceIdentity: "remote:ssh:demo.internal:22:root:/workspace/demo",
  693. });
  694. });
  695. it("rehydrates server token from credential store during reconnect", async () => {
  696. const activateTabByPath = vi.fn(() => true);
  697. const setReconnectingRemoteWorkspaceKeys = vi.fn((updater) => {
  698. updater([]);
  699. updater(["remote:server:studio:/workspace/demo"]);
  700. });
  701. const loadCredential = vi.fn(async (key: string) =>
  702. key.endsWith(":server-token") ? "server-secret" : null,
  703. );
  704. const connectRemoteWorkspaceTarget = vi.fn(async () => "session-1");
  705. const resolveRemoteWorkspaceCanonicalPath = vi.fn(async () => "/workspace/demo");
  706. const disposeRemoteWorkspaceSession = vi.fn(async () => undefined);
  707. const bindWorkspacePath = vi.fn();
  708. const bindWorkspaceIdentity = vi.fn();
  709. const upsertWorkspaceTab = vi.fn();
  710. const commitRemoteWorkspaceSessionMutation = vi.fn(async (mutation) => mutation.entry);
  711. const warn = vi.fn();
  712. const toast = vi.fn();
  713. const sessionEntry = {
  714. kind: "remote" as const,
  715. workspacePath: "/workspace/demo",
  716. workspaceIdentity: "remote:server:studio:/workspace/demo",
  717. target: {
  718. kind: "server" as const,
  719. url: "https://studio.example.com",
  720. serverId: "studio",
  721. tokenCredentialKey: "remote-workspace:remote:server:studio:/workspace/demo:server-token",
  722. },
  723. lastOpenedAt: 10,
  724. lastConnectionStatus: "failed" as const,
  725. };
  726. await reconnectRemoteWorkspaceHistoryEntry({
  727. sessionEntry,
  728. activateTabByPath,
  729. setReconnectingRemoteWorkspaceKeys,
  730. loadCredential,
  731. connectRemoteWorkspaceTarget,
  732. resolveRemoteWorkspaceCanonicalPath,
  733. disposeRemoteWorkspaceSession,
  734. bindRemoteWorkspaceSessionContext: vi.fn(async () => undefined),
  735. bindRemoteWorkspacePath: bindWorkspacePath,
  736. bindRemoteWorkspaceIdentity: bindWorkspaceIdentity,
  737. upsertWorkspaceTab,
  738. commitRemoteWorkspaceSessionMutation,
  739. getRemoteSessions: () => [sessionEntry],
  740. logger: { warn },
  741. toast,
  742. });
  743. expect(connectRemoteWorkspaceTarget).toHaveBeenCalledWith(
  744. {
  745. kind: "server",
  746. url: "https://studio.example.com",
  747. serverId: "studio",
  748. token: "server-secret",
  749. },
  750. undefined,
  751. {
  752. workspacePath: "/workspace/demo",
  753. workspaceIdentity: "remote:server:studio:/workspace/demo",
  754. connectTrigger: "reconnect",
  755. },
  756. );
  757. });
  758. it("disposes session and skips addTab when workspace was removed during reconnect", async () => {
  759. const activateTabByPath = vi.fn(() => true);
  760. const setReconnectingRemoteWorkspaceKeys = vi.fn((updater) => {
  761. updater([]);
  762. updater(["remote:docker:demo:/workspace/demo"]);
  763. });
  764. const loadCredential = vi.fn(async () => null);
  765. const connectRemoteWorkspaceTarget = vi.fn(async () => "session-1");
  766. const resolveRemoteWorkspaceCanonicalPath = vi.fn(async () => "/workspace/demo");
  767. const disposeRemoteWorkspaceSession = vi.fn(async () => undefined);
  768. const bindWorkspacePath = vi.fn();
  769. const bindWorkspaceIdentity = vi.fn();
  770. const upsertWorkspaceTab = vi.fn();
  771. const commitRemoteWorkspaceSessionMutation = vi.fn(async (mutation) => mutation.entry);
  772. const warn = vi.fn();
  773. const toast = vi.fn();
  774. const sessionEntry = {
  775. kind: "remote" as const,
  776. workspacePath: "/workspace/demo",
  777. target: {
  778. kind: "docker" as const,
  779. container: "demo",
  780. },
  781. lastOpenedAt: 10,
  782. lastConnectionStatus: "failed" as const,
  783. };
  784. await reconnectRemoteWorkspaceHistoryEntry({
  785. sessionEntry,
  786. activateTabByPath,
  787. setReconnectingRemoteWorkspaceKeys,
  788. loadCredential,
  789. connectRemoteWorkspaceTarget,
  790. resolveRemoteWorkspaceCanonicalPath,
  791. disposeRemoteWorkspaceSession,
  792. bindRemoteWorkspaceSessionContext: vi.fn(async () => undefined),
  793. bindRemoteWorkspacePath: bindWorkspacePath,
  794. bindRemoteWorkspaceIdentity: bindWorkspaceIdentity,
  795. upsertWorkspaceTab,
  796. commitRemoteWorkspaceSessionMutation,
  797. getRemoteSessions: () => [sessionEntry],
  798. logger: { warn },
  799. toast,
  800. shouldKeepReconnectedWorkspace: () => false,
  801. });
  802. expect(disposeRemoteWorkspaceSession).toHaveBeenCalledWith("session-1");
  803. expect(upsertWorkspaceTab).not.toHaveBeenCalled();
  804. expect(bindWorkspacePath).not.toHaveBeenCalled();
  805. expect(bindWorkspaceIdentity).not.toHaveBeenCalled();
  806. expect(commitRemoteWorkspaceSessionMutation).not.toHaveBeenCalled();
  807. expect(toast).not.toHaveBeenCalled();
  808. expect(warn).toHaveBeenCalledWith(
  809. "[Root] 远程 workspace 在重连过程中已被移除,跳过恢复并回收 session",
  810. expect.objectContaining({
  811. workspacePath: "/workspace/demo",
  812. }),
  813. );
  814. });
  815. it("skips workspace activation for background reconnect while still updating tab metadata", async () => {
  816. const activateTabByPath = vi.fn(() => true);
  817. const setReconnectingRemoteWorkspaceKeys = vi.fn((updater) => {
  818. updater([]);
  819. updater(["remote:docker:demo:/workspace/demo"]);
  820. });
  821. const loadCredential = vi.fn(async () => null);
  822. const connectRemoteWorkspaceTarget = vi.fn(async () => "session-1");
  823. const resolveRemoteWorkspaceCanonicalPath = vi.fn(async () => "/workspace/demo");
  824. const disposeRemoteWorkspaceSession = vi.fn(async () => undefined);
  825. const bindWorkspacePath = vi.fn();
  826. const bindWorkspaceIdentity = vi.fn();
  827. const upsertWorkspaceTab = vi.fn();
  828. const commitRemoteWorkspaceSessionMutation = vi.fn(async (mutation) => mutation.entry);
  829. const warn = vi.fn();
  830. const toast = vi.fn();
  831. const sessionEntry = {
  832. kind: "remote" as const,
  833. workspacePath: "/workspace/demo",
  834. target: {
  835. kind: "docker" as const,
  836. container: "demo",
  837. },
  838. lastOpenedAt: 10,
  839. lastConnectionStatus: "failed" as const,
  840. };
  841. await reconnectRemoteWorkspaceHistoryEntry({
  842. sessionEntry,
  843. activateTabByPath,
  844. setReconnectingRemoteWorkspaceKeys,
  845. loadCredential,
  846. connectRemoteWorkspaceTarget,
  847. resolveRemoteWorkspaceCanonicalPath,
  848. disposeRemoteWorkspaceSession,
  849. bindRemoteWorkspaceSessionContext: vi.fn(async () => undefined),
  850. bindRemoteWorkspacePath: bindWorkspacePath,
  851. bindRemoteWorkspaceIdentity: bindWorkspaceIdentity,
  852. upsertWorkspaceTab,
  853. commitRemoteWorkspaceSessionMutation,
  854. getRemoteSessions: () => [sessionEntry],
  855. logger: { warn },
  856. toast,
  857. options: {
  858. activateWorkspaceAfterReconnect: false,
  859. },
  860. });
  861. const expectedWorkspaceIdentity = buildRemoteWorkspaceIdentity("/workspace/demo", {
  862. kind: "docker",
  863. container: "demo",
  864. });
  865. expect(activateTabByPath).not.toHaveBeenCalled();
  866. expect(upsertWorkspaceTab).toHaveBeenCalledWith("/workspace/demo", {
  867. remoteSessionId: "session-1",
  868. remoteTarget: {
  869. kind: "docker",
  870. container: "demo",
  871. },
  872. workspaceIdentity: expectedWorkspaceIdentity,
  873. });
  874. expect(commitRemoteWorkspaceSessionMutation).toHaveBeenCalledTimes(1);
  875. });
  876. });
  877. describe("selectRemoteWorkspaceProjectFromDialog", () => {
  878. it("commits the remote draft before task-list refresh settles", async () => {
  879. const target = {
  880. kind: "docker" as const,
  881. container: "demo",
  882. };
  883. const workspacePath = "/workspace/demo";
  884. const workspaceIdentity = buildRemoteWorkspaceIdentity(workspacePath, target);
  885. let resolveRefresh!: () => void;
  886. const pendingRefresh = new Promise<void>((resolve) => {
  887. resolveRefresh = resolve;
  888. });
  889. const onWorkspaceActivated = vi.fn();
  890. let selectionSettled = false;
  891. const selection = selectRemoteWorkspaceProjectFromDialog({
  892. canUseRemoteWorkspace: true,
  893. sessionId: "session-1",
  894. path: workspacePath,
  895. loadingMessage: "loading",
  896. getRemoteWorkspaceSession: () => ({
  897. sessionId: "session-1",
  898. target,
  899. services: {} as never,
  900. }),
  901. getWorkspaceTabs: () => [],
  902. resolveRemoteWorkspaceCanonicalPath: vi.fn(async () => workspacePath),
  903. activateTabByPath: vi.fn(() => false),
  904. handleCancelRemoteProject: vi.fn(async () => undefined),
  905. bindRemoteWorkspaceSessionContext: vi.fn(async () => undefined),
  906. commitRemoteWorkspaceSessionMutation: vi.fn(async (mutation) => mutation.entry),
  907. getRemoteSessions: () => [],
  908. bindRemoteWorkspacePath: vi.fn(),
  909. bindRemoteWorkspaceIdentity: vi.fn(),
  910. addTab: vi.fn(),
  911. onWorkspaceActivated,
  912. refreshPinnedTasks: vi.fn(() => pendingRefresh),
  913. refreshTimelineTasks: vi.fn(() => pendingRefresh),
  914. }).then(() => {
  915. selectionSettled = true;
  916. });
  917. await vi.waitFor(() => {
  918. expect(onWorkspaceActivated).toHaveBeenCalledWith({
  919. workspacePath,
  920. workspaceIdentity,
  921. });
  922. });
  923. expect(selectionSettled).toBe(false);
  924. resolveRefresh();
  925. await selection;
  926. expect(selectionSettled).toBe(true);
  927. });
  928. it("attaches the new session to an existing disconnected workspace tab", async () => {
  929. const target = {
  930. kind: "docker" as const,
  931. container: "demo",
  932. };
  933. const workspacePath = "/workspace/demo";
  934. const workspaceIdentity = buildRemoteWorkspaceIdentity(workspacePath, target);
  935. const remoteSession = {
  936. sessionId: "session-1",
  937. target,
  938. services: {} as never,
  939. };
  940. const existingDisconnectedTab = createWorkspaceTab({
  941. workspacePath,
  942. workspaceIdentity,
  943. });
  944. const activateTabByPath = vi.fn(() => true);
  945. const handleCancelRemoteProject = vi.fn(async () => undefined);
  946. const commitRemoteWorkspaceSessionMutation = vi.fn(async (mutation) => mutation.entry);
  947. const bindWorkspacePath = vi.fn();
  948. const bindWorkspaceIdentity = vi.fn();
  949. const addTab = vi.fn();
  950. const refreshPinnedTasks = vi.fn(async () => undefined);
  951. const refreshTimelineTasks = vi.fn(async () => undefined);
  952. const localWorkspacePath = "/Users/alice/demo";
  953. await selectRemoteWorkspaceProjectFromDialog({
  954. canUseRemoteWorkspace: true,
  955. sessionId: remoteSession.sessionId,
  956. path: workspacePath,
  957. localWorkspacePath,
  958. loadingMessage: "loading",
  959. getRemoteWorkspaceSession: () => remoteSession,
  960. getWorkspaceTabs: () => [existingDisconnectedTab],
  961. resolveRemoteWorkspaceCanonicalPath: vi.fn(async () => workspacePath),
  962. activateTabByPath,
  963. handleCancelRemoteProject,
  964. bindRemoteWorkspaceSessionContext: vi.fn(async () => undefined),
  965. commitRemoteWorkspaceSessionMutation,
  966. getRemoteSessions: () => [
  967. createRemoteWorkspaceSessionEntry({
  968. workspacePath,
  969. workspaceIdentity,
  970. target,
  971. lastConnectionStatus: "failed",
  972. }),
  973. ],
  974. bindRemoteWorkspacePath: bindWorkspacePath,
  975. bindRemoteWorkspaceIdentity: bindWorkspaceIdentity,
  976. addTab,
  977. refreshPinnedTasks,
  978. refreshTimelineTasks,
  979. } as Parameters<typeof selectRemoteWorkspaceProjectFromDialog>[0] & {
  980. localWorkspacePath: string;
  981. });
  982. expect(activateTabByPath).not.toHaveBeenCalled();
  983. expect(handleCancelRemoteProject).not.toHaveBeenCalled();
  984. expect(bindWorkspacePath).toHaveBeenCalledWith(workspacePath, remoteSession.sessionId);
  985. expect(bindWorkspaceIdentity).toHaveBeenCalledWith(workspaceIdentity, remoteSession.sessionId);
  986. expect(addTab).toHaveBeenCalledWith(workspacePath, {
  987. remoteSessionId: remoteSession.sessionId,
  988. remoteTarget: target,
  989. workspaceIdentity,
  990. localWorkspacePath,
  991. });
  992. expect(commitRemoteWorkspaceSessionMutation).toHaveBeenCalledTimes(1);
  993. const committedMutation = commitRemoteWorkspaceSessionMutation.mock.calls[0]?.[0];
  994. expect(committedMutation).toBeDefined();
  995. const committedEntry = committedMutation?.entry as { localWorkspacePath?: string } | undefined;
  996. expect(committedEntry).toBeDefined();
  997. expect(committedEntry?.localWorkspacePath).toBe(localWorkspacePath);
  998. expect(refreshPinnedTasks).toHaveBeenCalledWith({
  999. sessionId: remoteSession.sessionId,
  1000. workspacePath,
  1001. workspaceIdentity,
  1002. });
  1003. expect(refreshTimelineTasks).toHaveBeenCalledWith({
  1004. sessionId: remoteSession.sessionId,
  1005. workspacePath,
  1006. workspaceIdentity,
  1007. });
  1008. });
  1009. it("提交 connected 历史与 addTab 之前,先把 canonical context 绑定到 main 的 logical session", async () => {
  1010. // Bugfix 回归(3.12.0 手机远控连不上 WSL 项目):新建连接不带 context,main descriptor 停留在 "/",
  1011. // 且 UI 用未解析的 {kind:"wsl"} 算出的 identity 与 Host 用解析后 target 算出的不同。
  1012. // 选目录后必须把 tab 将要使用的 path/identity 绑定回 main,手机桥接的三元校验才能通过。
  1013. const connectionTarget = { kind: "wsl" as const };
  1014. const workspacePath = "/home/dev";
  1015. const workspaceIdentity = buildRemoteWorkspaceIdentity(workspacePath, connectionTarget);
  1016. const bindRemoteWorkspaceSessionContext = vi.fn(async () => undefined);
  1017. const commitRemoteWorkspaceSessionMutation = vi.fn(async (mutation) => mutation.entry);
  1018. const handleCancelRemoteProject = vi.fn(async () => undefined);
  1019. const addTab = vi.fn();
  1020. await selectRemoteWorkspaceProjectFromDialog({
  1021. canUseRemoteWorkspace: true,
  1022. sessionId: "session-1",
  1023. path: "/home/dev/",
  1024. loadingMessage: "loading",
  1025. connectionTarget,
  1026. getRemoteWorkspaceSession: () => ({
  1027. sessionId: "session-1",
  1028. // main 回传给 renderer store 的是解析后的 WSL target
  1029. target: { kind: "wsl", distro: "Ubuntu", user: "dev" },
  1030. services: {} as never,
  1031. }),
  1032. getWorkspaceTabs: () => [],
  1033. resolveRemoteWorkspaceCanonicalPath: vi.fn(async () => workspacePath),
  1034. activateTabByPath: vi.fn(() => false),
  1035. handleCancelRemoteProject,
  1036. bindRemoteWorkspaceSessionContext,
  1037. commitRemoteWorkspaceSessionMutation,
  1038. getRemoteSessions: () => [],
  1039. bindRemoteWorkspacePath: vi.fn(),
  1040. bindRemoteWorkspaceIdentity: vi.fn(),
  1041. addTab,
  1042. refreshPinnedTasks: vi.fn(async () => undefined),
  1043. refreshTimelineTasks: vi.fn(async () => undefined),
  1044. });
  1045. expect(workspaceIdentity).toBe("remote:wsl:default:/home/dev");
  1046. expect(bindRemoteWorkspaceSessionContext).toHaveBeenCalledWith({
  1047. sessionId: "session-1",
  1048. workspacePath,
  1049. workspaceIdentity,
  1050. });
  1051. expect(bindRemoteWorkspaceSessionContext.mock.invocationCallOrder[0]).toBeLessThan(
  1052. commitRemoteWorkspaceSessionMutation.mock.invocationCallOrder[0]!,
  1053. );
  1054. expect(bindRemoteWorkspaceSessionContext.mock.invocationCallOrder[0]).toBeLessThan(
  1055. addTab.mock.invocationCallOrder[0]!,
  1056. );
  1057. expect(addTab).toHaveBeenCalledWith(workspacePath, {
  1058. remoteSessionId: "session-1",
  1059. remoteTarget: connectionTarget,
  1060. workspaceIdentity,
  1061. localWorkspacePath: undefined,
  1062. });
  1063. expect(handleCancelRemoteProject).not.toHaveBeenCalled();
  1064. });
  1065. it("main 绑定 canonical context 失败时回收 session,不落库也不建 tab", async () => {
  1066. // descriptor 与 tab 不一致的 session 正是手机桥接被拒的根源,绑定失败必须 fail-closed。
  1067. const target = { kind: "docker" as const, container: "demo" };
  1068. const workspacePath = "/workspace/demo";
  1069. const bindRemoteWorkspaceSessionContext = vi.fn(async () => {
  1070. throw new Error("bind failed");
  1071. });
  1072. const commitRemoteWorkspaceSessionMutation = vi.fn(async (mutation) => mutation.entry);
  1073. const handleCancelRemoteProject = vi.fn(async () => undefined);
  1074. const addTab = vi.fn();
  1075. await expect(
  1076. selectRemoteWorkspaceProjectFromDialog({
  1077. canUseRemoteWorkspace: true,
  1078. sessionId: "session-1",
  1079. path: workspacePath,
  1080. loadingMessage: "loading",
  1081. getRemoteWorkspaceSession: () => ({
  1082. sessionId: "session-1",
  1083. target,
  1084. services: {} as never,
  1085. }),
  1086. getWorkspaceTabs: () => [],
  1087. resolveRemoteWorkspaceCanonicalPath: vi.fn(async () => workspacePath),
  1088. activateTabByPath: vi.fn(() => false),
  1089. handleCancelRemoteProject,
  1090. bindRemoteWorkspaceSessionContext,
  1091. commitRemoteWorkspaceSessionMutation,
  1092. getRemoteSessions: () => [],
  1093. bindRemoteWorkspacePath: vi.fn(),
  1094. bindRemoteWorkspaceIdentity: vi.fn(),
  1095. addTab,
  1096. refreshPinnedTasks: vi.fn(async () => undefined),
  1097. refreshTimelineTasks: vi.fn(async () => undefined),
  1098. }),
  1099. ).rejects.toThrow("bind failed");
  1100. expect(handleCancelRemoteProject).toHaveBeenCalledWith("session-1");
  1101. expect(commitRemoteWorkspaceSessionMutation).not.toHaveBeenCalled();
  1102. expect(addTab).not.toHaveBeenCalled();
  1103. });
  1104. it("uses the temporary SSH target for credential persistence but strips it from the tab", async () => {
  1105. const connectionTarget = {
  1106. kind: "ssh" as const,
  1107. host: "demo.internal",
  1108. username: "root",
  1109. password: "password-secret",
  1110. };
  1111. const sanitizedTarget = {
  1112. kind: "ssh" as const,
  1113. host: "demo.internal",
  1114. username: "root",
  1115. };
  1116. const workspacePath = "/workspace/demo";
  1117. const workspaceIdentity = buildRemoteWorkspaceIdentity(workspacePath, connectionTarget);
  1118. const commitRemoteWorkspaceSessionMutation = vi.fn(async (mutation) => mutation.entry);
  1119. const addTab = vi.fn();
  1120. await selectRemoteWorkspaceProjectFromDialog({
  1121. canUseRemoteWorkspace: true,
  1122. sessionId: "session-1",
  1123. path: workspacePath,
  1124. loadingMessage: "loading",
  1125. connectionTarget,
  1126. getRemoteWorkspaceSession: () => ({
  1127. sessionId: "session-1",
  1128. target: sanitizedTarget,
  1129. services: {} as never,
  1130. }),
  1131. getWorkspaceTabs: () => [],
  1132. resolveRemoteWorkspaceCanonicalPath: vi.fn(async () => workspacePath),
  1133. activateTabByPath: vi.fn(() => false),
  1134. handleCancelRemoteProject: vi.fn(async () => undefined),
  1135. bindRemoteWorkspaceSessionContext: vi.fn(async () => undefined),
  1136. commitRemoteWorkspaceSessionMutation,
  1137. getRemoteSessions: () => [],
  1138. bindRemoteWorkspacePath: vi.fn(),
  1139. bindRemoteWorkspaceIdentity: vi.fn(),
  1140. addTab,
  1141. refreshPinnedTasks: vi.fn(async () => undefined),
  1142. refreshTimelineTasks: vi.fn(async () => undefined),
  1143. });
  1144. expect(addTab).toHaveBeenCalledWith(workspacePath, {
  1145. remoteSessionId: "session-1",
  1146. remoteTarget: sanitizedTarget,
  1147. workspaceIdentity,
  1148. localWorkspacePath: undefined,
  1149. });
  1150. const mutation = commitRemoteWorkspaceSessionMutation.mock.calls[0]?.[0];
  1151. expect(mutation?.credentialsToSave).toEqual([
  1152. expect.objectContaining({ value: "password-secret" }),
  1153. ]);
  1154. });
  1155. });
  1156. describe("reconnectRemoteWorkspaceByKey", () => {
  1157. it("reconnects a matching workspace with caller-provided mobile options", async () => {
  1158. const sessionEntry = createRemoteWorkspaceSessionEntry();
  1159. const runReconnectRemoteWorkspace = vi.fn(async () => undefined);
  1160. await expect(
  1161. reconnectRemoteWorkspaceByKey({
  1162. workspaceKey: buildWorkspaceSessionKey(sessionEntry),
  1163. canUseRemoteWorkspace: true,
  1164. getRemoteSessions: () => [sessionEntry],
  1165. runReconnectRemoteWorkspace,
  1166. options: {
  1167. activateWorkspaceAfterReconnect: false,
  1168. showErrorToast: false,
  1169. },
  1170. }),
  1171. ).resolves.toBe(true);
  1172. expect(runReconnectRemoteWorkspace).toHaveBeenCalledWith(sessionEntry, {
  1173. activateWorkspaceAfterReconnect: false,
  1174. showErrorToast: false,
  1175. });
  1176. });
  1177. it("rejects when the workspace is not available for reconnect", async () => {
  1178. const runReconnectRemoteWorkspace = vi.fn(async () => undefined);
  1179. await expect(
  1180. reconnectRemoteWorkspaceByKey({
  1181. workspaceKey: "missing",
  1182. canUseRemoteWorkspace: true,
  1183. getRemoteSessions: () => [createRemoteWorkspaceSessionEntry()],
  1184. runReconnectRemoteWorkspace,
  1185. }),
  1186. ).rejects.toThrow("远程 workspace 不在当前窗口中,无法重连: missing");
  1187. expect(runReconnectRemoteWorkspace).not.toHaveBeenCalled();
  1188. });
  1189. });
  1190. describe("collectSshReconnectGroup", () => {
  1191. it("collects open disconnected workspaces that share the same SSH Host identity", () => {
  1192. const first = createRemoteWorkspaceSessionEntry({
  1193. workspacePath: "/repo/a",
  1194. workspaceIdentity: "remote:ssh:root@mac-studio:/repo/a",
  1195. target: {
  1196. kind: "ssh",
  1197. host: "Mac-Studio",
  1198. username: "root",
  1199. passwordCredentialKey: "credential-a",
  1200. },
  1201. });
  1202. const second = createRemoteWorkspaceSessionEntry({
  1203. workspacePath: "/repo/b",
  1204. workspaceIdentity: "remote:ssh:root@mac-studio:/repo/b",
  1205. target: {
  1206. kind: "ssh",
  1207. host: "mac-studio",
  1208. port: 22,
  1209. username: "root",
  1210. passwordCredentialKey: "credential-b",
  1211. },
  1212. });
  1213. const differentAuth = createRemoteWorkspaceSessionEntry({
  1214. workspacePath: "/repo/c",
  1215. workspaceIdentity: "remote:ssh:root@mac-studio:/repo/c",
  1216. target: {
  1217. kind: "ssh",
  1218. host: "mac-studio",
  1219. username: "root",
  1220. privateKeyPath: "/keys/id_ed25519",
  1221. },
  1222. });
  1223. expect(
  1224. collectSshReconnectGroup({
  1225. selected: first,
  1226. // 回归:持久化顺序可能和用户实际点击的 workspace 不同,initiator 仍必须排在首位。
  1227. sessions: [second, first, differentAuth],
  1228. tabs: [
  1229. createWorkspaceTab({
  1230. id: "tab-a",
  1231. workspacePath: first.workspacePath,
  1232. workspaceIdentity: first.workspaceIdentity,
  1233. }),
  1234. createWorkspaceTab({
  1235. id: "tab-b",
  1236. workspacePath: second.workspacePath,
  1237. workspaceIdentity: second.workspaceIdentity,
  1238. }),
  1239. createWorkspaceTab({
  1240. id: "tab-c",
  1241. workspacePath: differentAuth.workspacePath,
  1242. workspaceIdentity: differentAuth.workspaceIdentity,
  1243. }),
  1244. ],
  1245. }),
  1246. ).toEqual([first, second]);
  1247. });
  1248. it("does not reconnect an already connected sibling workspace", () => {
  1249. const first = createRemoteWorkspaceSessionEntry({
  1250. workspacePath: "/repo/a",
  1251. workspaceIdentity: "remote:ssh:root@mac-studio:/repo/a",
  1252. target: { kind: "ssh", host: "mac-studio", username: "root" },
  1253. });
  1254. const connected = createRemoteWorkspaceSessionEntry({
  1255. workspacePath: "/repo/b",
  1256. workspaceIdentity: "remote:ssh:root@mac-studio:/repo/b",
  1257. target: { kind: "ssh", host: "mac-studio", username: "root" },
  1258. });
  1259. expect(
  1260. collectSshReconnectGroup({
  1261. selected: first,
  1262. sessions: [first, connected],
  1263. tabs: [
  1264. createWorkspaceTab({
  1265. id: "tab-a",
  1266. workspacePath: first.workspacePath,
  1267. workspaceIdentity: first.workspaceIdentity,
  1268. }),
  1269. createWorkspaceTab({
  1270. id: "tab-b",
  1271. workspacePath: connected.workspacePath,
  1272. workspaceIdentity: connected.workspaceIdentity,
  1273. remoteSessionId: "session-b",
  1274. }),
  1275. ],
  1276. }),
  1277. ).toEqual([first]);
  1278. });
  1279. });
  1280. describe("reconnectRemoteWorkspaceGroup", () => {
  1281. it("starts sibling workspaces as soon as the initiator Host is ready", async () => {
  1282. const initiator = createRemoteWorkspaceSessionEntry({
  1283. workspacePath: "/repo/a",
  1284. workspaceIdentity: "remote:ssh:root@mac-studio:/repo/a",
  1285. target: {
  1286. kind: "ssh",
  1287. host: "mac-studio",
  1288. username: "root",
  1289. passwordCredentialKey: "credential-a",
  1290. },
  1291. });
  1292. const sibling = createRemoteWorkspaceSessionEntry({
  1293. workspacePath: "/repo/b",
  1294. workspaceIdentity: "remote:ssh:root@mac-studio:/repo/b",
  1295. target: {
  1296. kind: "ssh",
  1297. host: "mac-studio",
  1298. username: "root",
  1299. passwordCredentialKey: "credential-b",
  1300. },
  1301. });
  1302. let releaseInitiator!: () => void;
  1303. const initiatorReady = new Promise<void>((resolve) => {
  1304. releaseInitiator = resolve;
  1305. });
  1306. const reconnectEntry = vi.fn(
  1307. async (entry: RemoteWorkspaceSessionEntry, options?: ReconnectRemoteWorkspaceOptions) => {
  1308. if (entry === initiator) {
  1309. options?.onSshHostReady?.({
  1310. password: "initiator-password",
  1311. privateKeyPassphrase: null,
  1312. });
  1313. await initiatorReady;
  1314. }
  1315. return true;
  1316. },
  1317. );
  1318. const reconnectPromise = reconnectRemoteWorkspaceGroup({
  1319. selected: initiator,
  1320. reconnectGroup: [initiator, sibling],
  1321. reconnectEntry,
  1322. options: { throwOnFailure: false },
  1323. });
  1324. await vi.waitFor(() => expect(reconnectEntry).toHaveBeenCalledTimes(2));
  1325. expect(reconnectEntry).toHaveBeenNthCalledWith(
  1326. 1,
  1327. initiator,
  1328. expect.objectContaining({
  1329. throwOnFailure: true,
  1330. onSshHostReady: expect.any(Function),
  1331. }),
  1332. );
  1333. expect(reconnectEntry).toHaveBeenNthCalledWith(
  1334. 2,
  1335. sibling,
  1336. expect.objectContaining({
  1337. activateWorkspaceAfterReconnect: false,
  1338. sshCredentialsOverride: {
  1339. password: "initiator-password",
  1340. privateKeyPassphrase: null,
  1341. },
  1342. }),
  1343. );
  1344. releaseInitiator();
  1345. await reconnectPromise;
  1346. });
  1347. it("does not let a sibling retry with its credential after the initiator fails", async () => {
  1348. const initiator = createRemoteWorkspaceSessionEntry({
  1349. workspacePath: "/repo/a",
  1350. workspaceIdentity: "remote:ssh:root@mac-studio:/repo/a",
  1351. target: { kind: "ssh", host: "mac-studio", username: "root" },
  1352. });
  1353. const sibling = createRemoteWorkspaceSessionEntry({
  1354. workspacePath: "/repo/b",
  1355. workspaceIdentity: "remote:ssh:root@mac-studio:/repo/b",
  1356. target: { kind: "ssh", host: "mac-studio", username: "root" },
  1357. });
  1358. const reconnectEntry = vi.fn(async () => {
  1359. throw new Error("initiator credential rejected");
  1360. });
  1361. await expect(
  1362. reconnectRemoteWorkspaceGroup({
  1363. selected: initiator,
  1364. reconnectGroup: [initiator, sibling],
  1365. reconnectEntry,
  1366. options: { throwOnFailure: false },
  1367. }),
  1368. ).resolves.toBeUndefined();
  1369. expect(reconnectEntry).toHaveBeenCalledTimes(1);
  1370. expect(reconnectEntry).toHaveBeenCalledWith(
  1371. initiator,
  1372. expect.objectContaining({ throwOnFailure: true }),
  1373. );
  1374. });
  1375. it("does not reconnect siblings when the initiator request was skipped", async () => {
  1376. const initiator = createRemoteWorkspaceSessionEntry({
  1377. workspacePath: "/repo/a",
  1378. workspaceIdentity: "remote:ssh:root@mac-studio:/repo/a",
  1379. target: { kind: "ssh", host: "mac-studio", username: "root" },
  1380. });
  1381. const sibling = createRemoteWorkspaceSessionEntry({
  1382. workspacePath: "/repo/b",
  1383. workspaceIdentity: "remote:ssh:root@mac-studio:/repo/b",
  1384. target: { kind: "ssh", host: "mac-studio", username: "root" },
  1385. });
  1386. const reconnectEntry = vi.fn(async () => false);
  1387. await reconnectRemoteWorkspaceGroup({
  1388. selected: initiator,
  1389. reconnectGroup: [initiator, sibling],
  1390. reconnectEntry,
  1391. });
  1392. expect(reconnectEntry).toHaveBeenCalledTimes(1);
  1393. });
  1394. it("keeps sibling initialization independent after the initiator Host is ready", async () => {
  1395. const initiator = createRemoteWorkspaceSessionEntry({
  1396. workspacePath: "/repo/a",
  1397. workspaceIdentity: "remote:ssh:root@mac-studio:/repo/a",
  1398. target: { kind: "ssh", host: "mac-studio", username: "root" },
  1399. });
  1400. const sibling = createRemoteWorkspaceSessionEntry({
  1401. workspacePath: "/repo/b",
  1402. workspaceIdentity: "remote:ssh:root@mac-studio:/repo/b",
  1403. target: { kind: "ssh", host: "mac-studio", username: "root" },
  1404. });
  1405. const reconnectEntry = vi.fn(
  1406. async (entry: RemoteWorkspaceSessionEntry, options?: ReconnectRemoteWorkspaceOptions) => {
  1407. if (entry === initiator) {
  1408. options?.onSshHostReady?.({
  1409. password: "initiator-password",
  1410. privateKeyPassphrase: null,
  1411. });
  1412. throw new Error("initiator provider sync failed");
  1413. }
  1414. return true;
  1415. },
  1416. );
  1417. await expect(
  1418. reconnectRemoteWorkspaceGroup({
  1419. selected: initiator,
  1420. reconnectGroup: [initiator, sibling],
  1421. reconnectEntry,
  1422. options: { throwOnFailure: false },
  1423. }),
  1424. ).resolves.toBeUndefined();
  1425. expect(reconnectEntry).toHaveBeenCalledTimes(2);
  1426. });
  1427. });
  1428. describe("cancelPendingRemoteReconnectsForWorkspaceKeys", () => {
  1429. it("cancels and clears pending reconnect request ids for removed workspace keys", async () => {
  1430. const pendingRequestIds = new Map([
  1431. ["remote:docker:demo:/workspace/demo", "request-1"],
  1432. ["remote:docker:keep:/workspace/keep", "request-2"],
  1433. ]);
  1434. const cancelPendingRemoteConnection = vi.fn(async () => undefined);
  1435. const warn = vi.fn();
  1436. await cancelPendingRemoteReconnectsForWorkspaceKeys({
  1437. workspaceKeys: ["remote:docker:demo:/workspace/demo"],
  1438. pendingRequestIds,
  1439. cancelPendingRemoteConnection,
  1440. logger: { warn },
  1441. });
  1442. expect(cancelPendingRemoteConnection).toHaveBeenCalledWith("request-1");
  1443. expect(pendingRequestIds.has("remote:docker:demo:/workspace/demo")).toBe(false);
  1444. expect(pendingRequestIds.get("remote:docker:keep:/workspace/keep")).toBe("request-2");
  1445. expect(warn).not.toHaveBeenCalled();
  1446. });
  1447. });
  1448. describe("openRemoteWorkspaceFromHistoryEntry", () => {
  1449. it("启动恢复阶段不会自动触发重连,只有用户主动打开远程历史才会重连", async () => {
  1450. const sessionEntry = createRemoteWorkspaceSessionEntry();
  1451. const context = createOpenRemoteWorkspaceContext({
  1452. sessionEntry,
  1453. tabs: [
  1454. createWorkspaceTab({
  1455. workspacePath: sessionEntry.workspacePath,
  1456. workspaceIdentity: sessionEntry.workspaceIdentity,
  1457. }),
  1458. ],
  1459. });
  1460. // Bugfix: 这个场景验证“重连只由用户入口触发”,避免把源码实现细节固化为测试契约。
  1461. expect(context.reconnectImpl).not.toHaveBeenCalled();
  1462. expect(context.resetLogsForWorkspaceKey).not.toHaveBeenCalled();
  1463. await openRemoteWorkspaceFromHistoryEntry(context.params);
  1464. expect(context.resetLogsForWorkspaceKey).toHaveBeenCalledWith(context.workspaceKey);
  1465. expect(context.reconnectImpl).toHaveBeenCalledTimes(1);
  1466. });
  1467. it("activates existing connected workspace tab instead of reconnecting", async () => {
  1468. const sessionEntry = createRemoteWorkspaceSessionEntry();
  1469. const context = createOpenRemoteWorkspaceContext({
  1470. sessionEntry,
  1471. tabs: [
  1472. createWorkspaceTab({
  1473. workspacePath: sessionEntry.workspacePath,
  1474. workspaceIdentity: sessionEntry.workspaceIdentity,
  1475. remoteSessionId: "session-live",
  1476. }),
  1477. ],
  1478. });
  1479. await openRemoteWorkspaceFromHistoryEntry(context.params);
  1480. expect(context.activateTabByPath).toHaveBeenCalledWith("/workspace/demo", {
  1481. workspaceIdentity: "remote:docker:demo:/workspace/demo",
  1482. });
  1483. expect(context.reconnectImpl).not.toHaveBeenCalled();
  1484. expect(context.resetLogsForWorkspaceKey).not.toHaveBeenCalled();
  1485. });
  1486. it("reconnects disconnected remote history entry with selector options", async () => {
  1487. const sessionEntry = createRemoteWorkspaceSessionEntry();
  1488. const context = createOpenRemoteWorkspaceContext({
  1489. sessionEntry,
  1490. tabs: [
  1491. createWorkspaceTab({
  1492. workspacePath: sessionEntry.workspacePath,
  1493. workspaceIdentity: sessionEntry.workspaceIdentity,
  1494. }),
  1495. ],
  1496. });
  1497. await openRemoteWorkspaceFromHistoryEntry(context.params);
  1498. expect(context.inflightReconnectWorkspaceKeys.size).toBe(0);
  1499. const reconnectArgs = context.reconnectImpl.mock.calls[0]?.[0];
  1500. expect(reconnectArgs.options).toEqual({
  1501. activateWorkspaceAfterReconnect: true,
  1502. showErrorToast: true,
  1503. requestId: undefined,
  1504. });
  1505. expect(reconnectArgs.onWorkspaceActivated).toEqual(expect.any(Function));
  1506. expect(reconnectArgs.shouldKeepReconnectedWorkspace).toEqual(expect.any(Function));
  1507. });
  1508. it("commits a disconnected history tab, activation, and draft in order", async () => {
  1509. const sessionEntry = createRemoteWorkspaceSessionEntry();
  1510. const context = createOpenRemoteWorkspaceContext({
  1511. sessionEntry,
  1512. tabs: [
  1513. createWorkspaceTab({
  1514. workspacePath: sessionEntry.workspacePath,
  1515. workspaceIdentity: sessionEntry.workspaceIdentity,
  1516. }),
  1517. ],
  1518. });
  1519. const addTab = vi.fn();
  1520. const activateTabByPath = vi.fn(() => true);
  1521. const onWorkspaceActivated = vi.fn();
  1522. context.params.addTab = addTab;
  1523. context.params.activateTabByPath = activateTabByPath;
  1524. context.params.onWorkspaceActivated = onWorkspaceActivated;
  1525. context.params.reconnectImpl = reconnectRemoteWorkspaceHistoryEntry;
  1526. await openRemoteWorkspaceFromHistoryEntry(context.params);
  1527. expect(addTab).toHaveBeenCalledWith(sessionEntry.workspacePath, {
  1528. remoteSessionId: "session-1",
  1529. remoteTarget: sessionEntry.target,
  1530. workspaceIdentity: sessionEntry.workspaceIdentity,
  1531. localWorkspacePath: undefined,
  1532. });
  1533. expect(activateTabByPath).toHaveBeenCalledWith(sessionEntry.workspacePath, {
  1534. workspaceIdentity: sessionEntry.workspaceIdentity,
  1535. });
  1536. expect(onWorkspaceActivated).toHaveBeenCalledWith({
  1537. workspacePath: sessionEntry.workspacePath,
  1538. workspaceIdentity: sessionEntry.workspaceIdentity,
  1539. });
  1540. expect(addTab.mock.invocationCallOrder[0]).toBeLessThan(
  1541. activateTabByPath.mock.invocationCallOrder[0]!,
  1542. );
  1543. expect(activateTabByPath.mock.invocationCallOrder[0]).toBeLessThan(
  1544. onWorkspaceActivated.mock.invocationCallOrder[0]!,
  1545. );
  1546. });
  1547. it("skips duplicate reconnect requests while workspace is inflight", async () => {
  1548. const context = createOpenRemoteWorkspaceContext();
  1549. context.inflightReconnectWorkspaceKeys.add(context.workspaceKey);
  1550. await openRemoteWorkspaceFromHistoryEntry(context.params);
  1551. expect(context.reconnectImpl).not.toHaveBeenCalled();
  1552. expect(context.resetLogsForWorkspaceKey).not.toHaveBeenCalled();
  1553. });
  1554. it("passes keep-check callback that reflects runtime tab removal", async () => {
  1555. const sessionEntry = createRemoteWorkspaceSessionEntry({
  1556. workspaceIdentity: "remote:docker:demo:/workspace/demo",
  1557. });
  1558. const context = createOpenRemoteWorkspaceContext({
  1559. sessionEntry,
  1560. tabs: [
  1561. createWorkspaceTab({
  1562. workspacePath: sessionEntry.workspacePath,
  1563. workspaceIdentity: ` ${sessionEntry.workspaceIdentity} `,
  1564. }),
  1565. ],
  1566. });
  1567. context.params.reconnectImpl = vi.fn(async (reconnectParams) => {
  1568. const shouldKeepReconnectedWorkspace = reconnectParams.shouldKeepReconnectedWorkspace;
  1569. expect(shouldKeepReconnectedWorkspace).toEqual(expect.any(Function));
  1570. expect(
  1571. shouldKeepReconnectedWorkspace?.({
  1572. workspacePath: sessionEntry.workspacePath,
  1573. workspaceIdentity: sessionEntry.workspaceIdentity,
  1574. }),
  1575. ).toBe(true);
  1576. context.setTabs([]);
  1577. expect(
  1578. shouldKeepReconnectedWorkspace?.({
  1579. workspacePath: sessionEntry.workspacePath,
  1580. workspaceIdentity: sessionEntry.workspaceIdentity,
  1581. }),
  1582. ).toBe(false);
  1583. });
  1584. await openRemoteWorkspaceFromHistoryEntry(context.params);
  1585. expect(context.params.reconnectImpl).toHaveBeenCalledTimes(1);
  1586. });
  1587. });