desktopRemoteSessions.test.ts 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991
  1. import { EventEmitter } from "node:events";
  2. import { beforeEach, describe, expect, it, vi } from "vitest";
  3. import {
  4. buildRemoteWorkspaceIdentity,
  5. HostMessageTypes,
  6. HostResponseTypes,
  7. InternalChannels,
  8. PlatformChannels,
  9. type RemoteTarget,
  10. } from "@zcode/shared";
  11. import { createRemoteWorkspaceSessionManager } from "../src/main/desktopRemoteSessions.js";
  12. const { browserWindowMock, channels } = vi.hoisted(() => {
  13. const windows: Array<unknown> = [];
  14. return {
  15. channels: [] as Array<{ port1: { close: ReturnType<typeof vi.fn> }; port2: object }>,
  16. browserWindowMock: {
  17. windows,
  18. fromId: vi.fn(
  19. (id: number) =>
  20. windows.find((candidate) => (candidate as { id: number }).id === id) ?? null,
  21. ),
  22. getAllWindows: vi.fn(() => windows),
  23. },
  24. };
  25. });
  26. vi.mock("electron", () => ({
  27. BrowserWindow: browserWindowMock,
  28. MessageChannelMain: vi.fn(function MessageChannelMainMock() {
  29. const channel = {
  30. port1: {
  31. close: vi.fn(),
  32. start: vi.fn(),
  33. on: vi.fn(),
  34. once: vi.fn(),
  35. off: vi.fn(),
  36. postMessage: vi.fn(),
  37. },
  38. port2: {
  39. close: vi.fn(),
  40. start: vi.fn(),
  41. on: vi.fn(),
  42. once: vi.fn(),
  43. off: vi.fn(),
  44. postMessage: vi.fn(),
  45. },
  46. };
  47. channels.push(channel);
  48. return channel;
  49. }),
  50. }));
  51. class MockUtilityProcess extends EventEmitter {
  52. pid: number;
  53. postMessage: ReturnType<typeof vi.fn>;
  54. provisioningResult: {
  55. status: "applied" | "already-applied" | "unsupported" | "failed" | "rollback_failed";
  56. error?: string;
  57. errorCode?: string;
  58. } = { status: "applied" };
  59. constructor(pid: number) {
  60. super();
  61. this.pid = pid;
  62. this.postMessage = vi.fn((message: unknown) => {
  63. const candidate = message as {
  64. type?: string;
  65. requestId?: string;
  66. environmentKey?: string;
  67. };
  68. if (candidate.type !== HostMessageTypes.ProviderProvisioningExecute) return;
  69. queueMicrotask(() => {
  70. this.emit("message", {
  71. type: HostResponseTypes.ProviderProvisioningExecutionResult,
  72. requestId: candidate.requestId,
  73. environmentKey: candidate.environmentKey,
  74. ...this.provisioningResult,
  75. });
  76. });
  77. });
  78. }
  79. }
  80. function createWindow(id: number, webContentsId: number) {
  81. const win = {
  82. id,
  83. isDestroyed: () => false,
  84. webContents: {
  85. id: webContentsId,
  86. isDestroyed: () => false,
  87. send: vi.fn(),
  88. postMessage: vi.fn(),
  89. },
  90. };
  91. browserWindowMock.windows.push(win);
  92. return win;
  93. }
  94. const sshTarget: RemoteTarget = {
  95. kind: "ssh",
  96. host: "dev.internal",
  97. username: "developer",
  98. };
  99. function createManager(
  100. windowHostProcessMap: Map<number, MockUtilityProcess>,
  101. options?: {
  102. rendererAttachmentReadyTimeoutMs?: number;
  103. reportRemoteConnectionStateChanged?: (params: {
  104. rendererId: number;
  105. remoteKind: RemoteTarget["kind"];
  106. transition:
  107. | "connected"
  108. | "connection-closed"
  109. | "disposed"
  110. | "window-closed"
  111. | "host-exit"
  112. | "app-shutdown";
  113. }) => void;
  114. reportRemoteDisconnect?: (params: {
  115. rendererId: number;
  116. remoteKind: RemoteTarget["kind"];
  117. disconnectReason:
  118. | "connection-closed"
  119. | "disposed"
  120. | "window-closed"
  121. | "host-exit"
  122. | "app-shutdown";
  123. durationMs: number;
  124. }) => void;
  125. monotonicNowMs?: () => number;
  126. resolveWslTarget?: (
  127. target: Extract<RemoteTarget, { kind: "wsl" }>,
  128. ) => Promise<Extract<RemoteTarget, { kind: "wsl" }>>;
  129. logger?: {
  130. info: ReturnType<typeof vi.fn>;
  131. warn: ReturnType<typeof vi.fn>;
  132. error: ReturnType<typeof vi.fn>;
  133. };
  134. },
  135. ) {
  136. return createRemoteWorkspaceSessionManager({
  137. logger: options?.logger ?? { info: vi.fn(), warn: vi.fn(), error: vi.fn() },
  138. windowHostProcessMap: windowHostProcessMap as never,
  139. resolveRemoteAssetDirs: () => ({}),
  140. resolveWslTarget: options?.resolveWslTarget,
  141. rendererAttachmentReadyTimeoutMs: options?.rendererAttachmentReadyTimeoutMs,
  142. reportRemoteConnectionStateChanged: options?.reportRemoteConnectionStateChanged,
  143. reportRemoteDisconnect: options?.reportRemoteDisconnect,
  144. monotonicNowMs: options?.monotonicNowMs,
  145. webRemoteControlManagerRef: { current: null },
  146. });
  147. }
  148. async function emitConnected(params: {
  149. child: MockUtilityProcess;
  150. requestId: string;
  151. remoteSessionId: string;
  152. target?: RemoteTarget;
  153. workspacePath?: string;
  154. workspaceIdentity?: string;
  155. }) {
  156. const target = params.target ?? sshTarget;
  157. const workspacePath = params.workspacePath ?? "/";
  158. params.child.emit("message", {
  159. type: HostResponseTypes.RemoteWorkspaceConnected,
  160. requestId: params.requestId,
  161. descriptor: {
  162. remoteSessionId: params.remoteSessionId,
  163. target,
  164. workspacePath,
  165. workspaceIdentity:
  166. params.workspaceIdentity ?? buildRemoteWorkspaceIdentity(workspacePath, target),
  167. generation: 1,
  168. },
  169. });
  170. // 连接发布前会等待 Environment 首次 Provisioning attempt;测试 Host 在微任务里回包,
  171. // 这里让完整 Promise 链排空后再检查 renderer attachment。
  172. for (let index = 0; index < 6; index += 1) await Promise.resolve();
  173. }
  174. function getLatestScopedAttachment(win: ReturnType<typeof createWindow>): {
  175. attachmentId: string;
  176. sessionId: string;
  177. } {
  178. const call = win.webContents.postMessage.mock.calls.findLast(
  179. ([channel]) => channel === InternalChannels.ScopedServicePort,
  180. );
  181. expect(call).toBeDefined();
  182. return call?.[1] as { attachmentId: string; sessionId: string };
  183. }
  184. function confirmLatestScopedAttachment(
  185. manager: ReturnType<typeof createManager>,
  186. win: ReturnType<typeof createWindow>,
  187. ): void {
  188. const payload = getLatestScopedAttachment(win);
  189. manager.confirmRendererAttachmentReady(win.webContents.id, payload);
  190. }
  191. describe("desktopRemoteSessions R1 window Host forwarding", () => {
  192. beforeEach(() => {
  193. browserWindowMock.windows.length = 0;
  194. channels.length = 0;
  195. browserWindowMock.fromId.mockClear();
  196. browserWindowMock.getAllWindows.mockClear();
  197. });
  198. it("按 requestId 把窗口 Host 的远程连接进度转发给发起连接的 renderer", () => {
  199. const child = new MockUtilityProcess(1001);
  200. const win = createWindow(1, 101);
  201. const manager = createManager(new Map([[101, child]]));
  202. void manager.createRemoteWorkspaceSession(win as never, sshTarget, "connect-1");
  203. win.webContents.send.mockClear();
  204. child.emit("message", {
  205. type: HostResponseTypes.RemoteWorkspaceConnectionLog,
  206. requestId: "connect-1",
  207. level: "info",
  208. message: "detecting remote env...",
  209. });
  210. expect(win.webContents.send).toHaveBeenCalledWith(
  211. PlatformChannels.RemoteConnectionLog,
  212. expect.objectContaining({
  213. requestId: "connect-1",
  214. level: "info",
  215. message: "detecting remote env...",
  216. timestamp: expect.stringMatching(/^\d{2}:\d{2}:\d{2}$/u),
  217. }),
  218. );
  219. });
  220. it("连接请求发给窗口唯一 Local Host,成功后由同一进程暴露 remote-scoped port", async () => {
  221. const child = new MockUtilityProcess(1001);
  222. const win = createWindow(1, 101);
  223. const manager = createManager(new Map([[101, child]]));
  224. const connecting = manager.createRemoteWorkspaceSession(win as never, sshTarget, "connect-1");
  225. expect(child.postMessage).toHaveBeenCalledWith(
  226. expect.objectContaining({
  227. type: HostMessageTypes.ConnectRemoteWorkspace,
  228. requestId: "connect-1",
  229. target: sshTarget,
  230. }),
  231. );
  232. await emitConnected({ child, requestId: "connect-1", remoteSessionId: "remote-session-1" });
  233. let connectionSettled = false;
  234. void connecting.then(() => {
  235. connectionSettled = true;
  236. });
  237. await Promise.resolve();
  238. expect(connectionSettled).toBe(false);
  239. confirmLatestScopedAttachment(manager, win);
  240. await expect(connecting).resolves.toBe("remote-session-1");
  241. expect(child.postMessage).toHaveBeenCalledWith(
  242. expect.objectContaining({
  243. type: HostMessageTypes.AttachServicePort,
  244. clientMode: "desktop-continuous",
  245. scope: expect.objectContaining({
  246. kind: "remote",
  247. remoteSessionId: "remote-session-1",
  248. workspaceIdentity: buildRemoteWorkspaceIdentity("/", sshTarget),
  249. }),
  250. }),
  251. expect.any(Array),
  252. );
  253. expect(win.webContents.postMessage).toHaveBeenCalledWith(
  254. InternalChannels.ScopedServicePort,
  255. expect.objectContaining({
  256. attachmentId: expect.any(String),
  257. sessionId: "remote-session-1",
  258. target: sshTarget,
  259. }),
  260. expect.any(Array),
  261. );
  262. });
  263. it.each(["failed", "rollback_failed", "unsupported"] as const)(
  264. "首次 Provisioning 返回 %s 时拒绝连接且不发布 Renderer port",
  265. async (status) => {
  266. const child = new MockUtilityProcess(1001);
  267. child.provisioningResult = { status, error: "sync unavailable" };
  268. const win = createWindow(1, 101);
  269. const manager = createManager(new Map([[101, child]]));
  270. const connecting = manager.createRemoteWorkspaceSession(win as never, sshTarget, "connect-1");
  271. await emitConnected({ child, requestId: "connect-1", remoteSessionId: "remote-session-1" });
  272. await expect(connecting).rejects.toThrow(/Provider Provisioning/u);
  273. expect(win.webContents.postMessage).not.toHaveBeenCalledWith(
  274. InternalChannels.ScopedServicePort,
  275. expect.anything(),
  276. expect.anything(),
  277. );
  278. },
  279. );
  280. it("已连接后的 Provisioning 失败只记录结构化 warning,不拆除 Workspace", async () => {
  281. const child = new MockUtilityProcess(1001);
  282. const win = createWindow(1, 101);
  283. const logger = { info: vi.fn(), warn: vi.fn(), error: vi.fn() };
  284. const manager = createManager(new Map([[101, child]]), { logger });
  285. const connecting = manager.createRemoteWorkspaceSession(
  286. win as never,
  287. sshTarget,
  288. "connect-1",
  289. undefined,
  290. { remoteUsageTelemetryEligible: true },
  291. );
  292. await emitConnected({ child, requestId: "connect-1", remoteSessionId: "remote-session-1" });
  293. confirmLatestScopedAttachment(manager, win);
  294. await connecting;
  295. child.provisioningResult = { status: "failed", error: "token=secret-value" };
  296. child.emit("message", {
  297. type: HostResponseTypes.ProviderProvisioningSourceChanged,
  298. trigger: "personal-config",
  299. });
  300. for (let index = 0; index < 6; index += 1) await Promise.resolve();
  301. expect(logger.warn).toHaveBeenCalledWith(
  302. "[provider-provisioning] Environment sync did not apply",
  303. expect.objectContaining({
  304. environmentKey: expect.any(String),
  305. trigger: "personal-config",
  306. status: "failed",
  307. }),
  308. );
  309. expect(logger.warn.mock.calls.at(-1)?.[1]).not.toHaveProperty("errorSummary");
  310. expect(manager.getRemoteConnectionStats()).toEqual({
  311. activeSessionCount: 1,
  312. activeTargetCount: 1,
  313. });
  314. });
  315. it.each([undefined, "source-read-failed"])(
  316. "首次同步失败把安全错误码 %s 写入日志和连接面板,不泄漏自由文本",
  317. async (errorCode) => {
  318. const child = new MockUtilityProcess(1001);
  319. child.provisioningResult = { status: "failed", error: "token=fixture-secret", errorCode };
  320. const win = createWindow(1, 101);
  321. const logger = { info: vi.fn(), warn: vi.fn(), error: vi.fn() };
  322. const manager = createManager(new Map([[101, child]]), { logger });
  323. const connecting = manager.createRemoteWorkspaceSession(
  324. win as never,
  325. sshTarget,
  326. "connect-diagnostic",
  327. );
  328. const outcome = connecting.catch((error: Error) => error.message);
  329. await emitConnected({
  330. child,
  331. requestId: "connect-diagnostic",
  332. remoteSessionId: "remote-diagnostic",
  333. });
  334. const code = errorCode ?? "target-apply-failed";
  335. expect(logger.warn).toHaveBeenCalledWith(
  336. "[provider-provisioning] Environment sync did not apply",
  337. expect.objectContaining({
  338. trigger: "environment-online",
  339. status: "failed",
  340. errorCode: code,
  341. }),
  342. );
  343. expect(await outcome).toContain(code);
  344. expect(win.webContents.send).toHaveBeenCalledWith(
  345. PlatformChannels.RemoteConnectionLog,
  346. expect.objectContaining({
  347. requestId: "connect-diagnostic",
  348. level: "error",
  349. message: expect.stringContaining(code),
  350. }),
  351. );
  352. expect(
  353. JSON.stringify([logger.warn.mock.calls, win.webContents.send.mock.calls, await outcome]),
  354. ).not.toContain("fixture-secret");
  355. expect(win.webContents.postMessage).not.toHaveBeenCalled();
  356. expect(child.postMessage).toHaveBeenCalledWith(
  357. expect.objectContaining({ type: HostMessageTypes.DisposeRemoteWorkspaceSession }),
  358. );
  359. },
  360. );
  361. it("只在 eligible 连接完成 renderer ACK 后计入并发并上报 connected gauge", async () => {
  362. const child = new MockUtilityProcess(1001);
  363. const win = createWindow(1, 101);
  364. const reportRemoteConnectionStateChanged = vi.fn();
  365. const reportRemoteDisconnect = vi.fn();
  366. const manager = createManager(new Map([[101, child]]), {
  367. reportRemoteConnectionStateChanged,
  368. reportRemoteDisconnect,
  369. });
  370. const eligible = manager.createRemoteWorkspaceSession(
  371. win as never,
  372. sshTarget,
  373. "connect-eligible",
  374. undefined,
  375. { remoteUsageTelemetryEligible: true },
  376. );
  377. await emitConnected({
  378. child,
  379. requestId: "connect-eligible",
  380. remoteSessionId: "remote-eligible",
  381. });
  382. expect(manager.getRemoteConnectionStats()).toEqual({
  383. activeSessionCount: 0,
  384. activeTargetCount: 0,
  385. });
  386. confirmLatestScopedAttachment(manager, win);
  387. await eligible;
  388. expect(manager.getRemoteConnectionStats()).toEqual({
  389. activeSessionCount: 1,
  390. activeTargetCount: 1,
  391. });
  392. expect(reportRemoteConnectionStateChanged).toHaveBeenCalledWith({
  393. rendererId: 101,
  394. remoteKind: "ssh",
  395. transition: "connected",
  396. });
  397. const internal = manager.createRemoteWorkspaceSession(
  398. win as never,
  399. { kind: "docker", container: "internal-only" },
  400. "connect-internal",
  401. );
  402. await emitConnected({
  403. child,
  404. requestId: "connect-internal",
  405. remoteSessionId: "remote-internal",
  406. target: { kind: "docker", container: "internal-only" },
  407. });
  408. confirmLatestScopedAttachment(manager, win);
  409. await internal;
  410. expect(manager.getRemoteConnectionStats()).toEqual({
  411. activeSessionCount: 1,
  412. activeTargetCount: 1,
  413. });
  414. manager.disposeRemoteWorkspaceSession("remote-internal", "internal-finished");
  415. expect(reportRemoteConnectionStateChanged).toHaveBeenCalledOnce();
  416. expect(reportRemoteDisconnect).not.toHaveBeenCalled();
  417. });
  418. it("连接异常关闭后上报一次 after-state gauge 与时长,随后 dispose 不重复", async () => {
  419. const child = new MockUtilityProcess(1001);
  420. const win = createWindow(1, 101);
  421. let now = 100;
  422. const reportRemoteConnectionStateChanged = vi.fn();
  423. const reportRemoteDisconnect = vi.fn();
  424. const manager = createManager(new Map([[101, child]]), {
  425. monotonicNowMs: () => now,
  426. reportRemoteConnectionStateChanged,
  427. reportRemoteDisconnect,
  428. });
  429. const connecting = manager.createRemoteWorkspaceSession(
  430. win as never,
  431. sshTarget,
  432. "connect-1",
  433. undefined,
  434. { remoteUsageTelemetryEligible: true },
  435. );
  436. await emitConnected({ child, requestId: "connect-1", remoteSessionId: "remote-session-1" });
  437. confirmLatestScopedAttachment(manager, win);
  438. await connecting;
  439. now = 600;
  440. child.emit("message", {
  441. type: HostResponseTypes.RemoteWorkspaceClosed,
  442. remoteSessionId: "remote-session-1",
  443. reason: "connection-closed",
  444. exitCode: 255,
  445. signal: null,
  446. });
  447. expect(manager.getRemoteConnectionStats()).toEqual({
  448. activeSessionCount: 0,
  449. activeTargetCount: 0,
  450. });
  451. expect(reportRemoteConnectionStateChanged).toHaveBeenNthCalledWith(2, {
  452. rendererId: 101,
  453. remoteKind: "ssh",
  454. transition: "connection-closed",
  455. });
  456. expect(reportRemoteDisconnect).toHaveBeenCalledWith({
  457. rendererId: 101,
  458. remoteKind: "ssh",
  459. disconnectReason: "connection-closed",
  460. durationMs: 500,
  461. });
  462. manager.disposeRemoteWorkspaceSession("remote-session-1", "tab-closed");
  463. expect(reportRemoteConnectionStateChanged).toHaveBeenCalledTimes(2);
  464. expect(reportRemoteDisconnect).toHaveBeenCalledOnce();
  465. });
  466. it.each([
  467. ["window-closed", "window"],
  468. ["host-exit", "host"],
  469. ["app-shutdown", "app"],
  470. ] as const)("%s 退出 eligible route 时上报对应终态", async (reason, owner) => {
  471. const child = new MockUtilityProcess(1001);
  472. const win = createWindow(1, 101);
  473. let now = 10;
  474. const reportRemoteConnectionStateChanged = vi.fn();
  475. const reportRemoteDisconnect = vi.fn();
  476. const manager = createManager(new Map([[101, child]]), {
  477. monotonicNowMs: () => now,
  478. reportRemoteConnectionStateChanged,
  479. reportRemoteDisconnect,
  480. });
  481. const connecting = manager.createRemoteWorkspaceSession(
  482. win as never,
  483. sshTarget,
  484. "connect-1",
  485. undefined,
  486. { remoteUsageTelemetryEligible: true },
  487. );
  488. await emitConnected({ child, requestId: "connect-1", remoteSessionId: "remote-session-1" });
  489. confirmLatestScopedAttachment(manager, win);
  490. await connecting;
  491. now = 210;
  492. if (owner === "window") manager.disposeRemoteWorkspaceSessionsForWindow(101);
  493. else if (owner === "host") child.emit("exit");
  494. else await manager.disposeAllAndWaitForAppShutdown("app-quit");
  495. expect(reportRemoteConnectionStateChanged).toHaveBeenLastCalledWith({
  496. rendererId: 101,
  497. remoteKind: "ssh",
  498. transition: reason,
  499. });
  500. expect(reportRemoteDisconnect).toHaveBeenCalledWith({
  501. rendererId: 101,
  502. remoteKind: "ssh",
  503. disconnectReason: reason,
  504. durationMs: 200,
  505. });
  506. expect(manager.getRemoteConnectionStats()).toEqual({
  507. activeSessionCount: 0,
  508. activeTargetCount: 0,
  509. });
  510. });
  511. it("按脱敏 target identity 去重诊断计数,但保留每个逻辑 session", async () => {
  512. const child = new MockUtilityProcess(1001);
  513. const win = createWindow(1, 101);
  514. const manager = createManager(new Map([[101, child]]));
  515. const targets: RemoteTarget[] = [
  516. sshTarget,
  517. sshTarget,
  518. { kind: "server", url: "ws://studio.example.com/ws" },
  519. { kind: "server", url: "http://studio.example.com" },
  520. { kind: "server", url: "wss://studio.example.com/ws" },
  521. { kind: "server", url: "https://studio.example.com" },
  522. ];
  523. for (const [index, target] of targets.entries()) {
  524. const requestId = `connect-${index}`;
  525. const remoteSessionId = `remote-${index}`;
  526. const connecting = manager.createRemoteWorkspaceSession(
  527. win as never,
  528. target,
  529. requestId,
  530. undefined,
  531. { remoteUsageTelemetryEligible: true },
  532. );
  533. await emitConnected({ child, requestId, remoteSessionId, target });
  534. confirmLatestScopedAttachment(manager, win);
  535. await connecting;
  536. }
  537. expect(manager.getRemoteConnectionStats()).toEqual({
  538. activeSessionCount: 6,
  539. activeTargetCount: 3,
  540. });
  541. });
  542. it("telemetry callback 抛错不改变连接成功或 dispose 结果", async () => {
  543. const child = new MockUtilityProcess(1001);
  544. const win = createWindow(1, 101);
  545. const reportRemoteConnectionStateChanged = vi.fn(() => {
  546. throw new Error("gauge reporter unavailable");
  547. });
  548. const reportRemoteDisconnect = vi.fn(() => {
  549. throw new Error("disconnect reporter unavailable");
  550. });
  551. const manager = createManager(new Map([[101, child]]), {
  552. reportRemoteConnectionStateChanged,
  553. reportRemoteDisconnect,
  554. });
  555. const connecting = manager.createRemoteWorkspaceSession(
  556. win as never,
  557. sshTarget,
  558. "connect-1",
  559. undefined,
  560. { remoteUsageTelemetryEligible: true },
  561. );
  562. await emitConnected({ child, requestId: "connect-1", remoteSessionId: "remote-session-1" });
  563. expect(() => confirmLatestScopedAttachment(manager, win)).not.toThrow();
  564. await expect(connecting).resolves.toBe("remote-session-1");
  565. expect(() =>
  566. manager.disposeRemoteWorkspaceSession("remote-session-1", "tab-closed"),
  567. ).not.toThrow();
  568. expect(reportRemoteConnectionStateChanged).toHaveBeenCalledTimes(2);
  569. expect(reportRemoteDisconnect).toHaveBeenCalledOnce();
  570. });
  571. it("WSL target 解析期间进入 app shutdown 后不发送迟到连接", async () => {
  572. const child = new MockUtilityProcess(1001);
  573. const win = createWindow(1, 101);
  574. let resolveWslTarget!: (target: Extract<RemoteTarget, { kind: "wsl" }>) => void;
  575. const manager = createManager(new Map([[101, child]]), {
  576. resolveWslTarget: () =>
  577. new Promise((resolve) => {
  578. resolveWslTarget = resolve;
  579. }),
  580. });
  581. const target = { kind: "wsl", distro: "Ubuntu" } as const;
  582. const connecting = manager.createRemoteWorkspaceSession(win as never, target, "connect-wsl");
  583. await vi.waitFor(() => expect(resolveWslTarget).toBeTypeOf("function"));
  584. await manager.disposeAllAndWaitForAppShutdown("app-quit");
  585. const settled = connecting.catch((error: unknown) => error);
  586. resolveWslTarget(target);
  587. await Promise.resolve();
  588. expect(child.postMessage).not.toHaveBeenCalledWith(
  589. expect.objectContaining({ type: HostMessageTypes.ConnectRemoteWorkspace }),
  590. );
  591. await expect(settled).resolves.toMatchObject({
  592. message: expect.stringContaining("应用正在退出"),
  593. });
  594. });
  595. it("两个窗口的连接、descriptor 和 attachment 都发往各自 Local Host", async () => {
  596. const firstChild = new MockUtilityProcess(1001);
  597. const secondChild = new MockUtilityProcess(1002);
  598. const firstWindow = createWindow(1, 101);
  599. const secondWindow = createWindow(2, 202);
  600. const manager = createManager(
  601. new Map([
  602. [101, firstChild],
  603. [202, secondChild],
  604. ]),
  605. );
  606. const first = manager.createRemoteWorkspaceSession(
  607. firstWindow as never,
  608. sshTarget,
  609. "connect-first",
  610. );
  611. const second = manager.createRemoteWorkspaceSession(
  612. secondWindow as never,
  613. sshTarget,
  614. "connect-second",
  615. );
  616. await emitConnected({
  617. child: firstChild,
  618. requestId: "connect-first",
  619. remoteSessionId: "remote-first",
  620. });
  621. await emitConnected({
  622. child: secondChild,
  623. requestId: "connect-second",
  624. remoteSessionId: "remote-second",
  625. });
  626. confirmLatestScopedAttachment(manager, firstWindow);
  627. confirmLatestScopedAttachment(manager, secondWindow);
  628. await expect(first).resolves.toBe("remote-first");
  629. await expect(second).resolves.toBe("remote-second");
  630. expect(firstChild.postMessage).not.toHaveBeenCalledWith(
  631. expect.objectContaining({
  632. scope: expect.objectContaining({ remoteSessionId: "remote-second" }),
  633. }),
  634. expect.anything(),
  635. );
  636. expect(secondChild.postMessage).not.toHaveBeenCalledWith(
  637. expect.objectContaining({
  638. scope: expect.objectContaining({ remoteSessionId: "remote-first" }),
  639. }),
  640. expect.anything(),
  641. );
  642. const provisioningExecutions = [
  643. ...firstChild.postMessage.mock.calls,
  644. ...secondChild.postMessage.mock.calls,
  645. ].filter(
  646. ([message]) =>
  647. (message as { type?: string }).type === HostMessageTypes.ProviderProvisioningExecute,
  648. );
  649. expect(provisioningExecutions).toHaveLength(1);
  650. });
  651. it("取消 pending connection 只发控制消息,不退出窗口 Host", () => {
  652. const child = new MockUtilityProcess(1001);
  653. const win = createWindow(1, 101);
  654. const manager = createManager(new Map([[101, child]]));
  655. void manager.createRemoteWorkspaceSession(win as never, sshTarget, "connect-cancel");
  656. manager.cancelPendingRemoteWorkspaceSessionsForWindow(101, "user-cancel", "connect-cancel");
  657. expect(child.postMessage).toHaveBeenCalledWith({
  658. type: HostMessageTypes.CancelRemoteWorkspaceConnect,
  659. requestId: "connect-cancel",
  660. });
  661. });
  662. it("绑定 canonical context 后先更新 Host,再重建 identity-validated renderer port", async () => {
  663. const child = new MockUtilityProcess(1001);
  664. const win = createWindow(1, 101);
  665. const manager = createManager(new Map([[101, child]]));
  666. const connecting = manager.createRemoteWorkspaceSession(win as never, sshTarget, "connect-1");
  667. await emitConnected({ child, requestId: "connect-1", remoteSessionId: "remote-session-1" });
  668. confirmLatestScopedAttachment(manager, win);
  669. await connecting;
  670. const firstAttachmentId = getLatestScopedAttachment(win).attachmentId;
  671. child.postMessage.mockClear();
  672. const binding = manager.bindRemoteWorkspaceSessionContext(
  673. "remote-session-1",
  674. {
  675. workspacePath: "/work/demo",
  676. workspaceIdentity: "remote:ssh:dev.internal:22:developer:/work/demo",
  677. },
  678. 101,
  679. );
  680. expect(child.postMessage.mock.calls[0]?.[0]).toMatchObject({
  681. type: HostMessageTypes.BindRemoteWorkspaceContext,
  682. remoteSessionId: "remote-session-1",
  683. workspacePath: "/work/demo",
  684. workspaceIdentity: "remote:ssh:dev.internal:22:developer:/work/demo",
  685. });
  686. expect(child.postMessage.mock.calls[1]?.[0]).toMatchObject({
  687. type: HostMessageTypes.AttachServicePort,
  688. scope: {
  689. kind: "remote",
  690. remoteSessionId: "remote-session-1",
  691. workspacePath: "/work/demo",
  692. workspaceIdentity: "remote:ssh:dev.internal:22:developer:/work/demo",
  693. },
  694. });
  695. expect(child.postMessage).not.toHaveBeenCalledWith({
  696. type: HostMessageTypes.DetachServicePort,
  697. attachmentId: firstAttachmentId,
  698. });
  699. confirmLatestScopedAttachment(manager, win);
  700. await binding;
  701. expect(child.postMessage).toHaveBeenCalledWith({
  702. type: HostMessageTypes.DetachServicePort,
  703. attachmentId: firstAttachmentId,
  704. });
  705. });
  706. it("忽略过期 ready ACK,超时只回收且不提升候选 attachment", async () => {
  707. vi.useFakeTimers();
  708. try {
  709. const child = new MockUtilityProcess(1001);
  710. const win = createWindow(1, 101);
  711. const manager = createManager(new Map([[101, child]]), {
  712. rendererAttachmentReadyTimeoutMs: 10,
  713. });
  714. const connecting = manager.createRemoteWorkspaceSession(win as never, sshTarget, "connect-1");
  715. await emitConnected({ child, requestId: "connect-1", remoteSessionId: "remote-session-1" });
  716. const firstAttachment = getLatestScopedAttachment(win);
  717. confirmLatestScopedAttachment(manager, win);
  718. await connecting;
  719. child.postMessage.mockClear();
  720. const binding = manager.bindRemoteWorkspaceSessionContext(
  721. "remote-session-1",
  722. { workspacePath: "/work/demo" },
  723. 101,
  724. );
  725. const candidateAttachment = getLatestScopedAttachment(win);
  726. manager.confirmRendererAttachmentReady(101, firstAttachment);
  727. const bindingRejection = expect(binding).rejects.toThrow("renderer attachment ready 超时");
  728. await vi.advanceTimersByTimeAsync(10);
  729. await bindingRejection;
  730. expect(child.postMessage).toHaveBeenCalledWith({
  731. type: HostMessageTypes.DetachServicePort,
  732. attachmentId: candidateAttachment.attachmentId,
  733. });
  734. } finally {
  735. vi.useRealTimers();
  736. }
  737. });
  738. it("手机与 Bot runtime 都 attachment 到同一个窗口 Local Host", async () => {
  739. const child = new MockUtilityProcess(1001);
  740. const win = createWindow(1, 101);
  741. const manager = createManager(new Map([[101, child]]));
  742. const workspaceIdentity = "remote:ssh:dev.internal:22:developer:/work/demo";
  743. const connecting = manager.createRemoteWorkspaceSession(win as never, sshTarget, "connect-1", {
  744. workspacePath: "/work/demo",
  745. workspaceIdentity,
  746. });
  747. await emitConnected({
  748. child,
  749. requestId: "connect-1",
  750. remoteSessionId: "remote-session-1",
  751. workspacePath: "/work/demo",
  752. workspaceIdentity,
  753. });
  754. confirmLatestScopedAttachment(manager, win);
  755. await connecting;
  756. child.postMessage.mockClear();
  757. const mobile = manager.attachRemoteWorkspaceSessionHost({
  758. windowId: 1,
  759. remoteSessionId: "remote-session-1",
  760. workspacePath: "/work/demo",
  761. workspaceIdentity,
  762. workspaceKey: workspaceIdentity,
  763. clientMode: "web-remote-replayable",
  764. });
  765. const botPort = await manager.createBotRemoteWorkspaceRuntimePort(win as never, {
  766. target: sshTarget,
  767. workspacePath: "/work/demo",
  768. workspaceIdentity,
  769. });
  770. expect(mobile.process).toBe(child);
  771. expect(botPort).toBeDefined();
  772. expect(child.postMessage).toHaveBeenCalledTimes(2);
  773. for (const [message] of child.postMessage.mock.calls) {
  774. expect(message).toMatchObject({
  775. type: HostMessageTypes.AttachServicePort,
  776. clientMode: "web-remote-replayable",
  777. scope: { kind: "remote", remoteSessionId: "remote-session-1" },
  778. });
  779. }
  780. });
  781. it("renderer reload 只重建 attachment,复用 session 与 Host PID", async () => {
  782. const child = new MockUtilityProcess(1001);
  783. const win = createWindow(1, 101);
  784. const manager = createManager(new Map([[101, child]]));
  785. const connecting = manager.createRemoteWorkspaceSession(win as never, sshTarget, "connect-1");
  786. await emitConnected({ child, requestId: "connect-1", remoteSessionId: "remote-session-1" });
  787. confirmLatestScopedAttachment(manager, win);
  788. await connecting;
  789. child.postMessage.mockClear();
  790. manager.reattachRemoteWorkspaceSessionsForWindow(win as never, "renderer-reload");
  791. expect(child.pid).toBe(1001);
  792. expect(child.postMessage.mock.calls[0]?.[0]).toMatchObject({
  793. type: HostMessageTypes.AttachServicePort,
  794. scope: { kind: "remote", remoteSessionId: "remote-session-1" },
  795. });
  796. expect(
  797. child.postMessage.mock.calls.some(
  798. ([message]) => message.type === HostMessageTypes.ConnectRemoteWorkspace,
  799. ),
  800. ).toBe(false);
  801. confirmLatestScopedAttachment(manager, win);
  802. });
  803. it("连接断开后保留离线路由供 tab dispose,但禁止 reload、手机和 Bot 重新 attachment", async () => {
  804. const child = new MockUtilityProcess(1001);
  805. const win = createWindow(1, 101);
  806. const manager = createManager(new Map([[101, child]]));
  807. const workspacePath = "/work/demo";
  808. const workspaceIdentity = "remote:ssh:dev.internal:22:developer:/work/demo";
  809. const connecting = manager.createRemoteWorkspaceSession(win as never, sshTarget, "connect-1", {
  810. workspacePath,
  811. workspaceIdentity,
  812. });
  813. await emitConnected({
  814. child,
  815. requestId: "connect-1",
  816. remoteSessionId: "remote-session-1",
  817. workspacePath,
  818. workspaceIdentity,
  819. });
  820. confirmLatestScopedAttachment(manager, win);
  821. await connecting;
  822. child.postMessage.mockClear();
  823. child.emit("message", {
  824. type: HostResponseTypes.RemoteWorkspaceClosed,
  825. remoteSessionId: "remote-session-1",
  826. reason: "connection-closed",
  827. exitCode: 255,
  828. signal: null,
  829. });
  830. manager.reattachRemoteWorkspaceSessionsForWindow(win as never, "renderer-reload");
  831. expect(child.postMessage).toHaveBeenCalledWith({
  832. type: HostMessageTypes.DetachServicePort,
  833. attachmentId: expect.any(String),
  834. });
  835. expect(child.postMessage).not.toHaveBeenCalledWith(
  836. expect.objectContaining({ type: HostMessageTypes.AttachServicePort }),
  837. expect.anything(),
  838. );
  839. expect(() =>
  840. manager.attachRemoteWorkspaceSessionHost({
  841. windowId: 1,
  842. remoteSessionId: "remote-session-1",
  843. workspacePath,
  844. workspaceIdentity,
  845. workspaceKey: workspaceIdentity,
  846. clientMode: "web-remote-replayable",
  847. }),
  848. ).toThrow("远程 workspace source 当前离线");
  849. await expect(
  850. manager.createBotRemoteWorkspaceRuntimePort(win as never, {
  851. target: sshTarget,
  852. workspacePath,
  853. workspaceIdentity,
  854. }),
  855. ).rejects.toThrow("未找到可供 Bot attachment 的远程 logical session");
  856. manager.disposeRemoteWorkspaceSession("remote-session-1", "tab-closed");
  857. expect(child.postMessage).toHaveBeenCalledWith(
  858. expect.objectContaining({
  859. type: HostMessageTypes.DisposeRemoteWorkspaceSession,
  860. remoteSessionId: "remote-session-1",
  861. }),
  862. );
  863. });
  864. it("新建连接未带 context 时,手机桥接必须等 UI 绑定选中目录后才能通过 identity 校验", async () => {
  865. // 回归锁定(3.12.0 手机远控连不上 WSL 项目):新建连接不带 context,Host descriptor 停留在 "/",
  866. // identity 由解析后的 target 生成;UI tab 用未解析 target 生成的 identity 与之不同。
  867. // BindRemoteWorkspaceSessionContext 是唯一能让 descriptor 与 tab 对齐的入口,缺了它桥接必然被拒。
  868. const child = new MockUtilityProcess(1001);
  869. const win = createWindow(1, 101);
  870. const resolvedWslTarget = { kind: "wsl", distro: "Ubuntu", user: "dev" } as const;
  871. const manager = createManager(new Map([[101, child]]), {
  872. resolveWslTarget: async () => resolvedWslTarget,
  873. });
  874. const connecting = manager.createRemoteWorkspaceSession(
  875. win as never,
  876. { kind: "wsl" },
  877. "connect-wsl",
  878. );
  879. for (let index = 0; index < 6; index += 1) await Promise.resolve();
  880. await emitConnected({
  881. child,
  882. requestId: "connect-wsl",
  883. remoteSessionId: "remote-session-1",
  884. target: resolvedWslTarget,
  885. });
  886. confirmLatestScopedAttachment(manager, win);
  887. await connecting;
  888. const tabIdentity = "remote:wsl:default:/home/dev";
  889. const attachMobile = () =>
  890. manager.attachRemoteWorkspaceSessionHost({
  891. windowId: 1,
  892. remoteSessionId: "remote-session-1",
  893. workspacePath: "/home/dev",
  894. workspaceIdentity: tabIdentity,
  895. workspaceKey: tabIdentity,
  896. clientMode: "web-remote-replayable",
  897. });
  898. expect(attachMobile).toThrow("远程 workspaceKey 与 logical session 不匹配。");
  899. const binding = manager.bindRemoteWorkspaceSessionContext(
  900. "remote-session-1",
  901. { workspacePath: "/home/dev", workspaceIdentity: tabIdentity },
  902. 101,
  903. );
  904. for (let index = 0; index < 4; index += 1) await Promise.resolve();
  905. confirmLatestScopedAttachment(manager, win);
  906. await binding;
  907. child.postMessage.mockClear();
  908. expect(attachMobile().remoteKind).toBe("wsl");
  909. expect(child.postMessage.mock.calls[0]?.[0]).toMatchObject({
  910. type: HostMessageTypes.AttachServicePort,
  911. clientMode: "web-remote-replayable",
  912. scope: {
  913. kind: "remote",
  914. remoteSessionId: "remote-session-1",
  915. workspacePath: "/home/dev",
  916. workspaceIdentity: tabIdentity,
  917. },
  918. });
  919. });
  920. });