webRemoteControlSharedHostAttachments.ts 6.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206
  1. import { BrowserWindow, MessageChannelMain } from "electron";
  2. import type { MessagePortMain, UtilityProcess as ElectronUtilityProcess } from "electron";
  3. import { HostMessageTypes, type RemoteUsageRemoteKind } from "@zcode/shared";
  4. type WebRemoteControlSharedHostKind = "local" | "remote";
  5. interface WebRemoteControlSharedHostAttachContext {
  6. kind: WebRemoteControlSharedHostKind;
  7. terminalOwnerId?: string;
  8. workspacePath: string;
  9. workspaceIdentity?: string;
  10. remoteSessionId?: string;
  11. initialTaskId?: string;
  12. }
  13. interface WebRemoteControlSharedHostAttachment {
  14. entryId: string;
  15. attachmentId: string;
  16. process: ElectronUtilityProcess;
  17. port: MessagePortMain;
  18. remoteKind?: RemoteUsageRemoteKind;
  19. }
  20. interface WebRemoteControlSharedHostError extends Error {
  21. code:
  22. | "DESKTOP_HOST_MISSING"
  23. | "REMOTE_WORKSPACE_IDENTITY_MISSING"
  24. | "REMOTE_WORKSPACE_IDENTITY_MISMATCH"
  25. | "REMOTE_SESSION_MISSING"
  26. | "REMOTE_SESSION_WINDOW_MISMATCH";
  27. }
  28. function createSharedHostError(
  29. code: WebRemoteControlSharedHostError["code"],
  30. message: string,
  31. ): WebRemoteControlSharedHostError {
  32. const error = new Error(message) as WebRemoteControlSharedHostError;
  33. error.code = code;
  34. return error;
  35. }
  36. export function createWebRemoteControlSharedHostAttachments(dependencies: {
  37. windowHostProcessMap: Map<number, ElectronUtilityProcess>;
  38. createMessageChannel?: () => { port1: MessagePortMain; port2: MessagePortMain };
  39. attachRemoteWorkspaceSessionHost: (params: {
  40. windowId: number;
  41. remoteSessionId: string;
  42. workspacePath: string;
  43. workspaceIdentity: string;
  44. workspaceKey: string;
  45. clientMode: "web-remote-replayable";
  46. terminalOwnerId?: string;
  47. }) => {
  48. process: ElectronUtilityProcess;
  49. port: MessagePortMain;
  50. remoteKind: RemoteUsageRemoteKind;
  51. };
  52. logger: {
  53. info: (...args: unknown[]) => void;
  54. warn: (...args: unknown[]) => void;
  55. error: (...args: unknown[]) => void;
  56. };
  57. }) {
  58. let nextAttachmentId = 0;
  59. const attachments = new Map<
  60. string,
  61. {
  62. windowId: number;
  63. remoteSessionId?: string;
  64. port: MessagePortMain;
  65. }
  66. >();
  67. function createMessageChannel() {
  68. return dependencies.createMessageChannel?.() ?? new MessageChannelMain();
  69. }
  70. function attachLocalHost(
  71. windowId: number,
  72. terminalOwnerId?: string,
  73. ): WebRemoteControlSharedHostAttachment {
  74. const hostProcessWindowId = BrowserWindow.fromId(windowId)?.webContents.id ?? windowId;
  75. const process = dependencies.windowHostProcessMap.get(hostProcessWindowId);
  76. if (!process) {
  77. throw createSharedHostError(
  78. "DESKTOP_HOST_MISSING",
  79. `未找到桌面窗口 host process,windowId=${windowId}`,
  80. );
  81. }
  82. const { port1, port2 } = createMessageChannel();
  83. const attachmentId = `shared-host-attachment-${++nextAttachmentId}`;
  84. process.postMessage(
  85. {
  86. type: HostMessageTypes.AttachServicePort,
  87. requestId: `shared-host-request-${nextAttachmentId}`,
  88. attachmentId,
  89. clientMode: "web-remote-replayable",
  90. ...(terminalOwnerId ? { terminalOwnerId } : {}),
  91. scope: { kind: "local" },
  92. },
  93. [port2],
  94. );
  95. attachments.set(attachmentId, { windowId, port: port1 });
  96. return {
  97. entryId: `desktop-host:${windowId}`,
  98. attachmentId,
  99. process,
  100. port: port1,
  101. };
  102. }
  103. async function attachWorkspaceHost(
  104. windowId: number,
  105. context: WebRemoteControlSharedHostAttachContext,
  106. ): Promise<WebRemoteControlSharedHostAttachment> {
  107. if (context.kind === "local") {
  108. return attachLocalHost(windowId, context.terminalOwnerId);
  109. }
  110. if (!context.remoteSessionId) {
  111. throw createSharedHostError(
  112. "REMOTE_SESSION_MISSING",
  113. "远程 workspace bridge 缺少 remoteSessionId。",
  114. );
  115. }
  116. const workspaceIdentity = context.workspaceIdentity?.trim();
  117. if (!workspaceIdentity) {
  118. throw createSharedHostError(
  119. "REMOTE_WORKSPACE_IDENTITY_MISSING",
  120. "远程 workspace bridge 缺少 workspaceIdentity,不能建立身份隔离。",
  121. );
  122. }
  123. const workspaceKey = workspaceIdentity || context.workspacePath;
  124. const attached = dependencies.attachRemoteWorkspaceSessionHost({
  125. windowId,
  126. remoteSessionId: context.remoteSessionId,
  127. workspacePath: context.workspacePath,
  128. workspaceIdentity,
  129. workspaceKey,
  130. clientMode: "web-remote-replayable",
  131. ...(context.terminalOwnerId ? { terminalOwnerId: context.terminalOwnerId } : {}),
  132. });
  133. const attachmentId = `shared-host-attachment-${++nextAttachmentId}`;
  134. attachments.set(attachmentId, {
  135. windowId,
  136. remoteSessionId: context.remoteSessionId,
  137. port: attached.port,
  138. });
  139. return {
  140. entryId: `remote-session-host:${context.remoteSessionId}`,
  141. attachmentId,
  142. process: attached.process,
  143. port: attached.port,
  144. remoteKind: attached.remoteKind,
  145. };
  146. }
  147. function releaseAttachment(attachmentId: string): void {
  148. const attachment = attachments.get(attachmentId);
  149. if (!attachment) {
  150. return;
  151. }
  152. attachments.delete(attachmentId);
  153. try {
  154. attachment.port.close();
  155. } catch (error) {
  156. dependencies.logger.warn("[web-remote-control] failed to close shared host attachment", {
  157. attachmentId,
  158. error,
  159. });
  160. }
  161. }
  162. function disposeWindow(windowId: number): void {
  163. for (const [attachmentId, attachment] of Array.from(attachments)) {
  164. if (attachment.windowId === windowId) {
  165. releaseAttachment(attachmentId);
  166. }
  167. }
  168. }
  169. function disposeRemoteSession(remoteSessionId: string): void {
  170. for (const [attachmentId, attachment] of Array.from(attachments)) {
  171. if (attachment.remoteSessionId === remoteSessionId) {
  172. releaseAttachment(attachmentId);
  173. }
  174. }
  175. }
  176. function setTerminalOwner(windowId: number, ownerId: string | null): void {
  177. // local/remote attachment 都归该窗口已有 Host;不把页面 owner 绑定到临时 port。
  178. const webContentsId = BrowserWindow.fromId(windowId)?.webContents.id ?? windowId;
  179. dependencies.windowHostProcessMap.get(webContentsId)?.postMessage({
  180. type: HostMessageTypes.SetTerminalOwner,
  181. ownerId,
  182. });
  183. }
  184. return {
  185. setTerminalOwner,
  186. attachWorkspaceHost,
  187. releaseAttachment,
  188. disposeWindow,
  189. disposeRemoteSession,
  190. };
  191. }