webRemoteControlManager.ts 93 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369
  1. import type { RendererTelemetryEventPayload } from "@zcode/shared";
  2. /* eslint-disable max-lines -- Web 远程控制 manager 承担外部 relay app payload 路由与 workspace bridge 编排。 */
  3. import type { MessagePortMain, UtilityProcess as ElectronUtilityProcess } from "electron";
  4. import { randomUUID } from "node:crypto";
  5. import { MessagePortProtocol, type MessagePortLike, type MessagePortPayload } from "@zcode/rpc";
  6. import {
  7. createAcknowledgedWebRemoteControlRelayProtocol,
  8. type AcknowledgedWebRemoteControlRelayProtocolAdapter,
  9. type WebRemoteControlPayloadSendResult,
  10. } from "@zcode/client";
  11. import {
  12. buildWebRemoteControlExternalQrUrl,
  13. buildWebRemoteControlBridgeResultTelemetry,
  14. buildWebRemoteControlPairResultTelemetry,
  15. classifyRemoteUsageError,
  16. parseRemoteWorkspaceIdentity,
  17. WEB_REMOTE_CONTROL_OUTBOUND_PAYLOAD_BUFFER_TIMEOUT_MS,
  18. type ZCodeEndpointUrls,
  19. type HostPreparedProjectWorkspace,
  20. type HostProjectWorkspaceNavigationInput,
  21. resolveUnrecognizedWebRemoteControlRequest,
  22. resolveWebRemoteControlWorkspaceKey,
  23. type WebRemoteControlAppPayload,
  24. type WebRemoteControlAuthStateChange,
  25. type WebRemoteControlContext,
  26. type WebRemoteControlExternalWorkspaceBridge,
  27. type WebRemoteControlFailure,
  28. type WebRemoteControlFailureReason,
  29. type WebRemoteControlMobileDeviceInfo,
  30. type WebRemoteControlMobileLogPayload,
  31. type WebRemoteControlMobileViewState,
  32. type WebRemoteControlMobileTaskViewUpdatePayload,
  33. type WebRemoteControlPlatformMethod,
  34. type WebRemoteControlPlatformMethodArgsMap,
  35. type WebRemoteControlPlatformMethodResultMap,
  36. type WebRemoteControlPlatformRequestPayload,
  37. type WebRemoteControlPlatformResponsePayload,
  38. type WebRemoteControlRpcTransportPayload,
  39. type WebRemoteControlStartResult,
  40. type WebRemoteControlStatus,
  41. type WebRemoteControlWindowBootstrapResult,
  42. type WebRemoteControlWorkspaceBridgeOpenPayload,
  43. type WebRemoteControlWorkspaceListResult,
  44. type WebRemoteControlWorkspaceTarget,
  45. type RemoteUsageRemoteKind,
  46. type TelemetryEventPayload,
  47. measureWebRemoteControlRpcRelayEnvelopeBytes,
  48. } from "@zcode/shared";
  49. import { WebRemoteControlV2ConnectionError } from "@zcode/shared/web-remote-relay";
  50. import {
  51. WebRemoteControlDeviceTransport,
  52. MobilePushConnection,
  53. type WebRemoteControlDeviceTransportOptions,
  54. type WebRemoteControlDeviceTransportState,
  55. buildWebRemoteControlClientLanguageHeader,
  56. createWebRemoteControlV2Http,
  57. type WebRemoteControlLogin,
  58. createMobileLogPullCoordinator,
  59. MobileLogPullError,
  60. type MobileLogPullQuery,
  61. type MobileLogPullShard,
  62. type MobileLogPullSummary,
  63. type MobileLogSink,
  64. } from "#src/main/web-remote-relay/index.js";
  65. import type { WebRemoteControlDeviceStorage } from "#src/main/web-remote-relay/index.js";
  66. import type { WebRemoteControlFeatureGate } from "./webRemoteControlFeatureGate.js";
  67. import {
  68. respondToWebRemoteControlActionRequest,
  69. type RunWebRemoteControlRendererAction,
  70. type WebRemoteControlActionRequestPayload,
  71. } from "#src/main/web-remote-relay/index.js";
  72. interface WebRemoteControlHostAttachmentHandle {
  73. entryId: string;
  74. attachmentId: string;
  75. process: ElectronUtilityProcess;
  76. port: MessagePortMain;
  77. remoteKind?: RemoteUsageRemoteKind;
  78. }
  79. interface WorkspaceBridgeRuntime {
  80. terminalOwnerId?: string;
  81. bridgeSessionId: string;
  82. bridgeGeneration?: number;
  83. recoveryId?: string;
  84. hostEntryId: string;
  85. attachmentId: string;
  86. kind: "local" | "remote";
  87. workspaceKey: string;
  88. workspacePath: string;
  89. workspaceIdentity?: string;
  90. remoteSessionId?: string;
  91. initialTaskId?: string;
  92. hostProtocol?: MessagePortProtocol;
  93. relayProtocol?: AcknowledgedWebRemoteControlRelayProtocolAdapter;
  94. disposeBridge?: () => void;
  95. readyAnnounced: boolean;
  96. degraded: boolean;
  97. }
  98. interface WebRemoteControlDeviceTransportLike {
  99. start(): void;
  100. sendPayload(payload: WebRemoteControlAppPayload): boolean;
  101. sendPayloadResult?(payload: WebRemoteControlAppPayload): WebRemoteControlPayloadSendResult;
  102. measurePayloadBytes?(payload: WebRemoteControlAppPayload): number;
  103. dispose(): void;
  104. }
  105. interface WebRemoteControlStartupRestoreContext {
  106. workspacePath: string;
  107. workspaceIdentity?: string;
  108. initialTaskId?: string;
  109. }
  110. export interface WebRemoteControlStartAuthorization {
  111. token: string;
  112. expiresAt: number;
  113. windowId: number;
  114. workspaceKey: string;
  115. remoteSessionId?: string;
  116. }
  117. const WEB_REMOTE_CONTROL_START_AUTHORIZATION_TTL_MS = 30_000;
  118. interface WindowControlLifecycle {
  119. controller: AbortController;
  120. identity?: { userId: string; endpointOrigin: string };
  121. }
  122. interface WindowControlRuntime {
  123. terminalOwner?: { clientSessionId: string; id: string };
  124. windowId: number;
  125. workspacePath: string;
  126. workspaceIdentity?: string;
  127. remoteSessionId?: string;
  128. initialTaskId?: string;
  129. theme?: WebRemoteControlContext["theme"];
  130. status: WebRemoteControlStatus["status"];
  131. error?: string;
  132. failure?: WebRemoteControlFailure;
  133. deviceSid: string;
  134. deviceMid: string;
  135. connectUrl: string;
  136. qrUrl: string;
  137. transport: WebRemoteControlDeviceTransportLike;
  138. mobileConnected: boolean;
  139. hasEverPaired: boolean;
  140. hasObservedSendReadyForPairing: boolean;
  141. transportState?: WebRemoteControlDeviceTransportState;
  142. mobileViewState?: WebRemoteControlMobileViewState;
  143. mobileTaskView?: NonNullable<WebRemoteControlStatus["mobileTaskView"]>;
  144. mobileTaskViewEpoch?: string;
  145. mobileTaskViewSeq?: number;
  146. mobileDeviceInfo?: WebRemoteControlMobileDeviceInfo;
  147. currentBridge?: WorkspaceBridgeRuntime;
  148. bridgeOpen?: {
  149. bridgeSessionId: string;
  150. bridgeGeneration?: number;
  151. intentKey: string;
  152. hostRequestId: string;
  153. preparingProject: boolean;
  154. promise: Promise<WebRemoteControlExternalWorkspaceBridge>;
  155. };
  156. pendingBridgeInvalidation?: Extract<
  157. WebRemoteControlAppPayload,
  158. { zcode_type: "bridge-degraded" }
  159. >;
  160. pendingOutboundPayloads: WebRemoteControlAppPayload[];
  161. pendingOutboundPayloadTimer?: ReturnType<typeof setTimeout>;
  162. mobileDisconnectGraceTimer?: ReturnType<typeof setTimeout>;
  163. }
  164. interface WebRemoteControlManagerDependencies {
  165. /** 当前界面语言(Main 的 currentApplicationLocale),用于 ZCode endpoint 请求的 X-Client-Language。 */
  166. getClientLanguage?: () => string | undefined;
  167. getEndpointUrls?: () => Promise<ZCodeEndpointUrls> | ZCodeEndpointUrls;
  168. relayWsUrl: string;
  169. mobileRemoteControlUrl: string;
  170. deviceMid: string;
  171. deviceName: string;
  172. appVersion: string;
  173. getLogin(): Promise<WebRemoteControlLogin | undefined>;
  174. deviceStorage: WebRemoteControlDeviceStorage;
  175. startupRestoreStorageProvider: {
  176. load(): Promise<WebRemoteControlStartupRestoreContext | undefined>;
  177. save(context: WebRemoteControlStartupRestoreContext): Promise<void>;
  178. clear(): Promise<void>;
  179. };
  180. featureGate: WebRemoteControlFeatureGate;
  181. logger: {
  182. info: (...args: unknown[]) => void;
  183. warn: (...args: unknown[]) => void;
  184. error: (...args: unknown[]) => void;
  185. };
  186. relayMessageLogger?: {
  187. info: (...args: unknown[]) => void;
  188. };
  189. platformHandlers: {
  190. [K in WebRemoteControlPlatformMethod]: (
  191. args: WebRemoteControlPlatformMethodArgsMap[K],
  192. ) => Promise<WebRemoteControlPlatformMethodResultMap[K]>;
  193. };
  194. reconnectWorkspace: (windowId: number, workspaceKey: string) => Promise<void>;
  195. /** 手机置顶/归档/新建本地项目交给目标窗口 Renderer 执行;缺省时三类请求回 success:false。 */
  196. runRendererAction?: RunWebRemoteControlRendererAction;
  197. prepareProjectWorkspace?: (
  198. windowId: number,
  199. project: HostProjectWorkspaceNavigationInput,
  200. requestId: string,
  201. ) => Promise<HostPreparedProjectWorkspace>;
  202. cancelProjectPreparation?: (windowId: number, requestId: string) => void;
  203. reportRemoteUsageEvent?: (windowId: number, event: TelemetryEventPayload) => void;
  204. reportRendererTelemetryEvent?: (event: RendererTelemetryEventPayload) => void;
  205. onStatusChanged?: (windowId: number, status: WebRemoteControlStatus) => void;
  206. attachWorkspaceHost: (
  207. windowId: number,
  208. context: WebRemoteControlContext & { kind: "local" | "remote"; terminalOwnerId?: string },
  209. ) => Promise<WebRemoteControlHostAttachmentHandle>;
  210. setTerminalOwner: (windowId: number, ownerId: string | null) => void;
  211. releaseWorkspaceHostAttachment: (attachmentId: string) => void;
  212. disposeWorkspaceHostAttachmentsForWindow: (windowId: number, reason: string) => void;
  213. disposeWorkspaceHostAttachmentsForRemoteSession: (
  214. remoteSessionId: string,
  215. reason: string,
  216. ) => void;
  217. createDeviceTransport?: (
  218. options: WebRemoteControlDeviceTransportOptions,
  219. ) => WebRemoteControlDeviceTransportLike;
  220. /** 手机实时日志(mobile-log)落盘;未注入时直接丢弃。 */
  221. mobileLogSink?: Pick<MobileLogSink, "append">;
  222. /** 手机日志拉取单片超时(单测注入)。 */
  223. mobileLogPullShardTimeoutMs?: number;
  224. }
  225. /** 可拉取手机日志的目标连接。 */
  226. export interface WebRemoteControlMobileLogPullTarget {
  227. windowId: number;
  228. deviceLabel: string;
  229. }
  230. // Bugfix: 外部 relay 首次鉴权会受边缘层冷启动和网络抖动影响,实测可能略超 15s。
  231. // 这里等待到 30s,避免在 device 已经快进入 waiting_terminal 时过早销毁可用连接。
  232. const EXTERNAL_RELAY_QR_READY_TIMEOUT_MS = 30_000;
  233. const MOBILE_DISCONNECT_STATUS_GRACE_MS = 3_000;
  234. function createFailure(
  235. reason: WebRemoteControlFailureReason,
  236. message?: string,
  237. ): WebRemoteControlFailure {
  238. return { reason, message };
  239. }
  240. function getErrorCode(error: unknown): string | undefined {
  241. return typeof error === "object" && error !== null && "code" in error
  242. ? String((error as { code?: unknown }).code)
  243. : undefined;
  244. }
  245. function mapWorkspaceBridgeFailureReason(error: unknown): WebRemoteControlFailureReason {
  246. switch (getErrorCode(error)) {
  247. case "DESKTOP_HOST_MISSING":
  248. return "desktop-disconnected";
  249. case "REMOTE_SESSION_MISSING":
  250. case "REMOTE_SESSION_WINDOW_MISMATCH":
  251. return "workspace-closed";
  252. case "REMOTE_WORKSPACE_IDENTITY_MISSING":
  253. case "REMOTE_WORKSPACE_IDENTITY_MISMATCH":
  254. return "unsupported-action";
  255. default:
  256. return "unexpected-error";
  257. }
  258. }
  259. function wrapElectronPort(port: MessagePortMain): MessagePortLike {
  260. return {
  261. addEventListener(_type: "message", listener: (e: { data: MessagePortPayload }) => void) {
  262. port.on("message", listener);
  263. },
  264. removeEventListener(_type: "message", listener: (e: { data: MessagePortPayload }) => void) {
  265. port.off("message", listener);
  266. },
  267. postMessage(data: MessagePortPayload) {
  268. port.postMessage(data);
  269. },
  270. start() {
  271. port.start();
  272. },
  273. close() {
  274. port.close();
  275. },
  276. };
  277. }
  278. function getPathLabel(workspacePath: string): string {
  279. const normalized = workspacePath.replace(/\\/g, "/");
  280. const segments = normalized.split("/").filter(Boolean);
  281. return segments[segments.length - 1] ?? workspacePath;
  282. }
  283. function isBridgeableRemoteTarget(target: WebRemoteControlWorkspaceTarget): boolean {
  284. return target.kind !== "remote" || Boolean(target.workspaceIdentity && target.remoteSessionId);
  285. }
  286. function toExternalBridge(
  287. runtime: WorkspaceBridgeRuntime,
  288. ): WebRemoteControlExternalWorkspaceBridge {
  289. const base = {
  290. ...(runtime.terminalOwnerId ? { terminalOwnerId: runtime.terminalOwnerId } : {}),
  291. bridgeSessionId: runtime.bridgeSessionId,
  292. ...(runtime.bridgeGeneration !== undefined
  293. ? { bridgeGeneration: runtime.bridgeGeneration }
  294. : {}),
  295. ...(runtime.recoveryId ? { recoveryId: runtime.recoveryId } : {}),
  296. workspaceKey: runtime.workspaceKey,
  297. workspacePath: runtime.workspacePath,
  298. initialTaskId: runtime.initialTaskId,
  299. };
  300. if (runtime.kind === "remote") {
  301. if (!runtime.workspaceIdentity || !runtime.remoteSessionId) {
  302. throw new Error("远程 workspace bridge 缺少 workspaceIdentity 或 remoteSessionId。");
  303. }
  304. return {
  305. ...base,
  306. kind: "remote",
  307. workspaceIdentity: runtime.workspaceIdentity,
  308. remoteSessionId: runtime.remoteSessionId,
  309. capabilities: { windowProjectDirectory: true },
  310. };
  311. }
  312. return {
  313. ...base,
  314. kind: "local",
  315. };
  316. }
  317. export function createWebRemoteControlManager(dependencies: WebRemoteControlManagerDependencies) {
  318. const runtimes = new Map<number, WindowControlRuntime>();
  319. // 身份绑定与取消令牌覆盖首次启动到连接释放的整个生命周期,不缓存 JWT。
  320. const windowLifecycles = new Map<number, WindowControlLifecycle>();
  321. const authRequiredWindows = new Set<number>();
  322. let registrationQueue: Promise<unknown> = Promise.resolve();
  323. const startAuthorizations = new Map<string, WebRemoteControlStartAuthorization>();
  324. const availableWorkspacesByWindowId = new Map<number, WebRemoteControlWorkspaceTarget[]>();
  325. const mobileLogPulls = createMobileLogPullCoordinator({
  326. shardTimeoutMs: dependencies.mobileLogPullShardTimeoutMs,
  327. });
  328. function reportRemoteUsageEvent(windowId: number, event: TelemetryEventPayload): void {
  329. try {
  330. dependencies.reportRemoteUsageEvent?.(windowId, event);
  331. } catch (error) {
  332. // 埋点是旁路能力,任何异常都不能改变远控配对和 bridge 的业务结果。
  333. dependencies.logger.warn("[web-remote-control] remote usage telemetry failed", {
  334. elementName: event.elementName,
  335. error,
  336. });
  337. }
  338. }
  339. function resolveRemoteKind(
  340. target: WebRemoteControlWorkspaceTarget,
  341. acquired?: WebRemoteControlHostAttachmentHandle,
  342. ): RemoteUsageRemoteKind | undefined {
  343. if (target.kind !== "remote") {
  344. return undefined;
  345. }
  346. return (
  347. acquired?.remoteKind ??
  348. (target.workspaceIdentity
  349. ? parseRemoteWorkspaceIdentity(target.workspaceIdentity)?.kind
  350. : undefined)
  351. );
  352. }
  353. function resolveRuntimeWorkspaceDimensions(runtime: WindowControlRuntime): {
  354. workspaceKind: "local" | "remote";
  355. remoteKind?: RemoteUsageRemoteKind;
  356. } {
  357. const remoteKind = runtime.workspaceIdentity
  358. ? parseRemoteWorkspaceIdentity(runtime.workspaceIdentity)?.kind
  359. : undefined;
  360. return {
  361. workspaceKind:
  362. runtime.workspaceIdentity?.trim() || runtime.remoteSessionId ? "remote" : "local",
  363. remoteKind,
  364. };
  365. }
  366. /**
  367. * Bugfix: 401 只否定发起请求时用的 JWT。旧实现直接把在途旧 JWT 的 401 当成当前登录失效,
  368. * 同账号刚重新登录(signed-in 已处理完)后旧请求才返回,远控就停在 auth-required,需要第二次登录通知。
  369. * 这里由凭据读取方 currentLogin 核对:JWT 已被替换时转为可重试,transport 退避后用新 JWT 重新申请;
  370. * 账号或 endpoint 变化仍由 currentLogin 抛出 auth-required,JWT 未变才保留原 401。
  371. */
  372. async function retryIfJwtReplaced<T>(
  373. currentLogin: () => Promise<WebRemoteControlLogin>,
  374. used: WebRemoteControlLogin,
  375. request: () => Promise<T>,
  376. ): Promise<T> {
  377. try {
  378. return await request();
  379. } catch (error) {
  380. if (!(error instanceof WebRemoteControlV2ConnectionError) || error.reason !== "auth-required")
  381. throw error;
  382. if ((await currentLogin()).jwt !== used.jwt)
  383. throw new WebRemoteControlV2ConnectionError("relay-unavailable", true);
  384. throw error;
  385. }
  386. }
  387. function resolveRegistration(
  388. currentLogin: () => Promise<WebRemoteControlLogin>,
  389. origin: string,
  390. force: boolean,
  391. registrationSignal: AbortSignal,
  392. ) {
  393. const http = createWebRemoteControlV2Http(origin, fetch, dependencies.getClientLanguage);
  394. // 同一 manager 串行读取/更新身份,避免多窗口首次启动各自覆盖持久化 SID。
  395. const operation = registrationQueue.then(async () => {
  396. const current = await currentLogin();
  397. const stored = await dependencies.deviceStorage.load();
  398. registrationSignal.throwIfAborted();
  399. if (!force && stored?.userId === current.userId && stored.endpointOrigin === origin)
  400. return stored.deviceSid;
  401. if (stored?.endpointOrigin === origin) {
  402. try {
  403. await http.delete(stored.deviceSid, current.jwt, registrationSignal);
  404. } catch {
  405. dependencies.logger.warn("[web-remote-control] V2 old device cleanup failed");
  406. }
  407. }
  408. registrationSignal.throwIfAborted();
  409. const deviceSid = await retryIfJwtReplaced(currentLogin, current, () =>
  410. http.register(dependencies.deviceMid, current.jwt, registrationSignal),
  411. );
  412. await currentLogin();
  413. registrationSignal.throwIfAborted();
  414. try {
  415. await dependencies.deviceStorage.save({
  416. deviceSid,
  417. userId: current.userId,
  418. endpointOrigin: origin,
  419. });
  420. } catch (error) {
  421. // 保存失败不是网络故障;裸错误会让 transport 每次退避都注册新 SID,留下孤儿设备。
  422. // 新 SID 尚未建连,先尽力撤销远端注册,再以不可重试错误结束本次启动。
  423. dependencies.logger.error(
  424. "[web-remote-control] V2 device identity persistence failed",
  425. error,
  426. );
  427. try {
  428. await http.delete(deviceSid, current.jwt, registrationSignal);
  429. } catch {
  430. dependencies.logger.warn("[web-remote-control] V2 new device cleanup failed");
  431. }
  432. throw new WebRemoteControlV2ConnectionError("relay-unavailable");
  433. }
  434. registrationSignal.throwIfAborted();
  435. dependencies.logger.info("[web-remote-control] V2 device registered");
  436. return deviceSid;
  437. });
  438. registrationQueue = operation.catch(() => {});
  439. return operation;
  440. }
  441. const notificationConnection = new MobilePushConnection(async (signal) => {
  442. const login = await dependencies.getLogin();
  443. const endpoint = await dependencies.getEndpointUrls?.();
  444. signal.throwIfAborted();
  445. if (!login?.jwt || !login.userId || !dependencies.featureGate.isEnabled()) return null;
  446. const origin = new URL(endpoint?.origin ?? dependencies.mobileRemoteControlUrl).origin;
  447. const http = createWebRemoteControlV2Http(origin, fetch, dependencies.getClientLanguage);
  448. let supported = false,
  449. status: "available" | "unavailable" | "unknown" = "unknown";
  450. try {
  451. const response = await fetch(new URL("/api/v1/remote/notification/status", origin), {
  452. // 这里直接 fetch,绕过了 NodeApiClient 的来源头;以前完全不带 X-Client-Language。
  453. headers: {
  454. Authorization: `Bearer ${login.jwt}`,
  455. ...buildWebRemoteControlClientLanguageHeader(dependencies.getClientLanguage),
  456. },
  457. signal: AbortSignal.any([signal, AbortSignal.timeout(5000)]),
  458. redirect: "error",
  459. });
  460. if (response.ok) {
  461. const body = (await response.json()) as {
  462. code?: number;
  463. data?: { protocol_version?: number; event_transport?: string; status?: string };
  464. };
  465. supported =
  466. body.code === 0 &&
  467. body.data?.protocol_version === 1 &&
  468. body.data?.event_transport === "http";
  469. if (
  470. supported &&
  471. (body.data?.status === "available" ||
  472. body.data?.status === "unavailable" ||
  473. body.data?.status === "unknown")
  474. )
  475. status = body.data.status;
  476. }
  477. } catch {
  478. signal.throwIfAborted();
  479. }
  480. const currentLogin = async () => {
  481. const current = await dependencies.getLogin();
  482. const endpointNow = await dependencies.getEndpointUrls?.();
  483. signal.throwIfAborted();
  484. if (
  485. !current?.jwt ||
  486. current.userId !== login.userId ||
  487. new URL(endpointNow?.origin ?? dependencies.mobileRemoteControlUrl).origin !== origin
  488. )
  489. throw new WebRemoteControlV2ConnectionError("auth-required");
  490. return current;
  491. };
  492. return {
  493. identity: `${origin}:${login.userId}`,
  494. report: async (event, reportSignal) => {
  495. // 总预算覆盖设备注册与同步推送,不能在注册后重新开始计时。
  496. const requestSignal = AbortSignal.any([signal, reportSignal, AbortSignal.timeout(20_000)]);
  497. const sid = await resolveRegistration(currentLogin, origin, false, requestSignal);
  498. const current = await currentLogin();
  499. requestSignal.throwIfAborted();
  500. return http.reportNotification(sid, event, current.jwt, requestSignal);
  501. },
  502. supported,
  503. status,
  504. };
  505. }, dependencies.logger);
  506. const pushedWorkspaceListSignaturesByWindowId = new Map<number, string>();
  507. let startupRestoreClaimed = false;
  508. let lifecycleRevision = 0;
  509. let authNotificationRevision = 0;
  510. function createTransport(options: WebRemoteControlDeviceTransportOptions) {
  511. return dependencies.createDeviceTransport
  512. ? dependencies.createDeviceTransport(options)
  513. : new WebRemoteControlDeviceTransport(options);
  514. }
  515. function clearStartAuthorizationsForWindow(windowId: number): void {
  516. for (const [token, authorization] of startAuthorizations) {
  517. if (authorization.windowId === windowId) {
  518. startAuthorizations.delete(token);
  519. }
  520. }
  521. }
  522. function authorizeStart(
  523. windowId: number,
  524. context: WebRemoteControlContext,
  525. ): WebRemoteControlStartAuthorization {
  526. const now = Date.now();
  527. // 同一窗口只保留最近一次 IPC dispatch 对应的内部票据,避免旧请求与新 workspace 上下文并存。
  528. clearStartAuthorizationsForWindow(windowId);
  529. for (const [token, authorization] of startAuthorizations) {
  530. if (authorization.expiresAt <= now) {
  531. startAuthorizations.delete(token);
  532. }
  533. }
  534. const authorization: WebRemoteControlStartAuthorization = {
  535. token: randomUUID(),
  536. expiresAt: now + WEB_REMOTE_CONTROL_START_AUTHORIZATION_TTL_MS,
  537. windowId,
  538. workspaceKey: resolveWebRemoteControlWorkspaceKey(context),
  539. ...(context.remoteSessionId ? { remoteSessionId: context.remoteSessionId } : {}),
  540. };
  541. startAuthorizations.set(authorization.token, authorization);
  542. return authorization;
  543. }
  544. function consumeStartAuthorization(
  545. windowId: number,
  546. context: WebRemoteControlContext,
  547. authorization: WebRemoteControlStartAuthorization,
  548. ): void {
  549. const stored = startAuthorizations.get(authorization.token);
  550. startAuthorizations.delete(authorization.token);
  551. if (!stored || stored !== authorization) {
  552. throw new Error("Web remote control authorization is invalid or already used");
  553. }
  554. if (stored.expiresAt <= Date.now()) {
  555. throw new Error("Web remote control authorization expired");
  556. }
  557. if (
  558. stored.windowId !== windowId ||
  559. stored.workspaceKey !== resolveWebRemoteControlWorkspaceKey(context) ||
  560. stored.remoteSessionId !== context.remoteSessionId
  561. ) {
  562. throw new Error("Web remote control authorization target mismatch");
  563. }
  564. }
  565. function disposeRuntimeBridgeResources(runtime: WindowControlRuntime): void {
  566. clearMobileTaskView(runtime);
  567. const bridge = runtime.currentBridge;
  568. if (!bridge) {
  569. return;
  570. }
  571. bridge.disposeBridge?.();
  572. bridge.disposeBridge = undefined;
  573. bridge.relayProtocol?.dispose();
  574. bridge.relayProtocol = undefined;
  575. try {
  576. bridge.hostProtocol?.disconnect();
  577. } catch {
  578. // MessagePortProtocol 已经关闭时 dispose 失败不影响主流程。
  579. }
  580. if (bridge.attachmentId) {
  581. dependencies.releaseWorkspaceHostAttachment(bridge.attachmentId);
  582. }
  583. runtime.currentBridge = undefined;
  584. }
  585. function endTerminalOwner(runtime: WindowControlRuntime): void {
  586. const hadOwner = runtime.terminalOwner !== undefined;
  587. runtime.terminalOwner = undefined;
  588. // 旧客户端没有页面 owner,但确认断线仍必须结束 attachment,才能回收其独立终端 scope。
  589. // 同时撤销在途 open,让晚到的 attachment 只释放而不能重新挂回。
  590. // 结束 owner 先撤销在途导航,不能让晚到的 attachment 把已回收的 PTY 再挂回。
  591. cancelBridgeOpen(runtime);
  592. const bridge = runtime.currentBridge;
  593. if (bridge) {
  594. runtime.pendingBridgeInvalidation = {
  595. zcode_type: "bridge-degraded",
  596. bridgeSessionId: bridge.bridgeSessionId,
  597. bridgeGeneration: bridge.bridgeGeneration,
  598. recoveryId: bridge.recoveryId,
  599. reason: "terminal-owner-ended",
  600. };
  601. }
  602. disposeRuntimeBridgeResources(runtime);
  603. if (hadOwner) dependencies.setTerminalOwner(runtime.windowId, null);
  604. sendPendingBridgeInvalidation(runtime);
  605. }
  606. function ensureTerminalOwner(runtime: WindowControlRuntime, clientSessionId?: string): void {
  607. if (!clientSessionId) {
  608. // 旧页面没有认领协议,不能继承上一页面的 owner;回退到 attachment 回收。
  609. // bootstrap 是认领/读取,不是断线事件;旧客户端重复 bootstrap 不应销毁其活跃 bridge。
  610. if (runtime.terminalOwner) endTerminalOwner(runtime);
  611. return;
  612. }
  613. if (runtime.terminalOwner?.clientSessionId === clientSessionId) return;
  614. endTerminalOwner(runtime);
  615. const id = randomUUID();
  616. runtime.terminalOwner = { clientSessionId, id };
  617. dependencies.setTerminalOwner(runtime.windowId, id);
  618. }
  619. function isCurrentBridgeRuntime(
  620. runtime: WindowControlRuntime,
  621. bridge: WorkspaceBridgeRuntime,
  622. ): boolean {
  623. return runtimes.get(runtime.windowId) === runtime && runtime.currentBridge === bridge;
  624. }
  625. function degradeBridgeAfterRawFault(
  626. runtime: WindowControlRuntime,
  627. bridge: WorkspaceBridgeRuntime,
  628. reasonCode: string,
  629. ): void {
  630. if (!isCurrentBridgeRuntime(runtime, bridge) || bridge.degraded) return;
  631. bridge.degraded = true;
  632. dependencies.logger.warn("[web-remote-control] raw relay bridge degraded", {
  633. windowId: runtime.windowId,
  634. session: runtime.deviceSid,
  635. bridgeSessionId: bridge.bridgeSessionId,
  636. bridgeGeneration: bridge.bridgeGeneration,
  637. recoveryId: bridge.recoveryId,
  638. reasonCode,
  639. });
  640. runtime.pendingBridgeInvalidation = {
  641. zcode_type: "bridge-degraded",
  642. bridgeSessionId: bridge.bridgeSessionId,
  643. ...(bridge.bridgeGeneration === undefined
  644. ? {}
  645. : { bridgeGeneration: bridge.bridgeGeneration }),
  646. ...(bridge.recoveryId ? { recoveryId: bridge.recoveryId } : {}),
  647. // Bugfix:checksum/oversize/future ACK 等 fault 不能伪装成 frame gap;
  648. // app control 只传通用恢复原因,typed reasonCode 留在上面的安全日志。
  649. reason: "rpc-transport-fault",
  650. };
  651. // Bug 原因:degraded 后 raw 两端都已禁止继续转发,保留旧 attachment 只会泄漏
  652. // scoped subscription。物理 Host/Agent 不受影响,只释放手机短生命周期 attachment。
  653. disposeRuntimeBridgeResources(runtime);
  654. sendPendingBridgeInvalidation(runtime);
  655. }
  656. function clearPendingOutboundPayloadTimer(runtime: WindowControlRuntime): void {
  657. if (!runtime.pendingOutboundPayloadTimer) {
  658. return;
  659. }
  660. clearTimeout(runtime.pendingOutboundPayloadTimer);
  661. runtime.pendingOutboundPayloadTimer = undefined;
  662. }
  663. function clearMobileDisconnectGraceTimer(runtime: WindowControlRuntime): void {
  664. if (!runtime.mobileDisconnectGraceTimer) {
  665. return;
  666. }
  667. clearTimeout(runtime.mobileDisconnectGraceTimer);
  668. runtime.mobileDisconnectGraceTimer = undefined;
  669. }
  670. function buildRuntimeStatus(runtime: WindowControlRuntime): WebRemoteControlStatus {
  671. const target = getRuntimeStatusTarget(runtime);
  672. return {
  673. status: runtime.status,
  674. sessionId: runtime.deviceSid,
  675. windowControlSessionId: runtime.deviceSid,
  676. mobileConnected: runtime.mobileConnected,
  677. mobileViewState: runtime.mobileViewState,
  678. mobileTaskView: runtime.mobileTaskView ?? null,
  679. mobileDeviceInfo: runtime.mobileDeviceInfo,
  680. qrUrl: runtime.qrUrl,
  681. connectUrl: runtime.connectUrl,
  682. workspacePath: target.workspacePath,
  683. workspaceIdentity: target.workspaceIdentity,
  684. remoteSessionId: target.remoteSessionId,
  685. initialTaskId: runtime.currentBridge?.initialTaskId ?? runtime.initialTaskId,
  686. error: runtime.error,
  687. failure: runtime.failure,
  688. };
  689. }
  690. function emitRuntimeStatus(runtime: WindowControlRuntime): void {
  691. dependencies.onStatusChanged?.(runtime.windowId, buildRuntimeStatus(runtime));
  692. }
  693. function clearMobileTaskView(runtime: WindowControlRuntime): void {
  694. if (!runtime.mobileTaskView) return;
  695. runtime.mobileTaskView = undefined;
  696. emitRuntimeStatus(runtime);
  697. }
  698. function requestMobileTaskView(runtime: WindowControlRuntime): void {
  699. if (runtime.transportState !== "paired" || !runtime.mobileTaskViewEpoch) return;
  700. sendAppPayload(runtime, {
  701. zcode_type: "mobile-task-view-request",
  702. epoch: runtime.mobileTaskViewEpoch,
  703. });
  704. }
  705. function emitIdleStatus(windowId: number): void {
  706. dependencies.onStatusChanged?.(windowId, { status: "idle" });
  707. }
  708. function scheduleMobileDisconnectGrace(runtime: WindowControlRuntime): void {
  709. if (runtime.mobileDisconnectGraceTimer) {
  710. return;
  711. }
  712. runtime.mobileDisconnectGraceTimer = setTimeout(() => {
  713. runtime.mobileDisconnectGraceTimer = undefined;
  714. if (runtimes.get(runtime.windowId) !== runtime || runtime.status === "error") {
  715. return;
  716. }
  717. endTerminalOwner(runtime);
  718. runtime.status = "running";
  719. runtime.mobileConnected = false;
  720. emitRuntimeStatus(runtime);
  721. }, MOBILE_DISCONNECT_STATUS_GRACE_MS);
  722. }
  723. function schedulePendingOutboundPayloadTimeout(runtime: WindowControlRuntime): void {
  724. if (runtime.pendingOutboundPayloadTimer || runtime.pendingOutboundPayloads.length === 0) {
  725. return;
  726. }
  727. runtime.pendingOutboundPayloadTimer = setTimeout(() => {
  728. runtime.pendingOutboundPayloadTimer = undefined;
  729. const droppedCount = runtime.pendingOutboundPayloads.splice(0).length;
  730. dependencies.logger.warn("[web-remote-control] dropped buffered outbound payloads", {
  731. windowId: runtime.windowId,
  732. session: runtime.deviceSid,
  733. droppedCount,
  734. });
  735. }, WEB_REMOTE_CONTROL_OUTBOUND_PAYLOAD_BUFFER_TIMEOUT_MS);
  736. }
  737. function sendPayloadToTransport(
  738. runtime: WindowControlRuntime,
  739. payload: WebRemoteControlAppPayload,
  740. ): WebRemoteControlPayloadSendResult {
  741. if (runtime.transport.sendPayloadResult) {
  742. return runtime.transport.sendPayloadResult(payload);
  743. }
  744. return runtime.transport.sendPayload(payload)
  745. ? { kind: "sent", bytes: 0 }
  746. : { kind: "unavailable" };
  747. }
  748. function sendPendingBridgeInvalidation(runtime: WindowControlRuntime): void {
  749. const payload = runtime.pendingBridgeInvalidation;
  750. if (!payload) return;
  751. const result = sendPayloadToTransport(runtime, payload);
  752. if (result.kind === "oversize") {
  753. dependencies.logger.error("[web-remote-control] bridge invalidation is oversized", {
  754. bridgeSessionId: payload.bridgeSessionId,
  755. bytes: result.bytes,
  756. maxBytes: result.maxBytes,
  757. });
  758. }
  759. // unavailable 时保持 latch;sent 后也保留,直到手机用新 bridge identity 发起 open。
  760. }
  761. function bufferOutboundPayload(
  762. runtime: WindowControlRuntime,
  763. payload: WebRemoteControlAppPayload,
  764. ): void {
  765. if (runtime.pendingOutboundPayloads.length >= 50) {
  766. const droppedCount = runtime.pendingOutboundPayloads.length + 1;
  767. runtime.pendingOutboundPayloads.length = 0;
  768. clearPendingOutboundPayloadTimer(runtime);
  769. dependencies.logger.warn("[web-remote-control] dropped overflowing outbound payloads", {
  770. windowId: runtime.windowId,
  771. session: runtime.deviceSid,
  772. droppedCount,
  773. });
  774. return;
  775. }
  776. runtime.pendingOutboundPayloads.push(payload);
  777. schedulePendingOutboundPayloadTimeout(runtime);
  778. }
  779. function flushPendingOutboundPayloads(runtime: WindowControlRuntime): void {
  780. while (runtime.pendingOutboundPayloads.length > 0) {
  781. const payload = runtime.pendingOutboundPayloads[0];
  782. if (!payload) {
  783. break;
  784. }
  785. const result = sendPayloadToTransport(runtime, payload);
  786. if (result.kind === "unavailable") {
  787. schedulePendingOutboundPayloadTimeout(runtime);
  788. return;
  789. }
  790. if (result.kind === "oversize") {
  791. // Bugfix:永久 oversize 不能伪装成临时不可发送后反复进入 50 项 buffer。
  792. dependencies.logger.warn("[web-remote-control] dropped oversize app payload", {
  793. zcodeType: payload.zcode_type,
  794. bytes: result.bytes,
  795. maxBytes: result.maxBytes,
  796. });
  797. }
  798. runtime.pendingOutboundPayloads.shift();
  799. }
  800. clearPendingOutboundPayloadTimer(runtime);
  801. }
  802. function sendAppPayload(
  803. runtime: WindowControlRuntime,
  804. payload: WebRemoteControlAppPayload,
  805. ): void {
  806. if (runtime.pendingOutboundPayloads.length > 0) {
  807. bufferOutboundPayload(runtime, payload);
  808. flushPendingOutboundPayloads(runtime);
  809. return;
  810. }
  811. const result = sendPayloadToTransport(runtime, payload);
  812. if (result.kind === "sent") {
  813. return;
  814. }
  815. if (result.kind === "oversize") {
  816. dependencies.logger.warn("[web-remote-control] rejected oversize app payload", {
  817. zcodeType: payload.zcode_type,
  818. bytes: result.bytes,
  819. maxBytes: result.maxBytes,
  820. });
  821. return;
  822. }
  823. // Bugfix: relay suspect 窗口内 sendPayload 会返回 false。
  824. // desktop 发出的响应/RPC 帧不能静默丢弃,先短暂缓冲,等 paired 恢复后再 flush。
  825. bufferOutboundPayload(runtime, payload);
  826. }
  827. function preserveWindowRuntimeFailure(
  828. windowId: number,
  829. runtime: WindowControlRuntime,
  830. reason: string,
  831. failure: WebRemoteControlFailure,
  832. ): void {
  833. if (runtime.status === "error" && runtime.failure?.reason === failure.reason) {
  834. return;
  835. }
  836. sendAppPayload(runtime, {
  837. zcode_type: "app-error",
  838. reason: failure.reason,
  839. error: failure.message ?? failure.reason,
  840. });
  841. endTerminalOwner(runtime);
  842. cancelBridgeOpen(runtime);
  843. disposeRuntimeBridgeResources(runtime);
  844. clearPendingOutboundPayloadTimer(runtime);
  845. clearMobileDisconnectGraceTimer(runtime);
  846. runtime.pendingOutboundPayloads.length = 0;
  847. runtime.transport.dispose();
  848. mobileLogPulls.cancelOwner(runtime, `remote control closed: ${failure.reason}`);
  849. runtime.status = "error";
  850. runtime.mobileConnected = false;
  851. runtime.error = failure.message;
  852. runtime.failure = failure;
  853. runtimes.set(windowId, runtime);
  854. dependencies.logger.warn(
  855. `[web-remote-control] runtime closed window=${windowId} session=${runtime.deviceSid} reason=${reason} failure=${failure.reason} message=${failure.message ?? "<none>"}`,
  856. );
  857. emitRuntimeStatus(runtime);
  858. }
  859. async function stopWindowRuntime(windowId: number, reason: string): Promise<void> {
  860. windowLifecycles.get(windowId)?.controller.abort();
  861. windowLifecycles.delete(windowId);
  862. const runtime = runtimes.get(windowId);
  863. if (!runtime) {
  864. return;
  865. }
  866. sendAppPayload(runtime, {
  867. zcode_type: "app-error",
  868. reason: "desktop-disconnected",
  869. error: "Desktop disconnected this Web remote control session.",
  870. });
  871. runtimes.delete(windowId);
  872. pushedWorkspaceListSignaturesByWindowId.delete(windowId);
  873. endTerminalOwner(runtime);
  874. cancelBridgeOpen(runtime);
  875. disposeRuntimeBridgeResources(runtime);
  876. clearPendingOutboundPayloadTimer(runtime);
  877. clearMobileDisconnectGraceTimer(runtime);
  878. runtime.pendingOutboundPayloads.length = 0;
  879. runtime.transport.dispose();
  880. mobileLogPulls.cancelOwner(runtime, `remote control stopped: ${reason}`);
  881. dependencies.disposeWorkspaceHostAttachmentsForWindow(windowId, reason);
  882. dependencies.logger.info(
  883. `[web-remote-control] stopped window=${windowId} session=${runtime.deviceSid} reason=${reason}`,
  884. );
  885. emitIdleStatus(windowId);
  886. }
  887. function requireAuthentication(windowId: number): void {
  888. void stopWindowRuntime(windowId, "auth-required");
  889. authRequiredWindows.add(windowId);
  890. startupRestoreClaimed = false;
  891. dependencies.onStatusChanged?.(windowId, { status: "auth-required" });
  892. }
  893. function getRuntimeWorkspaceTarget(
  894. runtime: WindowControlRuntime,
  895. ): WebRemoteControlWorkspaceTarget {
  896. const bridge = runtime.currentBridge;
  897. if (bridge) {
  898. return {
  899. workspacePath: bridge.workspacePath,
  900. workspaceIdentity: bridge.workspaceIdentity,
  901. remoteSessionId: bridge.remoteSessionId,
  902. label: getPathLabel(bridge.workspacePath),
  903. kind: bridge.kind,
  904. };
  905. }
  906. return {
  907. workspacePath: runtime.workspacePath,
  908. workspaceIdentity: runtime.workspaceIdentity,
  909. remoteSessionId: runtime.remoteSessionId,
  910. label: getPathLabel(runtime.workspacePath),
  911. kind: runtime.remoteSessionId || runtime.workspaceIdentity ? "remote" : "local",
  912. };
  913. }
  914. // Bugfix:远控可能以未连接的远端目标启动(重启恢复时远端还没重连)。runtime 的 remoteSessionId
  915. // 以前只在 start 时写一次,远端之后连上也不更新:桌面弹窗按“不同目标”重启 device relay,
  916. // initialViewState 也因目标不可 bridge 丢掉 initialTaskId。窗口快照是 workspace 连接身份的唯一来源,
  917. // 目标在快照里时 runtime 跟随快照;目标不在快照里时没有新事实,保留原值。
  918. function syncRuntimeRemoteSession(runtime: WindowControlRuntime): boolean {
  919. if (!runtime.workspaceIdentity) return false;
  920. const workspaceKey = resolveWebRemoteControlWorkspaceKey(runtime);
  921. const workspace = availableWorkspacesByWindowId
  922. .get(runtime.windowId)
  923. ?.find((candidate) => resolveWebRemoteControlWorkspaceKey(candidate) === workspaceKey);
  924. if (!workspace || workspace.remoteSessionId === runtime.remoteSessionId) return false;
  925. runtime.remoteSessionId = workspace.remoteSessionId;
  926. return true;
  927. }
  928. function getRuntimeStatusTarget(runtime: WindowControlRuntime): WebRemoteControlWorkspaceTarget {
  929. // Bugfix: 手机端可以在同一个远控会话里切到窗口内的其他 workspace。
  930. // 之前 getStatus() 复用了当前 bridge 目标,导致桌面弹层按启动 workspace 轮询时误判为“不是同一会话”,
  931. // 再次打开弹层会重启远控并把手机端踢成离线。状态接口保持窗口远控会话的原始目标,
  932. // 手机当前 workspace 仍通过 mobileViewState / workspace list 表达。
  933. return {
  934. workspacePath: runtime.workspacePath,
  935. workspaceIdentity: runtime.workspaceIdentity,
  936. remoteSessionId: runtime.remoteSessionId,
  937. label: getPathLabel(runtime.workspacePath),
  938. kind: runtime.remoteSessionId || runtime.workspaceIdentity ? "remote" : "local",
  939. };
  940. }
  941. function getAvailableWorkspaces(
  942. runtime: WindowControlRuntime,
  943. ): WebRemoteControlWorkspaceTarget[] {
  944. const workspaceByKey = new Map<string, WebRemoteControlWorkspaceTarget>();
  945. for (const workspace of availableWorkspacesByWindowId.get(runtime.windowId) ?? []) {
  946. // Bugfix: 手机端 workspace 列表需要和桌面端一致展示已断开的 SSH 项目。
  947. // 这里仅保留列表项;真正创建 bridge 时仍会校验 remoteSessionId,避免未连接项目被直接打开聊天。
  948. workspaceByKey.set(resolveWebRemoteControlWorkspaceKey(workspace), workspace);
  949. }
  950. const currentTarget = getRuntimeWorkspaceTarget(runtime);
  951. if (isBridgeableRemoteTarget(currentTarget)) {
  952. const currentKey = resolveWebRemoteControlWorkspaceKey(currentTarget);
  953. if (!workspaceByKey.has(currentKey)) {
  954. workspaceByKey.set(currentKey, currentTarget);
  955. }
  956. }
  957. return [...workspaceByKey.values()];
  958. }
  959. function getRuntimeInitialViewState(
  960. runtime: WindowControlRuntime,
  961. ): WebRemoteControlMobileViewState | undefined {
  962. const activeTarget = getRuntimeWorkspaceTarget(runtime);
  963. if (!runtime.initialTaskId || !isBridgeableRemoteTarget(activeTarget)) {
  964. return undefined;
  965. }
  966. return {
  967. activeWorkspaceKey: resolveWebRemoteControlWorkspaceKey(activeTarget),
  968. activeTaskId: runtime.initialTaskId,
  969. updatedAt: Date.now(),
  970. };
  971. }
  972. function buildBootstrapResult(
  973. runtime: WindowControlRuntime,
  974. ): WebRemoteControlWindowBootstrapResult {
  975. return {
  976. windowControlSessionId: runtime.deviceSid,
  977. desktopAppVersion: dependencies.appVersion,
  978. workspaces: getAvailableWorkspaces(runtime),
  979. initialViewState: getRuntimeInitialViewState(runtime),
  980. mobileViewState: runtime.mobileViewState,
  981. mobileTaskViewEpoch: runtime.mobileTaskViewEpoch,
  982. };
  983. }
  984. function buildWorkspaceListResult(
  985. runtime: WindowControlRuntime,
  986. ): WebRemoteControlWorkspaceListResult {
  987. const activeTarget = getRuntimeWorkspaceTarget(runtime);
  988. const initialViewState = getRuntimeInitialViewState(runtime);
  989. return {
  990. workspaces: getAvailableWorkspaces(runtime),
  991. activeWorkspaceKey:
  992. runtime.mobileViewState?.activeWorkspaceKey ??
  993. initialViewState?.activeWorkspaceKey ??
  994. resolveWebRemoteControlWorkspaceKey(activeTarget),
  995. activeTaskId:
  996. runtime.mobileViewState?.activeTaskId ??
  997. runtime.currentBridge?.initialTaskId ??
  998. initialViewState?.activeTaskId,
  999. };
  1000. }
  1001. function buildWorkspaceListPushSignature(result: WebRemoteControlWorkspaceListResult): string {
  1002. const workspaceSignatureEntries = result.workspaces
  1003. .map((workspace) => {
  1004. const workspaceKey = resolveWebRemoteControlWorkspaceKey(workspace);
  1005. return JSON.stringify([
  1006. workspaceKey,
  1007. workspace.kind,
  1008. workspace.connectionState ?? "connected",
  1009. workspace.remoteSessionId ?? "",
  1010. // Bugfix:连接状态不只包含枚举值;同一 disconnected 状态下错误原因也会变化,
  1011. // 手机 workspace card 直接展示 lastConnectionError,必须触发新快照。
  1012. workspace.lastConnectionError ?? "",
  1013. ]);
  1014. })
  1015. .sort();
  1016. // Bugfix:title / connection error 是任意用户可见字符串,不能再用控制字符拼接 tuple;
  1017. // 否则字段值本身包含分隔符时不同快照可能得到相同签名。JSON tuple 保持字段边界且仍忽略数组顺序。
  1018. return JSON.stringify(workspaceSignatureEntries);
  1019. }
  1020. function pushWorkspaceListUpdated(runtime: WindowControlRuntime, force = false): void {
  1021. const result = buildWorkspaceListResult(runtime);
  1022. const signature = buildWorkspaceListPushSignature(result);
  1023. // force:手机新建项目后列表可能未变(项目不一定在 tab 里),仍需一次推送驱动手机重读项目树。
  1024. if (!force && pushedWorkspaceListSignaturesByWindowId.get(runtime.windowId) === signature) {
  1025. return;
  1026. }
  1027. pushedWorkspaceListSignaturesByWindowId.set(runtime.windowId, signature);
  1028. sendAppPayload(runtime, {
  1029. zcode_type: "workspace-list-updated",
  1030. result,
  1031. });
  1032. }
  1033. async function respondToPlatformRequest(
  1034. runtime: WindowControlRuntime,
  1035. request: WebRemoteControlPlatformRequestPayload,
  1036. ): Promise<void> {
  1037. let response: WebRemoteControlPlatformResponsePayload;
  1038. try {
  1039. const result = await dependencies.platformHandlers[request.method](request.args as never);
  1040. response = {
  1041. zcode_type: "platform-response",
  1042. requestId: request.requestId,
  1043. method: request.method,
  1044. success: true,
  1045. result,
  1046. } as WebRemoteControlPlatformResponsePayload;
  1047. } catch (error) {
  1048. const message = error instanceof Error ? error.message : String(error);
  1049. dependencies.logger.warn(
  1050. `[web-remote-control] platform request failed window=${runtime.windowId} session=${runtime.deviceSid} method=${request.method} error=${message}`,
  1051. );
  1052. response = {
  1053. zcode_type: "platform-response",
  1054. requestId: request.requestId,
  1055. method: request.method,
  1056. success: false,
  1057. error: message,
  1058. };
  1059. }
  1060. sendAppPayload(runtime, response);
  1061. }
  1062. function cancelBridgeOpen(runtime: WindowControlRuntime): void {
  1063. const pending = runtime.bridgeOpen;
  1064. runtime.bridgeOpen = undefined;
  1065. if (pending?.preparingProject)
  1066. dependencies.cancelProjectPreparation?.(runtime.windowId, pending.hostRequestId);
  1067. }
  1068. function createWorkspaceBridge(
  1069. runtime: WindowControlRuntime,
  1070. request: WebRemoteControlWorkspaceBridgeOpenPayload,
  1071. ): Promise<WebRemoteControlExternalWorkspaceBridge> {
  1072. // 只有 bootstrap 建立页面 owner;旧页面迟到的 open 不得重新认领已结束的会话。
  1073. if (
  1074. request.terminalClientSessionId &&
  1075. runtime.terminalOwner?.clientSessionId !== request.terminalClientSessionId
  1076. ) {
  1077. return Promise.reject(new Error("Terminal page session has ended; bootstrap is required."));
  1078. }
  1079. const intentKey = JSON.stringify([
  1080. request.terminalClientSessionId,
  1081. request.workspaceKey,
  1082. request.taskId ?? null,
  1083. request.project?.projectId,
  1084. request.project?.hostId,
  1085. request.project?.draftId,
  1086. request.taskHostId,
  1087. request.fileTreeTaskId,
  1088. ]);
  1089. const previous = runtime.bridgeOpen;
  1090. if (
  1091. previous?.bridgeSessionId === request.bridgeSessionId &&
  1092. previous.bridgeGeneration === request.bridgeGeneration
  1093. ) {
  1094. if (previous.intentKey !== intentKey)
  1095. return Promise.reject(new Error("Workspace bridge identity cannot change intent."));
  1096. if (
  1097. runtime.currentBridge?.degraded ||
  1098. (runtime.pendingBridgeInvalidation?.bridgeSessionId === request.bridgeSessionId &&
  1099. runtime.pendingBridgeInvalidation.bridgeGeneration === request.bridgeGeneration)
  1100. )
  1101. return Promise.reject(new Error("Degraded workspace bridge requires a new identity."));
  1102. return previous.promise;
  1103. }
  1104. cancelBridgeOpen(runtime);
  1105. // 同一 transport identity 的重试复用整次 admission;新导航立即使旧异步结果失效。
  1106. const pending: NonNullable<WindowControlRuntime["bridgeOpen"]> = {
  1107. bridgeSessionId: request.bridgeSessionId,
  1108. bridgeGeneration: request.bridgeGeneration,
  1109. intentKey,
  1110. hostRequestId: randomUUID(),
  1111. preparingProject: Boolean(request.project || request.taskHostId),
  1112. promise: undefined as never,
  1113. };
  1114. runtime.bridgeOpen = pending;
  1115. pending.promise = buildWorkspaceBridge(runtime, request, pending);
  1116. return pending.promise;
  1117. }
  1118. async function buildWorkspaceBridge(
  1119. runtime: WindowControlRuntime,
  1120. request: WebRemoteControlWorkspaceBridgeOpenPayload,
  1121. pending: NonNullable<WindowControlRuntime["bridgeOpen"]>,
  1122. ): Promise<WebRemoteControlExternalWorkspaceBridge> {
  1123. let target: WebRemoteControlWorkspaceTarget | undefined;
  1124. const intent: HostProjectWorkspaceNavigationInput | undefined =
  1125. request.project ??
  1126. ((request.fileTreeTaskId || request.taskId) && request.taskHostId
  1127. ? {
  1128. hostId: request.taskHostId,
  1129. task: {
  1130. taskId: (request.fileTreeTaskId ?? request.taskId)!,
  1131. workspaceKey: request.workspaceKey,
  1132. },
  1133. }
  1134. : undefined);
  1135. if (intent) {
  1136. if ((request.project && request.taskId) || !dependencies.prepareProjectWorkspace)
  1137. throw new Error("Project navigation is unavailable.");
  1138. try {
  1139. const prepared = await dependencies.prepareProjectWorkspace(
  1140. runtime.windowId,
  1141. intent,
  1142. pending.hostRequestId,
  1143. );
  1144. target = {
  1145. workspacePath: prepared.workspacePath,
  1146. workspaceIdentity: prepared.workspaceIdentity,
  1147. remoteSessionId: prepared.remote?.remoteSessionId,
  1148. kind: prepared.remote ? "remote" : "local",
  1149. label: prepared.workspacePath,
  1150. ...(prepared.remote ? { connectionState: "connected" as const } : {}),
  1151. };
  1152. } finally {
  1153. pending.preparingProject = false;
  1154. }
  1155. } else {
  1156. target = getAvailableWorkspaces(runtime).find(
  1157. (workspace) => resolveWebRemoteControlWorkspaceKey(workspace) === request.workspaceKey,
  1158. );
  1159. }
  1160. if (runtimes.get(runtime.windowId) !== runtime || runtime.bridgeOpen !== pending)
  1161. throw new Error("Workspace bridge request was superseded.");
  1162. if (!target) {
  1163. throw new Error("目标工作区不在当前桌面窗口中,无法创建 Web 远程控制 bridge。");
  1164. }
  1165. if (!isBridgeableRemoteTarget(target)) {
  1166. throw new Error("目标远程工作区尚未连接,无法创建 bridge,请先重连。");
  1167. }
  1168. const targetWorkspaceKey = resolveWebRemoteControlWorkspaceKey(target);
  1169. const invalidation = runtime.pendingBridgeInvalidation;
  1170. if (
  1171. invalidation?.bridgeSessionId === request.bridgeSessionId &&
  1172. invalidation.bridgeGeneration === request.bridgeGeneration
  1173. ) {
  1174. throw new Error("Degraded workspace bridge must be rebuilt with a new transport identity.");
  1175. }
  1176. // 收到新 identity 的 open 已证明手机消费了 invalidation;后续失败由显式 bridge-error
  1177. // 和 Web 侧有界 retry 收口,不再重复旧 generation 的 degraded 通知。
  1178. runtime.pendingBridgeInvalidation = undefined;
  1179. disposeRuntimeBridgeResources(runtime);
  1180. runtime.status = "connecting";
  1181. runtime.error = undefined;
  1182. runtime.failure = undefined;
  1183. emitRuntimeStatus(runtime);
  1184. const bridgeRuntime: WorkspaceBridgeRuntime = {
  1185. terminalOwnerId: request.terminalClientSessionId ? runtime.terminalOwner?.id : undefined,
  1186. bridgeSessionId: request.bridgeSessionId,
  1187. bridgeGeneration: request.bridgeGeneration,
  1188. recoveryId: request.recoveryId,
  1189. hostEntryId: "",
  1190. attachmentId: "",
  1191. kind: target.kind,
  1192. workspaceKey: targetWorkspaceKey,
  1193. workspacePath: target.workspacePath,
  1194. workspaceIdentity: target.workspaceIdentity,
  1195. remoteSessionId: target.remoteSessionId,
  1196. initialTaskId: request.taskId,
  1197. readyAnnounced: false,
  1198. degraded: false,
  1199. };
  1200. runtime.currentBridge = bridgeRuntime;
  1201. dependencies.logger.info(
  1202. `[web-remote-control] attaching workspace bridge window=${runtime.windowId} session=${runtime.deviceSid} bridgeSession=${request.bridgeSessionId} workspace=${target.workspacePath}`,
  1203. );
  1204. let acquired: WebRemoteControlHostAttachmentHandle | undefined;
  1205. try {
  1206. acquired = await dependencies.attachWorkspaceHost(runtime.windowId, {
  1207. workspacePath: target.workspacePath,
  1208. workspaceIdentity: target.workspaceIdentity,
  1209. remoteSessionId: target.remoteSessionId,
  1210. initialTaskId: request.taskId,
  1211. kind: target.kind,
  1212. ...(bridgeRuntime.terminalOwnerId
  1213. ? { terminalOwnerId: bridgeRuntime.terminalOwnerId }
  1214. : {}),
  1215. });
  1216. if (!isCurrentBridgeRuntime(runtime, bridgeRuntime) || runtime.bridgeOpen !== pending) {
  1217. dependencies.releaseWorkspaceHostAttachment(acquired.attachmentId);
  1218. acquired = undefined;
  1219. throw new Error("Workspace bridge request was superseded.");
  1220. }
  1221. const hostProtocol = new MessagePortProtocol(wrapElectronPort(acquired.port));
  1222. const relayProtocol = createAcknowledgedWebRemoteControlRelayProtocol({
  1223. bridgeSessionId: bridgeRuntime.bridgeSessionId,
  1224. bridgeGeneration: bridgeRuntime.bridgeGeneration,
  1225. recoveryId: bridgeRuntime.recoveryId,
  1226. measureFrameBytes: (frame) =>
  1227. runtime.transport.measurePayloadBytes?.(frame) ??
  1228. measureWebRemoteControlRpcRelayEnvelopeBytes(frame),
  1229. sendFrame: (payload) => {
  1230. if (!bridgeRuntime.readyAnnounced || bridgeRuntime.degraded) return false;
  1231. const result = sendPayloadToTransport(runtime, payload);
  1232. if (result.kind === "oversize") {
  1233. throw new Error("remote.rpcFrame.envelopeTooLarge");
  1234. }
  1235. return result.kind === "sent";
  1236. },
  1237. });
  1238. // Bugfix:raw adapter 是唯一 replay owner;main 不再把 rpc-frame 放进普通 50 项 buffer。
  1239. const disposeHostToRelay = hostProtocol.onMessage((buffer) => {
  1240. relayProtocol.protocol.send(buffer);
  1241. });
  1242. const disposeRelayToHost = relayProtocol.protocol.onMessage((buffer) => {
  1243. hostProtocol.send(buffer);
  1244. });
  1245. const disposeDegraded = relayProtocol.onDegraded((fault) => {
  1246. degradeBridgeAfterRawFault(runtime, bridgeRuntime, fault.reasonCode);
  1247. });
  1248. const disposeSaturated = relayProtocol.onSaturated(() => {
  1249. if (!isCurrentBridgeRuntime(runtime, bridgeRuntime) || bridgeRuntime.degraded) return;
  1250. hostProtocol.sendFlowState("saturated");
  1251. });
  1252. const disposeDrained = relayProtocol.onDrained(() => {
  1253. if (!isCurrentBridgeRuntime(runtime, bridgeRuntime) || bridgeRuntime.degraded) return;
  1254. hostProtocol.sendFlowState("drained");
  1255. });
  1256. bridgeRuntime.hostEntryId = acquired.entryId;
  1257. bridgeRuntime.attachmentId = acquired.attachmentId;
  1258. bridgeRuntime.hostProtocol = hostProtocol;
  1259. bridgeRuntime.relayProtocol = relayProtocol;
  1260. bridgeRuntime.disposeBridge = () => {
  1261. disposeHostToRelay.dispose();
  1262. disposeRelayToHost.dispose();
  1263. disposeDegraded.dispose();
  1264. disposeSaturated.dispose();
  1265. disposeDrained.dispose();
  1266. };
  1267. runtime.status = "active";
  1268. runtime.error = undefined;
  1269. runtime.failure = undefined;
  1270. emitRuntimeStatus(runtime);
  1271. dependencies.logger.info(
  1272. `[web-remote-control] workspace bridge active window=${runtime.windowId} session=${runtime.deviceSid} bridgeSession=${request.bridgeSessionId}`,
  1273. );
  1274. reportRemoteUsageEvent(
  1275. runtime.windowId,
  1276. buildWebRemoteControlBridgeResultTelemetry({
  1277. result: "success",
  1278. workspaceKind: target.kind,
  1279. remoteKind: resolveRemoteKind(target, acquired),
  1280. entryKind: request.taskId ? "task" : "home",
  1281. }),
  1282. );
  1283. return toExternalBridge(bridgeRuntime);
  1284. } catch (error) {
  1285. reportRemoteUsageEvent(
  1286. runtime.windowId,
  1287. buildWebRemoteControlBridgeResultTelemetry({
  1288. result: "failure",
  1289. workspaceKind: target.kind,
  1290. remoteKind: resolveRemoteKind(target, acquired),
  1291. entryKind: request.taskId ? "task" : "home",
  1292. errorCategory: classifyRemoteUsageError(error),
  1293. }),
  1294. );
  1295. if (acquired) {
  1296. dependencies.releaseWorkspaceHostAttachment(acquired.attachmentId);
  1297. }
  1298. if (isCurrentBridgeRuntime(runtime, bridgeRuntime)) {
  1299. disposeRuntimeBridgeResources(runtime);
  1300. runtime.status = runtime.mobileConnected ? "active" : "running";
  1301. emitRuntimeStatus(runtime);
  1302. }
  1303. throw error;
  1304. }
  1305. }
  1306. async function respondToWorkspaceBridgeOpen(
  1307. runtime: WindowControlRuntime,
  1308. request: WebRemoteControlWorkspaceBridgeOpenPayload,
  1309. ): Promise<void> {
  1310. try {
  1311. const bridge = await createWorkspaceBridge(runtime, request);
  1312. sendAppPayload(runtime, {
  1313. zcode_type: "workspace-bridge-ready",
  1314. requestId: request.requestId,
  1315. bridgeSessionId: request.bridgeSessionId,
  1316. ...(request.bridgeGeneration !== undefined
  1317. ? { bridgeGeneration: request.bridgeGeneration }
  1318. : {}),
  1319. ...(request.recoveryId ? { recoveryId: request.recoveryId } : {}),
  1320. bridge,
  1321. });
  1322. const currentBridge = runtime.currentBridge;
  1323. if (
  1324. currentBridge?.bridgeSessionId === request.bridgeSessionId &&
  1325. currentBridge.bridgeGeneration === request.bridgeGeneration
  1326. ) {
  1327. // bridge-ready 必须先进入 ordinary app transport,才允许 queued raw frames 开闸。
  1328. currentBridge.readyAnnounced = true;
  1329. currentBridge.relayProtocol?.flushPendingFrames();
  1330. }
  1331. } catch (error) {
  1332. const message = error instanceof Error ? error.message : String(error);
  1333. dependencies.logger.warn(
  1334. `[web-remote-control] workspace bridge failed window=${runtime.windowId} session=${runtime.deviceSid} workspaceKey=${request.workspaceKey} error=${message}`,
  1335. );
  1336. sendAppPayload(runtime, {
  1337. zcode_type: "workspace-bridge-error",
  1338. requestId: request.requestId,
  1339. bridgeSessionId: request.bridgeSessionId,
  1340. ...(request.bridgeGeneration !== undefined
  1341. ? { bridgeGeneration: request.bridgeGeneration }
  1342. : {}),
  1343. ...(request.recoveryId ? { recoveryId: request.recoveryId } : {}),
  1344. reason: mapWorkspaceBridgeFailureReason(error),
  1345. error: message,
  1346. });
  1347. }
  1348. }
  1349. async function respondToWorkspaceReconnectRequest(
  1350. runtime: WindowControlRuntime,
  1351. request: Extract<WebRemoteControlAppPayload, { zcode_type: "workspace-reconnect-request" }>,
  1352. ): Promise<void> {
  1353. try {
  1354. await dependencies.reconnectWorkspace(runtime.windowId, request.workspaceKey);
  1355. sendAppPayload(runtime, {
  1356. zcode_type: "workspace-reconnect-response",
  1357. requestId: request.requestId,
  1358. workspaceKey: request.workspaceKey,
  1359. success: true,
  1360. });
  1361. } catch (error) {
  1362. sendAppPayload(runtime, {
  1363. zcode_type: "workspace-reconnect-response",
  1364. requestId: request.requestId,
  1365. workspaceKey: request.workspaceKey,
  1366. success: false,
  1367. error: error instanceof Error ? error.message : String(error),
  1368. });
  1369. }
  1370. }
  1371. async function respondToActionRequest(
  1372. runtime: WindowControlRuntime,
  1373. request: WebRemoteControlActionRequestPayload,
  1374. ): Promise<void> {
  1375. const response = await respondToWebRemoteControlActionRequest(
  1376. runtime.windowId,
  1377. request,
  1378. dependencies.runRendererAction,
  1379. );
  1380. if (runtimes.get(runtime.windowId) !== runtime) return;
  1381. sendAppPayload(runtime, response);
  1382. if (response.zcode_type === "workspace-create-response" && response.success) {
  1383. pushWorkspaceListUpdated(runtime, true);
  1384. }
  1385. }
  1386. /** 不认识的请求型 payload 回 app-error,让新手机连旧桌面时能立即降级而不是等超时。 */
  1387. function respondToUnrecognizedPayload(runtime: WindowControlRuntime, value: unknown): void {
  1388. const request = resolveUnrecognizedWebRemoteControlRequest(value);
  1389. if (!request) return;
  1390. sendAppPayload(runtime, {
  1391. zcode_type: "app-error",
  1392. requestId: request.requestId,
  1393. reason: "unsupported-action",
  1394. error: `Desktop does not recognize app payload type: ${request.zcodeType}`,
  1395. });
  1396. }
  1397. function applyMobileViewStateUpdate(
  1398. runtime: WindowControlRuntime,
  1399. viewState: WebRemoteControlMobileViewState,
  1400. deviceInfo?: WebRemoteControlMobileDeviceInfo,
  1401. ): void {
  1402. runtime.mobileViewState = viewState;
  1403. if (deviceInfo) {
  1404. runtime.mobileDeviceInfo = deviceInfo;
  1405. }
  1406. }
  1407. function applyMobileTaskViewUpdate(
  1408. runtime: WindowControlRuntime,
  1409. payload: WebRemoteControlMobileTaskViewUpdatePayload,
  1410. ): void {
  1411. const bridge = runtime.currentBridge;
  1412. const view = payload.view;
  1413. // 导航缓存、断线宽限和旧 bridge 回包都不能证明当前查看;只接收本代配对的完整地址。
  1414. if (
  1415. runtime.transportState !== "paired" ||
  1416. payload.epoch !== runtime.mobileTaskViewEpoch ||
  1417. payload.seq <= (runtime.mobileTaskViewSeq ?? -1) ||
  1418. !bridge?.readyAnnounced ||
  1419. bridge.degraded ||
  1420. payload.bridgeSessionId !== bridge.bridgeSessionId ||
  1421. payload.bridgeGeneration !== bridge.bridgeGeneration ||
  1422. (view &&
  1423. (view.workspacePath !== bridge.workspacePath ||
  1424. resolveWebRemoteControlWorkspaceKey(view) !== bridge.workspaceKey))
  1425. )
  1426. return;
  1427. runtime.mobileTaskViewSeq = payload.seq;
  1428. // legacy 身份不能反查 Source;读与 CAS 必须携带所属 bridge 的可信 session,不能接受 Web 自报。
  1429. const trustedView = view
  1430. ? {
  1431. ...view,
  1432. ...(bridge.kind === "remote" ? { remoteSessionId: bridge.remoteSessionId } : {}),
  1433. }
  1434. : undefined;
  1435. const previous = runtime.mobileTaskView;
  1436. if (
  1437. previous?.taskId === trustedView?.taskId &&
  1438. previous?.workspacePath === trustedView?.workspacePath &&
  1439. previous?.workspaceIdentity === trustedView?.workspaceIdentity &&
  1440. previous?.remoteSessionId === trustedView?.remoteSessionId
  1441. )
  1442. return;
  1443. runtime.mobileTaskView = trustedView;
  1444. emitRuntimeStatus(runtime);
  1445. }
  1446. function routeRpcTransportPayload(
  1447. runtime: WindowControlRuntime,
  1448. frame: WebRemoteControlRpcTransportPayload,
  1449. ): void {
  1450. routeRawTransportCandidate(runtime, frame);
  1451. }
  1452. function routeRawTransportCandidate(runtime: WindowControlRuntime, payload: unknown): boolean {
  1453. const bridge = runtime.currentBridge;
  1454. if (!bridge || bridge.degraded) return false;
  1455. return bridge.relayProtocol?.acceptPayload(payload) ?? false;
  1456. }
  1457. function logMobileDiagnostic(
  1458. runtime: WindowControlRuntime,
  1459. payload: Extract<WebRemoteControlAppPayload, { zcode_type: "mobile-diagnostic" }>,
  1460. ): void {
  1461. dependencies.logger.info("[web-remote-control] mobile diagnostic", {
  1462. window: runtime.windowId,
  1463. session: runtime.deviceSid,
  1464. event: payload.event,
  1465. state: payload.state,
  1466. previousState: payload.previousState,
  1467. pairStatus: payload.pairStatus,
  1468. closeCode: payload.closeCode,
  1469. closeReason: payload.closeReason,
  1470. wasClean: payload.wasClean,
  1471. wasPaired: payload.wasPaired,
  1472. failureReason: payload.failureReason,
  1473. failureMessage: payload.failureMessage,
  1474. visibilityState: payload.visibilityState,
  1475. online: payload.online,
  1476. hiddenDurationMs: payload.hiddenDurationMs,
  1477. timestamp: payload.timestamp,
  1478. });
  1479. }
  1480. function routePayload(runtime: WindowControlRuntime, payload: WebRemoteControlAppPayload): void {
  1481. switch (payload.zcode_type) {
  1482. case "bootstrap-request":
  1483. ensureTerminalOwner(runtime, payload.terminalClientSessionId);
  1484. sendAppPayload(runtime, {
  1485. zcode_type: "bootstrap-response",
  1486. requestId: payload.requestId,
  1487. success: true,
  1488. result: buildBootstrapResult(runtime),
  1489. });
  1490. break;
  1491. case "workspace-list-request":
  1492. sendAppPayload(runtime, {
  1493. zcode_type: "workspace-list-response",
  1494. requestId: payload.requestId,
  1495. success: true,
  1496. result: buildWorkspaceListResult(runtime),
  1497. });
  1498. break;
  1499. case "platform-request":
  1500. void respondToPlatformRequest(runtime, payload);
  1501. break;
  1502. case "mobile-view-state-update":
  1503. applyMobileViewStateUpdate(runtime, payload.viewState, payload.deviceInfo);
  1504. break;
  1505. case "mobile-task-view-update":
  1506. applyMobileTaskViewUpdate(runtime, payload);
  1507. break;
  1508. case "workspace-bridge-open":
  1509. void respondToWorkspaceBridgeOpen(runtime, payload);
  1510. break;
  1511. case "workspace-reconnect-request":
  1512. void respondToWorkspaceReconnectRequest(runtime, payload);
  1513. break;
  1514. case "rpc-frame":
  1515. case "rpc-frame-ack":
  1516. routeRpcTransportPayload(runtime, payload);
  1517. break;
  1518. case "telemetry-report":
  1519. // 手机已在创建边界构造事件;Main 只转发,不维护会话事实或干预 replayable 链路。
  1520. dependencies.reportRendererTelemetryEvent?.(payload.event);
  1521. break;
  1522. case "mobile-diagnostic":
  1523. logMobileDiagnostic(runtime, payload);
  1524. break;
  1525. case "task-pin-request":
  1526. case "task-archive-request":
  1527. case "workspace-create-request":
  1528. void respondToActionRequest(runtime, payload);
  1529. break;
  1530. case "mobile-log":
  1531. appendMobileLog(runtime, payload);
  1532. break;
  1533. case "mobile-log-pull-response":
  1534. if (!mobileLogPulls.handleResponse(payload)) {
  1535. dependencies.logger.info("[web-remote-control] dropped stale mobile log pull response", {
  1536. requestId: payload.requestId,
  1537. });
  1538. }
  1539. break;
  1540. case "app-error":
  1541. // 手机对桌面请求的报错:目前只有日志拉取会按 requestId 认领(unsupported-action 降级)。
  1542. mobileLogPulls.handleAppError(payload);
  1543. break;
  1544. default:
  1545. // 已能解析但本端不处理的请求型 payload 同样回 unsupported-action。
  1546. respondToUnrecognizedPayload(runtime, payload);
  1547. break;
  1548. }
  1549. }
  1550. function resolveMobileLogDeviceLabel(runtime: WindowControlRuntime): string {
  1551. const info = runtime.mobileDeviceInfo;
  1552. return info ? [info.name, info.platform].filter(Boolean).join("-") : "";
  1553. }
  1554. function appendMobileLog(
  1555. runtime: WindowControlRuntime,
  1556. payload: WebRemoteControlMobileLogPayload,
  1557. ): void {
  1558. if (!dependencies.mobileLogSink) return;
  1559. const info = runtime.mobileDeviceInfo;
  1560. dependencies.mobileLogSink.append(
  1561. {
  1562. deviceKey: payload.device?.id ?? (resolveMobileLogDeviceLabel(runtime) || "unknown-device"),
  1563. sessionKey: payload.sessionId ?? runtime.deviceSid,
  1564. header: {
  1565. device:
  1566. payload.device ??
  1567. (info
  1568. ? { name: info.name, platform: info.platform, appVersion: info.version }
  1569. : undefined),
  1570. mobileSessionId: payload.sessionId,
  1571. desktopSession: runtime.deviceSid,
  1572. windowId: runtime.windowId,
  1573. },
  1574. },
  1575. payload.events,
  1576. );
  1577. }
  1578. function findMobileLogPullRuntime(
  1579. windowId: number | undefined,
  1580. ): WindowControlRuntime | undefined {
  1581. const isPaired = (runtime: WindowControlRuntime | undefined) =>
  1582. runtime?.transportState === "paired" && runtime.mobileConnected;
  1583. const preferred = windowId === undefined ? undefined : runtimes.get(windowId);
  1584. if (isPaired(preferred)) return preferred;
  1585. return [...runtimes.values()].find((runtime) => isPaired(runtime));
  1586. }
  1587. function mapTransportState(
  1588. runtime: WindowControlRuntime,
  1589. state: WebRemoteControlDeviceTransportState,
  1590. ): void {
  1591. const previousTransportState = runtime.transportState;
  1592. runtime.transportState = state;
  1593. // 瞬时查看不能沿用连接弹窗的断线宽限;恢复必须由新 epoch 下的可见页面重新声明。
  1594. if (state !== "paired") {
  1595. runtime.mobileTaskViewEpoch = undefined;
  1596. runtime.mobileTaskViewSeq = undefined;
  1597. clearMobileTaskView(runtime);
  1598. } else if (previousTransportState !== "paired") {
  1599. runtime.mobileTaskViewEpoch = randomUUID();
  1600. runtime.mobileTaskViewSeq = -1;
  1601. }
  1602. if (state !== "paired") {
  1603. runtime.hasObservedSendReadyForPairing = false;
  1604. }
  1605. if (state === "waiting_terminal" || state === "paired") {
  1606. runtime.error = undefined;
  1607. runtime.failure = undefined;
  1608. }
  1609. if (state === "connecting" || state === "authenticating") {
  1610. if (runtime.mobileConnected) {
  1611. // Bugfix: 已配对会话的 relay 短抖会先经历 connecting/authenticating。
  1612. // 旧逻辑把 dialog 立刻切成“启动中”,用户会误以为远控重新启动;这里在宽限期内保持 active。
  1613. runtime.status = "active";
  1614. scheduleMobileDisconnectGrace(runtime);
  1615. emitRuntimeStatus(runtime);
  1616. return;
  1617. }
  1618. runtime.status = "starting";
  1619. emitRuntimeStatus(runtime);
  1620. return;
  1621. }
  1622. if (state === "waiting_terminal") {
  1623. if (runtime.mobileConnected) {
  1624. // Bugfix: 已配对会话恢复时 relay 可能短暂回 waiting。
  1625. // 旧逻辑会把 dialog 从 active 拉回“等待手机匹配”;这里先防抖,超时仍未 paired 再降级。
  1626. runtime.status = "active";
  1627. scheduleMobileDisconnectGrace(runtime);
  1628. emitRuntimeStatus(runtime);
  1629. return;
  1630. }
  1631. runtime.status = "running";
  1632. runtime.mobileConnected = false;
  1633. emitRuntimeStatus(runtime);
  1634. return;
  1635. }
  1636. if (state === "paired") {
  1637. if (previousTransportState !== "paired") {
  1638. const workspaceDimensions = resolveRuntimeWorkspaceDimensions(runtime);
  1639. reportRemoteUsageEvent(
  1640. runtime.windowId,
  1641. buildWebRemoteControlPairResultTelemetry({
  1642. result: "success",
  1643. pairKind: runtime.hasEverPaired ? "reconnect" : "initial",
  1644. ...workspaceDimensions,
  1645. }),
  1646. );
  1647. }
  1648. runtime.hasEverPaired = true;
  1649. clearMobileDisconnectGraceTimer(runtime);
  1650. runtime.status = "active";
  1651. runtime.mobileConnected = true;
  1652. emitRuntimeStatus(runtime);
  1653. // Bugfix: 普通断线重连重新 paired 时 transport 不一定触发 onSendReady。
  1654. // 这里在状态恢复为可发送后主动 flush,避免重连窗口内缓冲的响应/RPC 帧超时丢弃。
  1655. flushPendingOutboundPayloads(runtime);
  1656. sendPendingBridgeInvalidation(runtime);
  1657. if (previousTransportState !== "paired") requestMobileTaskView(runtime);
  1658. return;
  1659. }
  1660. if (state === "kicked") {
  1661. if (previousTransportState !== "kicked") {
  1662. const workspaceDimensions = resolveRuntimeWorkspaceDimensions(runtime);
  1663. reportRemoteUsageEvent(
  1664. runtime.windowId,
  1665. buildWebRemoteControlPairResultTelemetry({
  1666. result: "failure",
  1667. pairKind: runtime.hasEverPaired ? "reconnect" : "initial",
  1668. ...workspaceDimensions,
  1669. errorCategory: "relay",
  1670. }),
  1671. );
  1672. }
  1673. preserveWindowRuntimeFailure(
  1674. runtime.windowId,
  1675. runtime,
  1676. "external-relay-kicked",
  1677. createFailure("session-conflict", "Web remote control connection was kicked by relay."),
  1678. );
  1679. return;
  1680. }
  1681. if (state === "error") {
  1682. if (previousTransportState !== "error") {
  1683. const workspaceDimensions = resolveRuntimeWorkspaceDimensions(runtime);
  1684. reportRemoteUsageEvent(
  1685. runtime.windowId,
  1686. buildWebRemoteControlPairResultTelemetry({
  1687. result: "failure",
  1688. pairKind: runtime.hasEverPaired ? "reconnect" : "initial",
  1689. ...workspaceDimensions,
  1690. errorCategory: "relay",
  1691. }),
  1692. );
  1693. }
  1694. runtime.status = "error";
  1695. emitRuntimeStatus(runtime);
  1696. }
  1697. }
  1698. function createQrUrl(deviceSid: string, mobileRemoteControlUrl: string): string {
  1699. return buildWebRemoteControlExternalQrUrl({
  1700. baseUrl: mobileRemoteControlUrl,
  1701. deviceSid,
  1702. deviceMid: dependencies.deviceMid,
  1703. deviceName: dependencies.deviceName,
  1704. appVersion: dependencies.appVersion,
  1705. });
  1706. }
  1707. return {
  1708. startNotifications: () => notificationConnection.start(),
  1709. refreshNotifications: () => notificationConnection.refresh(),
  1710. observeNotificationRun: (run: unknown) => notificationConnection.observeRun(run),
  1711. sendNotification: (
  1712. event: unknown,
  1713. resolveLocale: Parameters<MobilePushConnection["send"]>[1],
  1714. ) => notificationConnection.send(event, resolveLocale),
  1715. disposeNotifications: () => notificationConnection.dispose(),
  1716. authorizeStart,
  1717. async startAuthorized(
  1718. windowId: number,
  1719. context: WebRemoteControlContext,
  1720. authorization: WebRemoteControlStartAuthorization,
  1721. ): Promise<WebRemoteControlStartResult> {
  1722. consumeStartAuthorization(windowId, context, authorization);
  1723. return this.start(windowId, context);
  1724. },
  1725. async start(
  1726. windowId: number,
  1727. context: WebRemoteControlContext,
  1728. ): Promise<WebRemoteControlStartResult> {
  1729. clearStartAuthorizationsForWindow(windowId);
  1730. dependencies.featureGate.assertEnabled();
  1731. startupRestoreClaimed = true;
  1732. const stopped = stopWindowRuntime(windowId, "restart");
  1733. const controller = new AbortController();
  1734. const lifecycle: WindowControlLifecycle = { controller };
  1735. windowLifecycles.set(windowId, lifecycle);
  1736. const signal = controller.signal;
  1737. const assertActive = () => signal.throwIfAborted();
  1738. try {
  1739. await stopped;
  1740. const readAuthContext = async () => {
  1741. for (;;) {
  1742. const revision = authNotificationRevision;
  1743. const endpointUrls = await dependencies.getEndpointUrls?.();
  1744. const login = await dependencies.getLogin();
  1745. assertActive();
  1746. // 首次读取尚未绑定身份时也可能发生换号,不能把旧读取绑定到新登录之后。
  1747. if (revision === authNotificationRevision) return { endpointUrls, login };
  1748. }
  1749. };
  1750. const { endpointUrls, login } = await readAuthContext();
  1751. const relayWsUrl = endpointUrls?.relayWsUrl ?? dependencies.relayWsUrl;
  1752. const mobileRemoteControlUrl =
  1753. endpointUrls?.remoteUrl ?? dependencies.mobileRemoteControlUrl;
  1754. const endpointOrigin = new URL(endpointUrls?.origin ?? mobileRemoteControlUrl).origin;
  1755. assertActive();
  1756. if (!login?.jwt || !login.userId) {
  1757. requireAuthentication(windowId);
  1758. throw new WebRemoteControlV2ConnectionError("auth-required");
  1759. }
  1760. lifecycle.identity = { userId: login.userId, endpointOrigin };
  1761. authRequiredWindows.delete(windowId);
  1762. await dependencies.deviceStorage.clearLegacy();
  1763. assertActive();
  1764. const http = createWebRemoteControlV2Http(
  1765. endpointOrigin,
  1766. fetch,
  1767. dependencies.getClientLanguage,
  1768. );
  1769. const currentLogin = async () => {
  1770. const current = await dependencies.getLogin();
  1771. const endpoint = await dependencies.getEndpointUrls?.();
  1772. assertActive();
  1773. if (
  1774. !current?.jwt ||
  1775. current.userId !== login.userId ||
  1776. (endpoint && endpoint.origin !== endpointOrigin)
  1777. ) {
  1778. throw new WebRemoteControlV2ConnectionError("auth-required");
  1779. }
  1780. return current;
  1781. };
  1782. const register = (force: boolean, transportSignal: AbortSignal) =>
  1783. resolveRegistration(
  1784. currentLogin,
  1785. endpointOrigin,
  1786. force,
  1787. AbortSignal.any([signal, transportSignal]),
  1788. );
  1789. let deviceSid = "";
  1790. let runtime: WindowControlRuntime;
  1791. let readySettled = false;
  1792. let persistEnabled: Promise<void> | undefined;
  1793. const readyPromise = new Promise<void>((resolve, reject) => {
  1794. const finish = (error?: Error) => {
  1795. if (readySettled) return;
  1796. readySettled = true;
  1797. clearTimeout(timeout);
  1798. signal.removeEventListener("abort", aborted);
  1799. if (error) reject(error);
  1800. else resolve();
  1801. };
  1802. const aborted = () => finish(new Error("Web remote control start cancelled"));
  1803. signal.addEventListener("abort", aborted, { once: true });
  1804. const timeout = setTimeout(
  1805. () =>
  1806. finish(
  1807. new Error("External relay device did not reach QR-ready state before timeout."),
  1808. ),
  1809. EXTERNAL_RELAY_QR_READY_TIMEOUT_MS,
  1810. );
  1811. const transport = createTransport({
  1812. relayWsUrl,
  1813. deviceMid: dependencies.deviceMid,
  1814. meta: {
  1815. platform: process.platform,
  1816. version: dependencies.appVersion,
  1817. name: dependencies.deviceName,
  1818. },
  1819. getToken: async (transportSignal) => {
  1820. const current = await currentLogin();
  1821. const token = await retryIfJwtReplaced(currentLogin, current, () =>
  1822. http.token(current.jwt, AbortSignal.any([signal, transportSignal])),
  1823. );
  1824. await currentLogin();
  1825. dependencies.logger.info("[web-remote-control] V2 device token acquired");
  1826. return token;
  1827. },
  1828. resolveDeviceSid: async (transportSignal, forceRegistration) => {
  1829. deviceSid = await register(forceRegistration, transportSignal);
  1830. if (runtimes.get(windowId) === runtime) {
  1831. runtime.deviceSid = deviceSid;
  1832. runtime.qrUrl = runtime.connectUrl = "";
  1833. }
  1834. return deviceSid;
  1835. },
  1836. logger: dependencies.logger,
  1837. onStateChange: (state) => {
  1838. if (runtimes.get(windowId) !== runtime) return;
  1839. if (state === "waiting_terminal" || state === "paired") {
  1840. runtime.qrUrl = runtime.connectUrl = createQrUrl(deviceSid, mobileRemoteControlUrl);
  1841. }
  1842. mapTransportState(runtime, state);
  1843. if (state === "waiting_terminal" || state === "paired") {
  1844. // 首个调用超时不撤销后台恢复;首次真正 ready 时仍须保存启用意图。
  1845. persistEnabled ??= dependencies.startupRestoreStorageProvider.save({
  1846. workspacePath: context.workspacePath,
  1847. workspaceIdentity: context.workspaceIdentity,
  1848. initialTaskId: context.initialTaskId,
  1849. });
  1850. void persistEnabled.then(
  1851. () => finish(),
  1852. (error: unknown) => {
  1853. finish(error instanceof Error ? error : new Error(String(error)));
  1854. if (runtimes.get(windowId) === runtime)
  1855. void stopWindowRuntime(windowId, "startup-restore-persist-failed");
  1856. },
  1857. );
  1858. }
  1859. if (state === "kicked") finish(new Error("session-conflict"));
  1860. },
  1861. onPayload: (payload) => routePayload(runtime, payload),
  1862. onUnrecognizedPayload: (value) => respondToUnrecognizedPayload(runtime, value),
  1863. onRawTransportPayload: (payload) => routeRawTransportCandidate(runtime, payload),
  1864. onRawTransportFault: (reasonCode) =>
  1865. runtime.currentBridge?.relayProtocol?.markDegraded(reasonCode),
  1866. onSendReady: (event) => {
  1867. flushPendingOutboundPayloads(runtime);
  1868. // 后台可能丢弃首次失效通知;沿已有心跳重送直到新 bridge identity 接管。
  1869. // Web 按 bridge 幂等消费,重复通知不会重置恢复或退避预算。
  1870. sendPendingBridgeInvalidation(runtime);
  1871. const isFirstSendReadyForPairing = !runtime.hasObservedSendReadyForPairing;
  1872. runtime.hasObservedSendReadyForPairing = true;
  1873. if (event.kind === "reconnected-socket" || isFirstSendReadyForPairing) {
  1874. requestMobileTaskView(runtime);
  1875. }
  1876. const relayProtocol = runtime.currentBridge?.relayProtocol;
  1877. // 同 bridge 未 ACK 批次仍由 adapter 独占;重连后重放,不刷新 queued age。
  1878. if (relayProtocol && !relayProtocol.isDegraded())
  1879. relayProtocol.replayUnacknowledged();
  1880. },
  1881. onError: (error) => {
  1882. if (runtimes.get(windowId) !== runtime) return;
  1883. const failure = createFailure(
  1884. error instanceof WebRemoteControlV2ConnectionError
  1885. ? error.reason
  1886. : "relay-unavailable",
  1887. error.message,
  1888. );
  1889. finish(error);
  1890. if (failure.reason === "auth-required") requireAuthentication(windowId);
  1891. else preserveWindowRuntimeFailure(windowId, runtime, "v2-auth-failed", failure);
  1892. },
  1893. });
  1894. runtime = {
  1895. windowId,
  1896. workspacePath: context.workspacePath,
  1897. workspaceIdentity: context.workspaceIdentity,
  1898. remoteSessionId: context.remoteSessionId,
  1899. initialTaskId: context.initialTaskId,
  1900. theme: context.theme,
  1901. status: "starting",
  1902. deviceSid,
  1903. deviceMid: dependencies.deviceMid,
  1904. connectUrl: "",
  1905. qrUrl: "",
  1906. transport,
  1907. mobileConnected: false,
  1908. hasEverPaired: false,
  1909. hasObservedSendReadyForPairing: false,
  1910. pendingOutboundPayloads: [],
  1911. };
  1912. runtimes.set(windowId, runtime);
  1913. // 启动前的 await 期间远端可能已连上,那次窗口同步还找不到 runtime,这里补读最新快照。
  1914. syncRuntimeRemoteSession(runtime);
  1915. emitRuntimeStatus(runtime);
  1916. transport.start();
  1917. });
  1918. await readyPromise;
  1919. assertActive();
  1920. return {
  1921. status: runtime!.status === "active" ? "active" : "running",
  1922. sessionId: deviceSid,
  1923. windowControlSessionId: deviceSid,
  1924. qrUrl: runtime!.qrUrl,
  1925. connectUrl: runtime!.connectUrl,
  1926. workspacePath: context.workspacePath,
  1927. workspaceIdentity: context.workspaceIdentity,
  1928. remoteSessionId: context.remoteSessionId,
  1929. initialTaskId: context.initialTaskId,
  1930. };
  1931. } catch (error) {
  1932. if (
  1933. !signal.aborted &&
  1934. error instanceof WebRemoteControlV2ConnectionError &&
  1935. error.reason === "auth-required"
  1936. ) {
  1937. requireAuthentication(windowId);
  1938. }
  1939. throw error;
  1940. }
  1941. },
  1942. async stop(windowId: number): Promise<void> {
  1943. lifecycleRevision += 1;
  1944. authNotificationRevision += 1;
  1945. startupRestoreClaimed = true;
  1946. authRequiredWindows.delete(windowId);
  1947. clearStartAuthorizationsForWindow(windowId);
  1948. // Bugfix: 清除自动恢复设置需要写磁盘,失败时不能阻止用户关闭当前远控连接。
  1949. // 先释放 transport 和 attachment,再把持久化错误返回 UI,保证本次运行立即停止。
  1950. await stopWindowRuntime(windowId, "manual-stop");
  1951. await dependencies.startupRestoreStorageProvider.clear();
  1952. },
  1953. async suspend(windowId: number, reason: string): Promise<void> {
  1954. clearStartAuthorizationsForWindow(windowId);
  1955. if (reason === "endpoint-changed") notificationConnection.invalidate();
  1956. await stopWindowRuntime(windowId, reason);
  1957. if (reason === "endpoint-changed") void notificationConnection.refresh();
  1958. },
  1959. async notifyAuthStateChanged(
  1960. windowId: number,
  1961. change: WebRemoteControlAuthStateChange,
  1962. ): Promise<void> {
  1963. const revision = ++authNotificationRevision;
  1964. if (change.state === "signed-in") {
  1965. const login = await dependencies.getLogin();
  1966. const endpointUrls = await dependencies.getEndpointUrls?.();
  1967. if (revision !== authNotificationRevision) return;
  1968. if (!login?.jwt || !login.userId) {
  1969. requireAuthentication(windowId);
  1970. return;
  1971. }
  1972. // 只刷新通知资格;身份是否变化由 MobilePushConnection 判定,同账号重复通知不清 owner。
  1973. void notificationConnection.refresh({ restart: true });
  1974. const endpointOrigin = new URL(endpointUrls?.origin ?? dependencies.mobileRemoteControlUrl)
  1975. .origin;
  1976. const staleWindows = [...windowLifecycles].filter(
  1977. ([, lifecycle]) =>
  1978. lifecycle.identity &&
  1979. (lifecycle.identity.userId !== login.userId ||
  1980. lifecycle.identity.endpointOrigin !== endpointOrigin),
  1981. );
  1982. if (staleWindows.length > 0) {
  1983. lifecycleRevision += 1;
  1984. startupRestoreClaimed = false;
  1985. // 先同步撤销所有旧代再等待;已认证 socket 不会重新验证 JWT,不能只等下一次取 token。
  1986. await Promise.all(
  1987. staleWindows.map(([id]) => {
  1988. clearStartAuthorizationsForWindow(id);
  1989. return stopWindowRuntime(id, "auth-identity-changed");
  1990. }),
  1991. );
  1992. if (revision !== authNotificationRevision) return;
  1993. }
  1994. for (const id of authRequiredWindows)
  1995. dependencies.onStatusChanged?.(id, { status: "idle" });
  1996. authRequiredWindows.clear();
  1997. for (const [candidateWindowId, contexts] of availableWorkspacesByWindowId) {
  1998. if (await this.restorePreviouslyEnabled(candidateWindowId, contexts)) break;
  1999. if (revision !== authNotificationRevision) return;
  2000. }
  2001. return;
  2002. }
  2003. notificationConnection.invalidate();
  2004. lifecycleRevision += 1;
  2005. startupRestoreClaimed = false;
  2006. const windowIds = new Set([
  2007. windowId,
  2008. ...availableWorkspacesByWindowId.keys(),
  2009. ...runtimes.keys(),
  2010. ...windowLifecycles.keys(),
  2011. ]);
  2012. // 先同步撤销所有窗口的启动/连接,再等待调用方;登出不能被慢 HTTP 写回复活。
  2013. for (const id of windowIds) {
  2014. clearStartAuthorizationsForWindow(id);
  2015. requireAuthentication(id);
  2016. }
  2017. },
  2018. async restorePreviouslyEnabled(
  2019. windowId: number,
  2020. candidates: Array<WebRemoteControlContext & { label?: string }>,
  2021. ): Promise<boolean> {
  2022. // 修复原因:候选快照与 syncAvailableWorkspaces 共用同一份 WorkspaceTarget 表,label 是必填展示字段;
  2023. // 生产调用方传入完整目标,只有仅携带 context 的调用需要回退到路径,不能写入缺 label 的列表项。
  2024. availableWorkspacesByWindowId.set(
  2025. windowId,
  2026. candidates.map((candidate) => ({
  2027. ...candidate,
  2028. label: candidate.label ?? candidate.workspacePath,
  2029. kind: candidate.workspaceIdentity || candidate.remoteSessionId ? "remote" : "local",
  2030. })),
  2031. );
  2032. // 401/登出后只有登录通知能解除门禁,workspace 同步不能重试失效 JWT。
  2033. if (startupRestoreClaimed || runtimes.has(windowId) || authRequiredWindows.has(windowId))
  2034. return false;
  2035. const revision = lifecycleRevision;
  2036. const persistedContext = await dependencies.startupRestoreStorageProvider
  2037. .load()
  2038. .catch((error) => {
  2039. dependencies.logger.warn(
  2040. "[web-remote-control] load startup restore context failed",
  2041. error,
  2042. );
  2043. return undefined;
  2044. });
  2045. if (revision !== lifecycleRevision || startupRestoreClaimed || !persistedContext) {
  2046. return false;
  2047. }
  2048. const persistedWorkspaceKey = resolveWebRemoteControlWorkspaceKey(persistedContext);
  2049. const isPersistedTarget = (candidate: WebRemoteControlWorkspaceTarget) =>
  2050. resolveWebRemoteControlWorkspaceKey(candidate) === persistedWorkspaceKey;
  2051. // 磁盘读取期间可能发生 tab 关闭或远端重连,只能消费最新完整快照。
  2052. const windowWorkspaces = availableWorkspacesByWindowId.get(windowId) ?? [];
  2053. const persistedTarget = windowWorkspaces.find(isPersistedTarget);
  2054. // Bugfix:启动只恢复上次激活的工作区,上次启用目标常不在窗口里,远端目标也可能还没重连。
  2055. // 旧逻辑把“目标在窗口里且已连接”当作恢复门槛,不满足就静默跳过,设备一直离线。
  2056. // 上次启用目标只用于手机初始定位:在本窗口就用它,否则用本窗口首个可 bridge 的工作区。
  2057. // 目标在其他窗口时交给那个窗口,保持原窗口归属;窗口没有工作区时等待下一次同步。
  2058. const ownedByOtherWindow = [...availableWorkspacesByWindowId].some(
  2059. ([id, workspaces]) => id !== windowId && workspaces.some(isPersistedTarget),
  2060. );
  2061. const currentContext =
  2062. persistedTarget ??
  2063. (ownedByOtherWindow
  2064. ? undefined
  2065. : (windowWorkspaces.find(isBridgeableRemoteTarget) ?? windowWorkspaces[0]));
  2066. if (!currentContext) {
  2067. return false;
  2068. }
  2069. startupRestoreClaimed = true;
  2070. dependencies.logger.info(
  2071. `[web-remote-control] restoring previous enabled state window=${windowId} target=${persistedTarget ? "saved" : "window"} workspace=${currentContext.workspacePath} remoteSession=${currentContext.remoteSessionId ?? "none"}`,
  2072. );
  2073. try {
  2074. await this.start(windowId, {
  2075. workspacePath: currentContext.workspacePath,
  2076. workspaceIdentity: currentContext.workspaceIdentity,
  2077. remoteSessionId: currentContext.remoteSessionId,
  2078. // 任务只属于上次启用目标;换成窗口里的其他工作区时不能带过去。
  2079. initialTaskId: persistedTarget ? persistedContext.initialTaskId : undefined,
  2080. });
  2081. return true;
  2082. } catch (error) {
  2083. if (revision === lifecycleRevision) startupRestoreClaimed = false;
  2084. dependencies.logger.warn(
  2085. "[web-remote-control] restore previous enabled state failed",
  2086. error,
  2087. );
  2088. return false;
  2089. }
  2090. },
  2091. /** 找到可拉日志的已配对连接:优先指定窗口,否则任一已配对窗口。 */
  2092. findMobileLogPullTarget(
  2093. windowId: number | undefined,
  2094. ): WebRemoteControlMobileLogPullTarget | undefined {
  2095. const runtime = findMobileLogPullRuntime(windowId);
  2096. if (!runtime) return undefined;
  2097. return {
  2098. windowId: runtime.windowId,
  2099. deviceLabel: resolveMobileLogDeviceLabel(runtime) || "mobile",
  2100. };
  2101. },
  2102. /** 向已配对手机拉取日志;分片逐片交给 onShard 落盘,全部完成后返回汇总。 */
  2103. pullMobileLogs(
  2104. windowId: number,
  2105. query: MobileLogPullQuery,
  2106. onShard: (shard: MobileLogPullShard) => Promise<void>,
  2107. ): Promise<MobileLogPullSummary> {
  2108. const runtime = findMobileLogPullRuntime(windowId);
  2109. if (!runtime || runtime.windowId !== windowId) {
  2110. return Promise.reject(
  2111. new MobileLogPullError("not-paired", "no paired mobile for this window"),
  2112. );
  2113. }
  2114. return mobileLogPulls.start({
  2115. owner: runtime,
  2116. query,
  2117. send: (payload) => sendAppPayload(runtime, payload),
  2118. onShard,
  2119. });
  2120. },
  2121. getStatus(windowId: number): WebRemoteControlStatus {
  2122. if (!dependencies.featureGate.isEnabled()) {
  2123. return {
  2124. status: "idle",
  2125. failure: createFailure(
  2126. "unsupported-action",
  2127. "Web remote control is disabled in this build.",
  2128. ),
  2129. };
  2130. }
  2131. if (authRequiredWindows.has(windowId)) return { status: "auth-required" };
  2132. const runtime = runtimes.get(windowId);
  2133. if (!runtime) {
  2134. return { status: "idle" };
  2135. }
  2136. return buildRuntimeStatus(runtime);
  2137. },
  2138. syncAvailableWorkspaces(windowId: number, workspaces: WebRemoteControlWorkspaceTarget[]): void {
  2139. availableWorkspacesByWindowId.set(windowId, workspaces);
  2140. const runtime = runtimes.get(windowId);
  2141. if (!runtime) {
  2142. return;
  2143. }
  2144. if (syncRuntimeRemoteSession(runtime)) emitRuntimeStatus(runtime);
  2145. pushWorkspaceListUpdated(runtime);
  2146. },
  2147. async replaceRemoteSession(event: {
  2148. previousSessionId: string;
  2149. sessionId: string;
  2150. workspacePath: string;
  2151. workspaceIdentity: string;
  2152. }): Promise<void> {
  2153. for (const [windowId, runtime] of runtimes) {
  2154. const bridge = runtime.currentBridge;
  2155. const bridgeMatches =
  2156. bridge?.remoteSessionId === event.previousSessionId &&
  2157. bridge.workspacePath === event.workspacePath &&
  2158. bridge.workspaceIdentity === event.workspaceIdentity;
  2159. const runtimeMatches = runtime.remoteSessionId === event.previousSessionId;
  2160. const availableWorkspaces = availableWorkspacesByWindowId.get(windowId);
  2161. if (availableWorkspaces) {
  2162. availableWorkspacesByWindowId.set(
  2163. windowId,
  2164. availableWorkspaces.map((workspace) =>
  2165. workspace.remoteSessionId === event.previousSessionId &&
  2166. workspace.workspacePath === event.workspacePath &&
  2167. workspace.workspaceIdentity === event.workspaceIdentity
  2168. ? { ...workspace, remoteSessionId: event.sessionId, connectionState: "connected" }
  2169. : workspace,
  2170. ),
  2171. );
  2172. }
  2173. if (runtimeMatches) runtime.remoteSessionId = event.sessionId;
  2174. if (!bridgeMatches || !bridge) {
  2175. if (runtimeMatches || availableWorkspaces) pushWorkspaceListUpdated(runtime);
  2176. continue;
  2177. }
  2178. // Bug 原因:过去 Main 复用相同 bridge identity 重建 acknowledged protocol,
  2179. // 新协议的 seq 从 1 开始,手机 assembler 却仍等待 N+1,新帧会被当成旧 duplicate
  2180. // 静默丢弃。这里只发非终态 degraded,由 Web 已有恢复流程以新 identity 主动重建。
  2181. bridge.degraded = true;
  2182. runtime.pendingBridgeInvalidation = {
  2183. zcode_type: "bridge-degraded",
  2184. bridgeSessionId: bridge.bridgeSessionId,
  2185. ...(bridge.bridgeGeneration === undefined
  2186. ? {}
  2187. : { bridgeGeneration: bridge.bridgeGeneration }),
  2188. ...(bridge.recoveryId ? { recoveryId: bridge.recoveryId } : {}),
  2189. reason: "source-session-replaced",
  2190. };
  2191. disposeRuntimeBridgeResources(runtime);
  2192. sendPendingBridgeInvalidation(runtime);
  2193. pushWorkspaceListUpdated(runtime);
  2194. }
  2195. },
  2196. async disposeWindow(windowId: number): Promise<void> {
  2197. lifecycleRevision += 1;
  2198. authRequiredWindows.delete(windowId);
  2199. clearStartAuthorizationsForWindow(windowId);
  2200. await stopWindowRuntime(windowId, "window-disposed");
  2201. availableWorkspacesByWindowId.delete(windowId);
  2202. pushedWorkspaceListSignaturesByWindowId.delete(windowId);
  2203. },
  2204. failRemoteSession(
  2205. remoteSessionId: string,
  2206. reason: string,
  2207. failure: WebRemoteControlFailure,
  2208. ): void {
  2209. for (const [windowId, runtime] of runtimes) {
  2210. const bridge = runtime.currentBridge;
  2211. const bridgeUsesRemoteSession = bridge?.remoteSessionId === remoteSessionId;
  2212. const runtimeUsesRemoteSession = runtime.remoteSessionId === remoteSessionId;
  2213. if (!bridgeUsesRemoteSession && !runtimeUsesRemoteSession) {
  2214. continue;
  2215. }
  2216. // Bugfix: 远程 workspace session 只是某个 workspace/bridge 的依赖,不能把它的断开升级成
  2217. // 窗口级 Web 远控 device WS 失败;否则单个远端空闲退出会错误关闭电脑端全局远控入口。
  2218. if (bridgeUsesRemoteSession) {
  2219. disposeRuntimeBridgeResources(runtime);
  2220. sendAppPayload(runtime, {
  2221. zcode_type: "workspace-bridge-error",
  2222. bridgeSessionId: bridge.bridgeSessionId,
  2223. ...(bridge.bridgeGeneration !== undefined
  2224. ? { bridgeGeneration: bridge.bridgeGeneration }
  2225. : {}),
  2226. ...(bridge.recoveryId ? { recoveryId: bridge.recoveryId } : {}),
  2227. requestId: `remote-session-closed:${remoteSessionId}`,
  2228. reason: failure.reason,
  2229. error: failure.message ?? failure.reason,
  2230. });
  2231. }
  2232. if (runtimeUsesRemoteSession) {
  2233. runtime.remoteSessionId = undefined;
  2234. }
  2235. // workspace 生命周期不能复活因401或KICKED终止的设备连接。
  2236. if (runtime.status !== "error") {
  2237. runtime.status = runtime.mobileConnected ? "active" : "running";
  2238. runtime.error = undefined;
  2239. runtime.failure = undefined;
  2240. }
  2241. runtimes.set(windowId, runtime);
  2242. emitRuntimeStatus(runtime);
  2243. }
  2244. dependencies.disposeWorkspaceHostAttachmentsForRemoteSession(remoteSessionId, reason);
  2245. },
  2246. };
  2247. }