useRemoteWorkspaceHistory.ts 52 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389
  1. /* eslint-disable max-lines -- 远端 workspace 历史目前需要在一个 hook 内同时收口恢复、重连、持久化和清理流程,先保留同文件协作边界,避免为过 lint 临时拆分后引入状态回归。*/
  2. import { useCallback, useEffect, useMemo, useRef, useState } from "react";
  3. import type { Dispatch, SetStateAction } from "react";
  4. import type {
  5. AppSettings,
  6. BotRemoteWorkspaceReconnectedEvent,
  7. IPlatformService,
  8. RemoteSessionClosedEvent,
  9. RemoteWorkspaceSessionEntry,
  10. } from "@zcode/shared";
  11. import { buildSshRemoteHostKey, createUuid, stripRemoteTargetSecrets } from "@zcode/shared";
  12. import type { IServiceAccessor } from "@zcode/services";
  13. import {
  14. bindRemoteWorkspaceIdentity,
  15. bindRemoteWorkspacePath,
  16. getRemoteWorkspaceSession,
  17. type RemoteWorkspaceSession,
  18. unregisterRemoteWorkspaceSession,
  19. } from "@/store/remoteWorkspaceSessionStore.js";
  20. import { useZCodeSessionStore } from "@/store/zcodeSessionStore.js";
  21. import { refreshRemotePinnedTasksForSession } from "@/store/remotePinnedTaskStore.js";
  22. import { refreshRemoteTimelineTasksForSession } from "@/store/remoteTimelineTaskStore.js";
  23. import { toast } from "@/components/ui/toast.js";
  24. import {
  25. buildRemoteWorkspaceIdentity,
  26. buildRemoteWorkspaceSessionMutation,
  27. buildWorkspaceSessionKey,
  28. createRemoteTargetFromSnapshot,
  29. getRemoteWorkspaceSessionEntries,
  30. removeRemoteWorkspaceSessionEntries,
  31. } from "@/lib/remoteWorkspaceHistory.js";
  32. import { getErrorMessage } from "@/lib/errorMessage.js";
  33. import { logger } from "@/logger.js";
  34. import { isWorkspaceTab, type TabStoreState, type WindowTabState } from "@/store/tabStore.js";
  35. import {
  36. buildRemoteWorkspacePersistPatch,
  37. restorePersistedRemoteWorkspaceSessions,
  38. } from "@/root/remoteWorkspaceSessionPersistence.js";
  39. import { useReconnectingRemoteWorkspaceLogs } from "@/root/useReconnectingRemoteWorkspaceLogs.js";
  40. import {
  41. reconnectRemoteWorkspaceHistoryEntry,
  42. type BindRemoteWorkspaceSessionContextFn,
  43. type ReconnectRemoteWorkspaceOptions,
  44. type SshReconnectCredentials,
  45. } from "@/root/reconnectRemoteWorkspaceHistoryEntry.js";
  46. import { useRemoteConnectionEntryVisibility } from "@/hooks/useRemoteConnectionEntryVisibility.js";
  47. import { markRemoteWorkspaceRunningTasksFailed } from "@/lib/remoteWorkspaceSessionRuntime.js";
  48. export { reconnectRemoteWorkspaceHistoryEntry };
  49. export async function bindRemoteWorkspaceContextAndGetSession(params: {
  50. platform: Pick<IPlatformService, "bindRemoteWorkspaceSessionContext">;
  51. sessionId: string;
  52. workspacePath: string;
  53. workspaceIdentity?: string;
  54. }): Promise<RemoteWorkspaceSession> {
  55. if (!getRemoteWorkspaceSession(params.sessionId)) {
  56. throw new Error(`远程 workspace session 不存在: ${params.sessionId}`);
  57. }
  58. await params.platform.bindRemoteWorkspaceSessionContext?.({
  59. remoteSessionId: params.sessionId,
  60. workspacePath: params.workspacePath,
  61. workspaceIdentity: params.workspaceIdentity,
  62. });
  63. // bind 会让同一 remoteSessionId 的 attachment/services 从 A 换代到 B。
  64. // bind 前捕获的对象仍指向 A,因此必须在 ready ACK 后按 sessionId 重新读取当前 services。
  65. const currentSession = getRemoteWorkspaceSession(params.sessionId);
  66. if (!currentSession) {
  67. throw new Error(`远程 workspace session 不存在: ${params.sessionId}`);
  68. }
  69. return currentSession;
  70. }
  71. export function resolveBotRemoteWorkspaceReconnectedIdentity(params: {
  72. event: Pick<BotRemoteWorkspaceReconnectedEvent, "workspaceIdentity">;
  73. resolvedWorkspacePath: string;
  74. target: BotRemoteWorkspaceReconnectedEvent["target"];
  75. }): string {
  76. const eventWorkspaceIdentity = params.event.workspaceIdentity.trim();
  77. if (eventWorkspaceIdentity) {
  78. // Bugfix: Bot task/stream 广播继续使用 bot context 捕获的 workspaceIdentity。
  79. // 这里如果用 canonical path 重新计算 identity,UI tab 会订阅到另一个 key,导致远端结果被过滤掉。
  80. return eventWorkspaceIdentity;
  81. }
  82. return buildRemoteWorkspaceIdentity(params.resolvedWorkspacePath, params.target);
  83. }
  84. export function shouldPersistRemoteWorkspaceFailure(params: {
  85. pendingReconnectRequestIds: ReadonlyMap<string, string>;
  86. sessionEntry: RemoteWorkspaceSessionEntry;
  87. workspaceKey: string;
  88. }): boolean {
  89. if (params.sessionEntry.target.kind !== "wsl") {
  90. return true;
  91. }
  92. // WSL 偶发断连时,旧 session 的关闭事件可能会晚于手动重连流程。
  93. // 只要当前 workspace 已经有 pending reconnect,就先别把 failed 写死到 setting,
  94. // 让最终结果由这次重连成功/失败决定。
  95. return !params.pendingReconnectRequestIds.has(params.workspaceKey);
  96. }
  97. interface RemoteWorkspaceTabStoreReader {
  98. getState(): {
  99. tabs: WindowTabState[];
  100. };
  101. }
  102. interface OpenRemoteWorkspaceFromHistoryParams {
  103. workspaceKey: string;
  104. tabStoreApi: RemoteWorkspaceTabStoreReader;
  105. getRemoteSessions: () => RemoteWorkspaceSessionEntry[];
  106. inflightReconnectWorkspaceKeys: Set<string>;
  107. activateTabByPath: (workspacePath: string, options?: { workspaceIdentity?: string }) => boolean;
  108. setReconnectingRemoteWorkspaceKeys: Dispatch<SetStateAction<string[]>>;
  109. loadCredential: IServiceAccessor["credentialService"]["load"];
  110. connectRemoteWorkspaceTarget: (
  111. target: Parameters<IPlatformService["connectRemote"]>[0],
  112. requestId?: string,
  113. ) => Promise<string>;
  114. resolveRemoteWorkspaceCanonicalPath: (
  115. sessionId: string,
  116. workspacePath: string,
  117. ) => Promise<string>;
  118. disposeRemoteWorkspaceSession: (sessionId: string) => Promise<void>;
  119. bindRemoteWorkspaceSessionContext: BindRemoteWorkspaceSessionContextFn;
  120. addTab: (
  121. workspacePath: string,
  122. options?: {
  123. remoteSessionId?: string;
  124. remoteTarget?: Parameters<IPlatformService["connectRemote"]>[0];
  125. workspaceIdentity?: string;
  126. localWorkspacePath?: string;
  127. },
  128. ) => void;
  129. commitRemoteWorkspaceSessionMutation: (
  130. mutation: ReturnType<typeof buildRemoteWorkspaceSessionMutation>,
  131. ) => Promise<RemoteWorkspaceSessionEntry>;
  132. resetLogsForWorkspaceKey: (workspaceKey: string) => void;
  133. onWorkspaceActivated?: (target: { workspacePath: string; workspaceIdentity: string }) => void;
  134. createReconnectRequestId?: () => string;
  135. pendingReconnectRequestIds?: Map<string, string>;
  136. reconnectImpl?: typeof reconnectRemoteWorkspaceHistoryEntry;
  137. }
  138. interface ReconnectRemoteWorkspaceByKeyParams {
  139. workspaceKey: string;
  140. canUseRemoteWorkspace: boolean;
  141. getRemoteSessions: () => RemoteWorkspaceSessionEntry[];
  142. runReconnectRemoteWorkspace: (
  143. sessionEntry: RemoteWorkspaceSessionEntry,
  144. options?: ReconnectRemoteWorkspaceOptions,
  145. ) => Promise<void>;
  146. options?: ReconnectRemoteWorkspaceOptions;
  147. }
  148. export async function reconnectRemoteWorkspaceByKey({
  149. workspaceKey,
  150. canUseRemoteWorkspace,
  151. getRemoteSessions,
  152. runReconnectRemoteWorkspace,
  153. options,
  154. }: ReconnectRemoteWorkspaceByKeyParams): Promise<boolean> {
  155. if (!canUseRemoteWorkspace) {
  156. throw new Error("Remote workspace is disabled in this mode");
  157. }
  158. const sessionEntry = getRemoteSessions().find(
  159. (entry) => buildWorkspaceSessionKey(entry) === workspaceKey,
  160. );
  161. if (!sessionEntry) {
  162. throw new Error(`远程 workspace 不在当前窗口中,无法重连: ${workspaceKey}`);
  163. }
  164. await runReconnectRemoteWorkspace(sessionEntry, options);
  165. return true;
  166. }
  167. export function collectSshReconnectGroup(params: {
  168. selected: RemoteWorkspaceSessionEntry;
  169. sessions: RemoteWorkspaceSessionEntry[];
  170. tabs: WindowTabState[];
  171. }): RemoteWorkspaceSessionEntry[] {
  172. if (params.selected.target.kind !== "ssh") {
  173. return [params.selected];
  174. }
  175. const remoteHostKey = buildSshRemoteHostKey(params.selected.target);
  176. const disconnectedWorkspaceKeys = new Set(
  177. params.tabs.flatMap((tab) => {
  178. if (!isWorkspaceTab(tab) || tab.remoteSessionId) {
  179. return [];
  180. }
  181. return [buildWorkspaceSessionKey(tab)];
  182. }),
  183. );
  184. const reconnectGroup = params.sessions.filter(
  185. (entry) =>
  186. entry.target.kind === "ssh" &&
  187. buildSshRemoteHostKey(entry.target) === remoteHostKey &&
  188. disconnectedWorkspaceKeys.has(buildWorkspaceSessionKey(entry)),
  189. );
  190. const selectedWorkspaceKey = buildWorkspaceSessionKey(params.selected);
  191. if (!reconnectGroup.some((entry) => buildWorkspaceSessionKey(entry) === selectedWorkspaceKey)) {
  192. return [params.selected];
  193. }
  194. // 历史记录顺序不代表本次重连发起者。initiator 必须固定在首位,
  195. // 否则并发加载凭据时 sibling 可能先创建共享 Host,导致整组误用旧凭据。
  196. return [
  197. params.selected,
  198. ...reconnectGroup.filter((entry) => buildWorkspaceSessionKey(entry) !== selectedWorkspaceKey),
  199. ];
  200. }
  201. export async function reconnectRemoteWorkspaceGroup(params: {
  202. selected: RemoteWorkspaceSessionEntry;
  203. reconnectGroup: RemoteWorkspaceSessionEntry[];
  204. reconnectEntry: (
  205. entry: RemoteWorkspaceSessionEntry,
  206. options?: ReconnectRemoteWorkspaceOptions,
  207. ) => Promise<boolean>;
  208. options?: ReconnectRemoteWorkspaceOptions;
  209. }): Promise<void> {
  210. const selectedWorkspaceKey = buildWorkspaceSessionKey(params.selected);
  211. const siblings = params.reconnectGroup.filter(
  212. (entry) => buildWorkspaceSessionKey(entry) !== selectedWorkspaceKey,
  213. );
  214. if (params.selected.target.kind !== "ssh") {
  215. try {
  216. await params.reconnectEntry(params.selected, {
  217. ...params.options,
  218. throwOnFailure: true,
  219. });
  220. } catch (error) {
  221. if (params.options?.throwOnFailure) {
  222. throw error;
  223. }
  224. }
  225. return;
  226. }
  227. type InitiatorHostGate =
  228. | { status: "ready"; credentials: SshReconnectCredentials }
  229. | { status: "skipped" }
  230. | { status: "failed"; error: unknown };
  231. let hostReadyCredentials: SshReconnectCredentials | undefined;
  232. let resolveHostReady!: (result: InitiatorHostGate) => void;
  233. const hostReadyPromise = new Promise<InitiatorHostGate>((resolve) => {
  234. resolveHostReady = resolve;
  235. });
  236. // 组内并发连接会让最先完成 credential load 的 sibling 抢建共享 Host。
  237. // initiator 先负责把 Host 建到 ready;后续 provider/task 初始化不再阻塞 sibling attachment。
  238. const initiatorPromise = params.reconnectEntry(params.selected, {
  239. ...params.options,
  240. throwOnFailure: true,
  241. onSshHostReady: (credentials) => {
  242. if (hostReadyCredentials) {
  243. return;
  244. }
  245. hostReadyCredentials = credentials;
  246. resolveHostReady({ status: "ready", credentials });
  247. },
  248. });
  249. const initiatorFinishedBeforeReady = initiatorPromise.then<InitiatorHostGate, InitiatorHostGate>(
  250. (didReconnect) => {
  251. if (hostReadyCredentials) {
  252. return { status: "ready", credentials: hostReadyCredentials };
  253. }
  254. return didReconnect
  255. ? {
  256. status: "failed",
  257. error: new Error("SSH initiator completed without reporting Host ready"),
  258. }
  259. : { status: "skipped" };
  260. },
  261. (error: unknown) =>
  262. hostReadyCredentials
  263. ? { status: "ready", credentials: hostReadyCredentials }
  264. : { status: "failed", error },
  265. );
  266. const hostGate = await Promise.race([hostReadyPromise, initiatorFinishedBeforeReady]);
  267. if (hostGate.status !== "ready") {
  268. if (hostGate.status === "failed" && params.options?.throwOnFailure) {
  269. throw hostGate.error;
  270. }
  271. return;
  272. }
  273. // sibling 只复用 initiator credential 命中 ready Host,不再读取各自历史 credential;
  274. // path/provider/task 初始化与 initiator 并行并保持独立失败语义。
  275. const siblingPromise = Promise.allSettled(
  276. siblings.map((entry) =>
  277. params.reconnectEntry(entry, {
  278. ...params.options,
  279. activateWorkspaceAfterReconnect: false,
  280. sshCredentialsOverride: hostGate.credentials,
  281. }),
  282. ),
  283. );
  284. const [initiatorResult] = await Promise.all([
  285. initiatorPromise.then(
  286. () => ({ status: "fulfilled" as const }),
  287. (error: unknown) => ({ status: "rejected" as const, error }),
  288. ),
  289. siblingPromise,
  290. ]);
  291. if (initiatorResult.status === "rejected" && params.options?.throwOnFailure) {
  292. throw initiatorResult.error;
  293. }
  294. }
  295. function shouldKeepRemoteWorkspaceInTabs(params: {
  296. tabStoreApi: RemoteWorkspaceTabStoreReader;
  297. workspacePath: string;
  298. workspaceIdentity?: string;
  299. }): boolean {
  300. const reconnectWorkspaceKey = params.workspaceIdentity?.trim() || params.workspacePath;
  301. return params.tabStoreApi
  302. .getState()
  303. .tabs.some(
  304. (tab): tab is import("@/store/tabStore.js").WorkspaceTabState =>
  305. isWorkspaceTab(tab) &&
  306. ((tab.workspaceIdentity?.trim() || tab.workspacePath) === reconnectWorkspaceKey ||
  307. tab.workspacePath === params.workspacePath),
  308. );
  309. }
  310. export async function cancelPendingRemoteReconnectsForWorkspaceKeys(params: {
  311. workspaceKeys: string[];
  312. pendingRequestIds: Map<string, string>;
  313. cancelPendingRemoteConnection?: (requestId?: string) => Promise<void>;
  314. logger: Pick<typeof logger, "warn">;
  315. }): Promise<void> {
  316. const requestIds = params.workspaceKeys.flatMap((workspaceKey) => {
  317. const requestId = params.pendingRequestIds.get(workspaceKey);
  318. if (!requestId) {
  319. return [];
  320. }
  321. params.pendingRequestIds.delete(workspaceKey);
  322. return [requestId];
  323. });
  324. if (!params.cancelPendingRemoteConnection || requestIds.length === 0) {
  325. return;
  326. }
  327. await Promise.all(
  328. requestIds.map(async (requestId) => {
  329. try {
  330. await params.cancelPendingRemoteConnection?.(requestId);
  331. } catch (error) {
  332. params.logger.warn("[Root] 取消远程 workspace 重连失败", {
  333. requestId,
  334. error,
  335. });
  336. }
  337. }),
  338. );
  339. }
  340. export async function openRemoteWorkspaceFromHistoryEntry({
  341. workspaceKey,
  342. tabStoreApi,
  343. getRemoteSessions,
  344. inflightReconnectWorkspaceKeys,
  345. activateTabByPath,
  346. setReconnectingRemoteWorkspaceKeys,
  347. loadCredential,
  348. connectRemoteWorkspaceTarget,
  349. resolveRemoteWorkspaceCanonicalPath,
  350. disposeRemoteWorkspaceSession,
  351. bindRemoteWorkspaceSessionContext,
  352. addTab,
  353. commitRemoteWorkspaceSessionMutation,
  354. resetLogsForWorkspaceKey,
  355. createReconnectRequestId,
  356. pendingReconnectRequestIds,
  357. reconnectImpl = reconnectRemoteWorkspaceHistoryEntry,
  358. onWorkspaceActivated,
  359. }: OpenRemoteWorkspaceFromHistoryParams): Promise<void> {
  360. const sessionEntry = getRemoteSessions().find(
  361. (entry) => buildWorkspaceSessionKey(entry) === workspaceKey,
  362. );
  363. if (!sessionEntry) {
  364. return;
  365. }
  366. if (inflightReconnectWorkspaceKeys.has(workspaceKey)) {
  367. return;
  368. }
  369. const existingWorkspaceTab = tabStoreApi
  370. .getState()
  371. .tabs.find(
  372. (tab): tab is import("@/store/tabStore.js").WorkspaceTabState =>
  373. isWorkspaceTab(tab) && buildWorkspaceSessionKey(tab) === workspaceKey,
  374. );
  375. if (existingWorkspaceTab?.remoteSessionId) {
  376. activateTabByPath(existingWorkspaceTab.workspacePath, {
  377. workspaceIdentity: existingWorkspaceTab.workspaceIdentity,
  378. });
  379. return;
  380. }
  381. // 选择页远程历史与侧栏重连都属于“恢复已有 remote workspace”语义。
  382. // 如果这里缺少“仍需保留该 workspace”的二次校验,用户在重连中移除后仍会被成功回调重新加回 tab。
  383. // 这里复用同一套 shouldKeep 判定,保证两条入口的竞态行为一致。
  384. resetLogsForWorkspaceKey(workspaceKey);
  385. inflightReconnectWorkspaceKeys.add(workspaceKey);
  386. const requestId = createReconnectRequestId?.();
  387. if (requestId) {
  388. pendingReconnectRequestIds?.set(workspaceKey, requestId);
  389. }
  390. try {
  391. await reconnectImpl({
  392. sessionEntry,
  393. activateTabByPath,
  394. setReconnectingRemoteWorkspaceKeys,
  395. loadCredential,
  396. connectRemoteWorkspaceTarget,
  397. resolveRemoteWorkspaceCanonicalPath,
  398. disposeRemoteWorkspaceSession,
  399. bindRemoteWorkspaceSessionContext,
  400. bindRemoteWorkspacePath,
  401. bindRemoteWorkspaceIdentity,
  402. upsertWorkspaceTab: addTab,
  403. commitRemoteWorkspaceSessionMutation,
  404. getRemoteSessions,
  405. logger,
  406. toast,
  407. shouldKeepReconnectedWorkspace: ({ workspacePath, workspaceIdentity }) =>
  408. shouldKeepRemoteWorkspaceInTabs({
  409. tabStoreApi,
  410. workspacePath,
  411. workspaceIdentity,
  412. }),
  413. onWorkspaceActivated: (target) => {
  414. logger.debug("[Root] 远程历史 workspace ready,提交 tab 与 draft 激活", target);
  415. onWorkspaceActivated?.(target);
  416. },
  417. options: {
  418. // 历史入口过去只回填 connected tab,却没有提交 tab activation 和 draft owner,
  419. // 所以连接成功后右侧仍停留在旧 workspace。共享 helper 只会在 services ready 后执行此提交,
  420. // 不会提前暴露缺少 remoteSessionId 的 remote-waiting tab。
  421. activateWorkspaceAfterReconnect: true,
  422. showErrorToast: true,
  423. requestId,
  424. },
  425. });
  426. } finally {
  427. inflightReconnectWorkspaceKeys.delete(workspaceKey);
  428. if (requestId && pendingReconnectRequestIds?.get(workspaceKey) === requestId) {
  429. pendingReconnectRequestIds.delete(workspaceKey);
  430. }
  431. }
  432. }
  433. export async function selectRemoteWorkspaceProjectFromDialog({
  434. canUseRemoteWorkspace,
  435. sessionId,
  436. path,
  437. localWorkspacePath,
  438. loadingMessage,
  439. getRemoteWorkspaceSession,
  440. connectionTarget,
  441. getWorkspaceTabs,
  442. resolveRemoteWorkspaceCanonicalPath,
  443. activateTabByPath,
  444. handleCancelRemoteProject,
  445. bindRemoteWorkspaceSessionContext,
  446. commitRemoteWorkspaceSessionMutation,
  447. getRemoteSessions,
  448. bindRemoteWorkspacePath,
  449. bindRemoteWorkspaceIdentity,
  450. addTab,
  451. onWorkspaceActivated,
  452. refreshPinnedTasks,
  453. refreshTimelineTasks,
  454. }: {
  455. canUseRemoteWorkspace: boolean;
  456. sessionId: string;
  457. path: string;
  458. localWorkspacePath?: string;
  459. loadingMessage: string;
  460. getRemoteWorkspaceSession: (sessionId: string) => RemoteWorkspaceSession | null;
  461. connectionTarget?: Parameters<IPlatformService["connectRemote"]>[0];
  462. getWorkspaceTabs: () => WindowTabState[];
  463. resolveRemoteWorkspaceCanonicalPath: (
  464. sessionId: string,
  465. workspacePath: string,
  466. ) => Promise<string>;
  467. activateTabByPath: (workspacePath: string, options?: { workspaceIdentity?: string }) => boolean;
  468. handleCancelRemoteProject: (sessionId: string) => Promise<void>;
  469. bindRemoteWorkspaceSessionContext: BindRemoteWorkspaceSessionContextFn;
  470. commitRemoteWorkspaceSessionMutation: (
  471. mutation: ReturnType<typeof buildRemoteWorkspaceSessionMutation>,
  472. ) => Promise<RemoteWorkspaceSessionEntry>;
  473. getRemoteSessions: () => RemoteWorkspaceSessionEntry[];
  474. bindRemoteWorkspacePath: (workspacePath: string, sessionId: string) => void;
  475. bindRemoteWorkspaceIdentity: (workspaceIdentity: string, sessionId: string) => void;
  476. addTab: (
  477. workspacePath: string,
  478. options?: {
  479. remoteSessionId?: string;
  480. remoteTarget?: Parameters<IPlatformService["connectRemote"]>[0];
  481. workspaceIdentity?: string;
  482. localWorkspacePath?: string;
  483. },
  484. ) => void;
  485. onWorkspaceActivated?: (target: { workspacePath: string; workspaceIdentity: string }) => void;
  486. refreshPinnedTasks: (params: {
  487. sessionId: string;
  488. workspacePath: string;
  489. workspaceIdentity?: string;
  490. }) => Promise<void>;
  491. refreshTimelineTasks: (params: {
  492. sessionId: string;
  493. workspacePath: string;
  494. workspaceIdentity?: string;
  495. }) => Promise<void>;
  496. }): Promise<void> {
  497. if (!canUseRemoteWorkspace) {
  498. throw new Error("Remote workspace is disabled in this mode");
  499. }
  500. const remoteSession = getRemoteWorkspaceSession(sessionId);
  501. if (!remoteSession) {
  502. throw new Error(loadingMessage);
  503. }
  504. const remoteTarget = connectionTarget ?? remoteSession.target;
  505. if (!remoteTarget) {
  506. // 手机 web relay 复用 remote session store 只做服务路由,没有本地可重连 target。
  507. // 远程历史的选目录/持久化流程必须有 target,缺失时直接阻断,避免把无 target 的桥接 session 写进历史。
  508. throw new Error(`远程 workspace session 缺少连接目标: ${sessionId}`);
  509. }
  510. const canonicalPath = await resolveRemoteWorkspaceCanonicalPath(sessionId, path);
  511. const workspaceIdentity = buildRemoteWorkspaceIdentity(canonicalPath, remoteTarget);
  512. const existingWorkspaceTab = getWorkspaceTabs().find(
  513. (tab): tab is import("@/store/tabStore.js").WorkspaceTabState =>
  514. isWorkspaceTab(tab) &&
  515. tab.workspacePath === canonicalPath &&
  516. (tab.workspaceIdentity?.trim() || tab.workspacePath) === workspaceIdentity,
  517. );
  518. if (
  519. existingWorkspaceTab?.remoteSessionId &&
  520. activateTabByPath(canonicalPath, { workspaceIdentity })
  521. ) {
  522. onWorkspaceActivated?.({ workspacePath: canonicalPath, workspaceIdentity });
  523. await handleCancelRemoteProject(sessionId);
  524. return;
  525. }
  526. // 断连 tab 以前会在 provider/session 绑定完成前先被 activateTabByPath 激活,
  527. // V4PaneConversationProvider 此时只能得到 remote-waiting,因 rpcReady=false 返回 null,
  528. // 右侧便会先空白,等后续 addTab 写回 remoteSessionId 后才出现新建对话。
  529. // 断连 tab 与首次连接统一等到服务绑定完成后再由 addTab 原子激活,避免暴露半连接 workspace。
  530. // 新建连接不带 context,main/host 的 logical session
  531. // descriptor 停留在连接根目录 "/",identity 也是 Host 用解析后 target 自建的;而 tab、远程历史与
  532. // 手机可见 workspace 列表用的都是这里算出的 canonicalPath/workspaceIdentity。
  533. // 手机桥接(attachRemoteWorkspaceSessionHost)要求二者三元全等,所以选目录后必须先把 canonical
  534. // context 绑定回 main,再提交 connected 状态与 tab。df2db1df7a 把 provider 同步移到 main/host 时
  535. // 顺带删掉了这次 bind,导致新建连接后选的目录在手机端必然被 REMOTE_WORKSPACE_IDENTITY_MISMATCH 拒绝。
  536. // bind 失败时 fail-closed:回收 session 并把错误抛回连接弹窗,不留下 descriptor 与 tab 不一致的 session。
  537. try {
  538. await bindRemoteWorkspaceSessionContext({
  539. sessionId,
  540. workspacePath: canonicalPath,
  541. workspaceIdentity,
  542. });
  543. } catch (error) {
  544. await handleCancelRemoteProject(sessionId);
  545. throw error;
  546. }
  547. await commitRemoteWorkspaceSessionMutation(
  548. buildRemoteWorkspaceSessionMutation({
  549. remoteSessions: getRemoteSessions(),
  550. workspacePath: canonicalPath,
  551. localWorkspacePath,
  552. workspaceIdentity,
  553. target: remoteTarget,
  554. lastConnectionStatus: "connected",
  555. touchOpenedAt: true,
  556. }),
  557. );
  558. bindRemoteWorkspacePath(canonicalPath, sessionId);
  559. bindRemoteWorkspaceIdentity(workspaceIdentity, sessionId);
  560. addTab(canonicalPath, {
  561. remoteSessionId: sessionId,
  562. remoteTarget: stripRemoteTargetSecrets(remoteTarget),
  563. workspaceIdentity,
  564. localWorkspacePath,
  565. });
  566. // startDraft 之前在调用方等待 pinned/timeline 刷新结束后才执行,
  567. // tab 已切到远端但草稿 owner 仍是旧状态,形成可见的空白中间帧。
  568. // 激活回调必须紧跟 addTab,在任何列表刷新 await 之前提交同一 workspaceKey 的草稿态。
  569. onWorkspaceActivated?.({ workspacePath: canonicalPath, workspaceIdentity });
  570. await Promise.all([
  571. refreshPinnedTasks({
  572. sessionId,
  573. workspacePath: canonicalPath,
  574. workspaceIdentity,
  575. }),
  576. refreshTimelineTasks({
  577. sessionId,
  578. workspacePath: canonicalPath,
  579. workspaceIdentity,
  580. }),
  581. ]);
  582. }
  583. export function useRemoteWorkspaceHistory({
  584. intl,
  585. services,
  586. platform,
  587. supportsSettings,
  588. allowRemoteWorkspace = true,
  589. ensureConversationWorkspaceOnRestore = false,
  590. deferInactiveWorkspaceRestore = false,
  591. unavailableWorkspacePath,
  592. tabStoreApi,
  593. activateTabByPath,
  594. addTab,
  595. onWorkspaceActivated,
  596. }: {
  597. intl: ReturnType<typeof import("@/i18n/IntlProvider.js").useZCodeIntl>["intl"];
  598. services: IServiceAccessor;
  599. platform: IPlatformService;
  600. supportsSettings: boolean;
  601. allowRemoteWorkspace?: boolean;
  602. ensureConversationWorkspaceOnRestore?: boolean;
  603. /** 仅 Desktop 主窗口:输入可用后再把 inactive workspace 加入 sidebar/task 数据源。 */
  604. deferInactiveWorkspaceRestore?: boolean;
  605. unavailableWorkspacePath?: string;
  606. tabStoreApi: ReturnType<typeof import("@/store/TabStoreProvider.js").useTabStoreApi>;
  607. activateTabByPath: (workspacePath: string, options?: { workspaceIdentity?: string }) => boolean;
  608. addTab: (
  609. workspacePath: string,
  610. options?: {
  611. remoteSessionId?: string;
  612. remoteTarget?: Parameters<IPlatformService["connectRemote"]>[0];
  613. workspaceIdentity?: string;
  614. localWorkspacePath?: string;
  615. },
  616. ) => void;
  617. onWorkspaceActivated?: (target: { workspacePath: string; workspaceIdentity: string }) => void;
  618. }) {
  619. const showRemoteConnectionEntry = useRemoteConnectionEntryVisibility();
  620. const canUseRemoteWorkspace = allowRemoteWorkspace && showRemoteConnectionEntry;
  621. const allowRemoteWorkspaceRestore = canUseRemoteWorkspace;
  622. const [remoteWorkspaceSessions, setRemoteWorkspaceSessions] = useState<
  623. RemoteWorkspaceSessionEntry[]
  624. >([]);
  625. const remoteWorkspaceSessionsRef = useRef<RemoteWorkspaceSessionEntry[]>([]);
  626. const [reconnectingRemoteWorkspaceKeys, setReconnectingRemoteWorkspaceKeys] = useState<string[]>(
  627. [],
  628. );
  629. const inflightReconnectWorkspaceKeysRef = useRef<Set<string>>(new Set());
  630. const pendingReconnectRequestIdsRef = useRef<Map<string, string>>(new Map());
  631. const pendingConnectionTargetsBySessionIdRef = useRef<
  632. Map<string, Parameters<IPlatformService["connectRemote"]>[0]>
  633. >(new Map());
  634. // 上一个版本这里有一个启动重连尝试用的 useRef。
  635. // 移除自动重连逻辑后,Vite Fast Refresh 会复用旧 fiber 的 hook slot,
  636. // 导致下一层 useReconnectingRemoteWorkspaceLogs 里的 useState 落到旧 useRef slot 上并触发 React "Should have a queue"。
  637. // 保留一个空 ref 只用于稳定热更新中的 hook 顺序,不恢复任何启动重连行为。
  638. const remoteStartupReconnectRefreshCompatibilityRef = useRef<null>(null);
  639. void remoteStartupReconnectRefreshCompatibilityRef;
  640. const {
  641. logsByWorkspaceKey: reconnectingRemoteWorkspaceLogsByWorkspaceKey,
  642. resetLogsForWorkspaceKey,
  643. } = useReconnectingRemoteWorkspaceLogs({
  644. platform,
  645. reconnectingWorkspaceKeys: reconnectingRemoteWorkspaceKeys,
  646. resolveWorkspaceTargetByKey: (workspaceKey) =>
  647. remoteWorkspaceSessionsRef.current.find(
  648. (entry) => buildWorkspaceSessionKey(entry) === workspaceKey,
  649. )?.target ?? null,
  650. resolveWorkspaceRequestIdByKey: (workspaceKey) =>
  651. pendingReconnectRequestIdsRef.current.get(workspaceKey) ?? null,
  652. });
  653. const syncPersistedWorkspaceSession = useCallback(
  654. async (nextRemoteSessions: readonly RemoteWorkspaceSessionEntry[]) => {
  655. setRemoteWorkspaceSessions([...nextRemoteSessions]);
  656. remoteWorkspaceSessionsRef.current = [...nextRemoteSessions];
  657. if (!supportsSettings) {
  658. return;
  659. }
  660. await services.settingService.update(
  661. buildRemoteWorkspacePersistPatch(tabStoreApi.getState(), nextRemoteSessions),
  662. );
  663. },
  664. [services.settingService, supportsSettings, tabStoreApi],
  665. );
  666. const commitRemoteWorkspaceSessionMutation = useCallback(
  667. async (mutation: ReturnType<typeof buildRemoteWorkspaceSessionMutation>) => {
  668. for (const credentialKey of mutation.credentialKeysToDelete) {
  669. try {
  670. await services.credentialService.delete(credentialKey);
  671. } catch (error) {
  672. logger.warn("[Root] 删除远程 workspace 凭据失败", {
  673. credentialKey,
  674. error,
  675. });
  676. }
  677. }
  678. for (const credential of mutation.credentialsToSave) {
  679. await services.credentialService.save(credential.key, credential.value);
  680. }
  681. await syncPersistedWorkspaceSession(mutation.nextRemoteSessions);
  682. return mutation.entry;
  683. },
  684. [services.credentialService, syncPersistedWorkspaceSession],
  685. );
  686. const waitForRemoteWorkspaceSessionReady = useCallback(async (sessionId: string) => {
  687. if (getRemoteWorkspaceSession(sessionId)) {
  688. return;
  689. }
  690. await new Promise<void>((resolve, reject) => {
  691. const startedAt = Date.now();
  692. const pollTimer = window.setInterval(() => {
  693. if (getRemoteWorkspaceSession(sessionId)) {
  694. window.clearInterval(pollTimer);
  695. resolve();
  696. return;
  697. }
  698. if (Date.now() - startedAt >= 3000) {
  699. window.clearInterval(pollTimer);
  700. reject(new Error(`等待远程 workspace session 就绪超时: ${sessionId}`));
  701. }
  702. }, 50);
  703. });
  704. }, []);
  705. const connectRemoteWorkspaceTarget = useCallback(
  706. async (
  707. target: Parameters<IPlatformService["connectRemote"]>[0],
  708. requestId?: string,
  709. context?: Parameters<IPlatformService["connectRemote"]>[2],
  710. ) => {
  711. const result = await platform.connectRemote(target, requestId, context);
  712. if (!result.success) {
  713. throw new Error(getErrorMessage(result.error || "Connection failed"));
  714. }
  715. if (!result.sessionId) {
  716. throw new Error("Remote session was not created");
  717. }
  718. // 远程连接成功只代表 main/host 已经建好 session,
  719. // renderer 侧的 MessagePort 仍然可能在下一拍才注册进 zustand store。
  720. // 如果此时立刻 addTab,会短暂走到本地 services,导致首屏读目录/预热 ZCode Agent 命中错误服务。
  721. // 这里等 session 真正挂进 store 再继续。
  722. await waitForRemoteWorkspaceSessionReady(result.sessionId);
  723. if (!context) {
  724. // 共享 Host 只向 renderer store 回传脱敏 target;完整凭据只在选目录流程完成前临时保留。
  725. pendingConnectionTargetsBySessionIdRef.current.set(result.sessionId, target);
  726. }
  727. return result.sessionId;
  728. },
  729. [platform, waitForRemoteWorkspaceSessionReady],
  730. );
  731. const resolveRemoteWorkspaceCanonicalPath = useCallback(
  732. async (sessionId: string, workspacePath: string): Promise<string> => {
  733. const remoteSession = getRemoteWorkspaceSession(sessionId);
  734. if (!remoteSession) {
  735. return workspacePath;
  736. }
  737. try {
  738. // 同一目录可能通过符号链接别名输入(例如 /dev 与 /home/dev),
  739. // 之前直接持久化用户输入会把同一 workspace 识别成两个身份。
  740. // 这里在远端 host 上做一次 realpath 归一化,再参与 identity 计算与持久化。
  741. return await remoteSession.services.fileService.resolvePath({
  742. path: workspacePath,
  743. });
  744. } catch {
  745. return workspacePath;
  746. }
  747. },
  748. [],
  749. );
  750. const buildPersistedTabPatch = useCallback(
  751. (state: TabStoreState) =>
  752. buildRemoteWorkspacePersistPatch(state, remoteWorkspaceSessionsRef.current),
  753. [],
  754. );
  755. const handleCancelRemoteProject = useCallback(
  756. async (sessionId: string) => {
  757. try {
  758. await platform.disposeRemoteSession(sessionId);
  759. } finally {
  760. pendingConnectionTargetsBySessionIdRef.current.delete(sessionId);
  761. // 远程目录选择如果在确认前就取消,session 释放失败也不能把前端状态卡在“仍有一个待选远程 session”。
  762. // 这里始终清掉本地映射,避免下次再次打开弹窗时复用到一条已经失效的 session 记录。
  763. unregisterRemoteWorkspaceSession(sessionId);
  764. }
  765. },
  766. [platform],
  767. );
  768. const bindRemoteWorkspaceSessionContext = useCallback<BindRemoteWorkspaceSessionContextFn>(
  769. async ({ sessionId, workspacePath, workspaceIdentity }) => {
  770. // bind 会换代同一 remoteSessionId 的 renderer attachment;
  771. // 复用 bindRemoteWorkspaceContextAndGetSession 等 ready ACK 后再返回,之后按 sessionId 读取的才是新代 services。
  772. await bindRemoteWorkspaceContextAndGetSession({
  773. platform,
  774. sessionId,
  775. workspacePath,
  776. workspaceIdentity,
  777. });
  778. },
  779. [platform],
  780. );
  781. const runReconnectRemoteWorkspaceEntry = useCallback(
  782. async (
  783. sessionEntry: RemoteWorkspaceSessionEntry,
  784. options?: ReconnectRemoteWorkspaceOptions,
  785. ): Promise<boolean> => {
  786. const workspaceKey = buildWorkspaceSessionKey(sessionEntry);
  787. if (inflightReconnectWorkspaceKeysRef.current.has(workspaceKey)) {
  788. return false;
  789. }
  790. const workspaceTab = tabStoreApi
  791. .getState()
  792. .tabs.find(
  793. (tab): tab is import("@/store/tabStore.js").WorkspaceTabState =>
  794. isWorkspaceTab(tab) && buildWorkspaceSessionKey(tab) === workspaceKey,
  795. );
  796. if (!workspaceTab || workspaceTab.remoteSessionId) {
  797. return false;
  798. }
  799. resetLogsForWorkspaceKey(workspaceKey);
  800. inflightReconnectWorkspaceKeysRef.current.add(workspaceKey);
  801. const requestId = createUuid();
  802. pendingReconnectRequestIdsRef.current.set(workspaceKey, requestId);
  803. try {
  804. // 重连期间只静默回填 ready 的 remoteSessionId;激活统一由 reconnect helper
  805. // 在回填之后执行,避免 active tab 暴露 remote-waiting 中间态。
  806. const upsertWorkspaceTab = tabStoreApi.getState().ensureWorkspaceTab;
  807. logger.debug("[Root] 远程 workspace 重连中,保留当前 conversation", {
  808. workspaceKey,
  809. });
  810. await reconnectRemoteWorkspaceHistoryEntry({
  811. sessionEntry,
  812. activateTabByPath,
  813. setReconnectingRemoteWorkspaceKeys,
  814. loadCredential: services.credentialService.load,
  815. connectRemoteWorkspaceTarget,
  816. resolveRemoteWorkspaceCanonicalPath,
  817. disposeRemoteWorkspaceSession: handleCancelRemoteProject,
  818. bindRemoteWorkspaceSessionContext,
  819. bindRemoteWorkspacePath,
  820. bindRemoteWorkspaceIdentity,
  821. upsertWorkspaceTab,
  822. commitRemoteWorkspaceSessionMutation,
  823. getRemoteSessions: () => remoteWorkspaceSessionsRef.current,
  824. logger,
  825. toast,
  826. shouldKeepReconnectedWorkspace: ({ workspacePath, workspaceIdentity }) =>
  827. shouldKeepRemoteWorkspaceInTabs({
  828. tabStoreApi,
  829. workspacePath,
  830. workspaceIdentity,
  831. }),
  832. onWorkspaceActivated: (target) => {
  833. logger.debug("[Root] 远程 workspace ready,提交 tab 与 draft 激活", target);
  834. onWorkspaceActivated?.(target);
  835. },
  836. options: {
  837. ...options,
  838. requestId,
  839. },
  840. });
  841. return true;
  842. } finally {
  843. inflightReconnectWorkspaceKeysRef.current.delete(workspaceKey);
  844. if (pendingReconnectRequestIdsRef.current.get(workspaceKey) === requestId) {
  845. pendingReconnectRequestIdsRef.current.delete(workspaceKey);
  846. }
  847. }
  848. },
  849. [
  850. activateTabByPath,
  851. bindRemoteWorkspaceSessionContext,
  852. commitRemoteWorkspaceSessionMutation,
  853. connectRemoteWorkspaceTarget,
  854. handleCancelRemoteProject,
  855. onWorkspaceActivated,
  856. resolveRemoteWorkspaceCanonicalPath,
  857. resetLogsForWorkspaceKey,
  858. services.credentialService,
  859. tabStoreApi,
  860. ],
  861. );
  862. const runReconnectRemoteWorkspace = useCallback(
  863. async (
  864. sessionEntry: RemoteWorkspaceSessionEntry,
  865. options?: ReconnectRemoteWorkspaceOptions,
  866. ) => {
  867. const reconnectGroup = collectSshReconnectGroup({
  868. selected: sessionEntry,
  869. sessions: remoteWorkspaceSessionsRef.current,
  870. tabs: tabStoreApi.getState().tabs,
  871. });
  872. await reconnectRemoteWorkspaceGroup({
  873. selected: sessionEntry,
  874. reconnectGroup,
  875. reconnectEntry: runReconnectRemoteWorkspaceEntry,
  876. options,
  877. });
  878. },
  879. [runReconnectRemoteWorkspaceEntry, tabStoreApi],
  880. );
  881. useEffect(() => {
  882. // 这里原来是启动自动重连 effect。
  883. // 删除 effect 本身会让 Fast Refresh 中已挂载的 RootInner 后续 hook 全部前移,
  884. // 旧 effect slot 被 useCallback 复用后容易触发 React hook 队列错位。
  885. // 这个空 effect 只保留 hook slot;启动恢复仍只产生断开态 tab,不会发起远程连接。
  886. const preserveRemoteStartupReconnectEffectSlot = true;
  887. void preserveRemoteStartupReconnectEffectSlot;
  888. }, []);
  889. const restorePersistedSession = useCallback(
  890. async (settings: AppSettings) => {
  891. const persistedRemoteSessions = getRemoteWorkspaceSessionEntries(settings);
  892. setRemoteWorkspaceSessions(persistedRemoteSessions);
  893. remoteWorkspaceSessionsRef.current = persistedRemoteSessions;
  894. let conversationWorkspacePath: string | undefined;
  895. if (ensureConversationWorkspaceOnRestore) {
  896. try {
  897. conversationWorkspacePath = (await services.fileService.ensureConversationWorkspace())
  898. .path;
  899. } catch (error) {
  900. // 路径创建失败不能连带吞掉真实项目恢复;后续显式新建对话仍会走原有可重试错误入口。
  901. logger.warn("[Root] 恢复阶段解析 conversation workspace 失败", { error });
  902. }
  903. }
  904. // 启动恢复远程 workspace 时只还原任务列表里的断开态 tab。
  905. // 之前这里之后还有后台 effect 会自动发起 SSH/WSL/Docker 重连,用户只是打开应用查看任务列表也会触发远端连接和 runtime 上传。
  906. // 现在把重连入口收口到用户点击“重连”或从远程历史主动打开,避免启动阶段产生隐藏副作用。
  907. // Web 普通模式还会把 allowRemoteWorkspaceRestore 置为 false:保留 setting 里的远程快照,但不恢复 tab/不展示入口。
  908. const workspaceRestore = restorePersistedRemoteWorkspaceSessions({
  909. settings,
  910. tabStoreApi,
  911. allowRemoteWorkspaceRestore,
  912. unavailableWorkspacePath,
  913. conversationWorkspacePath,
  914. restoreMode: deferInactiveWorkspaceRestore ? "active-first" : "all",
  915. });
  916. return {
  917. ...(conversationWorkspacePath
  918. ? { excludedRecentProjectPaths: [conversationWorkspacePath] }
  919. : {}),
  920. ...(workspaceRestore?.deferredRestore
  921. ? { deferredRestore: workspaceRestore.deferredRestore }
  922. : {}),
  923. };
  924. },
  925. [
  926. allowRemoteWorkspaceRestore,
  927. deferInactiveWorkspaceRestore,
  928. ensureConversationWorkspaceOnRestore,
  929. services.fileService,
  930. tabStoreApi,
  931. unavailableWorkspacePath,
  932. ],
  933. );
  934. const handleSelectRemoteProject = useCallback(
  935. async (sessionId: string, path: string, localWorkspacePath?: string) => {
  936. try {
  937. await selectRemoteWorkspaceProjectFromDialog({
  938. canUseRemoteWorkspace,
  939. sessionId,
  940. path,
  941. localWorkspacePath,
  942. loadingMessage: intl.formatMessage({ id: "common.loading" }),
  943. getRemoteWorkspaceSession,
  944. connectionTarget: pendingConnectionTargetsBySessionIdRef.current.get(sessionId),
  945. getWorkspaceTabs: () => tabStoreApi.getState().tabs,
  946. resolveRemoteWorkspaceCanonicalPath,
  947. activateTabByPath,
  948. handleCancelRemoteProject,
  949. bindRemoteWorkspaceSessionContext,
  950. commitRemoteWorkspaceSessionMutation,
  951. getRemoteSessions: () => remoteWorkspaceSessionsRef.current,
  952. bindRemoteWorkspacePath,
  953. bindRemoteWorkspaceIdentity,
  954. addTab,
  955. onWorkspaceActivated,
  956. refreshPinnedTasks: refreshRemotePinnedTasksForSession,
  957. refreshTimelineTasks: refreshRemoteTimelineTasksForSession,
  958. });
  959. } finally {
  960. pendingConnectionTargetsBySessionIdRef.current.delete(sessionId);
  961. }
  962. },
  963. [
  964. activateTabByPath,
  965. addTab,
  966. bindRemoteWorkspaceSessionContext,
  967. tabStoreApi,
  968. commitRemoteWorkspaceSessionMutation,
  969. handleCancelRemoteProject,
  970. intl,
  971. onWorkspaceActivated,
  972. resolveRemoteWorkspaceCanonicalPath,
  973. canUseRemoteWorkspace,
  974. ],
  975. );
  976. const handleConnectRemote = useCallback(
  977. async (
  978. options: Parameters<IPlatformService["connectRemote"]>[0],
  979. requestId?: string,
  980. context?: Parameters<IPlatformService["connectRemote"]>[2],
  981. ) => {
  982. if (!canUseRemoteWorkspace) {
  983. throw new Error("Remote workspace is disabled in this mode");
  984. }
  985. return connectRemoteWorkspaceTarget(options, requestId, context);
  986. },
  987. [canUseRemoteWorkspace, connectRemoteWorkspaceTarget],
  988. );
  989. const handleReconnectRemoteWorkspace = useCallback(
  990. async (workspaceKey: string, options?: ReconnectRemoteWorkspaceOptions) => {
  991. await reconnectRemoteWorkspaceByKey({
  992. workspaceKey,
  993. canUseRemoteWorkspace,
  994. getRemoteSessions: () => remoteWorkspaceSessionsRef.current,
  995. runReconnectRemoteWorkspace,
  996. options: {
  997. activateWorkspaceAfterReconnect: true,
  998. showErrorToast: true,
  999. throwOnFailure: false,
  1000. ...options,
  1001. },
  1002. });
  1003. },
  1004. [canUseRemoteWorkspace, runReconnectRemoteWorkspace],
  1005. );
  1006. const handleOpenRemoteWorkspaceFromHistory = useCallback(
  1007. async (workspaceKey: string) => {
  1008. if (!canUseRemoteWorkspace) {
  1009. return;
  1010. }
  1011. // 远程历史入口与侧栏重连都可能命中“重连中被用户移除”的竞态。
  1012. // 这里抽成统一入口,确保两条路径共享相同的并发保护、保留校验与错误处理语义。
  1013. await openRemoteWorkspaceFromHistoryEntry({
  1014. workspaceKey,
  1015. tabStoreApi,
  1016. getRemoteSessions: () => remoteWorkspaceSessionsRef.current,
  1017. inflightReconnectWorkspaceKeys: inflightReconnectWorkspaceKeysRef.current,
  1018. activateTabByPath,
  1019. setReconnectingRemoteWorkspaceKeys,
  1020. loadCredential: services.credentialService.load,
  1021. connectRemoteWorkspaceTarget,
  1022. resolveRemoteWorkspaceCanonicalPath,
  1023. disposeRemoteWorkspaceSession: handleCancelRemoteProject,
  1024. bindRemoteWorkspaceSessionContext,
  1025. addTab,
  1026. commitRemoteWorkspaceSessionMutation,
  1027. createReconnectRequestId: createUuid,
  1028. pendingReconnectRequestIds: pendingReconnectRequestIdsRef.current,
  1029. resetLogsForWorkspaceKey,
  1030. onWorkspaceActivated,
  1031. });
  1032. },
  1033. [
  1034. activateTabByPath,
  1035. addTab,
  1036. bindRemoteWorkspaceSessionContext,
  1037. commitRemoteWorkspaceSessionMutation,
  1038. connectRemoteWorkspaceTarget,
  1039. handleCancelRemoteProject,
  1040. resolveRemoteWorkspaceCanonicalPath,
  1041. resetLogsForWorkspaceKey,
  1042. onWorkspaceActivated,
  1043. services.credentialService,
  1044. tabStoreApi,
  1045. canUseRemoteWorkspace,
  1046. ],
  1047. );
  1048. const handleRemoteWorkspaceSessionClosed = useCallback(
  1049. async (event: RemoteSessionClosedEvent) => {
  1050. const sessionId = event.sessionId.trim();
  1051. if (!sessionId) {
  1052. return;
  1053. }
  1054. const matchedTabs = tabStoreApi
  1055. .getState()
  1056. .tabs.filter(
  1057. (tab): tab is import("@/store/tabStore.js").WorkspaceTabState =>
  1058. isWorkspaceTab(tab) && tab.remoteSessionId === sessionId,
  1059. );
  1060. if (matchedTabs.length === 0) {
  1061. unregisterRemoteWorkspaceSession(sessionId);
  1062. return;
  1063. }
  1064. // 远端 host 退出后,tab 上的 remoteSessionId 之前不会被清空。
  1065. // UI 因此持续显示“已连接”,并继续把请求路由到失效 session。
  1066. // 这里在收到 main 进程的 session-close 事件时立即降级为断连态,后续只走用户手动重连。
  1067. tabStoreApi.setState((state) => ({
  1068. tabs: state.tabs.map((tab) =>
  1069. isWorkspaceTab(tab) && tab.remoteSessionId === sessionId
  1070. ? { ...tab, remoteSessionId: undefined }
  1071. : tab,
  1072. ),
  1073. }));
  1074. unregisterRemoteWorkspaceSession(sessionId);
  1075. const matchedWorkspaceKeys = [
  1076. ...new Set(matchedTabs.map((tab) => buildWorkspaceSessionKey(tab))),
  1077. ];
  1078. const reason = [
  1079. "远程连接已断开",
  1080. event.exitCode != null ? `exitCode=${event.exitCode}` : null,
  1081. event.signal ? `signal=${event.signal}` : null,
  1082. ]
  1083. .filter(Boolean)
  1084. .join(" ");
  1085. const zcodeSessionStore = useZCodeSessionStore.getState();
  1086. const failedTaskCount = markRemoteWorkspaceRunningTasksFailed({
  1087. tabs: matchedTabs,
  1088. getWorkspaceState: zcodeSessionStore.getWorkspaceState,
  1089. setTaskRuntimeState: zcodeSessionStore.setTaskRuntimeState,
  1090. reason,
  1091. });
  1092. logger.warn("[Root] 远程 workspace session 已关闭", {
  1093. sessionId,
  1094. reason: event.reason,
  1095. exitCode: event.exitCode,
  1096. signal: event.signal,
  1097. matchedWorkspaceKeys,
  1098. failedTaskCount,
  1099. });
  1100. for (const workspaceKey of matchedWorkspaceKeys) {
  1101. const sessionEntry = remoteWorkspaceSessionsRef.current.find(
  1102. (entry) => buildWorkspaceSessionKey(entry) === workspaceKey,
  1103. );
  1104. if (!sessionEntry) {
  1105. continue;
  1106. }
  1107. const pendingReconnectRequestId = pendingReconnectRequestIdsRef.current.get(workspaceKey);
  1108. if (
  1109. !shouldPersistRemoteWorkspaceFailure({
  1110. pendingReconnectRequestIds: pendingReconnectRequestIdsRef.current,
  1111. sessionEntry,
  1112. workspaceKey,
  1113. })
  1114. ) {
  1115. logger.info("[Root] WSL workspace session 关闭时跳过失败落盘,等待重连结果", {
  1116. pendingReconnectRequestId,
  1117. sessionId,
  1118. workspaceIdentity: sessionEntry.workspaceIdentity ?? null,
  1119. workspacePath: sessionEntry.workspacePath,
  1120. workspaceKey,
  1121. });
  1122. continue;
  1123. }
  1124. await commitRemoteWorkspaceSessionMutation(
  1125. buildRemoteWorkspaceSessionMutation({
  1126. remoteSessions: remoteWorkspaceSessionsRef.current,
  1127. workspacePath: sessionEntry.workspacePath,
  1128. workspaceIdentity: sessionEntry.workspaceIdentity,
  1129. target: createRemoteTargetFromSnapshot(sessionEntry.target, {
  1130. password: null,
  1131. privateKeyPassphrase: null,
  1132. }),
  1133. lastConnectionStatus: "failed",
  1134. lastConnectionError: reason,
  1135. touchOpenedAt: false,
  1136. }),
  1137. );
  1138. }
  1139. },
  1140. [commitRemoteWorkspaceSessionMutation, tabStoreApi],
  1141. );
  1142. const handleBotRemoteWorkspaceReconnected = useCallback(
  1143. async (event: BotRemoteWorkspaceReconnectedEvent) => {
  1144. if (!canUseRemoteWorkspace) {
  1145. return;
  1146. }
  1147. const sessionId = event.sessionId.trim();
  1148. if (!sessionId) {
  1149. return;
  1150. }
  1151. try {
  1152. await waitForRemoteWorkspaceSessionReady(sessionId);
  1153. const remoteSession = getRemoteWorkspaceSession(sessionId);
  1154. if (!remoteSession) {
  1155. throw new Error(`远程 workspace session 不存在: ${sessionId}`);
  1156. }
  1157. if (!remoteSession.target) {
  1158. // Bugfix: Bot 重连事件来自 main/host,必须带可持久化的 target。
  1159. // Web relay 的桥接 session 没有 target,不能进入远程历史重连分支。
  1160. throw new Error(`远程 workspace session 缺少连接目标: ${sessionId}`);
  1161. }
  1162. const resolvedWorkspacePath = await resolveRemoteWorkspaceCanonicalPath(
  1163. sessionId,
  1164. event.workspacePath,
  1165. );
  1166. const resolvedWorkspaceIdentity = resolveBotRemoteWorkspaceReconnectedIdentity({
  1167. event,
  1168. resolvedWorkspacePath,
  1169. target: remoteSession.target,
  1170. });
  1171. bindRemoteWorkspacePath(resolvedWorkspacePath, sessionId);
  1172. bindRemoteWorkspaceIdentity(resolvedWorkspaceIdentity, sessionId);
  1173. // Bugfix: Bot 触发的远端重连发生在 main/host,不会经过侧栏手动重连的 React 流程。
  1174. // 这里收到 main 的成功事件后,把已创建的 session 绑定回 tab 和远端历史,UI 才会从“未连接”变为“已连接”。
  1175. tabStoreApi.getState().ensureWorkspaceTab(resolvedWorkspacePath, {
  1176. remoteSessionId: sessionId,
  1177. remoteTarget: remoteSession.target,
  1178. workspaceIdentity: resolvedWorkspaceIdentity,
  1179. });
  1180. await commitRemoteWorkspaceSessionMutation(
  1181. buildRemoteWorkspaceSessionMutation({
  1182. remoteSessions: remoteWorkspaceSessionsRef.current,
  1183. workspacePath: resolvedWorkspacePath,
  1184. workspaceIdentity: resolvedWorkspaceIdentity,
  1185. target: remoteSession.target,
  1186. lastConnectionStatus: "connected",
  1187. touchOpenedAt: true,
  1188. }),
  1189. );
  1190. await Promise.all([
  1191. refreshRemotePinnedTasksForSession({
  1192. sessionId,
  1193. workspacePath: resolvedWorkspacePath,
  1194. workspaceIdentity: resolvedWorkspaceIdentity,
  1195. }),
  1196. refreshRemoteTimelineTasksForSession({
  1197. sessionId,
  1198. workspacePath: resolvedWorkspacePath,
  1199. workspaceIdentity: resolvedWorkspaceIdentity,
  1200. }),
  1201. ]);
  1202. } catch (error) {
  1203. logger.warn("[Root] Bot 远端 workspace 重连成功后同步 UI 状态失败", {
  1204. sessionId,
  1205. workspacePath: event.workspacePath,
  1206. workspaceIdentity: event.workspaceIdentity,
  1207. error: error instanceof Error ? error.message : String(error),
  1208. });
  1209. }
  1210. },
  1211. [
  1212. canUseRemoteWorkspace,
  1213. commitRemoteWorkspaceSessionMutation,
  1214. resolveRemoteWorkspaceCanonicalPath,
  1215. tabStoreApi,
  1216. waitForRemoteWorkspaceSessionReady,
  1217. ],
  1218. );
  1219. useEffect(() => {
  1220. return platform.onRemoteSessionClosed((event) => {
  1221. void handleRemoteWorkspaceSessionClosed(event);
  1222. });
  1223. }, [handleRemoteWorkspaceSessionClosed, platform]);
  1224. useEffect(() => {
  1225. return platform.onBotRemoteWorkspaceReconnected((event) => {
  1226. void handleBotRemoteWorkspaceReconnected(event);
  1227. });
  1228. }, [handleBotRemoteWorkspaceReconnected, platform]);
  1229. const handleRemoteWorkspaceTabsClosed = useCallback(
  1230. (workspaceKeys: string[]) => {
  1231. if (workspaceKeys.length === 0) {
  1232. return;
  1233. }
  1234. const workspaceKeySet = new Set(workspaceKeys);
  1235. void (async () => {
  1236. // 关闭断连态 remote tab 时,tab 上还没有 remoteSessionId,但 main 进程可能已经在上传 remote runtime。
  1237. // 这里用重连 requestId 精准取消 pending host,避免 UI 已移除而后台 upload 继续跑。
  1238. await cancelPendingRemoteReconnectsForWorkspaceKeys({
  1239. workspaceKeys,
  1240. pendingRequestIds: pendingReconnectRequestIdsRef.current,
  1241. cancelPendingRemoteConnection: platform.cancelPendingRemoteConnection
  1242. ? (requestId) =>
  1243. platform.cancelPendingRemoteConnection?.(requestId) ?? Promise.resolve()
  1244. : undefined,
  1245. logger,
  1246. });
  1247. setReconnectingRemoteWorkspaceKeys((currentKeys) =>
  1248. currentKeys.filter((key) => !workspaceKeySet.has(key)),
  1249. );
  1250. const removal = removeRemoteWorkspaceSessionEntries(
  1251. remoteWorkspaceSessionsRef.current,
  1252. workspaceKeys,
  1253. );
  1254. if (
  1255. removal.nextRemoteSessions.length === remoteWorkspaceSessionsRef.current.length &&
  1256. removal.credentialKeysToDelete.length === 0
  1257. ) {
  1258. return;
  1259. }
  1260. // 用户在侧栏“移除”远程 workspace 后,只删 tab 不够:
  1261. // remoteWorkspaceSessionsRef 仍被持久化补丁合并回 setting.json,
  1262. // 所以下次启动又会恢复同一个断连项。这里把显式移除视为删除远程历史,
  1263. // 同时清理该历史独占的 SSH 凭据,避免留下不可达的 credential key。
  1264. await syncPersistedWorkspaceSession(removal.nextRemoteSessions);
  1265. for (const credentialKey of removal.credentialKeysToDelete) {
  1266. try {
  1267. await services.credentialService.delete(credentialKey);
  1268. } catch (error) {
  1269. logger.warn("[Root] 删除已移除远程 workspace 凭据失败", {
  1270. credentialKey,
  1271. error,
  1272. });
  1273. }
  1274. }
  1275. })();
  1276. },
  1277. [platform, services.credentialService, syncPersistedWorkspaceSession],
  1278. );
  1279. const remoteWorkspaceErrorByWorkspaceKey = useMemo(
  1280. () =>
  1281. Object.fromEntries(
  1282. remoteWorkspaceSessions.flatMap((entry) =>
  1283. entry.lastConnectionError?.trim()
  1284. ? [[buildWorkspaceSessionKey(entry), entry.lastConnectionError] as const]
  1285. : [],
  1286. ),
  1287. ),
  1288. [remoteWorkspaceSessions],
  1289. );
  1290. return {
  1291. remoteWorkspaceSessions,
  1292. reconnectingRemoteWorkspaceKeys,
  1293. remoteWorkspaceErrorByWorkspaceKey,
  1294. reconnectingRemoteWorkspaceLogsByWorkspaceKey,
  1295. buildPersistedTabPatch,
  1296. restorePersistedSession,
  1297. handleCancelRemoteProject,
  1298. handleSelectRemoteProject,
  1299. handleConnectRemote,
  1300. handleReconnectRemoteWorkspace,
  1301. handleOpenRemoteWorkspaceFromHistory,
  1302. handleRemoteWorkspaceTabsClosed,
  1303. };
  1304. }