windowRemoteConnectionRegistry.ts 71 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776
  1. /* eslint-disable max-lines -- 所有 transport 生命周期共享同一个 registry 状态机,必须原子演进。 */
  2. import {
  3. buildSshRemoteHostKey,
  4. buildServerRemoteWorkspaceIdentity,
  5. stripRemoteTargetSecrets,
  6. type RemoteTarget,
  7. type SourceServerArtifactPolicy,
  8. type WorkspacePurpose,
  9. type WindowHostAttachmentScope,
  10. type WindowHostRemoteWorkspaceDescriptor,
  11. } from "@zcode/shared";
  12. export interface WindowRemoteAssetDirs {
  13. mockCdnDir?: string;
  14. remoteCdnBaseUrl?: string;
  15. remoteCdnBaseUrls?: string[];
  16. remoteCacheDir?: string;
  17. sourceServerArtifactPolicy?: SourceServerArtifactPolicy;
  18. }
  19. export interface WindowRemoteConnectionCloseEvent {
  20. exitCode: number | null;
  21. signal: string | null;
  22. error?: string;
  23. recoverable?: boolean;
  24. recoveryAttempt?: number;
  25. recoveryLimit?: number;
  26. recoveryBudgetExhausted?: boolean;
  27. reasonCode?: string;
  28. retryable?: boolean;
  29. }
  30. export interface WindowRemoteConnectionHandle<TServices, TCapabilities = never> {
  31. services: TServices;
  32. reusedConnectionTarget?: RemoteTarget;
  33. capabilities?: TCapabilities;
  34. dispose(): void | Promise<void>;
  35. onDidClose?(listener: (event: WindowRemoteConnectionCloseEvent) => void): {
  36. dispose(): void;
  37. };
  38. /** 同一 Source transport 自动重连完成;services/capabilities getter 已切到新连接。 */
  39. onDidReconnect?(listener: () => void): { dispose(): void };
  40. }
  41. export interface WindowRemoteConnectionConnectRequest {
  42. membershipIntent?: "add" | "retain";
  43. existingSourceServerId?: string;
  44. target: RemoteTarget;
  45. remoteAssets: WindowRemoteAssetDirs;
  46. signal: AbortSignal;
  47. confirmSourceServerInstall?: boolean;
  48. }
  49. export type WindowRemoteConnectionState =
  50. | "connecting"
  51. | "online"
  52. | "closing"
  53. | "failed"
  54. | "disconnected";
  55. export interface WindowRemoteLogicalSessionSnapshot {
  56. sourceServerId?: string;
  57. remoteSessionId: string;
  58. requestId: string;
  59. target: RemoteTarget;
  60. workspacePath?: string;
  61. workspaceIdentity?: string;
  62. workspacePurpose?: WorkspacePurpose;
  63. generation: number;
  64. state: WindowRemoteConnectionState;
  65. sourceAvailability: "online" | "offline";
  66. }
  67. export class WindowRemoteConnectCancelledError extends Error {
  68. public readonly code = "remote-connection-canceled";
  69. constructor() {
  70. super("远程连接已取消");
  71. this.name = "WindowRemoteConnectCancelledError";
  72. }
  73. }
  74. export class WindowRemoteConnectionUnavailableError extends Error {
  75. constructor(remoteSessionId: string) {
  76. super(`远程连接当前不可用,remoteSessionId=${remoteSessionId}`);
  77. this.name = "WindowRemoteConnectionUnavailableError";
  78. }
  79. }
  80. interface ConnectionEntry<TServices, TCapabilities> {
  81. key: string;
  82. sourceServerId?: string;
  83. target: RemoteTarget;
  84. state: WindowRemoteConnectionState;
  85. abortController: AbortController;
  86. sessions: Set<string>;
  87. ready: Promise<WindowRemoteConnectionHandle<TServices, TCapabilities>>;
  88. handle?: WindowRemoteConnectionHandle<TServices, TCapabilities>;
  89. closeSubscription?: { dispose(): void };
  90. reconnectSubscription?: { dispose(): void };
  91. reconnectFlight?: Promise<void>;
  92. replacementRetryTimer?: ReturnType<typeof setTimeout>;
  93. recoveryReplacements?: Array<{
  94. previous: LogicalSession<TServices, TCapabilities>;
  95. current: LogicalSession<TServices, TCapabilities>;
  96. }>;
  97. closePhase: "none" | "recovering" | "terminal";
  98. lastRecoveryAttemptNotified?: number;
  99. recoveryReady?: Promise<void>;
  100. recoveryFailure?: Error;
  101. resolveRecovery?: () => void;
  102. rejectRecovery?: (error: Error) => void;
  103. disposePromise?: Promise<void>;
  104. disposed: boolean;
  105. transitionEpoch: number;
  106. idleTimer?: ReturnType<typeof setTimeout>;
  107. idleReason: string;
  108. workspaceKeys: Set<string>;
  109. runningTaskCountByWorkspaceKey: Map<string, number>;
  110. workspaceRuntimeByKey: Map<string, WorkspaceRuntimeState>;
  111. }
  112. class WindowRemoteConnectionTransitionStaleError extends Error {
  113. public constructor() {
  114. super("远程连接状态已在异步操作期间换代");
  115. this.name = "WindowRemoteConnectionTransitionStaleError";
  116. }
  117. }
  118. interface RemoteWorkspaceContext {
  119. workspacePath: string;
  120. workspaceIdentity?: string;
  121. }
  122. interface WorkspaceRuntimeState {
  123. context: RemoteWorkspaceContext;
  124. generation: number;
  125. pendingReleaseGeneration?: number;
  126. releaseInFlight?: Promise<void>;
  127. }
  128. interface LogicalSession<TServices, TCapabilities> {
  129. sourceServerId?: string;
  130. remoteSessionId: string;
  131. requestId: string;
  132. target: RemoteTarget;
  133. workspacePath?: string;
  134. workspaceIdentity?: string;
  135. workspacePurpose?: WorkspacePurpose;
  136. legacyWorkspaceIdentity?: string;
  137. generation: number;
  138. state: WindowRemoteConnectionState;
  139. sourceAvailability: "online" | "offline";
  140. entry: ConnectionEntry<TServices, TCapabilities>;
  141. workspaceKey?: string;
  142. workspaceGeneration?: number;
  143. workspaceReady: Promise<void>;
  144. workspaceReadyState: "pending" | "ready" | "failed";
  145. cancelled: boolean;
  146. rejectCancellation: (error: WindowRemoteConnectCancelledError) => void;
  147. cancellation: Promise<never>;
  148. }
  149. function normalizeWslSegment(value: string | undefined): string {
  150. return value?.trim() || "<default>";
  151. }
  152. function normalizeServerConnectionUrl(value: string): string {
  153. try {
  154. const url = new URL(value.trim());
  155. if (url.protocol === "ws:") url.protocol = "http:";
  156. if (url.protocol === "wss:") url.protocol = "https:";
  157. url.search = "";
  158. url.hash = "";
  159. const path = url.pathname.replace(/\/+$/u, "");
  160. url.pathname = path.endsWith("/ws/host")
  161. ? path.slice(0, -"/ws/host".length) || "/"
  162. : path.endsWith("/ws")
  163. ? path.slice(0, -"/ws".length) || "/"
  164. : path || "/";
  165. return url.toString().replace(/\/$/u, "");
  166. } catch {
  167. return value.trim().replace(/\/+$/u, "");
  168. }
  169. }
  170. function buildConnectionKey(target: RemoteTarget): string {
  171. switch (target.kind) {
  172. case "ssh":
  173. return `ssh:${buildSshRemoteHostKey(target)}`;
  174. case "wsl":
  175. return `wsl:${normalizeWslSegment(target.distro)}\0${normalizeWslSegment(target.user)}`;
  176. case "docker":
  177. return `docker:${target.container.trim()}`;
  178. case "server":
  179. return `server:${target.serverId?.trim() || normalizeServerConnectionUrl(target.url)}`;
  180. }
  181. }
  182. function toSessionSnapshot<TServices, TCapabilities>(
  183. session: LogicalSession<TServices, TCapabilities>,
  184. ): WindowRemoteLogicalSessionSnapshot {
  185. return {
  186. ...(session.sourceServerId ? { sourceServerId: session.sourceServerId } : {}),
  187. remoteSessionId: session.remoteSessionId,
  188. requestId: session.requestId,
  189. target: stripRemoteTargetSecrets(session.target),
  190. ...(session.workspacePath ? { workspacePath: session.workspacePath } : {}),
  191. ...(session.workspaceIdentity ? { workspaceIdentity: session.workspaceIdentity } : {}),
  192. ...(session.workspacePurpose ? { workspacePurpose: session.workspacePurpose } : {}),
  193. generation: session.generation,
  194. state: session.state,
  195. sourceAvailability: session.sourceAvailability,
  196. };
  197. }
  198. export function createWindowRemoteConnectionRegistry<TServices, TCapabilities = never>(options: {
  199. connect: (
  200. request: WindowRemoteConnectionConnectRequest,
  201. ) => Promise<WindowRemoteConnectionHandle<TServices, TCapabilities>>;
  202. createId: () => string;
  203. onConnectionChanged?: () => void;
  204. onSessionClosed?: (event: WindowRemoteConnectionCloseEvent & { remoteSessionId: string }) => void;
  205. onSessionReconnected?: (event: {
  206. previous: WindowRemoteLogicalSessionSnapshot;
  207. current: WindowRemoteLogicalSessionSnapshot;
  208. services: TServices;
  209. isCurrent: () => boolean;
  210. commit: () => boolean;
  211. }) => void | Promise<void>;
  212. onSessionReconnectError?: (error: unknown) => void;
  213. releaseWorkspace?: (services: TServices, context: RemoteWorkspaceContext) => Promise<void>;
  214. onWorkspaceReleaseError?: (context: RemoteWorkspaceContext, error: unknown) => void;
  215. resolveSourceServerId?: (
  216. handle: WindowRemoteConnectionHandle<TServices, TCapabilities>,
  217. ) => string | undefined;
  218. shouldKeepConnectionAlive?: (
  219. handle: WindowRemoteConnectionHandle<TServices, TCapabilities>,
  220. ) => boolean;
  221. prepareWorkspaceIdentity?: (
  222. handle: WindowRemoteConnectionHandle<TServices, TCapabilities>,
  223. input: {
  224. sourceServerId: string;
  225. workspacePath: string;
  226. stableWorkspaceIdentity: string;
  227. legacyRouteHint?: string;
  228. signal?: AbortSignal;
  229. },
  230. ) => Promise<void>;
  231. wslIdleTtlMs?: number;
  232. logicalReplacementRetryDelaysMs?: readonly number[];
  233. }) {
  234. const entriesByKey = new Map<string, ConnectionEntry<TServices, TCapabilities>>();
  235. const entriesBySourceServerId = new Map<string, ConnectionEntry<TServices, TCapabilities>>();
  236. const sessionsById = new Map<string, LogicalSession<TServices, TCapabilities>>();
  237. const pendingSessionsByRequestId = new Map<string, LogicalSession<TServices, TCapabilities>>();
  238. let disposed = false;
  239. let disposePromise: Promise<void> | null = null;
  240. const wslIdleTtlMs = options.wslIdleTtlMs ?? 60_000;
  241. const logicalReplacementRetryDelaysMs =
  242. options.logicalReplacementRetryDelaysMs ?? ([500, 1_000, 2_000] as const);
  243. function shouldKeepConnectionAlive(entry: ConnectionEntry<TServices, TCapabilities>): boolean {
  244. return Boolean(entry.handle && options.shouldKeepConnectionAlive?.(entry.handle));
  245. }
  246. function removeEntryOwners(entry: ConnectionEntry<TServices, TCapabilities>): void {
  247. for (const [key, owner] of entriesByKey) {
  248. if (owner === entry) entriesByKey.delete(key);
  249. }
  250. if (entry.sourceServerId && entriesBySourceServerId.get(entry.sourceServerId) === entry) {
  251. entriesBySourceServerId.delete(entry.sourceServerId);
  252. }
  253. }
  254. function canOwnManagedSource(entry: ConnectionEntry<TServices, TCapabilities>): boolean {
  255. return (
  256. !entry.disposed &&
  257. !entry.abortController.signal.aborted &&
  258. (entry.state === "connecting" ||
  259. entry.state === "online" ||
  260. (entry.state === "disconnected" &&
  261. entry.closePhase === "recovering" &&
  262. shouldKeepConnectionAlive(entry)))
  263. );
  264. }
  265. function assignSessionToSourceOwner(
  266. session: LogicalSession<TServices, TCapabilities>,
  267. owner: ConnectionEntry<TServices, TCapabilities>,
  268. sourceServerId: string,
  269. ): void {
  270. session.entry = owner;
  271. session.target = owner.target;
  272. session.state = owner.state === "online" ? "online" : owner.state;
  273. session.sourceAvailability = owner.state === "online" ? "online" : "offline";
  274. applyStableWorkspaceIdentity(session, sourceServerId);
  275. }
  276. /**
  277. * Source 身份已知后,logical session 的 workspace identity/workspaceKey 只允许是
  278. * `remote:server:<sourceServerId>:<path>`;调用方传入的 route identity 只保留为 legacyRouteHint。
  279. * 握手上线、Source owner 转交、在线 entry 直接 join 三条路径必须共用这一处规则。
  280. */
  281. function applyStableWorkspaceIdentity(
  282. session: LogicalSession<TServices, TCapabilities>,
  283. sourceServerId: string,
  284. ): void {
  285. session.sourceServerId = sourceServerId;
  286. if (!session.workspacePath) return;
  287. session.legacyWorkspaceIdentity ??= session.workspaceIdentity;
  288. session.workspaceIdentity = buildServerRemoteWorkspaceIdentity({
  289. serverId: sourceServerId,
  290. workspacePath: session.workspacePath,
  291. });
  292. session.workspaceKey = session.workspaceIdentity;
  293. session.entry.workspaceKeys.add(session.workspaceIdentity);
  294. }
  295. function subscribeEntryHandle(
  296. entry: ConnectionEntry<TServices, TCapabilities>,
  297. handle: WindowRemoteConnectionHandle<TServices, TCapabilities>,
  298. ): void {
  299. entry.handle = handle;
  300. entry.closeSubscription = handle.onDidClose?.((event) => {
  301. handleConnectionClosed(entry, event);
  302. });
  303. entry.reconnectSubscription = handle.onDidReconnect?.(() => {
  304. handleConnectionReconnected(entry);
  305. });
  306. }
  307. async function takeOverRecoveringSourceOwner(
  308. provisional: ConnectionEntry<TServices, TCapabilities>,
  309. owner: ConnectionEntry<TServices, TCapabilities>,
  310. handle: WindowRemoteConnectionHandle<TServices, TCapabilities>,
  311. sourceServerId: string,
  312. ): Promise<void> {
  313. const previousHandle = owner.handle;
  314. owner.closeSubscription?.dispose();
  315. owner.closeSubscription = undefined;
  316. owner.reconnectSubscription?.dispose();
  317. owner.reconnectSubscription = undefined;
  318. if (owner.replacementRetryTimer) {
  319. clearTimeout(owner.replacementRetryTimer);
  320. owner.replacementRetryTimer = undefined;
  321. }
  322. owner.target = provisional.target;
  323. subscribeEntryHandle(owner, handle);
  324. for (const remoteSessionId of Array.from(provisional.sessions)) {
  325. const session = sessionsById.get(remoteSessionId);
  326. if (!session || session.entry !== provisional) continue;
  327. provisional.sessions.delete(remoteSessionId);
  328. owner.sessions.add(remoteSessionId);
  329. assignSessionToSourceOwner(session, owner, sourceServerId);
  330. // 当前 request 只是 recovery waiter,不能被 replaceDisconnectedSessions 当成上一代
  331. // logical owner 再换代一次;恢复完成后它会 join 真正的 replacement session。
  332. session.state = "connecting";
  333. }
  334. removeEntryOwners(provisional);
  335. entriesByKey.set(provisional.key, owner);
  336. provisional.handle = undefined;
  337. await disposeSupersededEntryTransport(provisional);
  338. await Promise.resolve(previousHandle?.dispose());
  339. handleConnectionReconnected(owner);
  340. }
  341. async function promoteOrJoinSourceOwner(
  342. entry: ConnectionEntry<TServices, TCapabilities>,
  343. handle: WindowRemoteConnectionHandle<TServices, TCapabilities>,
  344. sourceServerId: string,
  345. ): Promise<ConnectionEntry<TServices, TCapabilities>> {
  346. entry.sourceServerId = sourceServerId;
  347. const existing = entriesBySourceServerId.get(sourceServerId);
  348. if (!existing || existing === entry || !canOwnManagedSource(existing)) {
  349. entriesBySourceServerId.set(sourceServerId, entry);
  350. return entry;
  351. }
  352. if (
  353. existing.state === "disconnected" &&
  354. existing.closePhase === "recovering" &&
  355. !existing.reconnectFlight
  356. ) {
  357. // 不同 Profile 的手动连接已经拿到同一 Source 的新 handle,而旧 wrapper 尚未收到
  358. // reconnect(Manager 在发布点统一 fire,通常旧 wrapper 会先换代并把 entry 置回 online;
  359. // 只有它仍停在 recovering 且没有换代 flight 时才由新 handle 直接接管,避免 join 挂起)。
  360. await takeOverRecoveringSourceOwner(entry, existing, handle, sourceServerId);
  361. return existing;
  362. }
  363. // Bug 根因:route entry 在握手后曾直接成为 online owner,导致同一 Source 的多个
  364. // Profile 各自持有 logical wrapper。握手得到稳定身份后,竞争失败的 provisional
  365. // entry 必须在发布 online 前把 waiter/session 转交给 canonical Source entry。
  366. for (const remoteSessionId of Array.from(entry.sessions)) {
  367. const session = sessionsById.get(remoteSessionId);
  368. if (!session || session.entry !== entry) continue;
  369. entry.sessions.delete(remoteSessionId);
  370. existing.sessions.add(remoteSessionId);
  371. assignSessionToSourceOwner(session, existing, sourceServerId);
  372. }
  373. removeEntryOwners(entry);
  374. entriesByKey.set(entry.key, existing);
  375. await disposeSupersededEntryTransport(entry);
  376. return existing;
  377. }
  378. function clearIdleTimer(entry: ConnectionEntry<TServices, TCapabilities>): void {
  379. if (!entry.idleTimer) {
  380. return;
  381. }
  382. clearTimeout(entry.idleTimer);
  383. entry.idleTimer = undefined;
  384. }
  385. function hasRunningTasks(entry: ConnectionEntry<TServices, TCapabilities>): boolean {
  386. return Array.from(entry.runningTaskCountByWorkspaceKey.values()).some((count) => count > 0);
  387. }
  388. function beginRecovery(entry: ConnectionEntry<TServices, TCapabilities>): void {
  389. if (entry.recoveryReady) return;
  390. entry.recoveryFailure = undefined;
  391. entry.recoveryReady = new Promise<void>((resolve, reject) => {
  392. entry.resolveRecovery = resolve;
  393. entry.rejectRecovery = reject;
  394. });
  395. // 无手动 waiter 时终态拒绝也不得变成 unhandled rejection。
  396. void entry.recoveryReady.catch(() => undefined);
  397. }
  398. function completeRecovery(entry: ConnectionEntry<TServices, TCapabilities>): void {
  399. entry.resolveRecovery?.();
  400. entry.recoveryReady = undefined;
  401. entry.resolveRecovery = undefined;
  402. entry.rejectRecovery = undefined;
  403. entry.closePhase = "none";
  404. entry.lastRecoveryAttemptNotified = undefined;
  405. entry.recoveryFailure = undefined;
  406. }
  407. function notifyEntrySessionsClosed(
  408. entry: ConnectionEntry<TServices, TCapabilities>,
  409. event: WindowRemoteConnectionCloseEvent,
  410. ): void {
  411. for (const remoteSessionId of entry.sessions) {
  412. const session = sessionsById.get(remoteSessionId);
  413. if (!session || pendingSessionsByRequestId.get(session.requestId) === session) continue;
  414. options.onSessionClosed?.({ remoteSessionId, ...event });
  415. }
  416. }
  417. function failRecovery(entry: ConnectionEntry<TServices, TCapabilities>, error: Error): void {
  418. entry.recoveryFailure = error;
  419. entry.rejectRecovery?.(error);
  420. entry.recoveryReady = undefined;
  421. entry.resolveRecovery = undefined;
  422. entry.rejectRecovery = undefined;
  423. }
  424. function createRecoveryFailure(
  425. entry: ConnectionEntry<TServices, TCapabilities>,
  426. event: WindowRemoteConnectionCloseEvent,
  427. ): Error {
  428. const error = new Error(event.error || `Remote connection recovery exhausted: ${entry.key}`);
  429. if (event.reasonCode) Object.assign(error, { code: event.reasonCode });
  430. if (event.retryable !== undefined) Object.assign(error, { retryable: event.retryable });
  431. if (event.recoveryAttempt !== undefined) {
  432. Object.assign(error, { recoveryAttempt: event.recoveryAttempt });
  433. }
  434. if (event.recoveryLimit !== undefined) {
  435. Object.assign(error, { recoveryLimit: event.recoveryLimit });
  436. }
  437. return error;
  438. }
  439. function rollbackRecoveryReplacements(entry: ConnectionEntry<TServices, TCapabilities>): void {
  440. const replacements = entry.recoveryReplacements;
  441. if (!replacements) return;
  442. entry.recoveryReplacements = undefined;
  443. for (const { previous, current } of replacements) {
  444. if (sessionsById.get(current.remoteSessionId) === current) {
  445. sessionsById.delete(current.remoteSessionId);
  446. }
  447. entry.sessions.delete(current.remoteSessionId);
  448. previous.state = "disconnected";
  449. previous.sourceAvailability = "offline";
  450. sessionsById.set(previous.remoteSessionId, previous);
  451. entry.sessions.add(previous.remoteSessionId);
  452. }
  453. }
  454. function listDisconnectedSessions(
  455. entry: ConnectionEntry<TServices, TCapabilities>,
  456. ): LogicalSession<TServices, TCapabilities>[] {
  457. return [...entry.sessions]
  458. .map((remoteSessionId) => sessionsById.get(remoteSessionId))
  459. .filter(
  460. (session): session is LogicalSession<TServices, TCapabilities> =>
  461. Boolean(session) &&
  462. session?.state === "disconnected" &&
  463. pendingSessionsByRequestId.get(session.requestId) !== session,
  464. );
  465. }
  466. function isCurrentRecoveryReplacement(
  467. entry: ConnectionEntry<TServices, TCapabilities>,
  468. current: LogicalSession<TServices, TCapabilities>,
  469. transitionEpoch: number,
  470. ): boolean {
  471. return (
  472. !entry.disposed &&
  473. entriesByKey.get(entry.key) === entry &&
  474. entry.transitionEpoch === transitionEpoch &&
  475. entry.state === "online" &&
  476. sessionsById.get(current.remoteSessionId) === current &&
  477. entry.recoveryReplacements?.some((replacement) => replacement.current === current) === true
  478. );
  479. }
  480. function sessionOwnsWorkspace(
  481. session: LogicalSession<TServices, TCapabilities>,
  482. entry: ConnectionEntry<TServices, TCapabilities>,
  483. workspaceKey: string,
  484. ): boolean {
  485. return (
  486. !session.cancelled &&
  487. session.entry === entry &&
  488. session.workspaceKey === workspaceKey &&
  489. sessionsById.get(session.remoteSessionId) === session
  490. );
  491. }
  492. function hasOtherWorkspaceOwner(
  493. entry: ConnectionEntry<TServices, TCapabilities>,
  494. workspaceKey: string,
  495. excludedRemoteSessionId: string,
  496. ): boolean {
  497. return Array.from(sessionsById.values()).some(
  498. (candidate) =>
  499. candidate.remoteSessionId !== excludedRemoteSessionId &&
  500. sessionOwnsWorkspace(candidate, entry, workspaceKey),
  501. );
  502. }
  503. function startWorkspaceRelease(
  504. entry: ConnectionEntry<TServices, TCapabilities>,
  505. workspaceKey: string,
  506. state: WorkspaceRuntimeState,
  507. generation: number,
  508. ): Promise<void> | undefined {
  509. if (
  510. entry.target.kind !== "wsl" ||
  511. state.generation !== generation ||
  512. state.releaseInFlight ||
  513. !entry.handle ||
  514. entry.state !== "online" ||
  515. !options.releaseWorkspace
  516. ) {
  517. return state.releaseInFlight;
  518. }
  519. state.pendingReleaseGeneration = undefined;
  520. const release = options
  521. .releaseWorkspace(entry.handle.services, state.context)
  522. .catch((error) => {
  523. options.onWorkspaceReleaseError?.(state.context, error);
  524. throw error;
  525. })
  526. .finally(() => {
  527. if (state.releaseInFlight === release) {
  528. state.releaseInFlight = undefined;
  529. }
  530. if (
  531. state.generation === generation &&
  532. !state.pendingReleaseGeneration &&
  533. !Array.from(sessionsById.values()).some((candidate) =>
  534. sessionOwnsWorkspace(candidate, entry, workspaceKey),
  535. )
  536. ) {
  537. entry.workspaceRuntimeByKey.delete(workspaceKey);
  538. }
  539. });
  540. // release 由 dispose/running-task 事件触发;失败由结构化回调记录,同时保留 rejecting
  541. // Promise 给同 workspace 的下一代 acquire,使其 fail-closed 而不是踩过未完成清理。
  542. void release.catch(() => undefined);
  543. state.releaseInFlight = release;
  544. return release;
  545. }
  546. function requestWorkspaceRelease(params: {
  547. entry: ConnectionEntry<TServices, TCapabilities>;
  548. remoteSessionId: string;
  549. workspaceKey?: string;
  550. workspaceGeneration?: number;
  551. }): Promise<void> | undefined {
  552. const { entry, workspaceKey, workspaceGeneration } = params;
  553. if (
  554. entry.target.kind !== "wsl" ||
  555. shouldKeepConnectionAlive(entry) ||
  556. !workspaceKey ||
  557. !workspaceGeneration
  558. ) {
  559. return undefined;
  560. }
  561. if (hasOtherWorkspaceOwner(entry, workspaceKey, params.remoteSessionId)) {
  562. return undefined;
  563. }
  564. const state = entry.workspaceRuntimeByKey.get(workspaceKey);
  565. if (!state || state.generation !== workspaceGeneration) {
  566. return undefined;
  567. }
  568. if ((entry.runningTaskCountByWorkspaceKey.get(workspaceKey) ?? 0) > 0) {
  569. state.pendingReleaseGeneration = workspaceGeneration;
  570. return undefined;
  571. }
  572. return startWorkspaceRelease(entry, workspaceKey, state, workspaceGeneration);
  573. }
  574. function abortError(): Error {
  575. return Object.assign(new Error("Remote workspace bind was aborted"), {
  576. name: "AbortError",
  577. });
  578. }
  579. async function waitWithAbort<T>(operation: Promise<T>, signal?: AbortSignal): Promise<T> {
  580. if (!signal) return await operation;
  581. if (signal.aborted) throw abortError();
  582. let onAbort!: () => void;
  583. const aborted = new Promise<never>((_resolve, reject) => {
  584. onAbort = () => reject(abortError());
  585. signal.addEventListener("abort", onAbort, { once: true });
  586. });
  587. try {
  588. return await Promise.race([operation, aborted]);
  589. } finally {
  590. signal.removeEventListener("abort", onAbort);
  591. }
  592. }
  593. function prepareWorkspaceRuntime(
  594. session: LogicalSession<TServices, TCapabilities>,
  595. signal?: AbortSignal,
  596. ): Promise<void> {
  597. const expectedSessionGeneration = session.generation;
  598. const identityPreparation =
  599. session.entry.handle &&
  600. session.sourceServerId &&
  601. session.workspacePath &&
  602. session.workspaceIdentity &&
  603. options.prepareWorkspaceIdentity
  604. ? options.prepareWorkspaceIdentity(session.entry.handle, {
  605. sourceServerId: session.sourceServerId,
  606. workspacePath: session.workspacePath,
  607. stableWorkspaceIdentity: session.workspaceIdentity,
  608. ...(session.legacyWorkspaceIdentity
  609. ? { legacyRouteHint: session.legacyWorkspaceIdentity }
  610. : {}),
  611. ...(signal ? { signal } : {}),
  612. })
  613. : null;
  614. const identityReady = waitWithAbort(identityPreparation ?? Promise.resolve(), signal);
  615. if (session.entry.target.kind !== "wsl" || !session.workspacePath || !session.workspaceKey) {
  616. if (!identityPreparation) {
  617. session.workspaceReadyState = "ready";
  618. session.workspaceReady = Promise.resolve();
  619. return session.workspaceReady;
  620. }
  621. session.workspaceReadyState = "pending";
  622. session.workspaceReady = identityReady.then(
  623. () => {
  624. if (session.generation !== expectedSessionGeneration) throw abortError();
  625. session.workspaceReadyState = "ready";
  626. },
  627. (error) => {
  628. if (session.generation === expectedSessionGeneration) {
  629. session.workspaceReadyState = "failed";
  630. }
  631. throw error;
  632. },
  633. );
  634. return session.workspaceReady;
  635. }
  636. const workspaceKey = session.workspaceKey;
  637. const entry = session.entry;
  638. const existing = entry.workspaceRuntimeByKey.get(workspaceKey);
  639. const hasOtherOwner = hasOtherWorkspaceOwner(entry, workspaceKey, session.remoteSessionId);
  640. const state =
  641. existing ??
  642. ({
  643. context: {
  644. workspacePath: session.workspacePath,
  645. ...(session.workspaceIdentity ? { workspaceIdentity: session.workspaceIdentity } : {}),
  646. },
  647. generation: 0,
  648. } satisfies WorkspaceRuntimeState);
  649. entry.workspaceRuntimeByKey.set(workspaceKey, state);
  650. state.context = {
  651. workspacePath: session.workspacePath,
  652. ...(session.workspaceIdentity ? { workspaceIdentity: session.workspaceIdentity } : {}),
  653. };
  654. if (!hasOtherOwner) {
  655. state.generation += 1;
  656. // 上一代 release 仍因 running task 等待时,新 logical owner 已重新持有
  657. // workspace;尚未开始的旧 release 必须失效,不能在 task 归零后误清新 runtime。
  658. }
  659. state.pendingReleaseGeneration = undefined;
  660. session.workspaceGeneration = state.generation;
  661. session.workspaceReadyState = "pending";
  662. const releaseToWait = state.releaseInFlight;
  663. const ready = Promise.all([identityReady, releaseToWait ?? Promise.resolve()])
  664. .then(() => {
  665. if (
  666. sessionsById.get(session.remoteSessionId) !== session ||
  667. session.cancelled ||
  668. entry.workspaceRuntimeByKey.get(workspaceKey)?.generation !== session.workspaceGeneration
  669. ) {
  670. throw new WindowRemoteConnectCancelledError();
  671. }
  672. session.workspaceReadyState = "ready";
  673. })
  674. .catch((error) => {
  675. session.workspaceReadyState = "failed";
  676. throw error;
  677. });
  678. session.workspaceReady = ready;
  679. return ready;
  680. }
  681. function scheduleWslIdleDispose(
  682. entry: ConnectionEntry<TServices, TCapabilities>,
  683. reason: string,
  684. ): void {
  685. clearIdleTimer(entry);
  686. entry.idleReason = reason;
  687. if (
  688. entry.target.kind !== "wsl" ||
  689. entry.disposed ||
  690. entry.sessions.size > 0 ||
  691. hasRunningTasks(entry)
  692. ) {
  693. return;
  694. }
  695. entry.idleTimer = setTimeout(() => {
  696. entry.idleTimer = undefined;
  697. if (
  698. entriesByKey.get(entry.key) !== entry ||
  699. entry.disposed ||
  700. entry.sessions.size > 0 ||
  701. hasRunningTasks(entry)
  702. ) {
  703. return;
  704. }
  705. void disposeEntry(entry);
  706. }, wslIdleTtlMs);
  707. }
  708. async function disposeEntry(entry: ConnectionEntry<TServices, TCapabilities>): Promise<void> {
  709. if (entry.disposePromise) {
  710. return entry.disposePromise;
  711. }
  712. entry.disposed = true;
  713. clearIdleTimer(entry);
  714. if (entry.replacementRetryTimer) clearTimeout(entry.replacementRetryTimer);
  715. entry.replacementRetryTimer = undefined;
  716. failRecovery(entry, new WindowRemoteConnectCancelledError());
  717. entry.state = "closing";
  718. entry.abortController.abort();
  719. entry.closeSubscription?.dispose();
  720. entry.closeSubscription = undefined;
  721. entry.reconnectSubscription?.dispose();
  722. entry.reconnectSubscription = undefined;
  723. removeEntryOwners(entry);
  724. options.onConnectionChanged?.();
  725. entry.disposePromise = Promise.resolve(entry.handle?.dispose()).then(() => undefined);
  726. return entry.disposePromise;
  727. }
  728. async function disposeSupersededEntryTransport(
  729. entry: ConnectionEntry<TServices, TCapabilities>,
  730. ): Promise<void> {
  731. if (entry.disposePromise) return entry.disposePromise;
  732. // Bug 原因:自动恢复的旧 entry 在手动重连抢占 connection key 后只是 return,
  733. // 旧 handle 上的 Manager state/reconnect 订阅永不释放。这里只回收失去 owner 的 transport
  734. // wrapper。旧 logical session 已经不可路由,必须在新 owner 接管时同步退休;否则每轮
  735. // 手动重连都会累积一份 disconnected session,下一次断开后 workspace scope 变成多解。
  736. for (const remoteSessionId of entry.sessions) {
  737. const session = sessionsById.get(remoteSessionId);
  738. if (
  739. !session ||
  740. session.entry !== entry ||
  741. session.state !== "disconnected" ||
  742. pendingSessionsByRequestId.get(session.requestId) === session
  743. ) {
  744. continue;
  745. }
  746. sessionsById.delete(remoteSessionId);
  747. entry.sessions.delete(remoteSessionId);
  748. }
  749. entry.disposed = true;
  750. clearIdleTimer(entry);
  751. if (entry.replacementRetryTimer) clearTimeout(entry.replacementRetryTimer);
  752. entry.replacementRetryTimer = undefined;
  753. // Bug 原因:abort 只取消 transport,不能结束 connect 对 recoveryReady 的等待。
  754. // 旧 entry 被抢占后不再收到恢复事件,必须在释放订阅前主动拒绝其等待者。
  755. failRecovery(entry, new WindowRemoteConnectCancelledError());
  756. entry.abortController.abort();
  757. entry.closeSubscription?.dispose();
  758. entry.closeSubscription = undefined;
  759. entry.reconnectSubscription?.dispose();
  760. entry.reconnectSubscription = undefined;
  761. entry.disposePromise = Promise.resolve(entry.handle?.dispose()).then(() => undefined);
  762. return entry.disposePromise;
  763. }
  764. function handleConnectionClosed(
  765. entry: ConnectionEntry<TServices, TCapabilities>,
  766. event: WindowRemoteConnectionCloseEvent,
  767. ): void {
  768. // Bug 原因:逻辑替换重试曾跨物理断线存活,定时器会冒充重连把 entry 标回 online,
  769. // 耗尽预算后还会提前放行 recovery waiter。close 必须撤销旧 transport 的逻辑重试。
  770. if (entry.replacementRetryTimer) clearTimeout(entry.replacementRetryTimer);
  771. entry.replacementRetryTimer = undefined;
  772. if (entry.disposed || entry.state === "closing") return;
  773. if (entry.state === "disconnected") {
  774. if (entry.closePhase === "recovering" && event.recoverable !== false) {
  775. if (
  776. event.recoveryAttempt !== undefined &&
  777. event.recoveryAttempt !== entry.lastRecoveryAttemptNotified
  778. ) {
  779. // Bug 原因:Manager 会发布 1/3、2/3、3/3,但 registry 曾把 disconnected 后的
  780. // recoverable close 全部丢弃,Renderer 永远停在首轮。只按 attempt 去重并继续投影。
  781. entry.lastRecoveryAttemptNotified = event.recoveryAttempt;
  782. notifyEntrySessionsClosed(entry, event);
  783. }
  784. return;
  785. }
  786. if (entry.closePhase !== "recovering" || event.recoverable !== false) return;
  787. entry.transitionEpoch += 1;
  788. entry.closePhase = "terminal";
  789. failRecovery(entry, createRecoveryFailure(entry, event));
  790. notifyEntrySessionsClosed(entry, event);
  791. return;
  792. }
  793. entry.transitionEpoch += 1;
  794. const hadRecoveryReplacement = Boolean(entry.recoveryReplacements?.length);
  795. if (hadRecoveryReplacement) {
  796. rollbackRecoveryReplacements(entry);
  797. }
  798. if (
  799. (entry.state === "connecting" || hadRecoveryReplacement || Boolean(entry.recoveryReady)) &&
  800. event.recoverable === false
  801. ) {
  802. // Bug 原因:恢复换代已经先发布了 provisional session id,终态 close 若直接沿用它,
  803. // Renderer 会收到一个从未完成连接的幽灵 id;同时 recoveryReady 无人 reject,join 永久等待。
  804. // 终态到达时先恢复上一代 logical session,再拒绝 recovery flight 并广播真实离线 owner。
  805. failRecovery(entry, createRecoveryFailure(entry, event));
  806. }
  807. entry.state = "disconnected";
  808. options.onConnectionChanged?.();
  809. entry.closePhase = event.recoverable === true ? "recovering" : "terminal";
  810. entry.lastRecoveryAttemptNotified = event.recoveryAttempt;
  811. if (entry.closePhase === "recovering") beginRecovery(entry);
  812. clearIdleTimer(entry);
  813. if (!shouldKeepConnectionAlive(entry) && entriesByKey.get(entry.key) === entry) {
  814. entriesByKey.delete(entry.key);
  815. }
  816. for (const remoteSessionId of entry.sessions) {
  817. const session = sessionsById.get(remoteSessionId);
  818. if (!session || pendingSessionsByRequestId.get(session.requestId) === session) continue;
  819. session.state = "disconnected";
  820. session.sourceAvailability = "offline";
  821. options.onSessionClosed?.({ remoteSessionId, ...event });
  822. }
  823. }
  824. async function replaceDisconnectedSessions(
  825. entry: ConnectionEntry<TServices, TCapabilities>,
  826. ): Promise<void> {
  827. if (
  828. entry.disposed ||
  829. !entry.handle ||
  830. (entry.state !== "disconnected" && entry.state !== "online")
  831. )
  832. return;
  833. const transitionEpoch = entry.transitionEpoch;
  834. // 物理 Source 已经恢复;logical replacement 的失败只属于对应 workspace,不能把
  835. // 已提交 sibling 的共享 transport 再标回 disconnected。
  836. entry.state = "online";
  837. entriesByKey.set(entry.key, entry);
  838. const disconnectedSessions = listDisconnectedSessions(entry);
  839. let firstReplacementError: unknown;
  840. let hasReplacementError = false;
  841. for (const previous of disconnectedSessions) {
  842. if (
  843. entry.disposed ||
  844. entriesByKey.get(entry.key) !== entry ||
  845. entry.transitionEpoch !== transitionEpoch ||
  846. entry.state !== "online"
  847. ) {
  848. throw new WindowRemoteConnectionTransitionStaleError();
  849. }
  850. if (
  851. sessionsById.get(previous.remoteSessionId) !== previous ||
  852. previous.state !== "disconnected"
  853. ) {
  854. continue;
  855. }
  856. const current: LogicalSession<TServices, TCapabilities> = {
  857. ...previous,
  858. remoteSessionId: options.createId(),
  859. target: entry.target,
  860. generation: previous.generation + 1,
  861. state: "connecting",
  862. sourceAvailability: "offline",
  863. sourceServerId: options.resolveSourceServerId?.(entry.handle) ?? previous.sourceServerId,
  864. workspaceReady: Promise.resolve(),
  865. workspaceReadyState: "pending",
  866. cancelled: false,
  867. rejectCancellation: () => undefined,
  868. cancellation: new Promise<never>(() => undefined),
  869. };
  870. entry.recoveryReplacements = [{ previous, current }];
  871. entry.sessions.delete(previous.remoteSessionId);
  872. sessionsById.delete(previous.remoteSessionId);
  873. sessionsById.set(current.remoteSessionId, current);
  874. entry.sessions.add(current.remoteSessionId);
  875. try {
  876. await prepareWorkspaceRuntime(current);
  877. if (!isCurrentRecoveryReplacement(entry, current, transitionEpoch)) {
  878. throw new WindowRemoteConnectionTransitionStaleError();
  879. }
  880. const commit = (): boolean => {
  881. if (!isCurrentRecoveryReplacement(entry, current, transitionEpoch)) {
  882. return false;
  883. }
  884. current.state = "online";
  885. current.sourceAvailability = "online";
  886. // 当前 workspace 的外部 owner 已提交;后续 sibling 失败不得再回滚本 generation。
  887. entry.recoveryReplacements = undefined;
  888. return true;
  889. };
  890. if (options.onSessionReconnected) {
  891. await options.onSessionReconnected({
  892. previous: toSessionSnapshot(previous),
  893. current: toSessionSnapshot(current),
  894. services: entry.handle.services,
  895. isCurrent: () => isCurrentRecoveryReplacement(entry, current, transitionEpoch),
  896. commit,
  897. });
  898. } else {
  899. commit();
  900. }
  901. if (
  902. sessionsById.get(current.remoteSessionId) !== current ||
  903. current.state !== "online" ||
  904. current.sourceAvailability !== "online" ||
  905. entry.recoveryReplacements !== undefined
  906. ) {
  907. throw new WindowRemoteConnectionTransitionStaleError();
  908. }
  909. } catch (error) {
  910. rollbackRecoveryReplacements(entry);
  911. if (
  912. sessionsById.get(current.remoteSessionId) === current &&
  913. current.state === "online" &&
  914. current.sourceAvailability === "online" &&
  915. entry.recoveryReplacements === undefined
  916. ) {
  917. // commit 是不可逆边界;提交后的旁路日志/通知异常只能上报,不能把已经对外发布的
  918. // generation 再塞回 rollback 路径。
  919. options.onSessionReconnectError?.(error);
  920. continue;
  921. }
  922. if (
  923. error instanceof WindowRemoteConnectionTransitionStaleError ||
  924. entry.disposed ||
  925. entriesByKey.get(entry.key) !== entry ||
  926. entry.transitionEpoch !== transitionEpoch ||
  927. entry.state !== "online"
  928. ) {
  929. throw new WindowRemoteConnectionTransitionStaleError();
  930. }
  931. // 单个 workspace 的 replacement 失败不能阻断同一 Source 上后续 sibling;继续提交
  932. // 其余 workspace,最后只为仍 disconnected 的 owner 安排下一轮 retry。
  933. if (!hasReplacementError) firstReplacementError = error;
  934. hasReplacementError = true;
  935. }
  936. }
  937. if (hasReplacementError) throw firstReplacementError;
  938. completeRecovery(entry);
  939. }
  940. function scheduleLogicalReplacementRetry(
  941. entry: ConnectionEntry<TServices, TCapabilities>,
  942. attempt: number,
  943. error: unknown,
  944. ): void {
  945. const delay = logicalReplacementRetryDelaysMs[attempt];
  946. if (entry.disposed || entry.state !== "online" || listDisconnectedSessions(entry).length === 0)
  947. return;
  948. if (delay === undefined) {
  949. const terminalError = error instanceof Error ? error : new Error(String(error));
  950. for (const session of listDisconnectedSessions(entry)) {
  951. options.onSessionClosed?.({
  952. remoteSessionId: session.remoteSessionId,
  953. exitCode: null,
  954. signal: null,
  955. recoverable: false,
  956. error: terminalError.message,
  957. ...("code" in terminalError && typeof terminalError.code === "string"
  958. ? { reasonCode: terminalError.code }
  959. : {}),
  960. ...("retryable" in terminalError && typeof terminalError.retryable === "boolean"
  961. ? { retryable: terminalError.retryable }
  962. : {}),
  963. });
  964. }
  965. // logical replacement 预算耗尽不能污染仍在线的 Source entry;等待中的手动 join
  966. // 继续使用已恢复 transport,并由自身 workspace admission 决定结果。
  967. completeRecovery(entry);
  968. return;
  969. }
  970. if (entry.replacementRetryTimer) clearTimeout(entry.replacementRetryTimer);
  971. const retryEpoch = entry.transitionEpoch;
  972. entry.replacementRetryTimer = setTimeout(() => {
  973. // 迟到回调只属于安排时仍在线的 transport;先校验,避免摘掉新 epoch 的 timer。
  974. if (entry.state !== "online" || entry.transitionEpoch !== retryEpoch) return;
  975. entry.replacementRetryTimer = undefined;
  976. handleConnectionReconnected(entry, attempt + 1);
  977. }, delay);
  978. }
  979. function handleConnectionReconnected(
  980. entry: ConnectionEntry<TServices, TCapabilities>,
  981. attempt = 0,
  982. ): void {
  983. if (
  984. entry.reconnectFlight ||
  985. entry.disposed ||
  986. (entry.state !== "disconnected" && entry.state !== "online")
  987. )
  988. return;
  989. const currentOwner = entriesByKey.get(entry.key);
  990. if (currentOwner && currentOwner !== entry) {
  991. // Bug 原因:自动 retry 与用户手动重连可能共享 Manager 的新 connection。迟到的旧 entry
  992. // 曾无条件 set 回 connection key,制造两个 online logical session 并互相 dispose。
  993. // connection key 已有新 owner 时,旧恢复 flight 必须失效,交给 Host 清理离线 session。
  994. void disposeSupersededEntryTransport(entry);
  995. return;
  996. }
  997. if (entry.closePhase === "terminal") {
  998. // 新物理连接到达后,旧终态失败不能污染新线路的 join;挂回完成前用新屏障等待。
  999. entry.closePhase = "recovering";
  1000. beginRecovery(entry);
  1001. }
  1002. let shouldRetry = false;
  1003. let retryError: unknown;
  1004. const flight = replaceDisconnectedSessions(entry)
  1005. .catch((error) => {
  1006. options.onSessionReconnectError?.(error);
  1007. shouldRetry =
  1008. !(error instanceof WindowRemoteConnectionTransitionStaleError) &&
  1009. listDisconnectedSessions(entry).length > 0;
  1010. retryError = error;
  1011. })
  1012. .finally(() => {
  1013. if (entry.reconnectFlight === flight) entry.reconnectFlight = undefined;
  1014. if (shouldRetry) scheduleLogicalReplacementRetry(entry, attempt, retryError);
  1015. });
  1016. entry.reconnectFlight = flight;
  1017. }
  1018. function createEntry(params: {
  1019. key: string;
  1020. membershipIntent?: "add" | "retain";
  1021. existingSourceServerId?: string;
  1022. target: RemoteTarget;
  1023. remoteAssets: WindowRemoteAssetDirs;
  1024. confirmSourceServerInstall?: boolean;
  1025. }): ConnectionEntry<TServices, TCapabilities> {
  1026. const abortController = new AbortController();
  1027. const entry: ConnectionEntry<TServices, TCapabilities> = {
  1028. key: params.key,
  1029. target: params.target,
  1030. state: "connecting" as const,
  1031. abortController,
  1032. sessions: new Set<string>(),
  1033. ready: Promise.resolve(undefined as never),
  1034. disposed: false,
  1035. transitionEpoch: 0,
  1036. closePhase: "none",
  1037. idleReason: "wsl-host-idle",
  1038. workspaceKeys: new Set(),
  1039. runningTaskCountByWorkspaceKey: new Map(),
  1040. workspaceRuntimeByKey: new Map(),
  1041. };
  1042. entry.ready = options
  1043. .connect({
  1044. target: params.target,
  1045. membershipIntent: params.membershipIntent,
  1046. existingSourceServerId: params.existingSourceServerId,
  1047. remoteAssets: params.remoteAssets,
  1048. signal: abortController.signal,
  1049. ...(params.confirmSourceServerInstall ? { confirmSourceServerInstall: true } : {}),
  1050. })
  1051. .then(async (handle) => {
  1052. // 关闭可能早于不可中断的握手返回;disposePromise 已完成时仍必须释放迟到的 socket。
  1053. if (entry.disposed) {
  1054. await handle.dispose();
  1055. return handle;
  1056. }
  1057. entry.handle = handle;
  1058. if (entry.disposed || (entry.sessions.size === 0 && !shouldKeepConnectionAlive(entry))) {
  1059. // 修复原因:底层 SSH/WSL connector 可能无法中断认证或部署。
  1060. // 最后一个 logical owner 取消后,迟到的成功结果必须立即释放,不能复活旧连接。
  1061. await disposeEntry(entry);
  1062. return handle;
  1063. }
  1064. const sourceServerId = options.resolveSourceServerId?.(handle);
  1065. if (params.existingSourceServerId && sourceServerId !== params.existingSourceServerId) {
  1066. await disposeEntry(entry);
  1067. throw new WindowRemoteConnectionUnavailableError(params.existingSourceServerId);
  1068. }
  1069. const sourceOwner = sourceServerId
  1070. ? await promoteOrJoinSourceOwner(entry, handle, sourceServerId)
  1071. : entry;
  1072. if (sourceOwner !== entry) return handle;
  1073. entry.target = handle.reusedConnectionTarget ?? entry.target;
  1074. entry.state = "online";
  1075. subscribeEntryHandle(entry, handle);
  1076. options.onConnectionChanged?.();
  1077. for (const remoteSessionId of entry.sessions) {
  1078. const session = sessionsById.get(remoteSessionId);
  1079. if (!session || session.cancelled) {
  1080. continue;
  1081. }
  1082. session.target = entry.target;
  1083. session.state = "online";
  1084. session.sourceAvailability = "online";
  1085. if (sourceServerId) {
  1086. applyStableWorkspaceIdentity(session, sourceServerId);
  1087. }
  1088. }
  1089. return handle;
  1090. })
  1091. .catch((error) => {
  1092. entry.state = "failed";
  1093. removeEntryOwners(entry);
  1094. options.onConnectionChanged?.();
  1095. for (const remoteSessionId of Array.from(entry.sessions)) {
  1096. const session = sessionsById.get(remoteSessionId);
  1097. if (!session) {
  1098. continue;
  1099. }
  1100. session.state = "failed";
  1101. session.sourceAvailability = "offline";
  1102. sessionsById.delete(remoteSessionId);
  1103. pendingSessionsByRequestId.delete(session.requestId);
  1104. }
  1105. entry.sessions.clear();
  1106. throw error;
  1107. });
  1108. entriesByKey.set(entry.key, entry);
  1109. options.onConnectionChanged?.();
  1110. return entry;
  1111. }
  1112. function resolveEntry(params: {
  1113. key: string;
  1114. membershipIntent?: "add" | "retain";
  1115. existingSourceServerId?: string;
  1116. target: RemoteTarget;
  1117. remoteAssets: WindowRemoteAssetDirs;
  1118. confirmSourceServerInstall?: boolean;
  1119. }): ConnectionEntry<TServices, TCapabilities> {
  1120. const existing = entriesByKey.get(params.key);
  1121. if (
  1122. existing &&
  1123. !existing.disposed &&
  1124. !existing.abortController.signal.aborted &&
  1125. (existing.state !== "disconnected" ||
  1126. (existing.closePhase === "recovering" && shouldKeepConnectionAlive(existing)))
  1127. ) {
  1128. clearIdleTimer(existing);
  1129. return existing;
  1130. }
  1131. const created = createEntry(params);
  1132. if (existing && existing !== created) {
  1133. // Bug 原因:terminal entry 被新 owner 覆盖后仍保留 Manager close/reconnect 订阅,
  1134. // 每次手动重连都会泄漏一代 wrapper。物理 Source 仍由 Manager 持有,只回收 wrapper。
  1135. void disposeSupersededEntryTransport(existing);
  1136. }
  1137. return created;
  1138. }
  1139. async function connect(
  1140. params: {
  1141. requestId: string;
  1142. target: RemoteTarget;
  1143. remoteAssets: WindowRemoteAssetDirs;
  1144. workspacePath?: string;
  1145. workspaceIdentity?: string;
  1146. workspacePurpose?: WorkspacePurpose;
  1147. confirmSourceServerInstall?: boolean;
  1148. },
  1149. admission?: {
  1150. entry: ConnectionEntry<TServices, TCapabilities>;
  1151. services: TServices;
  1152. assertCurrent(): Promise<void>;
  1153. },
  1154. ): Promise<WindowHostRemoteWorkspaceDescriptor> {
  1155. if (disposed) {
  1156. throw new Error("窗口 Host 的远程连接 registry 已释放");
  1157. }
  1158. if (pendingSessionsByRequestId.has(params.requestId)) {
  1159. throw new Error(`远程连接 requestId 重复,requestId=${params.requestId}`);
  1160. }
  1161. const remoteSessionId = options.createId();
  1162. const key = buildConnectionKey(params.target);
  1163. const previousEntry = entriesByKey.get(key);
  1164. const initialEntry =
  1165. admission?.entry ??
  1166. resolveEntry({
  1167. key,
  1168. target: params.target,
  1169. remoteAssets: params.remoteAssets,
  1170. ...(params.confirmSourceServerInstall ? { confirmSourceServerInstall: true } : {}),
  1171. });
  1172. let reusedConnectionTarget =
  1173. initialEntry.state === "online" ? stripRemoteTargetSecrets(initialEntry.target) : undefined;
  1174. let rejectCancellation!: (error: WindowRemoteConnectCancelledError) => void;
  1175. const cancellation = new Promise<never>((_resolve, reject) => {
  1176. rejectCancellation = reject;
  1177. });
  1178. const sourceServerId = initialEntry.handle
  1179. ? options.resolveSourceServerId?.(initialEntry.handle)
  1180. : undefined;
  1181. // 复用已在线的 Host 时不会再触发握手回调,仍须先绑定稳定 workspace 身份。
  1182. const workspaceIdentity =
  1183. sourceServerId && params.workspacePath
  1184. ? buildServerRemoteWorkspaceIdentity({
  1185. serverId: sourceServerId,
  1186. workspacePath: params.workspacePath,
  1187. })
  1188. : params.workspaceIdentity;
  1189. const session: LogicalSession<TServices, TCapabilities> = {
  1190. ...(sourceServerId ? { sourceServerId } : {}),
  1191. remoteSessionId,
  1192. requestId: params.requestId,
  1193. target: initialEntry.target,
  1194. ...(params.workspacePath ? { workspacePath: params.workspacePath } : {}),
  1195. ...(workspaceIdentity ? { workspaceIdentity } : {}),
  1196. ...(params.workspacePurpose ? { workspacePurpose: params.workspacePurpose } : {}),
  1197. ...(params.workspaceIdentity ? { legacyWorkspaceIdentity: params.workspaceIdentity } : {}),
  1198. generation: 1,
  1199. state: initialEntry.state === "online" ? "online" : "connecting",
  1200. sourceAvailability: initialEntry.state === "online" ? "online" : "offline",
  1201. entry: initialEntry,
  1202. workspaceReady: Promise.resolve(),
  1203. workspaceReadyState: "pending",
  1204. cancelled: false,
  1205. rejectCancellation,
  1206. cancellation,
  1207. };
  1208. initialEntry.sessions.add(remoteSessionId);
  1209. if (sourceServerId) {
  1210. // Bug 原因:entry 已在线时 connect 能直接拿到 sourceServerId,却没有像握手上线、Source owner
  1211. // 转交和 bindWorkspaceContext 那样把 identity 归一成 remote:server:*。Renderer 对未换代的
  1212. // legacy 条目手动重连、或 Host 为无 context 的 connect 补 route identity 时,owner 去重按原值
  1213. // 比对必然不命中,会为同一 workspace 发布第二个 online logical session,并把 legacy identity
  1214. // 当权威值返回;随后 bind 把它改写成 stable,两条 session 同 key,findSessionForWorkspace 多解。
  1215. applyStableWorkspaceIdentity(session, sourceServerId);
  1216. }
  1217. if (!session.workspaceKey) {
  1218. const initialWorkspaceKey = params.workspaceIdentity?.trim() || params.workspacePath;
  1219. if (initialWorkspaceKey) {
  1220. initialEntry.workspaceKeys.add(initialWorkspaceKey);
  1221. session.workspaceKey = initialWorkspaceKey;
  1222. }
  1223. }
  1224. sessionsById.set(remoteSessionId, session);
  1225. pendingSessionsByRequestId.set(params.requestId, session);
  1226. const preparationController = new AbortController();
  1227. try {
  1228. const initialTransitionEpoch = initialEntry.transitionEpoch;
  1229. const readyHandle = await Promise.race([initialEntry.ready, cancellation]);
  1230. reusedConnectionTarget ??= readyHandle.reusedConnectionTarget;
  1231. // 加入别人的 connecting entry 也没有使用本次凭据;以最终 owner 的实际目标投影结果。
  1232. if (previousEntry === initialEntry) {
  1233. reusedConnectionTarget = stripRemoteTargetSecrets(session.entry.target);
  1234. }
  1235. const entry = session.entry;
  1236. const transitionEpoch =
  1237. entry === initialEntry ? initialTransitionEpoch : entry.transitionEpoch;
  1238. if (entry.recoveryFailure) throw entry.recoveryFailure;
  1239. if (entry.recoveryReady) {
  1240. await Promise.race([entry.recoveryReady, cancellation]);
  1241. }
  1242. if (entry.recoveryFailure) throw entry.recoveryFailure;
  1243. await Promise.race([
  1244. prepareWorkspaceRuntime(session, preparationController.signal),
  1245. cancellation,
  1246. ]);
  1247. if (admission) await Promise.race([admission.assertCurrent(), cancellation]);
  1248. if (
  1249. session.cancelled ||
  1250. sessionsById.get(remoteSessionId) !== session ||
  1251. entry.disposed ||
  1252. entriesByKey.get(entry.key) !== entry ||
  1253. entry.transitionEpoch !== transitionEpoch ||
  1254. entry.state !== "online" ||
  1255. (admission && entry.handle?.services !== admission.services)
  1256. ) {
  1257. if (!session.cancelled && sessionsById.get(remoteSessionId) === session) {
  1258. throw new WindowRemoteConnectionUnavailableError(remoteSessionId);
  1259. }
  1260. throw new WindowRemoteConnectCancelledError();
  1261. }
  1262. const existingWorkspaceOwner =
  1263. session.workspaceKey && session.workspacePath && session.workspaceIdentity
  1264. ? Array.from(sessionsById.values()).find(
  1265. (candidate) =>
  1266. candidate !== session &&
  1267. // Bug 根因:Manager 已按 sourceServerId 复用物理连接,但 Registry 曾只在
  1268. // 同 route entry 内查找 workspace owner。不同 Profile 握手到同一 Source 后
  1269. // 必须按稳定 Source 身份收敛;未识别 Source 仍只允许同 entry 复用。
  1270. (candidate.entry === entry ||
  1271. (session.sourceServerId !== undefined &&
  1272. candidate.sourceServerId === session.sourceServerId)) &&
  1273. candidate.workspaceKey === session.workspaceKey &&
  1274. candidate.workspacePath === session.workspacePath &&
  1275. candidate.workspaceIdentity === session.workspaceIdentity &&
  1276. candidate.state === "online" &&
  1277. candidate.sourceAvailability === "online" &&
  1278. // Bug 原因:entry online 会先把 logical session 标成 online,但 workspace identity
  1279. // preparation 可能仍在运行。join 只能复用已经可安全暴露 scoped services 的 owner。
  1280. candidate.workspaceReadyState === "ready",
  1281. )
  1282. : undefined;
  1283. if (existingWorkspaceOwner) {
  1284. // Bug 原因:recovery replacement 与 Bot/手动 join 曾各创建一个 online logical
  1285. // session。workspace owner 已恢复时,join caller 复用唯一 owner,不发布第二份 session。
  1286. sessionsById.delete(remoteSessionId);
  1287. entry.sessions.delete(remoteSessionId);
  1288. if (existingWorkspaceOwner.entry !== entry && entry.sessions.size === 0) {
  1289. // 不同 Profile 创建的 provisional wrapper 已失去最后一个 logical owner;只回收
  1290. // wrapper/Manager 订阅,handle.dispose 不会断开 Manager 持有的物理 Source connection。
  1291. await disposeEntry(entry);
  1292. }
  1293. return {
  1294. ...(existingWorkspaceOwner.sourceServerId
  1295. ? { sourceServerId: existingWorkspaceOwner.sourceServerId }
  1296. : {}),
  1297. ...(reusedConnectionTarget ? { reusedConnectionTarget } : {}),
  1298. remoteSessionId: existingWorkspaceOwner.remoteSessionId,
  1299. target: stripRemoteTargetSecrets(existingWorkspaceOwner.target),
  1300. workspacePath: existingWorkspaceOwner.workspacePath,
  1301. workspaceIdentity: existingWorkspaceOwner.workspaceIdentity,
  1302. ...(existingWorkspaceOwner.workspacePurpose
  1303. ? { workspacePurpose: existingWorkspaceOwner.workspacePurpose }
  1304. : {}),
  1305. generation: existingWorkspaceOwner.generation,
  1306. };
  1307. }
  1308. session.state = "online";
  1309. session.sourceAvailability = "online";
  1310. return {
  1311. ...(reusedConnectionTarget ? { reusedConnectionTarget } : {}),
  1312. ...(session.sourceServerId ? { sourceServerId: session.sourceServerId } : {}),
  1313. remoteSessionId,
  1314. target: stripRemoteTargetSecrets(session.target),
  1315. ...(session.workspacePath ? { workspacePath: session.workspacePath } : {}),
  1316. ...(session.workspaceIdentity ? { workspaceIdentity: session.workspaceIdentity } : {}),
  1317. ...(session.workspacePurpose ? { workspacePurpose: session.workspacePurpose } : {}),
  1318. generation: session.generation,
  1319. };
  1320. } catch (error) {
  1321. const entry = session.entry;
  1322. if (sessionsById.get(remoteSessionId) === session) {
  1323. sessionsById.delete(remoteSessionId);
  1324. entry.sessions.delete(remoteSessionId);
  1325. session.state = "failed";
  1326. session.sourceAvailability = "offline";
  1327. if (
  1328. entry.sessions.size === 0 &&
  1329. !shouldKeepConnectionAlive(entry) &&
  1330. (entry.target.kind === "docker" || entry.target.kind === "server")
  1331. ) {
  1332. await disposeEntry(entry);
  1333. }
  1334. }
  1335. throw error;
  1336. } finally {
  1337. // logical caller 取消或已结束后,迟到的远端 stat 不得再进入身份绑定;信号只属于
  1338. // 这次 preparation,不能 abort 同 Source 其他工作区共用的物理连接。
  1339. preparationController.abort();
  1340. if (pendingSessionsByRequestId.get(params.requestId) === session) {
  1341. pendingSessionsByRequestId.delete(params.requestId);
  1342. }
  1343. }
  1344. }
  1345. function cancelConnect(requestId: string): void {
  1346. const session = pendingSessionsByRequestId.get(requestId);
  1347. if (!session || session.cancelled) {
  1348. return;
  1349. }
  1350. session.cancelled = true;
  1351. pendingSessionsByRequestId.delete(requestId);
  1352. sessionsById.delete(session.remoteSessionId);
  1353. session.entry.sessions.delete(session.remoteSessionId);
  1354. const workspaceRelease = requestWorkspaceRelease({
  1355. entry: session.entry,
  1356. remoteSessionId: session.remoteSessionId,
  1357. workspaceKey: session.workspaceKey,
  1358. workspaceGeneration: session.workspaceGeneration,
  1359. });
  1360. void workspaceRelease?.catch(() => undefined);
  1361. session.rejectCancellation(new WindowRemoteConnectCancelledError());
  1362. if (session.entry.sessions.size === 0) {
  1363. if (session.entry.target.kind === "ssh" && session.entry.state === "connecting") {
  1364. // Bug 根因:最后一个 waiter 取消后,旧 entry 仍以 connecting 留在复用表;立即重连会
  1365. // 继续等待已经 aborted 的 readiness,并沿用上一次凭据。先按对象身份退休旧 entry,
  1366. // 再触发底层取消;迟到的旧 completion 不能删除或复活同 key 的新连接。
  1367. if (entriesByKey.get(session.entry.key) === session.entry) {
  1368. entriesByKey.delete(session.entry.key);
  1369. }
  1370. session.entry.state = "closing";
  1371. session.entry.abortController.abort();
  1372. } else if (
  1373. (session.entry.target.kind === "docker" || session.entry.target.kind === "server") &&
  1374. session.entry.state === "connecting"
  1375. ) {
  1376. // Bug 根因:Docker/Server 的 pending transport 不可被 logical cancel 中断,但也不能继续
  1377. // 占用 connection key,否则下一次 dedicated connect 会错误复用已经没有 waiter 的旧 flight。
  1378. if (entriesByKey.get(session.entry.key) === session.entry) {
  1379. entriesByKey.delete(session.entry.key);
  1380. }
  1381. } else if (shouldKeepConnectionAlive(session.entry)) {
  1382. // Managed Source 的物理连接归 Manager;registry handle 只持有 logical wrapper/订阅。
  1383. void disposeEntry(session.entry);
  1384. } else if (session.entry.target.kind === "wsl" && session.entry.state === "online") {
  1385. scheduleWslIdleDispose(session.entry, "cancelled-logical-connect");
  1386. } else if (session.entry.target.kind === "ssh" && session.entry.state === "online") {
  1387. // ready SSH connection 是窗口 cache;取消一次 logical attach 不应把后续 workspace 的
  1388. // 复用连接一并销毁,真实窗口 Host shutdown 时统一释放。
  1389. clearIdleTimer(session.entry);
  1390. } else if (session.entry.handle) {
  1391. void disposeEntry(session.entry);
  1392. }
  1393. }
  1394. }
  1395. function bindWorkspaceContext(params: {
  1396. remoteSessionId: string;
  1397. workspacePath: string;
  1398. workspaceIdentity: string;
  1399. workspacePurpose?: WorkspacePurpose;
  1400. legacyWorkspaceIdentity?: string;
  1401. signal?: AbortSignal;
  1402. }): Promise<void> {
  1403. const session = sessionsById.get(params.remoteSessionId);
  1404. if (!session) {
  1405. throw new Error(`未找到远程 logical session,remoteSessionId=${params.remoteSessionId}`);
  1406. }
  1407. const previousOwnership = {
  1408. entry: session.entry,
  1409. remoteSessionId: session.remoteSessionId,
  1410. workspaceKey: session.workspaceKey,
  1411. workspaceGeneration: session.workspaceGeneration,
  1412. };
  1413. const previousSession = {
  1414. workspacePath: session.workspacePath,
  1415. legacyWorkspaceIdentity: session.legacyWorkspaceIdentity,
  1416. workspaceIdentity: session.workspaceIdentity,
  1417. workspacePurpose: session.workspacePurpose,
  1418. generation: session.generation,
  1419. workspaceKey: session.workspaceKey,
  1420. workspaceGeneration: session.workspaceGeneration,
  1421. workspaceReady: session.workspaceReady,
  1422. workspaceReadyState: session.workspaceReadyState,
  1423. };
  1424. session.workspacePath = params.workspacePath;
  1425. session.legacyWorkspaceIdentity = params.legacyWorkspaceIdentity ?? params.workspaceIdentity;
  1426. session.workspaceIdentity = session.sourceServerId
  1427. ? buildServerRemoteWorkspaceIdentity({
  1428. serverId: session.sourceServerId,
  1429. workspacePath: params.workspacePath,
  1430. })
  1431. : params.workspaceIdentity;
  1432. session.workspacePurpose = params.workspacePurpose ?? session.workspacePurpose;
  1433. session.generation += 1;
  1434. // Bug 原因:managed Source 会把 params 中的 route identity 换成 stable identity,
  1435. // workspaceKey 若仍从原参数取值,session 就会同时持有两个身份源。
  1436. session.workspaceKey = session.workspaceIdentity.trim() || params.workspacePath;
  1437. session.entry.workspaceKeys.add(session.workspaceKey);
  1438. const nextWorkspaceKey = session.workspaceKey;
  1439. const ready = prepareWorkspaceRuntime(session, params.signal);
  1440. return ready.then(
  1441. () => {
  1442. if (previousOwnership.workspaceKey !== nextWorkspaceKey) {
  1443. const release = requestWorkspaceRelease(previousOwnership);
  1444. void release?.catch(() => undefined);
  1445. }
  1446. },
  1447. (error) => {
  1448. const failedOwnership = {
  1449. entry: session.entry,
  1450. remoteSessionId: session.remoteSessionId,
  1451. workspaceKey: nextWorkspaceKey,
  1452. workspaceGeneration: session.workspaceGeneration,
  1453. };
  1454. session.workspacePath = previousSession.workspacePath;
  1455. session.legacyWorkspaceIdentity = previousSession.legacyWorkspaceIdentity;
  1456. session.workspaceIdentity = previousSession.workspaceIdentity;
  1457. session.workspacePurpose = previousSession.workspacePurpose;
  1458. session.generation = previousSession.generation;
  1459. session.workspaceKey = previousSession.workspaceKey;
  1460. session.workspaceGeneration = previousSession.workspaceGeneration;
  1461. session.workspaceReady = previousSession.workspaceReady;
  1462. session.workspaceReadyState = previousSession.workspaceReadyState;
  1463. if (
  1464. nextWorkspaceKey &&
  1465. !Array.from(sessionsById.values()).some(
  1466. (candidate) => candidate !== session && candidate.workspaceKey === nextWorkspaceKey,
  1467. )
  1468. ) {
  1469. session.entry.workspaceKeys.delete(nextWorkspaceKey);
  1470. }
  1471. const release = requestWorkspaceRelease(failedOwnership);
  1472. void release?.catch(() => undefined);
  1473. throw error;
  1474. },
  1475. );
  1476. }
  1477. function resolveScopedHandle(
  1478. scope: WindowHostAttachmentScope,
  1479. ): WindowRemoteConnectionHandle<TServices, TCapabilities> {
  1480. if (scope.kind !== "remote") {
  1481. throw new Error("远程连接 registry 不能解析 local attachment scope");
  1482. }
  1483. const session = sessionsById.get(scope.remoteSessionId);
  1484. if (!session) {
  1485. throw new WindowRemoteConnectionUnavailableError(scope.remoteSessionId);
  1486. }
  1487. if (
  1488. session.workspacePath !== scope.workspacePath ||
  1489. session.workspaceIdentity !== scope.workspaceIdentity
  1490. ) {
  1491. throw new Error(
  1492. `远程 attachment scope 与 logical session 不匹配,remoteSessionId=${scope.remoteSessionId}`,
  1493. );
  1494. }
  1495. if (
  1496. session.state !== "online" ||
  1497. session.sourceAvailability !== "online" ||
  1498. session.workspaceReadyState !== "ready" ||
  1499. !session.entry.handle
  1500. ) {
  1501. throw new WindowRemoteConnectionUnavailableError(scope.remoteSessionId);
  1502. }
  1503. return session.entry.handle;
  1504. }
  1505. function resolveScopedServices(scope: WindowHostAttachmentScope): TServices {
  1506. return resolveScopedHandle(scope).services;
  1507. }
  1508. function resolveScopedCapabilities(scope: WindowHostAttachmentScope): TCapabilities | undefined {
  1509. return resolveScopedHandle(scope).capabilities;
  1510. }
  1511. async function disposeSession(remoteSessionId: string): Promise<void> {
  1512. const session = sessionsById.get(remoteSessionId);
  1513. if (!session) {
  1514. return;
  1515. }
  1516. sessionsById.delete(remoteSessionId);
  1517. pendingSessionsByRequestId.delete(session.requestId);
  1518. session.entry.sessions.delete(remoteSessionId);
  1519. const workspaceRelease = requestWorkspaceRelease({
  1520. entry: session.entry,
  1521. remoteSessionId,
  1522. workspaceKey: session.workspaceKey,
  1523. workspaceGeneration: session.workspaceGeneration,
  1524. });
  1525. if (session.entry.sessions.size === 0) {
  1526. if (shouldKeepConnectionAlive(session.entry)) {
  1527. // Bug 原因:把“物理 Source 常驻”误当成“logical wrapper 常驻”,关最后 tab
  1528. // 后 close/reconnect 订阅会永久残留。handle.dispose 不会断开 Manager 物理连接。
  1529. await disposeEntry(session.entry);
  1530. } else if (session.entry.target.kind === "wsl" && session.entry.state === "online") {
  1531. scheduleWslIdleDispose(session.entry, "last-logical-session-disposed");
  1532. } else if (session.entry.target.kind === "ssh" && session.entry.state === "online") {
  1533. // R1 只迁移 SSH pool 的 owner:ready connection 继续保持 window-scoped cache,
  1534. // logical session 清空不等于连接退出;真实窗口 Host shutdown 时统一释放。
  1535. clearIdleTimer(session.entry);
  1536. } else {
  1537. await disposeEntry(session.entry);
  1538. }
  1539. }
  1540. await workspaceRelease?.catch(() => undefined);
  1541. }
  1542. function getOnlineSource(sourceServerId: string) {
  1543. const entry = entriesBySourceServerId.get(sourceServerId);
  1544. return entry && !entry.disposed && entry.state === "online" ? entry.handle : undefined;
  1545. }
  1546. return {
  1547. async connectSource(params: {
  1548. target: RemoteTarget;
  1549. remoteAssets: WindowRemoteAssetDirs;
  1550. membershipIntent?: "add" | "retain";
  1551. existingSourceServerId?: string;
  1552. }) {
  1553. if (disposed) throw new WindowRemoteConnectCancelledError();
  1554. if (params.existingSourceServerId) {
  1555. const current = getOnlineSource(params.existingSourceServerId);
  1556. if (current) return { sourceServerId: params.existingSourceServerId, handle: current };
  1557. }
  1558. const entry = resolveEntry({ ...params, key: buildConnectionKey(params.target) });
  1559. await entry.ready;
  1560. const owner = entry.sourceServerId
  1561. ? entriesBySourceServerId.get(entry.sourceServerId)
  1562. : entry;
  1563. if (
  1564. !owner ||
  1565. owner.disposed ||
  1566. owner.state !== "online" ||
  1567. !owner.sourceServerId ||
  1568. !owner.handle
  1569. )
  1570. throw new WindowRemoteConnectionUnavailableError("host-connection");
  1571. return { sourceServerId: owner.sourceServerId, handle: owner.handle };
  1572. },
  1573. getOnlineSource,
  1574. listConnections() {
  1575. return Array.from(new Set(entriesByKey.values()), (entry) => ({
  1576. sourceServerId: entry.sourceServerId,
  1577. target: stripRemoteTargetSecrets(entry.target),
  1578. state: entry.state,
  1579. }));
  1580. },
  1581. connect: (params: Parameters<typeof connect>[0]) => connect(params),
  1582. async openWorkspaceOnSource(params: {
  1583. requestId: string;
  1584. sourceServerId: string;
  1585. workspacePath: string;
  1586. workspaceIdentity?: string;
  1587. workspacePurpose?: WorkspacePurpose;
  1588. assertCurrent(): Promise<void>;
  1589. }): Promise<WindowHostRemoteWorkspaceDescriptor> {
  1590. const entry = entriesBySourceServerId.get(params.sourceServerId);
  1591. // 手机项目导航只取得已在线连接,不走 resolveEntry/connector,也不等待后台恢复。
  1592. if (!entry || entry.disposed || entry.state !== "online" || !entry.handle)
  1593. throw new WindowRemoteConnectionUnavailableError(params.sourceServerId);
  1594. return connect(
  1595. { ...params, target: entry.target, remoteAssets: {} },
  1596. {
  1597. entry,
  1598. services: entry.handle.services,
  1599. assertCurrent: params.assertCurrent,
  1600. },
  1601. );
  1602. },
  1603. cancelConnect,
  1604. bindWorkspaceContext,
  1605. resolveScopedServices,
  1606. resolveScopedCapabilities,
  1607. getSession(remoteSessionId: string): WindowRemoteLogicalSessionSnapshot | null {
  1608. const session = sessionsById.get(remoteSessionId);
  1609. return session ? toSessionSnapshot(session) : null;
  1610. },
  1611. listSessions(): WindowRemoteLogicalSessionSnapshot[] {
  1612. return Array.from(sessionsById.values(), toSessionSnapshot);
  1613. },
  1614. /**
  1615. * 已就绪、未释放的连接(按连接去重,同一 SSH 连接上的多个 logical session 只出现一次)。
  1616. * 供窗口级事实广播给每个远程 Host,例如动态工作流的用户选择(launch.md「The user's choice」)。
  1617. */
  1618. listReadyConnections(): Array<{ target: RemoteTarget; services: TServices }> {
  1619. return Array.from(entriesByKey.values()).flatMap((entry) =>
  1620. entry.handle && !entry.disposed
  1621. ? [{ target: entry.target, services: entry.handle.services }]
  1622. : [],
  1623. );
  1624. },
  1625. findSessionForWorkspace(params: {
  1626. workspacePath: string;
  1627. workspaceIdentity?: string;
  1628. }): WindowRemoteLogicalSessionSnapshot | null {
  1629. const matches = Array.from(sessionsById.values()).filter(
  1630. (session) =>
  1631. session.workspacePath === params.workspacePath &&
  1632. session.workspaceIdentity === params.workspaceIdentity,
  1633. );
  1634. const onlineMatches = matches.filter(
  1635. (session) => session.state === "online" && session.sourceAvailability === "online",
  1636. );
  1637. if (onlineMatches.length > 1 || (onlineMatches.length === 0 && matches.length > 1)) {
  1638. throw new Error(
  1639. `远程 workspace scope 匹配到多个 logical session,workspacePath=${params.workspacePath}`,
  1640. );
  1641. }
  1642. const match = onlineMatches[0] ?? matches[0];
  1643. return match ? toSessionSnapshot(match) : null;
  1644. },
  1645. getStats(): { connectionCount: number; logicalSessionCount: number } {
  1646. return {
  1647. connectionCount: new Set(entriesByKey.values()).size,
  1648. logicalSessionCount: sessionsById.size,
  1649. };
  1650. },
  1651. setWorkspaceRunningTaskCount(params: {
  1652. workspacePath: string;
  1653. workspaceIdentity?: string;
  1654. runningTaskCount: number;
  1655. }): void {
  1656. const workspaceKey = params.workspaceIdentity?.trim() || params.workspacePath;
  1657. // 同一 Source entry 可能被多条 route alias 引用;workspace 生命周期副作用只执行一次。
  1658. for (const entry of new Set(entriesByKey.values())) {
  1659. if (entry.target.kind !== "wsl" || !entry.workspaceKeys.has(workspaceKey)) {
  1660. continue;
  1661. }
  1662. if (params.runningTaskCount > 0) {
  1663. entry.runningTaskCountByWorkspaceKey.set(workspaceKey, params.runningTaskCount);
  1664. clearIdleTimer(entry);
  1665. } else {
  1666. entry.runningTaskCountByWorkspaceKey.delete(workspaceKey);
  1667. const state = entry.workspaceRuntimeByKey.get(workspaceKey);
  1668. if (state?.pendingReleaseGeneration) {
  1669. void startWorkspaceRelease(
  1670. entry,
  1671. workspaceKey,
  1672. state,
  1673. state.pendingReleaseGeneration,
  1674. )?.catch(() => undefined);
  1675. }
  1676. scheduleWslIdleDispose(entry, entry.idleReason);
  1677. }
  1678. }
  1679. },
  1680. async waitForScopedServices(scope: WindowHostAttachmentScope): Promise<TServices> {
  1681. if (scope.kind !== "remote") {
  1682. throw new Error("远程连接 registry 不能解析 local attachment scope");
  1683. }
  1684. const session = sessionsById.get(scope.remoteSessionId);
  1685. if (!session) {
  1686. throw new WindowRemoteConnectionUnavailableError(scope.remoteSessionId);
  1687. }
  1688. await session.workspaceReady;
  1689. return resolveScopedServices(scope);
  1690. },
  1691. disposeSession,
  1692. async dispose(): Promise<void> {
  1693. if (disposePromise) {
  1694. return disposePromise;
  1695. }
  1696. disposed = true;
  1697. for (const requestId of Array.from(pendingSessionsByRequestId.keys())) {
  1698. cancelConnect(requestId);
  1699. }
  1700. const entries = new Set(Array.from(sessionsById.values(), (session) => session.entry));
  1701. for (const entry of entriesByKey.values()) {
  1702. entries.add(entry);
  1703. }
  1704. sessionsById.clear();
  1705. pendingSessionsByRequestId.clear();
  1706. disposePromise = Promise.all(Array.from(entries, disposeEntry)).then(() => undefined);
  1707. return disposePromise;
  1708. },
  1709. };
  1710. }