reconnectRemoteWorkspaceHistoryEntry.ts 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271
  1. import type { Dispatch, SetStateAction } from "react";
  2. import type { IPlatformService, RemoteWorkspaceSessionEntry } from "@zcode/shared";
  3. import { stripRemoteTargetSecrets } from "@zcode/shared";
  4. import type { IServiceAccessor } from "@zcode/services";
  5. import { toast } from "@/components/ui/toast.js";
  6. import {
  7. buildRemoteWorkspaceSessionMutation,
  8. buildRemoteWorkspaceIdentity,
  9. createRemoteTargetFromSnapshot,
  10. resolveRemoteWorkspaceSessionIdentity,
  11. } from "@/lib/remoteWorkspaceHistory.js";
  12. import { logger } from "@/logger.js";
  13. import {
  14. bindRemoteWorkspaceIdentity,
  15. bindRemoteWorkspacePath,
  16. } from "@/store/remoteWorkspaceSessionStore.js";
  17. import { refreshRemotePinnedTasksForSession } from "@/store/remotePinnedTaskStore.js";
  18. import { refreshRemoteTimelineTasksForSession } from "@/store/remoteTimelineTaskStore.js";
  19. /** 把 UI 最终确定的 canonical workspacePath/workspaceIdentity 绑定回 main/host 的 logical session。 */
  20. export type BindRemoteWorkspaceSessionContextFn = (params: {
  21. sessionId: string;
  22. workspacePath: string;
  23. workspaceIdentity: string;
  24. }) => Promise<void>;
  25. type ManualReconnectRemoteWorkspaceParams = {
  26. sessionEntry: RemoteWorkspaceSessionEntry;
  27. activateTabByPath: (workspacePath: string, options?: { workspaceIdentity?: string }) => boolean;
  28. setReconnectingRemoteWorkspaceKeys: Dispatch<SetStateAction<string[]>>;
  29. loadCredential: IServiceAccessor["credentialService"]["load"];
  30. connectRemoteWorkspaceTarget: (
  31. target: Parameters<IPlatformService["connectRemote"]>[0],
  32. requestId?: string,
  33. context?: Parameters<IPlatformService["connectRemote"]>[2],
  34. ) => Promise<string>;
  35. resolveRemoteWorkspaceCanonicalPath: (
  36. sessionId: string,
  37. workspacePath: string,
  38. ) => Promise<string>;
  39. disposeRemoteWorkspaceSession: (sessionId: string) => Promise<void>;
  40. bindRemoteWorkspaceSessionContext: BindRemoteWorkspaceSessionContextFn;
  41. bindRemoteWorkspacePath: typeof bindRemoteWorkspacePath;
  42. bindRemoteWorkspaceIdentity: typeof bindRemoteWorkspaceIdentity;
  43. upsertWorkspaceTab: (
  44. workspacePath: string,
  45. options?: {
  46. remoteSessionId?: string;
  47. remoteTarget?: Parameters<IPlatformService["connectRemote"]>[0];
  48. workspaceIdentity?: string;
  49. localWorkspacePath?: string;
  50. },
  51. ) => void;
  52. commitRemoteWorkspaceSessionMutation: (
  53. mutation: ReturnType<typeof buildRemoteWorkspaceSessionMutation>,
  54. ) => Promise<RemoteWorkspaceSessionEntry>;
  55. getRemoteSessions: () => RemoteWorkspaceSessionEntry[];
  56. logger: Pick<typeof logger, "warn">;
  57. toast: typeof toast;
  58. shouldKeepReconnectedWorkspace?: (
  59. context: Pick<RemoteWorkspaceSessionEntry, "workspacePath" | "workspaceIdentity">,
  60. ) => boolean;
  61. onWorkspaceActivated?: (target: { workspacePath: string; workspaceIdentity: string }) => void;
  62. options?: ReconnectRemoteWorkspaceOptions;
  63. };
  64. export interface SshReconnectCredentials {
  65. password: string | null;
  66. privateKeyPassphrase: string | null;
  67. }
  68. export interface ReconnectRemoteWorkspaceOptions {
  69. activateWorkspaceAfterReconnect?: boolean;
  70. showErrorToast?: boolean;
  71. requestId?: string;
  72. throwOnFailure?: boolean;
  73. /** 共享 Host ready 后,sibling 复用 initiator 凭据附着,禁止再次读取各自历史凭据。 */
  74. sshCredentialsOverride?: SshReconnectCredentials;
  75. /** logical connect 已返回,表示共享 SSH Host ready;workspace 初始化仍可能继续或失败。 */
  76. onSshHostReady?: (credentials: SshReconnectCredentials) => void;
  77. }
  78. export async function reconnectRemoteWorkspaceHistoryEntry({
  79. sessionEntry,
  80. activateTabByPath,
  81. setReconnectingRemoteWorkspaceKeys,
  82. loadCredential,
  83. connectRemoteWorkspaceTarget,
  84. resolveRemoteWorkspaceCanonicalPath,
  85. disposeRemoteWorkspaceSession,
  86. bindRemoteWorkspaceSessionContext,
  87. bindRemoteWorkspacePath,
  88. bindRemoteWorkspaceIdentity,
  89. upsertWorkspaceTab,
  90. commitRemoteWorkspaceSessionMutation,
  91. getRemoteSessions,
  92. logger,
  93. toast,
  94. shouldKeepReconnectedWorkspace,
  95. onWorkspaceActivated,
  96. options,
  97. }: ManualReconnectRemoteWorkspaceParams): Promise<void> {
  98. const activateWorkspaceAfterReconnect = options?.activateWorkspaceAfterReconnect ?? true;
  99. const showErrorToast = options?.showErrorToast ?? true;
  100. const fallbackWorkspaceIdentity = resolveRemoteWorkspaceSessionIdentity(sessionEntry);
  101. const reconnectWorkspaceKey = fallbackWorkspaceIdentity?.trim() || sessionEntry.workspacePath;
  102. setReconnectingRemoteWorkspaceKeys((currentKeys) =>
  103. currentKeys.includes(reconnectWorkspaceKey)
  104. ? currentKeys
  105. : [...currentKeys, reconnectWorkspaceKey],
  106. );
  107. let reconnectTarget = createRemoteTargetFromSnapshot(sessionEntry.target, {
  108. password: null,
  109. privateKeyPassphrase: null,
  110. token: null,
  111. });
  112. let resolvedWorkspacePath = sessionEntry.workspacePath;
  113. let resolvedWorkspaceIdentity = fallbackWorkspaceIdentity;
  114. try {
  115. const sshCredentials = options?.sshCredentialsOverride ?? {
  116. password:
  117. sessionEntry.target.kind === "ssh" && sessionEntry.target.passwordCredentialKey
  118. ? await loadCredential(sessionEntry.target.passwordCredentialKey)
  119. : null,
  120. privateKeyPassphrase:
  121. sessionEntry.target.kind === "ssh" && sessionEntry.target.privateKeyPassphraseCredentialKey
  122. ? await loadCredential(sessionEntry.target.privateKeyPassphraseCredentialKey)
  123. : null,
  124. };
  125. const token =
  126. sessionEntry.target.kind === "server" && sessionEntry.target.tokenCredentialKey
  127. ? await loadCredential(sessionEntry.target.tokenCredentialKey)
  128. : null;
  129. reconnectTarget = createRemoteTargetFromSnapshot(sessionEntry.target, {
  130. ...sshCredentials,
  131. token,
  132. });
  133. const sessionId = await connectRemoteWorkspaceTarget(reconnectTarget, options?.requestId, {
  134. workspacePath: sessionEntry.workspacePath,
  135. workspaceIdentity: fallbackWorkspaceIdentity,
  136. connectTrigger: "reconnect",
  137. });
  138. if (reconnectTarget.kind === "ssh") {
  139. // Host ready 与 provider/task 等 workspace 初始化必须分阶段通知。
  140. // sibling 从此刻即可复用 initiator credential 创建 attachment,无需等待或重复读取凭据。
  141. options?.onSshHostReady?.(sshCredentials);
  142. }
  143. resolvedWorkspacePath = await resolveRemoteWorkspaceCanonicalPath(
  144. sessionId,
  145. sessionEntry.workspacePath,
  146. );
  147. resolvedWorkspaceIdentity = buildRemoteWorkspaceIdentity(
  148. resolvedWorkspacePath,
  149. reconnectTarget,
  150. );
  151. if (
  152. resolvedWorkspacePath !== sessionEntry.workspacePath ||
  153. resolvedWorkspaceIdentity !== fallbackWorkspaceIdentity
  154. ) {
  155. // connect 只携带历史记录里的 path/identity,main 的 logical session descriptor 也停在这组值上;
  156. // realpath 归一化后若结果不同,tab 会用新值而 descriptor 仍是旧值,
  157. // 手机远控桥接按 tab 的 path/identity 比对 descriptor 时就会被 REMOTE_WORKSPACE_IDENTITY_MISMATCH 拒绝。
  158. // 绑定失败说明 session 与 tab 无法对齐:回收 session 并走失败落库,不留下半连接 workspace。
  159. // 这次 await 必须放在下方保留校验之前:校验与 upsertWorkspaceTab 之间不能再有异步间隙,
  160. // 否则用户在 bind 等待 ready ACK 期间移除 tab,校验结果已过期,workspace 会被重新加回来。
  161. try {
  162. await bindRemoteWorkspaceSessionContext({
  163. sessionId,
  164. workspacePath: resolvedWorkspacePath,
  165. workspaceIdentity: resolvedWorkspaceIdentity,
  166. });
  167. } catch (error) {
  168. await disposeRemoteWorkspaceSession(sessionId);
  169. throw error;
  170. }
  171. }
  172. // 手动重连过程中,用户可能先点重连再立即把该远端 tab 移除。
  173. // 如果这里不在成功落库前再做一次保留校验,会把用户刚移除的 workspace 又重新加回来。
  174. if (
  175. shouldKeepReconnectedWorkspace &&
  176. !shouldKeepReconnectedWorkspace({
  177. workspacePath: resolvedWorkspacePath,
  178. workspaceIdentity: resolvedWorkspaceIdentity,
  179. })
  180. ) {
  181. logger.warn("[Root] 远程 workspace 在重连过程中已被移除,跳过恢复并回收 session", {
  182. workspacePath: resolvedWorkspacePath,
  183. });
  184. await disposeRemoteWorkspaceSession(sessionId);
  185. return;
  186. }
  187. bindRemoteWorkspacePath(resolvedWorkspacePath, sessionId);
  188. bindRemoteWorkspaceIdentity(resolvedWorkspaceIdentity, sessionId);
  189. upsertWorkspaceTab(resolvedWorkspacePath, {
  190. remoteSessionId: sessionId,
  191. remoteTarget: stripRemoteTargetSecrets(reconnectTarget),
  192. workspaceIdentity: resolvedWorkspaceIdentity,
  193. localWorkspacePath: sessionEntry.localWorkspacePath,
  194. });
  195. if (activateWorkspaceAfterReconnect) {
  196. // 侧栏重连过去会先激活只有 identity、尚无 remoteSessionId 的断连 tab,
  197. // conversation provider 因 remote-waiting 返回 null,导致连接期间右侧整块黑屏。
  198. // 必须先绑定 services 并静默回填 tab 的 session 元数据,再一次性激活 tab 与草稿。
  199. const activated = activateTabByPath(resolvedWorkspacePath, {
  200. workspaceIdentity: resolvedWorkspaceIdentity,
  201. });
  202. if (activated) {
  203. onWorkspaceActivated?.({
  204. workspacePath: resolvedWorkspacePath,
  205. workspaceIdentity: resolvedWorkspaceIdentity,
  206. });
  207. }
  208. }
  209. await commitRemoteWorkspaceSessionMutation(
  210. buildRemoteWorkspaceSessionMutation({
  211. remoteSessions: getRemoteSessions(),
  212. workspacePath: resolvedWorkspacePath,
  213. localWorkspacePath: sessionEntry.localWorkspacePath,
  214. workspaceIdentity: resolvedWorkspaceIdentity,
  215. target: reconnectTarget,
  216. lastConnectionStatus: "connected",
  217. touchOpenedAt: true,
  218. }),
  219. );
  220. await Promise.all([
  221. refreshRemotePinnedTasksForSession({
  222. sessionId,
  223. workspacePath: resolvedWorkspacePath,
  224. workspaceIdentity: resolvedWorkspaceIdentity,
  225. }),
  226. refreshRemoteTimelineTasksForSession({
  227. sessionId,
  228. workspacePath: resolvedWorkspacePath,
  229. workspaceIdentity: resolvedWorkspaceIdentity,
  230. }),
  231. ]);
  232. } catch (error) {
  233. const message = error instanceof Error ? error.message : String(error);
  234. logger.warn("[Root] 手动重连远程 workspace 失败", {
  235. workspacePath: resolvedWorkspacePath,
  236. error: message,
  237. });
  238. await commitRemoteWorkspaceSessionMutation(
  239. buildRemoteWorkspaceSessionMutation({
  240. remoteSessions: getRemoteSessions(),
  241. workspacePath: resolvedWorkspacePath,
  242. workspaceIdentity: resolvedWorkspaceIdentity,
  243. target: reconnectTarget,
  244. lastConnectionStatus: "failed",
  245. lastConnectionError: message,
  246. touchOpenedAt: false,
  247. }),
  248. );
  249. if (showErrorToast) {
  250. toast(message);
  251. }
  252. if (options?.throwOnFailure) {
  253. // 桌面端重连按钮需要吞掉异常并通过 toast/状态落库反馈,
  254. // 但手机端 Web 远控是 RPC 语义,必须把失败明确回传给手机端。
  255. throw error;
  256. }
  257. } finally {
  258. setReconnectingRemoteWorkspaceKeys((currentKeys) =>
  259. currentKeys.filter((key) => key !== reconnectWorkspaceKey),
  260. );
  261. }
  262. }