desktopRemoteSessions.test.ts 76 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141
  1. import { EventEmitter } from "node:events";
  2. import { beforeEach, describe, expect, it, vi } from "vitest";
  3. import {
  4. buildRemoteWorkspaceIdentity,
  5. buildServerRemoteWorkspaceIdentity,
  6. HostMessageTypes,
  7. HostResponseTypes,
  8. InternalChannels,
  9. PlatformChannels,
  10. type RemoteTarget,
  11. } from "@zcode/shared";
  12. import { resolveBotRemoteWorkspace } from "../src/host/botRemoteWorkspaceResolver.js";
  13. import { createRemoteWorkspaceSessionManager } from "../src/main/desktopRemoteSessions.js";
  14. const { browserWindowMock, channels } = vi.hoisted(() => {
  15. const windows: Array<unknown> = [];
  16. return {
  17. channels: [] as Array<{ port1: { close: ReturnType<typeof vi.fn> }; port2: object }>,
  18. browserWindowMock: {
  19. windows,
  20. fromId: vi.fn(
  21. (id: number) =>
  22. windows.find((candidate) => (candidate as { id: number }).id === id) ?? null,
  23. ),
  24. getAllWindows: vi.fn(() => windows),
  25. },
  26. };
  27. });
  28. vi.mock("electron", () => ({
  29. BrowserWindow: browserWindowMock,
  30. MessageChannelMain: vi.fn(function MessageChannelMainMock() {
  31. const channel = {
  32. port1: {
  33. close: vi.fn(),
  34. start: vi.fn(),
  35. on: vi.fn(),
  36. once: vi.fn(),
  37. off: vi.fn(),
  38. postMessage: vi.fn(),
  39. },
  40. port2: {
  41. close: vi.fn(),
  42. start: vi.fn(),
  43. on: vi.fn(),
  44. once: vi.fn(),
  45. off: vi.fn(),
  46. postMessage: vi.fn(),
  47. },
  48. };
  49. channels.push(channel);
  50. return channel;
  51. }),
  52. }));
  53. class MockUtilityProcess extends EventEmitter {
  54. pid: number;
  55. postMessage: ReturnType<typeof vi.fn>;
  56. provisioningResult: {
  57. status: "applied" | "already-applied" | "unsupported" | "failed" | "rollback_failed";
  58. error?: string;
  59. errorCode?: string;
  60. } = { status: "applied" };
  61. constructor(pid: number) {
  62. super();
  63. this.pid = pid;
  64. this.postMessage = vi.fn((message: unknown) => {
  65. const candidate = message as {
  66. type?: string;
  67. requestId?: string;
  68. environmentKey?: string;
  69. };
  70. if (candidate.type !== HostMessageTypes.ProviderProvisioningExecute) return;
  71. queueMicrotask(() => {
  72. this.emit("message", {
  73. type: HostResponseTypes.ProviderProvisioningExecutionResult,
  74. requestId: candidate.requestId,
  75. environmentKey: candidate.environmentKey,
  76. ...this.provisioningResult,
  77. });
  78. });
  79. });
  80. }
  81. }
  82. function createWindow(id: number, webContentsId: number) {
  83. const win = {
  84. id,
  85. isDestroyed: () => false,
  86. webContents: {
  87. id: webContentsId,
  88. isDestroyed: () => false,
  89. send: vi.fn(),
  90. postMessage: vi.fn(),
  91. },
  92. };
  93. browserWindowMock.windows.push(win);
  94. return win;
  95. }
  96. const sshTarget: RemoteTarget = {
  97. kind: "ssh",
  98. host: "dev.internal",
  99. username: "developer",
  100. };
  101. function createManager(
  102. windowHostProcessMap: Map<number, MockUtilityProcess>,
  103. options?: {
  104. rendererAttachmentReadyTimeoutMs?: number;
  105. workspaceBindReadyTimeoutMs?: number;
  106. reportRemoteConnectionStateChanged?: (params: {
  107. rendererId: number;
  108. remoteKind: RemoteTarget["kind"];
  109. transition:
  110. | "connected"
  111. | "connection-closed"
  112. | "disposed"
  113. | "window-closed"
  114. | "host-exit"
  115. | "app-shutdown";
  116. }) => void;
  117. reportRemoteDisconnect?: (params: {
  118. rendererId: number;
  119. remoteKind: RemoteTarget["kind"];
  120. disconnectReason:
  121. | "connection-closed"
  122. | "disposed"
  123. | "window-closed"
  124. | "host-exit"
  125. | "app-shutdown";
  126. durationMs: number;
  127. }) => void;
  128. monotonicNowMs?: () => number;
  129. resolveWslTarget?: (
  130. target: Extract<RemoteTarget, { kind: "wsl" }>,
  131. ) => Promise<Extract<RemoteTarget, { kind: "wsl" }>>;
  132. webRemoteControlManager?: {
  133. failRemoteSession: ReturnType<typeof vi.fn>;
  134. replaceRemoteSession: ReturnType<typeof vi.fn>;
  135. };
  136. logger?: {
  137. info: ReturnType<typeof vi.fn>;
  138. warn: ReturnType<typeof vi.fn>;
  139. error: ReturnType<typeof vi.fn>;
  140. };
  141. },
  142. ) {
  143. return createRemoteWorkspaceSessionManager({
  144. logger: options?.logger ?? { info: vi.fn(), warn: vi.fn(), error: vi.fn() },
  145. windowHostProcessMap: windowHostProcessMap as never,
  146. resolveRemoteAssetDirs: () => ({}),
  147. resolveWslTarget: options?.resolveWslTarget,
  148. rendererAttachmentReadyTimeoutMs: options?.rendererAttachmentReadyTimeoutMs,
  149. workspaceBindReadyTimeoutMs: options?.workspaceBindReadyTimeoutMs,
  150. reportRemoteConnectionStateChanged: options?.reportRemoteConnectionStateChanged,
  151. reportRemoteDisconnect: options?.reportRemoteDisconnect,
  152. monotonicNowMs: options?.monotonicNowMs,
  153. webRemoteControlManagerRef: { current: options?.webRemoteControlManager ?? null },
  154. });
  155. }
  156. async function emitConnected(params: {
  157. child: MockUtilityProcess;
  158. requestId: string;
  159. remoteSessionId: string;
  160. sourceServerId?: string;
  161. reusedConnectionTarget?: RemoteTarget;
  162. target?: RemoteTarget;
  163. workspacePath?: string;
  164. workspaceIdentity?: string;
  165. workspacePurpose?: "project" | "conversation";
  166. }) {
  167. const target = params.target ?? sshTarget;
  168. const workspacePath = params.workspacePath ?? "/";
  169. params.child.emit("message", {
  170. type: HostResponseTypes.RemoteWorkspaceConnected,
  171. requestId: params.requestId,
  172. descriptor: {
  173. ...(params.sourceServerId ? { sourceServerId: params.sourceServerId } : {}),
  174. ...(params.reusedConnectionTarget
  175. ? { reusedConnectionTarget: params.reusedConnectionTarget }
  176. : {}),
  177. remoteSessionId: params.remoteSessionId,
  178. target,
  179. workspacePath,
  180. workspaceIdentity:
  181. params.workspaceIdentity ?? buildRemoteWorkspaceIdentity(workspacePath, target),
  182. ...(params.workspacePurpose ? { workspacePurpose: params.workspacePurpose } : {}),
  183. generation: 1,
  184. },
  185. });
  186. // 连接发布前会等待 Environment 首次 Provisioning attempt;测试 Host 在微任务里回包,
  187. // 这里让完整 Promise 链排空后再检查 renderer attachment。
  188. for (let index = 0; index < 6; index += 1) await Promise.resolve();
  189. }
  190. function getLatestScopedAttachment(win: ReturnType<typeof createWindow>): {
  191. attachmentId: string;
  192. sessionId: string;
  193. } {
  194. const call = win.webContents.postMessage.mock.calls.findLast(
  195. ([channel]) => channel === InternalChannels.ScopedServicePort,
  196. );
  197. expect(call).toBeDefined();
  198. return call?.[1] as { attachmentId: string; sessionId: string };
  199. }
  200. function confirmLatestScopedAttachment(
  201. manager: ReturnType<typeof createManager>,
  202. win: ReturnType<typeof createWindow>,
  203. ): void {
  204. const payload = getLatestScopedAttachment(win);
  205. manager.confirmRendererAttachmentReady(win.webContents.id, payload);
  206. }
  207. // 各组都复用窗口 ID;只在首组清理会让后续 bind 把新 attachment 发给上一组的旧窗口。
  208. beforeEach(() => {
  209. browserWindowMock.windows.length = 0;
  210. channels.length = 0;
  211. browserWindowMock.fromId.mockClear();
  212. browserWindowMock.getAllWindows.mockClear();
  213. });
  214. describe("desktopRemoteSessions R1 window Host forwarding", () => {
  215. it("按 requestId 把窗口 Host 的远程连接进度转发给发起连接的 renderer", () => {
  216. const child = new MockUtilityProcess(1001);
  217. const win = createWindow(1, 101);
  218. const manager = createManager(new Map([[101, child]]));
  219. void manager.createRemoteWorkspaceSession(win as never, sshTarget, "connect-1");
  220. win.webContents.send.mockClear();
  221. child.emit("message", {
  222. type: HostResponseTypes.RemoteWorkspaceConnectionLog,
  223. requestId: "connect-1",
  224. level: "info",
  225. message: "detecting remote env...",
  226. });
  227. expect(win.webContents.send).toHaveBeenCalledWith(
  228. PlatformChannels.RemoteConnectionLog,
  229. expect.objectContaining({
  230. requestId: "connect-1",
  231. level: "info",
  232. message: "detecting remote env...",
  233. timestamp: expect.stringMatching(/^\d{2}:\d{2}:\d{2}$/u),
  234. }),
  235. );
  236. });
  237. it("按当前请求返回在线复用信息,等待 desktop-continuous attachment 就绪后才通知", async () => {
  238. const child = new MockUtilityProcess(1001);
  239. const win = createWindow(1, 101);
  240. const manager = createManager(new Map([[101, child]]));
  241. const onConnected = vi.fn();
  242. const connecting = manager.createRemoteWorkspaceSession(
  243. win as never,
  244. sshTarget,
  245. "reuse",
  246. undefined,
  247. { onConnected },
  248. );
  249. await emitConnected({
  250. child,
  251. requestId: "reuse",
  252. remoteSessionId: "session-reused",
  253. reusedConnectionTarget: sshTarget,
  254. });
  255. expect(onConnected).not.toHaveBeenCalled();
  256. confirmLatestScopedAttachment(manager, win);
  257. await expect(connecting).resolves.toBe("session-reused");
  258. expect(onConnected).toHaveBeenCalledWith(
  259. expect.objectContaining({ reusedConnectionTarget: sshTarget }),
  260. );
  261. });
  262. it.each(["source-server-upgrade-required", "source-server-install-required"])(
  263. "WSL 参数补全后的 %s 保留实际 Profile 和安装目标",
  264. async (reasonCode) => {
  265. const child = new MockUtilityProcess(1001);
  266. const win = createWindow(1, 101);
  267. const resolvedTarget = { kind: "wsl", distro: "Ubuntu", user: "dev" } as const;
  268. const manager = createManager(new Map([[101, child]]), {
  269. resolveWslTarget: async () => resolvedTarget,
  270. });
  271. const connecting = manager.createRemoteWorkspaceSession(
  272. win as never,
  273. { kind: "wsl" },
  274. "wsl-upgrade",
  275. );
  276. const profileId = "17ef20b3-622d-4a53-98c1-0cdff29f3e6d";
  277. const resolved = { resolvedWslTarget: resolvedTarget };
  278. const assertion = expect(connecting).rejects.toMatchObject({
  279. code: reasonCode,
  280. retryable: false,
  281. profileId,
  282. ...resolved,
  283. });
  284. await vi.waitFor(() =>
  285. expect(child.postMessage).toHaveBeenCalledWith(
  286. expect.objectContaining({
  287. type: HostMessageTypes.ConnectRemoteWorkspace,
  288. target: resolvedTarget,
  289. }),
  290. ),
  291. );
  292. child.emit("message", {
  293. type: HostResponseTypes.RemoteWorkspaceConnectFailed,
  294. requestId: "wsl-upgrade",
  295. error: "upgrade required",
  296. reasonCode,
  297. retryable: false,
  298. profileId,
  299. ...resolved,
  300. });
  301. await assertion;
  302. manager.disposeRemoteWorkspaceSessionsForWindow(101);
  303. },
  304. );
  305. it("连接请求发给窗口唯一 Local Host,成功后由同一进程暴露 remote-scoped port", async () => {
  306. const child = new MockUtilityProcess(1001);
  307. const win = createWindow(1, 101);
  308. const manager = createManager(new Map([[101, child]]));
  309. const connecting = manager.createRemoteWorkspaceSession(win as never, sshTarget, "connect-1");
  310. expect(child.postMessage).toHaveBeenCalledWith(
  311. expect.objectContaining({
  312. type: HostMessageTypes.ConnectRemoteWorkspace,
  313. requestId: "connect-1",
  314. target: sshTarget,
  315. }),
  316. );
  317. await emitConnected({ child, requestId: "connect-1", remoteSessionId: "remote-session-1" });
  318. let connectionSettled = false;
  319. void connecting.then(() => {
  320. connectionSettled = true;
  321. });
  322. await Promise.resolve();
  323. expect(connectionSettled).toBe(false);
  324. confirmLatestScopedAttachment(manager, win);
  325. await expect(connecting).resolves.toBe("remote-session-1");
  326. expect(child.postMessage).toHaveBeenCalledWith(
  327. expect.objectContaining({
  328. type: HostMessageTypes.AttachServicePort,
  329. clientMode: "desktop-continuous",
  330. scope: expect.objectContaining({
  331. kind: "remote",
  332. remoteSessionId: "remote-session-1",
  333. workspaceIdentity: buildRemoteWorkspaceIdentity("/", sshTarget),
  334. }),
  335. }),
  336. expect.any(Array),
  337. );
  338. expect(win.webContents.postMessage).toHaveBeenCalledWith(
  339. InternalChannels.ScopedServicePort,
  340. expect.objectContaining({
  341. attachmentId: expect.any(String),
  342. sessionId: "remote-session-1",
  343. target: sshTarget,
  344. workspacePath: "/",
  345. workspaceIdentity: buildRemoteWorkspaceIdentity("/", sshTarget),
  346. }),
  347. expect.any(Array),
  348. );
  349. });
  350. it.each(["failed", "rollback_failed", "unsupported"] as const)(
  351. "首次 Provisioning 返回 %s 时拒绝连接且不发布 Renderer port",
  352. async (status) => {
  353. const child = new MockUtilityProcess(1001);
  354. child.provisioningResult = { status, error: "sync unavailable" };
  355. const win = createWindow(1, 101);
  356. const manager = createManager(new Map([[101, child]]));
  357. const connecting = manager.createRemoteWorkspaceSession(win as never, sshTarget, "connect-1");
  358. await emitConnected({ child, requestId: "connect-1", remoteSessionId: "remote-session-1" });
  359. await expect(connecting).rejects.toThrow(/Provider Provisioning/u);
  360. expect(win.webContents.postMessage).not.toHaveBeenCalledWith(
  361. InternalChannels.ScopedServicePort,
  362. expect.anything(),
  363. expect.anything(),
  364. );
  365. },
  366. );
  367. it("已连接后的 Provisioning 失败只记录结构化 warning,不拆除 Workspace", async () => {
  368. const child = new MockUtilityProcess(1001);
  369. const win = createWindow(1, 101);
  370. const logger = { info: vi.fn(), warn: vi.fn(), error: vi.fn() };
  371. const manager = createManager(new Map([[101, child]]), { logger });
  372. const connecting = manager.createRemoteWorkspaceSession(
  373. win as never,
  374. sshTarget,
  375. "connect-1",
  376. undefined,
  377. { remoteUsageTelemetryEligible: true },
  378. );
  379. await emitConnected({ child, requestId: "connect-1", remoteSessionId: "remote-session-1" });
  380. confirmLatestScopedAttachment(manager, win);
  381. await connecting;
  382. child.provisioningResult = { status: "failed", error: "token=secret-value" };
  383. child.emit("message", {
  384. type: HostResponseTypes.ProviderProvisioningSourceChanged,
  385. trigger: "personal-config",
  386. });
  387. for (let index = 0; index < 6; index += 1) await Promise.resolve();
  388. expect(logger.warn).toHaveBeenCalledWith(
  389. "[provider-provisioning] Environment sync did not apply",
  390. expect.objectContaining({
  391. environmentKey: expect.any(String),
  392. trigger: "personal-config",
  393. status: "failed",
  394. }),
  395. );
  396. expect(logger.warn.mock.calls.at(-1)?.[1]).not.toHaveProperty("errorSummary");
  397. expect(manager.getRemoteConnectionStats()).toEqual({
  398. activeSessionCount: 1,
  399. activeTargetCount: 1,
  400. });
  401. });
  402. it.each([undefined, "source-read-failed"])(
  403. "首次同步失败把安全错误码 %s 写入日志和连接面板,不泄漏自由文本",
  404. async (errorCode) => {
  405. const child = new MockUtilityProcess(1001);
  406. child.provisioningResult = { status: "failed", error: "token=fixture-secret", errorCode };
  407. const win = createWindow(1, 101);
  408. const logger = { info: vi.fn(), warn: vi.fn(), error: vi.fn() };
  409. const manager = createManager(new Map([[101, child]]), { logger });
  410. const connecting = manager.createRemoteWorkspaceSession(
  411. win as never,
  412. sshTarget,
  413. "connect-diagnostic",
  414. );
  415. const outcome = connecting.catch((error: Error) => error.message);
  416. await emitConnected({
  417. child,
  418. requestId: "connect-diagnostic",
  419. remoteSessionId: "remote-diagnostic",
  420. });
  421. const code = errorCode ?? "target-apply-failed";
  422. expect(logger.warn).toHaveBeenCalledWith(
  423. "[provider-provisioning] Environment sync did not apply",
  424. expect.objectContaining({
  425. trigger: "environment-online",
  426. status: "failed",
  427. errorCode: code,
  428. }),
  429. );
  430. expect(await outcome).toContain(code);
  431. expect(win.webContents.send).toHaveBeenCalledWith(
  432. PlatformChannels.RemoteConnectionLog,
  433. expect.objectContaining({
  434. requestId: "connect-diagnostic",
  435. level: "error",
  436. message: expect.stringContaining(code),
  437. }),
  438. );
  439. expect(
  440. JSON.stringify([logger.warn.mock.calls, win.webContents.send.mock.calls, await outcome]),
  441. ).not.toContain("fixture-secret");
  442. expect(win.webContents.postMessage).not.toHaveBeenCalled();
  443. expect(child.postMessage).toHaveBeenCalledWith(
  444. expect.objectContaining({ type: HostMessageTypes.DisposeRemoteWorkspaceSession }),
  445. );
  446. },
  447. );
  448. it("只在 eligible 连接完成 renderer ACK 后计入并发并上报 connected gauge", async () => {
  449. const child = new MockUtilityProcess(1001);
  450. const win = createWindow(1, 101);
  451. const reportRemoteConnectionStateChanged = vi.fn();
  452. const reportRemoteDisconnect = vi.fn();
  453. const manager = createManager(new Map([[101, child]]), {
  454. reportRemoteConnectionStateChanged,
  455. reportRemoteDisconnect,
  456. });
  457. const eligible = manager.createRemoteWorkspaceSession(
  458. win as never,
  459. sshTarget,
  460. "connect-eligible",
  461. undefined,
  462. { remoteUsageTelemetryEligible: true },
  463. );
  464. await emitConnected({
  465. child,
  466. requestId: "connect-eligible",
  467. remoteSessionId: "remote-eligible",
  468. });
  469. expect(manager.getRemoteConnectionStats()).toEqual({
  470. activeSessionCount: 0,
  471. activeTargetCount: 0,
  472. });
  473. confirmLatestScopedAttachment(manager, win);
  474. await eligible;
  475. expect(manager.getRemoteConnectionStats()).toEqual({
  476. activeSessionCount: 1,
  477. activeTargetCount: 1,
  478. });
  479. expect(reportRemoteConnectionStateChanged).toHaveBeenCalledWith({
  480. rendererId: 101,
  481. remoteKind: "ssh",
  482. transition: "connected",
  483. });
  484. const internal = manager.createRemoteWorkspaceSession(
  485. win as never,
  486. { kind: "docker", container: "internal-only" },
  487. "connect-internal",
  488. );
  489. await emitConnected({
  490. child,
  491. requestId: "connect-internal",
  492. remoteSessionId: "remote-internal",
  493. target: { kind: "docker", container: "internal-only" },
  494. });
  495. confirmLatestScopedAttachment(manager, win);
  496. await internal;
  497. expect(manager.getRemoteConnectionStats()).toEqual({
  498. activeSessionCount: 1,
  499. activeTargetCount: 1,
  500. });
  501. manager.disposeRemoteWorkspaceSession("remote-internal", "internal-finished");
  502. expect(reportRemoteConnectionStateChanged).toHaveBeenCalledOnce();
  503. expect(reportRemoteDisconnect).not.toHaveBeenCalled();
  504. });
  505. it("连接异常关闭后上报一次 after-state gauge 与时长,随后 dispose 不重复", async () => {
  506. const child = new MockUtilityProcess(1001);
  507. const win = createWindow(1, 101);
  508. let now = 100;
  509. const reportRemoteConnectionStateChanged = vi.fn();
  510. const reportRemoteDisconnect = vi.fn();
  511. const manager = createManager(new Map([[101, child]]), {
  512. monotonicNowMs: () => now,
  513. reportRemoteConnectionStateChanged,
  514. reportRemoteDisconnect,
  515. });
  516. const connecting = manager.createRemoteWorkspaceSession(
  517. win as never,
  518. sshTarget,
  519. "connect-1",
  520. undefined,
  521. { remoteUsageTelemetryEligible: true },
  522. );
  523. await emitConnected({ child, requestId: "connect-1", remoteSessionId: "remote-session-1" });
  524. confirmLatestScopedAttachment(manager, win);
  525. await connecting;
  526. now = 600;
  527. child.emit("message", {
  528. type: HostResponseTypes.RemoteWorkspaceClosed,
  529. remoteSessionId: "remote-session-1",
  530. reason: "connection-closed",
  531. exitCode: 255,
  532. signal: null,
  533. });
  534. expect(manager.getRemoteConnectionStats()).toEqual({
  535. activeSessionCount: 0,
  536. activeTargetCount: 0,
  537. });
  538. expect(reportRemoteConnectionStateChanged).toHaveBeenNthCalledWith(2, {
  539. rendererId: 101,
  540. remoteKind: "ssh",
  541. transition: "connection-closed",
  542. });
  543. expect(reportRemoteDisconnect).toHaveBeenCalledWith({
  544. rendererId: 101,
  545. remoteKind: "ssh",
  546. disconnectReason: "connection-closed",
  547. durationMs: 500,
  548. });
  549. manager.disposeRemoteWorkspaceSession("remote-session-1", "tab-closed");
  550. expect(reportRemoteConnectionStateChanged).toHaveBeenCalledTimes(2);
  551. expect(reportRemoteDisconnect).toHaveBeenCalledOnce();
  552. });
  553. it.each([
  554. ["window-closed", "window"],
  555. ["host-exit", "host"],
  556. ["app-shutdown", "app"],
  557. ] as const)("%s 退出 eligible route 时上报对应终态", async (reason, owner) => {
  558. const child = new MockUtilityProcess(1001);
  559. const win = createWindow(1, 101);
  560. let now = 10;
  561. const reportRemoteConnectionStateChanged = vi.fn();
  562. const reportRemoteDisconnect = vi.fn();
  563. const manager = createManager(new Map([[101, child]]), {
  564. monotonicNowMs: () => now,
  565. reportRemoteConnectionStateChanged,
  566. reportRemoteDisconnect,
  567. });
  568. const connecting = manager.createRemoteWorkspaceSession(
  569. win as never,
  570. sshTarget,
  571. "connect-1",
  572. undefined,
  573. { remoteUsageTelemetryEligible: true },
  574. );
  575. await emitConnected({ child, requestId: "connect-1", remoteSessionId: "remote-session-1" });
  576. confirmLatestScopedAttachment(manager, win);
  577. await connecting;
  578. now = 210;
  579. if (owner === "window") manager.disposeRemoteWorkspaceSessionsForWindow(101);
  580. else if (owner === "host") child.emit("exit");
  581. else await manager.disposeAllAndWaitForAppShutdown("app-quit");
  582. expect(reportRemoteConnectionStateChanged).toHaveBeenLastCalledWith({
  583. rendererId: 101,
  584. remoteKind: "ssh",
  585. transition: reason,
  586. });
  587. expect(reportRemoteDisconnect).toHaveBeenCalledWith({
  588. rendererId: 101,
  589. remoteKind: "ssh",
  590. disconnectReason: reason,
  591. durationMs: 200,
  592. });
  593. expect(manager.getRemoteConnectionStats()).toEqual({
  594. activeSessionCount: 0,
  595. activeTargetCount: 0,
  596. });
  597. });
  598. it("按脱敏 target identity 去重诊断计数,但保留每个逻辑 session", async () => {
  599. const child = new MockUtilityProcess(1001);
  600. const win = createWindow(1, 101);
  601. const manager = createManager(new Map([[101, child]]));
  602. const targets: RemoteTarget[] = [
  603. sshTarget,
  604. sshTarget,
  605. { kind: "server", url: "ws://studio.example.com/ws" },
  606. { kind: "server", url: "http://studio.example.com" },
  607. { kind: "server", url: "wss://studio.example.com/ws" },
  608. { kind: "server", url: "https://studio.example.com" },
  609. ];
  610. for (const [index, target] of targets.entries()) {
  611. const requestId = `connect-${index}`;
  612. const remoteSessionId = `remote-${index}`;
  613. const connecting = manager.createRemoteWorkspaceSession(
  614. win as never,
  615. target,
  616. requestId,
  617. undefined,
  618. { remoteUsageTelemetryEligible: true },
  619. );
  620. await emitConnected({ child, requestId, remoteSessionId, target });
  621. confirmLatestScopedAttachment(manager, win);
  622. await connecting;
  623. }
  624. expect(manager.getRemoteConnectionStats()).toEqual({
  625. activeSessionCount: 6,
  626. activeTargetCount: 3,
  627. });
  628. });
  629. it("telemetry callback 抛错不改变连接成功或 dispose 结果", async () => {
  630. const child = new MockUtilityProcess(1001);
  631. const win = createWindow(1, 101);
  632. const reportRemoteConnectionStateChanged = vi.fn(() => {
  633. throw new Error("gauge reporter unavailable");
  634. });
  635. const reportRemoteDisconnect = vi.fn(() => {
  636. throw new Error("disconnect reporter unavailable");
  637. });
  638. const manager = createManager(new Map([[101, child]]), {
  639. reportRemoteConnectionStateChanged,
  640. reportRemoteDisconnect,
  641. });
  642. const connecting = manager.createRemoteWorkspaceSession(
  643. win as never,
  644. sshTarget,
  645. "connect-1",
  646. undefined,
  647. { remoteUsageTelemetryEligible: true },
  648. );
  649. await emitConnected({ child, requestId: "connect-1", remoteSessionId: "remote-session-1" });
  650. expect(() => confirmLatestScopedAttachment(manager, win)).not.toThrow();
  651. await expect(connecting).resolves.toBe("remote-session-1");
  652. expect(() =>
  653. manager.disposeRemoteWorkspaceSession("remote-session-1", "tab-closed"),
  654. ).not.toThrow();
  655. expect(reportRemoteConnectionStateChanged).toHaveBeenCalledTimes(2);
  656. expect(reportRemoteDisconnect).toHaveBeenCalledOnce();
  657. });
  658. it("WSL target 解析期间进入 app shutdown 后不发送迟到连接", async () => {
  659. const child = new MockUtilityProcess(1001);
  660. const win = createWindow(1, 101);
  661. let resolveWslTarget!: (target: Extract<RemoteTarget, { kind: "wsl" }>) => void;
  662. const manager = createManager(new Map([[101, child]]), {
  663. resolveWslTarget: () =>
  664. new Promise((resolve) => {
  665. resolveWslTarget = resolve;
  666. }),
  667. });
  668. const target = { kind: "wsl", distro: "Ubuntu" } as const;
  669. const connecting = manager.createRemoteWorkspaceSession(win as never, target, "connect-wsl");
  670. await vi.waitFor(() => expect(resolveWslTarget).toBeTypeOf("function"));
  671. await manager.disposeAllAndWaitForAppShutdown("app-quit");
  672. const settled = connecting.catch((error: unknown) => error);
  673. resolveWslTarget(target);
  674. await Promise.resolve();
  675. expect(child.postMessage).not.toHaveBeenCalledWith(
  676. expect.objectContaining({ type: HostMessageTypes.ConnectRemoteWorkspace }),
  677. );
  678. await expect(settled).resolves.toMatchObject({
  679. message: expect.stringContaining("应用正在退出"),
  680. });
  681. });
  682. it("两个窗口的连接、descriptor 和 attachment 都发往各自 Local Host", async () => {
  683. const firstChild = new MockUtilityProcess(1001);
  684. const secondChild = new MockUtilityProcess(1002);
  685. const firstWindow = createWindow(1, 101);
  686. const secondWindow = createWindow(2, 202);
  687. const manager = createManager(
  688. new Map([
  689. [101, firstChild],
  690. [202, secondChild],
  691. ]),
  692. );
  693. const first = manager.createRemoteWorkspaceSession(
  694. firstWindow as never,
  695. sshTarget,
  696. "connect-first",
  697. );
  698. const second = manager.createRemoteWorkspaceSession(
  699. secondWindow as never,
  700. sshTarget,
  701. "connect-second",
  702. );
  703. await emitConnected({
  704. child: firstChild,
  705. requestId: "connect-first",
  706. remoteSessionId: "remote-first",
  707. });
  708. await emitConnected({
  709. child: secondChild,
  710. requestId: "connect-second",
  711. remoteSessionId: "remote-second",
  712. });
  713. confirmLatestScopedAttachment(manager, firstWindow);
  714. confirmLatestScopedAttachment(manager, secondWindow);
  715. await expect(first).resolves.toBe("remote-first");
  716. await expect(second).resolves.toBe("remote-second");
  717. expect(firstChild.postMessage).not.toHaveBeenCalledWith(
  718. expect.objectContaining({
  719. scope: expect.objectContaining({ remoteSessionId: "remote-second" }),
  720. }),
  721. expect.anything(),
  722. );
  723. expect(secondChild.postMessage).not.toHaveBeenCalledWith(
  724. expect.objectContaining({
  725. scope: expect.objectContaining({ remoteSessionId: "remote-first" }),
  726. }),
  727. expect.anything(),
  728. );
  729. const provisioningExecutions = [
  730. ...firstChild.postMessage.mock.calls,
  731. ...secondChild.postMessage.mock.calls,
  732. ].filter(
  733. ([message]) =>
  734. (message as { type?: string }).type === HostMessageTypes.ProviderProvisioningExecute,
  735. );
  736. expect(provisioningExecutions).toHaveLength(1);
  737. });
  738. it("取消 pending connection 只发控制消息,不退出窗口 Host", () => {
  739. const child = new MockUtilityProcess(1001);
  740. const win = createWindow(1, 101);
  741. const manager = createManager(new Map([[101, child]]));
  742. void manager.createRemoteWorkspaceSession(win as never, sshTarget, "connect-cancel");
  743. manager.cancelPendingRemoteWorkspaceSessionsForWindow(101, "user-cancel", "connect-cancel");
  744. expect(child.postMessage).toHaveBeenCalledWith({
  745. type: HostMessageTypes.CancelRemoteWorkspaceConnect,
  746. requestId: "connect-cancel",
  747. });
  748. });
  749. it("绑定 canonical context 后先更新 Host,再重建 identity-validated renderer port", async () => {
  750. const child = new MockUtilityProcess(1001);
  751. const win = createWindow(1, 101);
  752. const manager = createManager(new Map([[101, child]]));
  753. const connecting = manager.createRemoteWorkspaceSession(win as never, sshTarget, "connect-1");
  754. const sourceServerId = "3cd4f9da-cd79-426c-9d70-75f36e9f6a87";
  755. await emitConnected({
  756. child,
  757. requestId: "connect-1",
  758. remoteSessionId: "remote-session-1",
  759. sourceServerId,
  760. });
  761. confirmLatestScopedAttachment(manager, win);
  762. await connecting;
  763. const firstAttachmentId = getLatestScopedAttachment(win).attachmentId;
  764. child.postMessage.mockClear();
  765. const binding = manager.bindRemoteWorkspaceSessionContext(
  766. "remote-session-1",
  767. {
  768. workspacePath: "/work/demo",
  769. workspaceIdentity: "remote:ssh:dev.internal:22:developer:/work/demo",
  770. },
  771. 101,
  772. );
  773. expect(child.postMessage.mock.calls[0]?.[0]).toMatchObject({
  774. type: HostMessageTypes.BindRemoteWorkspaceContext,
  775. remoteSessionId: "remote-session-1",
  776. workspacePath: "/work/demo",
  777. workspaceIdentity: `remote:server:${sourceServerId}:/work/demo`,
  778. legacyRouteHint: "remote:ssh:dev.internal:22:developer:/work/demo",
  779. });
  780. const bindRequest = child.postMessage.mock.calls[0]?.[0] as { requestId: string };
  781. child.emit("message", {
  782. type: HostResponseTypes.RemoteWorkspaceContextBound,
  783. requestId: bindRequest.requestId,
  784. previousWorkspaceIdentity: "remote:ssh:dev.internal:22:developer:/work/demo",
  785. });
  786. await Promise.resolve();
  787. expect(child.postMessage.mock.calls[1]?.[0]).toMatchObject({
  788. type: HostMessageTypes.AttachServicePort,
  789. scope: {
  790. kind: "remote",
  791. remoteSessionId: "remote-session-1",
  792. workspacePath: "/work/demo",
  793. workspaceIdentity: `remote:server:${sourceServerId}:/work/demo`,
  794. },
  795. });
  796. expect(child.postMessage).not.toHaveBeenCalledWith({
  797. type: HostMessageTypes.DetachServicePort,
  798. attachmentId: firstAttachmentId,
  799. });
  800. confirmLatestScopedAttachment(manager, win);
  801. await expect(binding).resolves.toEqual({
  802. sourceServerId,
  803. remoteSessionId: "remote-session-1",
  804. workspacePath: "/work/demo",
  805. workspaceIdentity: `remote:server:${sourceServerId}:/work/demo`,
  806. previousWorkspaceIdentity: "remote:ssh:dev.internal:22:developer:/work/demo",
  807. });
  808. expect(child.postMessage).toHaveBeenCalledWith({
  809. type: HostMessageTypes.DetachServicePort,
  810. attachmentId: firstAttachmentId,
  811. });
  812. });
  813. it("rejects bind before attaching a renderer port when Host workspace preparation fails", async () => {
  814. const child = new MockUtilityProcess(1001);
  815. const win = createWindow(1, 101);
  816. const manager = createManager(new Map([[101, child]]));
  817. const connecting = manager.createRemoteWorkspaceSession(win as never, sshTarget, "connect-1");
  818. await emitConnected({ child, requestId: "connect-1", remoteSessionId: "remote-session-1" });
  819. confirmLatestScopedAttachment(manager, win);
  820. await connecting;
  821. child.postMessage.mockClear();
  822. const binding = manager.bindRemoteWorkspaceSessionContext(
  823. "remote-session-1",
  824. { workspacePath: "/work/demo" },
  825. 101,
  826. );
  827. const request = child.postMessage.mock.calls[0]?.[0] as { requestId: string };
  828. child.emit("message", {
  829. type: HostResponseTypes.RemoteWorkspaceContextBindFailed,
  830. requestId: request.requestId,
  831. error: "workspace migration conflict",
  832. reasonCode: "workspace-task-identity-conflict",
  833. retryable: false,
  834. });
  835. await expect(binding).rejects.toMatchObject({
  836. message: "workspace migration conflict",
  837. code: "workspace-task-identity-conflict",
  838. retryable: false,
  839. });
  840. expect(child.postMessage).not.toHaveBeenCalledWith(
  841. expect.objectContaining({ type: HostMessageTypes.AttachServicePort }),
  842. expect.anything(),
  843. );
  844. });
  845. it("rejects a pending workspace bind when its Window Host exits", async () => {
  846. const child = new MockUtilityProcess(1001);
  847. const win = createWindow(1, 101);
  848. const manager = createManager(new Map([[101, child]]));
  849. const connecting = manager.createRemoteWorkspaceSession(win as never, sshTarget, "connect-1");
  850. await emitConnected({ child, requestId: "connect-1", remoteSessionId: "remote-session-1" });
  851. confirmLatestScopedAttachment(manager, win);
  852. await connecting;
  853. child.postMessage.mockClear();
  854. const binding = manager.bindRemoteWorkspaceSessionContext(
  855. "remote-session-1",
  856. { workspacePath: "/work/demo" },
  857. 101,
  858. );
  859. child.emit("exit", 1);
  860. await expect(binding).rejects.toThrow("窗口 Local Host 已退出");
  861. });
  862. it("times out a workspace bind that receives no Host ACK", async () => {
  863. vi.useFakeTimers();
  864. try {
  865. const child = new MockUtilityProcess(1001);
  866. const win = createWindow(1, 101);
  867. const manager = createManager(new Map([[101, child]]), {
  868. workspaceBindReadyTimeoutMs: 10,
  869. });
  870. const connecting = manager.createRemoteWorkspaceSession(win as never, sshTarget, "connect-1");
  871. await emitConnected({ child, requestId: "connect-1", remoteSessionId: "remote-session-1" });
  872. confirmLatestScopedAttachment(manager, win);
  873. await connecting;
  874. child.postMessage.mockClear();
  875. const binding = manager.bindRemoteWorkspaceSessionContext(
  876. "remote-session-1",
  877. { workspacePath: "/work/demo" },
  878. 101,
  879. );
  880. const rejection = expect(binding).rejects.toMatchObject({
  881. message: expect.stringContaining("workspace bind ACK 超时"),
  882. code: "remote-bind-canceled",
  883. retryable: true,
  884. });
  885. await vi.advanceTimersByTimeAsync(10);
  886. await rejection;
  887. const bindMessage = child.postMessage.mock.calls.find(
  888. ([message]) => message.type === HostMessageTypes.BindRemoteWorkspaceContext,
  889. )?.[0];
  890. expect(child.postMessage).toHaveBeenCalledWith(
  891. expect.objectContaining({
  892. type: HostMessageTypes.CancelRemoteWorkspaceBind,
  893. requestId: bindMessage.requestId,
  894. remoteSessionId: "remote-session-1",
  895. }),
  896. );
  897. } finally {
  898. vi.useRealTimers();
  899. }
  900. });
  901. it("joins a duplicate connected response to the existing pending bind without orphaning its attachment", async () => {
  902. vi.useFakeTimers();
  903. try {
  904. const child = new MockUtilityProcess(1001);
  905. const win = createWindow(1, 101);
  906. const manager = createManager(new Map([[101, child]]), {
  907. rendererAttachmentReadyTimeoutMs: 10,
  908. });
  909. const connecting = manager.createRemoteWorkspaceSession(win as never, sshTarget, "connect-1");
  910. await emitConnected({
  911. child,
  912. requestId: "connect-1",
  913. remoteSessionId: "remote-session-1",
  914. sourceServerId: "source-1",
  915. });
  916. confirmLatestScopedAttachment(manager, win);
  917. await connecting;
  918. const workspacePath = "/work/conversation";
  919. const workspaceIdentity = "remote:server:source-1:/work/conversation";
  920. const binding = manager.bindRemoteWorkspaceSessionContext(
  921. "remote-session-1",
  922. {
  923. workspacePath,
  924. workspaceIdentity,
  925. workspacePurpose: "conversation",
  926. },
  927. 101,
  928. );
  929. const bindRequest = child.postMessage.mock.calls.find(
  930. ([message]) => message.type === HostMessageTypes.BindRemoteWorkspaceContext,
  931. )?.[0] as { requestId: string };
  932. child.emit("message", {
  933. type: HostResponseTypes.RemoteWorkspaceContextBound,
  934. requestId: bindRequest.requestId,
  935. });
  936. await Promise.resolve();
  937. const bindingAttachment = getLatestScopedAttachment(win);
  938. const joined = manager.createRemoteWorkspaceSession(win as never, sshTarget, "connect-2", {
  939. workspacePath,
  940. workspaceIdentity,
  941. });
  942. await emitConnected({
  943. child,
  944. requestId: "connect-2",
  945. remoteSessionId: "remote-session-1",
  946. sourceServerId: "source-1",
  947. workspacePath,
  948. workspaceIdentity,
  949. workspacePurpose: "conversation",
  950. });
  951. expect(
  952. win.webContents.postMessage.mock.calls.filter(
  953. ([channel]) => channel === InternalChannels.ScopedServicePort,
  954. ),
  955. ).toHaveLength(2);
  956. manager.confirmRendererAttachmentReady(win.webContents.id, bindingAttachment);
  957. await expect(binding).resolves.toMatchObject({
  958. remoteSessionId: "remote-session-1",
  959. workspaceIdentity,
  960. });
  961. await expect(joined).resolves.toBe("remote-session-1");
  962. await vi.advanceTimersByTimeAsync(10);
  963. expect(child.postMessage).not.toHaveBeenCalledWith(
  964. expect.objectContaining({
  965. type: HostMessageTypes.DisposeRemoteWorkspaceSession,
  966. remoteSessionId: "remote-session-1",
  967. }),
  968. );
  969. } finally {
  970. vi.useRealTimers();
  971. }
  972. });
  973. it("keeps a joined connect pending until the matching context bind becomes renderer-ready", async () => {
  974. const child = new MockUtilityProcess(1001);
  975. const win = createWindow(1, 101);
  976. const manager = createManager(new Map([[101, child]]));
  977. const connecting = manager.createRemoteWorkspaceSession(win as never, sshTarget, "connect-1");
  978. await emitConnected({
  979. child,
  980. requestId: "connect-1",
  981. remoteSessionId: "remote-session-1",
  982. sourceServerId: "source-1",
  983. });
  984. confirmLatestScopedAttachment(manager, win);
  985. await connecting;
  986. const workspacePath = "/work/conversation";
  987. const workspaceIdentity = "remote:server:source-1:/work/conversation";
  988. const binding = manager.bindRemoteWorkspaceSessionContext(
  989. "remote-session-1",
  990. {
  991. workspacePath,
  992. workspaceIdentity,
  993. workspacePurpose: "conversation",
  994. },
  995. 101,
  996. );
  997. const joined = manager.createRemoteWorkspaceSession(win as never, sshTarget, "connect-2", {
  998. workspacePath,
  999. workspaceIdentity,
  1000. });
  1001. await emitConnected({
  1002. child,
  1003. requestId: "connect-2",
  1004. remoteSessionId: "remote-session-1",
  1005. sourceServerId: "source-1",
  1006. workspacePath,
  1007. workspaceIdentity,
  1008. workspacePurpose: "conversation",
  1009. });
  1010. const joinedBeforeBindReady = await Promise.race([
  1011. joined.then(
  1012. () => "resolved" as const,
  1013. () => "rejected" as const,
  1014. ),
  1015. new Promise<"pending">((resolve) => setImmediate(() => resolve("pending"))),
  1016. ]);
  1017. expect(joinedBeforeBindReady).toBe("pending");
  1018. const bindRequest = child.postMessage.mock.calls.find(
  1019. ([message]) => message.type === HostMessageTypes.BindRemoteWorkspaceContext,
  1020. )?.[0] as { requestId: string };
  1021. child.emit("message", {
  1022. type: HostResponseTypes.RemoteWorkspaceContextBound,
  1023. requestId: bindRequest.requestId,
  1024. });
  1025. await Promise.resolve();
  1026. confirmLatestScopedAttachment(manager, win);
  1027. await expect(binding).resolves.toMatchObject({ workspaceIdentity });
  1028. await expect(joined).resolves.toBe("remote-session-1");
  1029. });
  1030. it("shares one workspace bind flight for the same session context", async () => {
  1031. const child = new MockUtilityProcess(1001);
  1032. const win = createWindow(1, 101);
  1033. const manager = createManager(new Map([[101, child]]));
  1034. const connecting = manager.createRemoteWorkspaceSession(win as never, sshTarget, "connect-1");
  1035. await emitConnected({
  1036. child,
  1037. requestId: "connect-1",
  1038. remoteSessionId: "remote-session-1",
  1039. sourceServerId: "source-1",
  1040. });
  1041. confirmLatestScopedAttachment(manager, win);
  1042. await connecting;
  1043. child.postMessage.mockClear();
  1044. const context = {
  1045. workspacePath: "/work/conversation",
  1046. workspaceIdentity: "remote:server:source-1:/work/conversation",
  1047. workspacePurpose: "conversation" as const,
  1048. };
  1049. const first = manager.bindRemoteWorkspaceSessionContext("remote-session-1", context, 101);
  1050. const second = manager.bindRemoteWorkspaceSessionContext("remote-session-1", context, 101);
  1051. const bindMessages = child.postMessage.mock.calls.filter(
  1052. ([message]) => message.type === HostMessageTypes.BindRemoteWorkspaceContext,
  1053. );
  1054. expect(bindMessages).toHaveLength(1);
  1055. child.emit("message", {
  1056. type: HostResponseTypes.RemoteWorkspaceContextBound,
  1057. requestId: bindMessages[0]?.[0].requestId,
  1058. previousWorkspaceIdentity: "remote:ssh:legacy:/work/conversation",
  1059. });
  1060. await Promise.resolve();
  1061. confirmLatestScopedAttachment(manager, win);
  1062. await expect(first).resolves.toMatchObject({
  1063. workspaceIdentity: context.workspaceIdentity,
  1064. previousWorkspaceIdentity: "remote:ssh:legacy:/work/conversation",
  1065. });
  1066. await expect(second).resolves.toEqual(await first);
  1067. });
  1068. it("returns an already-ready identical workspace context without rotating the attachment", async () => {
  1069. const child = new MockUtilityProcess(1001);
  1070. const win = createWindow(1, 101);
  1071. const manager = createManager(new Map([[101, child]]));
  1072. const connecting = manager.createRemoteWorkspaceSession(win as never, sshTarget, "connect-1");
  1073. await emitConnected({
  1074. child,
  1075. requestId: "connect-1",
  1076. remoteSessionId: "remote-session-1",
  1077. sourceServerId: "source-1",
  1078. });
  1079. confirmLatestScopedAttachment(manager, win);
  1080. await connecting;
  1081. const context = {
  1082. workspacePath: "/work/conversation",
  1083. workspaceIdentity: "remote:server:source-1:/work/conversation",
  1084. workspacePurpose: "conversation" as const,
  1085. };
  1086. const first = manager.bindRemoteWorkspaceSessionContext("remote-session-1", context, 101);
  1087. const bindRequest = child.postMessage.mock.calls.find(
  1088. ([message]) => message.type === HostMessageTypes.BindRemoteWorkspaceContext,
  1089. )?.[0] as { requestId: string };
  1090. child.emit("message", {
  1091. type: HostResponseTypes.RemoteWorkspaceContextBound,
  1092. requestId: bindRequest.requestId,
  1093. });
  1094. await Promise.resolve();
  1095. const attachment = getLatestScopedAttachment(win);
  1096. manager.confirmRendererAttachmentReady(win.webContents.id, attachment);
  1097. await first;
  1098. child.postMessage.mockClear();
  1099. win.webContents.postMessage.mockClear();
  1100. const repeated = manager.bindRemoteWorkspaceSessionContext("remote-session-1", context, 101);
  1101. expect(child.postMessage).not.toHaveBeenCalledWith(
  1102. expect.objectContaining({
  1103. type: HostMessageTypes.BindRemoteWorkspaceContext,
  1104. }),
  1105. );
  1106. expect(win.webContents.postMessage).not.toHaveBeenCalledWith(
  1107. InternalChannels.ScopedServicePort,
  1108. expect.anything(),
  1109. expect.anything(),
  1110. );
  1111. await expect(repeated).resolves.toMatchObject({
  1112. remoteSessionId: "remote-session-1",
  1113. workspacePath: context.workspacePath,
  1114. workspaceIdentity: context.workspaceIdentity,
  1115. workspacePurpose: "conversation",
  1116. });
  1117. });
  1118. it("promotes telemetry eligibility once when an eligible request joins a ready route", async () => {
  1119. const child = new MockUtilityProcess(1001);
  1120. const win = createWindow(1, 101);
  1121. const reportRemoteConnectionStateChanged = vi.fn();
  1122. const manager = createManager(new Map([[101, child]]), {
  1123. reportRemoteConnectionStateChanged,
  1124. });
  1125. const background = manager.createRemoteWorkspaceSession(
  1126. win as never,
  1127. sshTarget,
  1128. "connect-background",
  1129. );
  1130. await emitConnected({
  1131. child,
  1132. requestId: "connect-background",
  1133. remoteSessionId: "remote-session-1",
  1134. });
  1135. confirmLatestScopedAttachment(manager, win);
  1136. await background;
  1137. expect(reportRemoteConnectionStateChanged).not.toHaveBeenCalled();
  1138. const eligible = manager.createRemoteWorkspaceSession(
  1139. win as never,
  1140. sshTarget,
  1141. "connect-eligible",
  1142. undefined,
  1143. { remoteUsageTelemetryEligible: true },
  1144. );
  1145. await emitConnected({
  1146. child,
  1147. requestId: "connect-eligible",
  1148. remoteSessionId: "remote-session-1",
  1149. });
  1150. await expect(eligible).resolves.toBe("remote-session-1");
  1151. expect(reportRemoteConnectionStateChanged).toHaveBeenCalledTimes(1);
  1152. expect(reportRemoteConnectionStateChanged).toHaveBeenCalledWith({
  1153. rendererId: 101,
  1154. remoteKind: "ssh",
  1155. transition: "connected",
  1156. });
  1157. expect(manager.getRemoteConnectionStats()).toEqual({
  1158. activeSessionCount: 1,
  1159. activeTargetCount: 1,
  1160. });
  1161. });
  1162. it("rejects a concurrent different context without disturbing the owning bind", async () => {
  1163. const child = new MockUtilityProcess(1001);
  1164. const win = createWindow(1, 101);
  1165. const manager = createManager(new Map([[101, child]]));
  1166. const connecting = manager.createRemoteWorkspaceSession(win as never, sshTarget, "connect-1");
  1167. await emitConnected({
  1168. child,
  1169. requestId: "connect-1",
  1170. remoteSessionId: "remote-session-1",
  1171. sourceServerId: "source-1",
  1172. });
  1173. confirmLatestScopedAttachment(manager, win);
  1174. await connecting;
  1175. child.postMessage.mockClear();
  1176. const owningContext = {
  1177. workspacePath: "/work/conversation",
  1178. workspaceIdentity: "remote:server:source-1:/work/conversation",
  1179. workspacePurpose: "conversation" as const,
  1180. };
  1181. const owningBind = manager.bindRemoteWorkspaceSessionContext(
  1182. "remote-session-1",
  1183. owningContext,
  1184. 101,
  1185. );
  1186. await expect(
  1187. manager.bindRemoteWorkspaceSessionContext(
  1188. "remote-session-1",
  1189. {
  1190. workspacePath: "/work/project",
  1191. workspaceIdentity: "remote:server:source-1:/work/project",
  1192. workspacePurpose: "project",
  1193. },
  1194. 101,
  1195. ),
  1196. ).rejects.toThrow("正在绑定其它 context");
  1197. const bindMessages = child.postMessage.mock.calls.filter(
  1198. ([message]) => message.type === HostMessageTypes.BindRemoteWorkspaceContext,
  1199. );
  1200. expect(bindMessages).toHaveLength(1);
  1201. child.emit("message", {
  1202. type: HostResponseTypes.RemoteWorkspaceContextBound,
  1203. requestId: bindMessages[0]?.[0].requestId,
  1204. });
  1205. await Promise.resolve();
  1206. confirmLatestScopedAttachment(manager, win);
  1207. await expect(owningBind).resolves.toMatchObject({
  1208. workspacePath: owningContext.workspacePath,
  1209. workspaceIdentity: owningContext.workspaceIdentity,
  1210. });
  1211. expect(child.postMessage).not.toHaveBeenCalledWith(
  1212. expect.objectContaining({
  1213. type: HostMessageTypes.DisposeRemoteWorkspaceSession,
  1214. remoteSessionId: "remote-session-1",
  1215. }),
  1216. );
  1217. });
  1218. it("rejects a same-session join from a mismatched target without replacing the owner route", async () => {
  1219. const child = new MockUtilityProcess(1001);
  1220. const win = createWindow(1, 101);
  1221. const manager = createManager(new Map([[101, child]]));
  1222. const owner = manager.createRemoteWorkspaceSession(win as never, sshTarget, "connect-owner");
  1223. await emitConnected({
  1224. child,
  1225. requestId: "connect-owner",
  1226. remoteSessionId: "remote-session-1",
  1227. });
  1228. confirmLatestScopedAttachment(manager, win);
  1229. await owner;
  1230. win.webContents.postMessage.mockClear();
  1231. child.postMessage.mockClear();
  1232. const otherTarget: RemoteTarget = {
  1233. kind: "docker",
  1234. container: "other-runtime",
  1235. };
  1236. const conflicting = manager.createRemoteWorkspaceSession(
  1237. win as never,
  1238. otherTarget,
  1239. "connect-conflict",
  1240. );
  1241. await emitConnected({
  1242. child,
  1243. requestId: "connect-conflict",
  1244. remoteSessionId: "remote-session-1",
  1245. target: otherTarget,
  1246. });
  1247. await expect(conflicting).rejects.toThrow("join 与已有 route 不匹配");
  1248. expect(win.webContents.postMessage).not.toHaveBeenCalledWith(
  1249. InternalChannels.ScopedServicePort,
  1250. expect.anything(),
  1251. expect.anything(),
  1252. );
  1253. expect(child.postMessage).not.toHaveBeenCalledWith(
  1254. expect.objectContaining({
  1255. type: HostMessageTypes.DisposeRemoteWorkspaceSession,
  1256. remoteSessionId: "remote-session-1",
  1257. }),
  1258. );
  1259. expect(manager.getRemoteConnectionStats()).toEqual({
  1260. activeSessionCount: 0,
  1261. activeTargetCount: 0,
  1262. });
  1263. expect(manager.hasRemoteWorkspaceSessionForTarget(win as never, sshTarget)).toBe(true);
  1264. });
  1265. it("joins a different Profile request when Host returns the canonical Source owner target", async () => {
  1266. const child = new MockUtilityProcess(1001);
  1267. const win = createWindow(1, 101);
  1268. const manager = createManager(new Map([[101, child]]));
  1269. const owner = manager.createRemoteWorkspaceSession(win as never, sshTarget, "connect-owner");
  1270. await emitConnected({
  1271. child,
  1272. requestId: "connect-owner",
  1273. remoteSessionId: "remote-session-1",
  1274. sourceServerId: "source-1",
  1275. });
  1276. confirmLatestScopedAttachment(manager, win);
  1277. await owner;
  1278. win.webContents.postMessage.mockClear();
  1279. child.postMessage.mockClear();
  1280. const alternateProfileTarget: RemoteTarget = {
  1281. kind: "ssh",
  1282. host: "route-b.internal",
  1283. username: "developer",
  1284. };
  1285. const joined = manager.createRemoteWorkspaceSession(
  1286. win as never,
  1287. alternateProfileTarget,
  1288. "connect-alternate-profile",
  1289. );
  1290. await emitConnected({
  1291. child,
  1292. requestId: "connect-alternate-profile",
  1293. remoteSessionId: "remote-session-1",
  1294. sourceServerId: "source-1",
  1295. // Host 返回真正持有 logical session 的 canonical entry target,而不是请求线路。
  1296. target: sshTarget,
  1297. });
  1298. await expect(joined).resolves.toBe("remote-session-1");
  1299. expect(win.webContents.postMessage).not.toHaveBeenCalledWith(
  1300. InternalChannels.ScopedServicePort,
  1301. expect.anything(),
  1302. expect.anything(),
  1303. );
  1304. expect(child.postMessage).not.toHaveBeenCalledWith(
  1305. expect.objectContaining({
  1306. type: HostMessageTypes.DisposeRemoteWorkspaceSession,
  1307. remoteSessionId: "remote-session-1",
  1308. }),
  1309. );
  1310. expect(manager.hasRemoteWorkspaceSessionForTarget(win as never, sshTarget)).toBe(true);
  1311. expect(manager.hasRemoteWorkspaceSessionForTarget(win as never, alternateProfileTarget)).toBe(
  1312. false,
  1313. );
  1314. });
  1315. it("忽略过期 ready ACK,超时只回收且不提升候选 attachment", async () => {
  1316. vi.useFakeTimers();
  1317. try {
  1318. const child = new MockUtilityProcess(1001);
  1319. const win = createWindow(1, 101);
  1320. const manager = createManager(new Map([[101, child]]), {
  1321. rendererAttachmentReadyTimeoutMs: 10,
  1322. });
  1323. const connecting = manager.createRemoteWorkspaceSession(win as never, sshTarget, "connect-1");
  1324. await emitConnected({ child, requestId: "connect-1", remoteSessionId: "remote-session-1" });
  1325. const firstAttachment = getLatestScopedAttachment(win);
  1326. confirmLatestScopedAttachment(manager, win);
  1327. await connecting;
  1328. child.postMessage.mockClear();
  1329. const binding = manager.bindRemoteWorkspaceSessionContext(
  1330. "remote-session-1",
  1331. { workspacePath: "/work/demo" },
  1332. 101,
  1333. );
  1334. const bindRequest = child.postMessage.mock.calls[0]?.[0] as { requestId: string };
  1335. child.emit("message", {
  1336. type: HostResponseTypes.RemoteWorkspaceContextBound,
  1337. requestId: bindRequest.requestId,
  1338. });
  1339. await Promise.resolve();
  1340. const candidateAttachment = getLatestScopedAttachment(win);
  1341. manager.confirmRendererAttachmentReady(101, firstAttachment);
  1342. const bindingRejection = expect(binding).rejects.toThrow("renderer attachment ready 超时");
  1343. await vi.advanceTimersByTimeAsync(10);
  1344. await bindingRejection;
  1345. expect(child.postMessage).toHaveBeenCalledWith({
  1346. type: HostMessageTypes.DetachServicePort,
  1347. attachmentId: candidateAttachment.attachmentId,
  1348. });
  1349. } finally {
  1350. vi.useRealTimers();
  1351. }
  1352. });
  1353. it("手机 runtime attachment 到已有窗口 Local Host", async () => {
  1354. const child = new MockUtilityProcess(1001);
  1355. const win = createWindow(1, 101);
  1356. const manager = createManager(new Map([[101, child]]));
  1357. const workspaceIdentity = "remote:ssh:dev.internal:22:developer:/work/demo";
  1358. const connecting = manager.createRemoteWorkspaceSession(win as never, sshTarget, "connect-1", {
  1359. workspacePath: "/work/demo",
  1360. workspaceIdentity,
  1361. });
  1362. await emitConnected({
  1363. child,
  1364. requestId: "connect-1",
  1365. remoteSessionId: "remote-session-1",
  1366. workspacePath: "/work/demo",
  1367. workspaceIdentity,
  1368. });
  1369. confirmLatestScopedAttachment(manager, win);
  1370. await connecting;
  1371. child.postMessage.mockClear();
  1372. const mobile = manager.attachRemoteWorkspaceSessionHost({
  1373. windowId: 1,
  1374. remoteSessionId: "remote-session-1",
  1375. workspacePath: "/work/demo",
  1376. workspaceIdentity,
  1377. workspaceKey: workspaceIdentity,
  1378. clientMode: "web-remote-replayable",
  1379. });
  1380. expect(mobile.process).toBe(child);
  1381. expect(child.postMessage).toHaveBeenCalledTimes(1);
  1382. for (const [message] of child.postMessage.mock.calls) {
  1383. expect(message).toMatchObject({
  1384. type: HostMessageTypes.AttachServicePort,
  1385. clientMode: "web-remote-replayable",
  1386. scope: { kind: "remote", remoteSessionId: "remote-session-1" },
  1387. });
  1388. }
  1389. });
  1390. it("renderer reload 只重建 attachment,复用 session 与 Host PID", async () => {
  1391. const child = new MockUtilityProcess(1001);
  1392. const win = createWindow(1, 101);
  1393. const manager = createManager(new Map([[101, child]]));
  1394. const connecting = manager.createRemoteWorkspaceSession(win as never, sshTarget, "connect-1");
  1395. await emitConnected({ child, requestId: "connect-1", remoteSessionId: "remote-session-1" });
  1396. confirmLatestScopedAttachment(manager, win);
  1397. await connecting;
  1398. child.postMessage.mockClear();
  1399. manager.reattachRemoteWorkspaceSessionsForWindow(win as never, "renderer-reload");
  1400. expect(child.pid).toBe(1001);
  1401. expect(child.postMessage.mock.calls[0]?.[0]).toMatchObject({
  1402. type: HostMessageTypes.AttachServicePort,
  1403. scope: { kind: "remote", remoteSessionId: "remote-session-1" },
  1404. });
  1405. expect(
  1406. child.postMessage.mock.calls.some(
  1407. ([message]) => message.type === HostMessageTypes.ConnectRemoteWorkspace,
  1408. ),
  1409. ).toBe(false);
  1410. confirmLatestScopedAttachment(manager, win);
  1411. });
  1412. it("连接断开后保留离线路由供 tab dispose,但禁止 reload、手机和 Bot 重新 attachment", async () => {
  1413. const child = new MockUtilityProcess(1001);
  1414. const win = createWindow(1, 101);
  1415. const manager = createManager(new Map([[101, child]]));
  1416. const workspacePath = "/work/demo";
  1417. const workspaceIdentity = "remote:ssh:dev.internal:22:developer:/work/demo";
  1418. const connecting = manager.createRemoteWorkspaceSession(win as never, sshTarget, "connect-1", {
  1419. workspacePath,
  1420. workspaceIdentity,
  1421. });
  1422. await emitConnected({
  1423. child,
  1424. requestId: "connect-1",
  1425. remoteSessionId: "remote-session-1",
  1426. workspacePath,
  1427. workspaceIdentity,
  1428. });
  1429. confirmLatestScopedAttachment(manager, win);
  1430. await connecting;
  1431. child.postMessage.mockClear();
  1432. child.emit("message", {
  1433. type: HostResponseTypes.RemoteWorkspaceClosed,
  1434. remoteSessionId: "remote-session-1",
  1435. reason: "connection-closed",
  1436. exitCode: 255,
  1437. signal: null,
  1438. recoverable: true,
  1439. recoveryAttempt: 2,
  1440. recoveryLimit: 3,
  1441. });
  1442. manager.reattachRemoteWorkspaceSessionsForWindow(win as never, "renderer-reload");
  1443. expect(child.postMessage).toHaveBeenCalledWith({
  1444. type: HostMessageTypes.DetachServicePort,
  1445. attachmentId: expect.any(String),
  1446. });
  1447. expect(child.postMessage).not.toHaveBeenCalledWith(
  1448. expect.objectContaining({ type: HostMessageTypes.AttachServicePort }),
  1449. expect.anything(),
  1450. );
  1451. expect(() =>
  1452. manager.attachRemoteWorkspaceSessionHost({
  1453. windowId: 1,
  1454. remoteSessionId: "remote-session-1",
  1455. workspacePath,
  1456. workspaceIdentity,
  1457. workspaceKey: workspaceIdentity,
  1458. clientMode: "web-remote-replayable",
  1459. }),
  1460. ).toThrow("远程 workspace source 当前离线");
  1461. manager.disposeRemoteWorkspaceSession("remote-session-1", "tab-closed");
  1462. expect(child.postMessage).toHaveBeenCalledWith(
  1463. expect.objectContaining({
  1464. type: HostMessageTypes.DisposeRemoteWorkspaceSession,
  1465. remoteSessionId: "remote-session-1",
  1466. }),
  1467. );
  1468. });
  1469. it("Source 自动重连后先恢复 Desktop,手机 bridge 失败不回滚新 session", async () => {
  1470. const child = new MockUtilityProcess(1001);
  1471. const win = createWindow(1, 101);
  1472. const webRemoteControlManager = {
  1473. failRemoteSession: vi.fn(),
  1474. replaceRemoteSession: vi.fn(async () => {
  1475. throw new Error("mobile bridge unavailable");
  1476. }),
  1477. };
  1478. const manager = createManager(new Map([[101, child]]), { webRemoteControlManager });
  1479. const workspacePath = "/work/demo";
  1480. const workspaceIdentity = "remote:ssh:dev.internal:22:developer:/work/demo";
  1481. const connecting = manager.createRemoteWorkspaceSession(win as never, sshTarget, "connect-1", {
  1482. workspacePath,
  1483. workspaceIdentity,
  1484. });
  1485. await emitConnected({
  1486. child,
  1487. requestId: "connect-1",
  1488. remoteSessionId: "remote-session-1",
  1489. workspacePath,
  1490. workspaceIdentity,
  1491. });
  1492. confirmLatestScopedAttachment(manager, win);
  1493. await connecting;
  1494. child.emit("message", {
  1495. type: HostResponseTypes.RemoteWorkspaceClosed,
  1496. remoteSessionId: "remote-session-1",
  1497. reason: "connection-closed",
  1498. exitCode: 255,
  1499. signal: null,
  1500. recoverable: true,
  1501. recoveryAttempt: 2,
  1502. recoveryLimit: 3,
  1503. });
  1504. expect(webRemoteControlManager.failRemoteSession).not.toHaveBeenCalled();
  1505. expect(win.webContents.send).toHaveBeenCalledWith(PlatformChannels.RemoteSessionClosed, {
  1506. sessionId: "remote-session-1",
  1507. reason: "host-exit",
  1508. exitCode: 255,
  1509. signal: null,
  1510. recoverable: true,
  1511. recoveryAttempt: 2,
  1512. recoveryLimit: 3,
  1513. });
  1514. win.webContents.send.mockClear();
  1515. child.emit("message", {
  1516. type: HostResponseTypes.RemoteWorkspaceReconnected,
  1517. previousRemoteSessionId: "remote-session-1",
  1518. descriptor: {
  1519. remoteSessionId: "remote-session-2",
  1520. target: sshTarget,
  1521. workspacePath,
  1522. workspaceIdentity,
  1523. generation: 2,
  1524. },
  1525. });
  1526. expect(getLatestScopedAttachment(win).sessionId).toBe("remote-session-2");
  1527. confirmLatestScopedAttachment(manager, win);
  1528. await vi.waitFor(() =>
  1529. expect(win.webContents.send).toHaveBeenCalledWith(PlatformChannels.RemoteSessionReconnected, {
  1530. previousSessionId: "remote-session-1",
  1531. sessionId: "remote-session-2",
  1532. workspacePath,
  1533. workspaceIdentity,
  1534. }),
  1535. );
  1536. expect(webRemoteControlManager.replaceRemoteSession).toHaveBeenCalledWith({
  1537. previousSessionId: "remote-session-1",
  1538. sessionId: "remote-session-2",
  1539. workspacePath,
  1540. workspaceIdentity,
  1541. });
  1542. expect(child.postMessage).not.toHaveBeenCalledWith(
  1543. expect.objectContaining({
  1544. type: HostMessageTypes.DisposeRemoteWorkspaceSession,
  1545. remoteSessionId: "remote-session-2",
  1546. }),
  1547. );
  1548. child.emit("message", {
  1549. type: HostResponseTypes.RemoteWorkspaceClosed,
  1550. remoteSessionId: "remote-session-2",
  1551. reason: "connection-closed",
  1552. exitCode: 255,
  1553. signal: null,
  1554. recoverable: false,
  1555. });
  1556. expect(webRemoteControlManager.failRemoteSession).toHaveBeenCalledWith(
  1557. "remote-session-2",
  1558. "window-host:connection-offline",
  1559. expect.objectContaining({ reason: "workspace-closed" }),
  1560. );
  1561. });
  1562. async function reconnectSourceSession(params: {
  1563. child: MockUtilityProcess;
  1564. win: ReturnType<typeof createWindow>;
  1565. manager: ReturnType<typeof createManager>;
  1566. workspacePath: string;
  1567. workspaceIdentity: string;
  1568. }) {
  1569. params.child.emit("message", {
  1570. type: HostResponseTypes.RemoteWorkspaceClosed,
  1571. remoteSessionId: "remote-session-1",
  1572. reason: "connection-closed",
  1573. exitCode: 255,
  1574. signal: null,
  1575. recoverable: true,
  1576. recoveryAttempt: 1,
  1577. recoveryLimit: 3,
  1578. });
  1579. params.child.emit("message", {
  1580. type: HostResponseTypes.RemoteWorkspaceReconnected,
  1581. previousRemoteSessionId: "remote-session-1",
  1582. descriptor: {
  1583. remoteSessionId: "remote-session-2",
  1584. target: sshTarget,
  1585. workspacePath: params.workspacePath,
  1586. workspaceIdentity: params.workspaceIdentity,
  1587. generation: 2,
  1588. },
  1589. });
  1590. for (let index = 0; index < 6; index += 1) await Promise.resolve();
  1591. confirmLatestScopedAttachment(params.manager, params.win);
  1592. await vi.waitFor(() =>
  1593. expect(params.win.webContents.send).toHaveBeenCalledWith(
  1594. PlatformChannels.RemoteSessionReconnected,
  1595. expect.objectContaining({ sessionId: "remote-session-2" }),
  1596. ),
  1597. );
  1598. }
  1599. it("Source 自动重连后以新 sessionId 重新登记 Provisioning lane 并重新下发", async () => {
  1600. const child = new MockUtilityProcess(1001);
  1601. const win = createWindow(1, 101);
  1602. const manager = createManager(new Map([[101, child]]));
  1603. const workspacePath = "/work/demo";
  1604. const workspaceIdentity = "remote:ssh:dev.internal:22:developer:/work/demo";
  1605. const connecting = manager.createRemoteWorkspaceSession(win as never, sshTarget, "connect-1", {
  1606. workspacePath,
  1607. workspaceIdentity,
  1608. });
  1609. await emitConnected({
  1610. child,
  1611. requestId: "connect-1",
  1612. remoteSessionId: "remote-session-1",
  1613. workspacePath,
  1614. workspaceIdentity,
  1615. });
  1616. confirmLatestScopedAttachment(manager, win);
  1617. await connecting;
  1618. expect(child.postMessage).toHaveBeenCalledWith(
  1619. expect.objectContaining({
  1620. type: HostMessageTypes.ProviderProvisioningExecute,
  1621. remoteSessionId: "remote-session-1",
  1622. trigger: "environment-online",
  1623. }),
  1624. );
  1625. child.postMessage.mockClear();
  1626. await reconnectSourceSession({ child, win, manager, workspacePath, workspaceIdentity });
  1627. // 远端 daemon 重连视为 Environment 重新上线:离线期间的本机配置变更必须整份重新下发。
  1628. expect(child.postMessage).toHaveBeenCalledWith(
  1629. expect.objectContaining({
  1630. type: HostMessageTypes.ProviderProvisioningExecute,
  1631. remoteSessionId: "remote-session-2",
  1632. trigger: "environment-online",
  1633. }),
  1634. );
  1635. child.postMessage.mockClear();
  1636. child.emit("message", {
  1637. type: HostResponseTypes.ProviderProvisioningSourceChanged,
  1638. trigger: "personal-config",
  1639. });
  1640. for (let index = 0; index < 6; index += 1) await Promise.resolve();
  1641. const provisioningExecutions = child.postMessage.mock.calls
  1642. .map(([message]) => message as { type?: string; remoteSessionId?: string; trigger?: string })
  1643. .filter((message) => message.type === HostMessageTypes.ProviderProvisioningExecute);
  1644. expect(provisioningExecutions).toEqual([
  1645. expect.objectContaining({ remoteSessionId: "remote-session-2", trigger: "personal-config" }),
  1646. ]);
  1647. });
  1648. it("重连触发的 Provisioning 失败只记录 warning,不拆除已重连的 Workspace", async () => {
  1649. const child = new MockUtilityProcess(1001);
  1650. const win = createWindow(1, 101);
  1651. const logger = { info: vi.fn(), warn: vi.fn(), error: vi.fn() };
  1652. const manager = createManager(new Map([[101, child]]), { logger });
  1653. const workspacePath = "/work/demo";
  1654. const workspaceIdentity = "remote:ssh:dev.internal:22:developer:/work/demo";
  1655. const connecting = manager.createRemoteWorkspaceSession(win as never, sshTarget, "connect-1", {
  1656. workspacePath,
  1657. workspaceIdentity,
  1658. });
  1659. await emitConnected({
  1660. child,
  1661. requestId: "connect-1",
  1662. remoteSessionId: "remote-session-1",
  1663. workspacePath,
  1664. workspaceIdentity,
  1665. });
  1666. confirmLatestScopedAttachment(manager, win);
  1667. await connecting;
  1668. child.provisioningResult = { status: "failed", error: "token=secret-value" };
  1669. await reconnectSourceSession({ child, win, manager, workspacePath, workspaceIdentity });
  1670. expect(getLatestScopedAttachment(win).sessionId).toBe("remote-session-2");
  1671. expect(logger.warn).toHaveBeenCalledWith(
  1672. "[provider-provisioning] Environment resync after reconnect did not apply",
  1673. expect.objectContaining({ remoteSessionId: "remote-session-2" }),
  1674. );
  1675. expect(JSON.stringify(logger.warn.mock.calls)).not.toContain("secret-value");
  1676. expect(child.postMessage).not.toHaveBeenCalledWith(
  1677. expect.objectContaining({
  1678. type: HostMessageTypes.DisposeRemoteWorkspaceSession,
  1679. remoteSessionId: "remote-session-2",
  1680. }),
  1681. );
  1682. });
  1683. it("手机项目准备只转交 Host descriptor,不创建桌面 tab/continuous attachment", async () => {
  1684. const child = new MockUtilityProcess(1001);
  1685. const win = createWindow(1, 101);
  1686. const remoteControl = {
  1687. failRemoteSession: vi.fn(),
  1688. replaceRemoteSession: vi.fn(async () => undefined),
  1689. };
  1690. const manager = createManager(new Map([[101, child]]), {
  1691. webRemoteControlManager: remoteControl,
  1692. });
  1693. const pending = manager.prepareProjectWorkspace(
  1694. win as never,
  1695. { projectId: "p", hostId: "remote:server:s" },
  1696. "mobile-project",
  1697. );
  1698. expect(child.postMessage).toHaveBeenCalledWith({
  1699. type: HostMessageTypes.PrepareProjectWorkspace,
  1700. requestId: "mobile-project",
  1701. projectId: "p",
  1702. hostId: "remote:server:s",
  1703. clientMode: "web-remote-replayable",
  1704. });
  1705. const remote = {
  1706. sourceServerId: "s",
  1707. remoteSessionId: "mobile-scope",
  1708. workspacePath: "/new",
  1709. workspaceIdentity: "remote:server:s:/new",
  1710. generation: 1,
  1711. target: sshTarget,
  1712. };
  1713. child.emit("message", {
  1714. type: HostResponseTypes.ProjectWorkspacePrepared,
  1715. requestId: "mobile-project",
  1716. result: {
  1717. ok: true,
  1718. value: {
  1719. projectId: "p",
  1720. hostId: "remote:server:s",
  1721. workspacePath: "/new",
  1722. workspaceIdentity: remote.workspaceIdentity,
  1723. additionalDirectories: [],
  1724. remote,
  1725. },
  1726. },
  1727. });
  1728. expect((await pending).remote?.remoteSessionId).toBe("mobile-scope");
  1729. manager.reattachRemoteWorkspaceSessionsForWindow(win as never, "renderer-reload");
  1730. expect(win.webContents.postMessage).not.toHaveBeenCalled();
  1731. const mobile = manager.attachRemoteWorkspaceSessionHost({
  1732. windowId: 1,
  1733. remoteSessionId: "mobile-scope",
  1734. workspacePath: "/new",
  1735. workspaceIdentity: remote.workspaceIdentity,
  1736. workspaceKey: remote.workspaceIdentity,
  1737. clientMode: "web-remote-replayable",
  1738. });
  1739. expect(mobile.process).toBe(child);
  1740. child.emit("message", {
  1741. type: HostResponseTypes.RemoteWorkspaceReconnected,
  1742. previousRemoteSessionId: "mobile-scope",
  1743. descriptor: { ...remote, remoteSessionId: "mobile-reconnected", generation: 2 },
  1744. });
  1745. await vi.waitFor(() =>
  1746. expect(remoteControl.replaceRemoteSession).toHaveBeenCalledWith(
  1747. expect.objectContaining({ sessionId: "mobile-reconnected" }),
  1748. ),
  1749. );
  1750. expect(win.webContents.postMessage).not.toHaveBeenCalled();
  1751. manager.disposeRemoteWorkspaceSessionsForWindow(101);
  1752. });
  1753. it("Host 退出使尚未完成的项目导航失败,不留下永不返回的请求", async () => {
  1754. const child = new MockUtilityProcess(1001);
  1755. const win = createWindow(1, 101);
  1756. const manager = createManager(new Map([[101, child]]));
  1757. const pending = manager.prepareProjectWorkspace(
  1758. win as never,
  1759. { projectId: null },
  1760. "mobile-project",
  1761. );
  1762. const rejected = expect(pending).rejects.toThrow("Host");
  1763. child.emit("exit", 1);
  1764. await rejected;
  1765. });
  1766. it("Host 返回目录后、首次配置同步完成前退出也必须结束导航请求", async () => {
  1767. const child = new MockUtilityProcess(1001);
  1768. child.postMessage.mockImplementation(() => undefined);
  1769. const win = createWindow(1, 101);
  1770. const manager = createManager(new Map([[101, child]]));
  1771. const rejected = vi.fn();
  1772. void manager
  1773. .prepareProjectWorkspace(
  1774. win as never,
  1775. { projectId: "p", hostId: "remote:server:s" },
  1776. "mobile-project",
  1777. )
  1778. .catch(rejected);
  1779. child.emit("message", {
  1780. type: HostResponseTypes.ProjectWorkspacePrepared,
  1781. requestId: "mobile-project",
  1782. result: {
  1783. ok: true,
  1784. value: {
  1785. projectId: "p",
  1786. hostId: "remote:server:s",
  1787. workspacePath: "/new",
  1788. workspaceIdentity: "remote:server:s:/new",
  1789. additionalDirectories: [],
  1790. remote: {
  1791. sourceServerId: "s",
  1792. remoteSessionId: "mobile-scope",
  1793. workspacePath: "/new",
  1794. workspaceIdentity: "remote:server:s:/new",
  1795. generation: 1,
  1796. target: sshTarget,
  1797. },
  1798. },
  1799. },
  1800. });
  1801. child.emit("exit", 1);
  1802. await vi.waitFor(() =>
  1803. expect(rejected).toHaveBeenCalledWith(
  1804. expect.objectContaining({ message: expect.stringContaining("Host") }),
  1805. ),
  1806. );
  1807. });
  1808. it("窗口关闭后不能把迟到的配置成功结果返回为导航成功", async () => {
  1809. const child = new MockUtilityProcess(1001);
  1810. child.postMessage.mockImplementation(() => undefined);
  1811. const win = createWindow(1, 101);
  1812. const manager = createManager(new Map([[101, child]]));
  1813. const settled = vi.fn();
  1814. void manager
  1815. .prepareProjectWorkspace(
  1816. win as never,
  1817. { projectId: "p", hostId: "remote:server:s" },
  1818. "mobile-project",
  1819. )
  1820. .then(
  1821. () => settled("success"),
  1822. () => settled("rejected"),
  1823. );
  1824. child.emit("message", {
  1825. type: HostResponseTypes.ProjectWorkspacePrepared,
  1826. requestId: "mobile-project",
  1827. result: {
  1828. ok: true,
  1829. value: {
  1830. projectId: "p",
  1831. hostId: "remote:server:s",
  1832. workspacePath: "/new",
  1833. workspaceIdentity: "remote:server:s:/new",
  1834. additionalDirectories: [],
  1835. remote: {
  1836. sourceServerId: "s",
  1837. remoteSessionId: "mobile-scope",
  1838. workspacePath: "/new",
  1839. workspaceIdentity: "remote:server:s:/new",
  1840. generation: 1,
  1841. target: sshTarget,
  1842. },
  1843. },
  1844. },
  1845. });
  1846. await vi.waitFor(() =>
  1847. expect(child.postMessage).toHaveBeenCalledWith(
  1848. expect.objectContaining({ type: HostMessageTypes.ProviderProvisioningExecute }),
  1849. ),
  1850. );
  1851. const command = child.postMessage.mock.calls.find(
  1852. ([message]) => message.type === HostMessageTypes.ProviderProvisioningExecute,
  1853. )![0];
  1854. manager.disposeRemoteWorkspaceSessionsForWindow(101);
  1855. child.emit("message", {
  1856. type: HostResponseTypes.ProviderProvisioningExecutionResult,
  1857. requestId: command.requestId,
  1858. environmentKey: command.environmentKey,
  1859. status: "applied",
  1860. });
  1861. await vi.waitFor(() => expect(settled).toHaveBeenCalled());
  1862. expect(settled).toHaveBeenCalledWith("rejected");
  1863. });
  1864. });
  1865. describe("mobile scope admission joins", () => {
  1866. function setup() {
  1867. const child = new MockUtilityProcess(1001);
  1868. const win = createWindow(1, 101);
  1869. const reportRemoteConnectionStateChanged = vi.fn();
  1870. const manager = createManager(new Map([[101, child]]), { reportRemoteConnectionStateChanged });
  1871. const value = {
  1872. projectId: "p",
  1873. hostId: "remote:server:s",
  1874. workspacePath: "/new",
  1875. workspaceIdentity: "remote:server:s:/new",
  1876. additionalDirectories: [],
  1877. remote: {
  1878. sourceServerId: "s",
  1879. remoteSessionId: "mobile-scope",
  1880. workspacePath: "/new",
  1881. workspaceIdentity: "remote:server:s:/new",
  1882. generation: 1,
  1883. target: sshTarget,
  1884. },
  1885. };
  1886. const prepare = (requestId: string) => {
  1887. const result = manager.prepareProjectWorkspace(
  1888. win as never,
  1889. { projectId: "p", hostId: value.hostId },
  1890. requestId,
  1891. );
  1892. child.emit("message", {
  1893. type: HostResponseTypes.ProjectWorkspacePrepared,
  1894. requestId,
  1895. result: { ok: true, value },
  1896. });
  1897. return result;
  1898. };
  1899. return { child, win, manager, prepare, reportRemoteConnectionStateChanged };
  1900. }
  1901. it("a second navigation waits for the shared scope's initial provisioning", async () => {
  1902. const { child, manager, prepare } = setup();
  1903. child.postMessage.mockImplementation(() => undefined);
  1904. const first = prepare("first");
  1905. await vi.waitFor(() =>
  1906. expect(child.postMessage).toHaveBeenCalledWith(
  1907. expect.objectContaining({ type: HostMessageTypes.ProviderProvisioningExecute }),
  1908. ),
  1909. );
  1910. const settled = vi.fn();
  1911. const second = prepare("second").then(settled);
  1912. await Promise.resolve();
  1913. await Promise.resolve();
  1914. const completedBeforeProvisioning = settled.mock.calls.length;
  1915. const command = child.postMessage.mock.calls.find(
  1916. ([message]) => message.type === HostMessageTypes.ProviderProvisioningExecute,
  1917. )![0];
  1918. child.emit("message", {
  1919. type: HostResponseTypes.ProviderProvisioningExecutionResult,
  1920. requestId: command.requestId,
  1921. environmentKey: command.environmentKey,
  1922. status: "applied",
  1923. });
  1924. await Promise.all([first, second]);
  1925. manager.disposeRemoteWorkspaceSessionsForWindow(101);
  1926. expect(completedBeforeProvisioning).toBe(0);
  1927. });
  1928. it("desktop adoption of a mobile scope reports connection only after renderer readiness", async () => {
  1929. const { child, win, manager, prepare, reportRemoteConnectionStateChanged } = setup();
  1930. await prepare("mobile");
  1931. const desktop = manager.createRemoteWorkspaceSession(
  1932. win as never,
  1933. sshTarget,
  1934. "desktop",
  1935. undefined,
  1936. { remoteUsageTelemetryEligible: true },
  1937. );
  1938. await emitConnected({ child, requestId: "desktop", remoteSessionId: "mobile-scope" });
  1939. expect(reportRemoteConnectionStateChanged).not.toHaveBeenCalled();
  1940. confirmLatestScopedAttachment(manager, win);
  1941. await desktop;
  1942. expect(reportRemoteConnectionStateChanged).toHaveBeenCalledWith({
  1943. rendererId: 101,
  1944. remoteKind: "ssh",
  1945. transition: "connected",
  1946. });
  1947. manager.disposeRemoteWorkspaceSessionsForWindow(101);
  1948. });
  1949. it("新建连接未带 context 时,手机桥接必须等 UI 绑定选中目录后才能通过 identity 校验", async () => {
  1950. // 回归锁定(3.12.0 手机远控连不上 WSL 项目):新建连接不带 context,Host descriptor 停留在 "/",
  1951. // identity 由解析后的 target 生成;UI tab 用未解析 target 生成的 identity 与之不同。
  1952. // BindRemoteWorkspaceSessionContext 是唯一能让 descriptor 与 tab 对齐的入口,缺了它桥接必然被拒。
  1953. const child = new MockUtilityProcess(1001);
  1954. const win = createWindow(1, 101);
  1955. const resolvedWslTarget = { kind: "wsl", distro: "Ubuntu", user: "dev" } as const;
  1956. const manager = createManager(new Map([[101, child]]), {
  1957. resolveWslTarget: async () => resolvedWslTarget,
  1958. });
  1959. const connecting = manager.createRemoteWorkspaceSession(
  1960. win as never,
  1961. { kind: "wsl" },
  1962. "connect-wsl",
  1963. );
  1964. for (let index = 0; index < 6; index += 1) await Promise.resolve();
  1965. await emitConnected({
  1966. child,
  1967. requestId: "connect-wsl",
  1968. remoteSessionId: "remote-session-1",
  1969. target: resolvedWslTarget,
  1970. });
  1971. confirmLatestScopedAttachment(manager, win);
  1972. await connecting;
  1973. const tabIdentity = "remote:wsl:default:/home/dev";
  1974. const attachMobile = () =>
  1975. manager.attachRemoteWorkspaceSessionHost({
  1976. windowId: 1,
  1977. remoteSessionId: "remote-session-1",
  1978. workspacePath: "/home/dev",
  1979. workspaceIdentity: tabIdentity,
  1980. workspaceKey: tabIdentity,
  1981. clientMode: "web-remote-replayable",
  1982. });
  1983. expect(attachMobile).toThrow("远程 workspaceKey 与 logical session 不匹配。");
  1984. child.postMessage.mockClear();
  1985. const previousAttachmentId = getLatestScopedAttachment(win).attachmentId;
  1986. const binding = manager.bindRemoteWorkspaceSessionContext(
  1987. "remote-session-1",
  1988. { workspacePath: "/home/dev", workspaceIdentity: tabIdentity },
  1989. 101,
  1990. );
  1991. // R3 的 main bind 先等 Host 回 RemoteWorkspaceContextBound ACK,再换代 renderer attachment。
  1992. const bindRequest = child.postMessage.mock.calls.find(
  1993. ([message]) => message.type === HostMessageTypes.BindRemoteWorkspaceContext,
  1994. )?.[0] as { requestId: string };
  1995. expect(bindRequest).toBeDefined();
  1996. child.emit("message", {
  1997. type: HostResponseTypes.RemoteWorkspaceContextBound,
  1998. requestId: bindRequest.requestId,
  1999. });
  2000. // 合并后 bind 仍等待新的 scoped attachment;不能用旧 attachment 的 ACK 越过新门禁。
  2001. await vi.waitFor(() =>
  2002. expect(getLatestScopedAttachment(win).attachmentId).not.toBe(previousAttachmentId),
  2003. );
  2004. confirmLatestScopedAttachment(manager, win);
  2005. await binding;
  2006. child.postMessage.mockClear();
  2007. expect(attachMobile().remoteKind).toBe("wsl");
  2008. expect(child.postMessage.mock.calls[0]?.[0]).toMatchObject({
  2009. type: HostMessageTypes.AttachServicePort,
  2010. clientMode: "web-remote-replayable",
  2011. scope: {
  2012. kind: "remote",
  2013. remoteSessionId: "remote-session-1",
  2014. workspacePath: "/home/dev",
  2015. workspaceIdentity: tabIdentity,
  2016. },
  2017. });
  2018. });
  2019. });