remoteWorkspaceHistory.ts 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550
  1. /* eslint-disable max-lines -- 远端 workspace 历史集中维护持久化、凭据和 MCP 路径映射元数据,拆分会扩大恢复链路回归面。 */
  2. import type {
  3. AppSettings,
  4. PersistedWorkspaceSessionEntry,
  5. RemoteTarget,
  6. RemoteTargetSnapshot,
  7. RemoteWorkspaceSessionEntry,
  8. } from "@zcode/shared";
  9. import { buildServerRemoteWorkspaceIdentity } from "@zcode/shared";
  10. import type { WindowTabState } from "@/store/tabStore.js";
  11. import { isWorkspaceTab } from "@/store/tabStore.js";
  12. const REMOTE_WORKSPACE_SESSION_LIMIT = 20;
  13. interface RemoteWorkspaceSessionMutation {
  14. entry: RemoteWorkspaceSessionEntry;
  15. nextRemoteSessions: RemoteWorkspaceSessionEntry[];
  16. credentialsToSave: {
  17. key: string;
  18. value: string;
  19. }[];
  20. credentialKeysToDelete: string[];
  21. }
  22. interface RemoveRemoteWorkspaceSessionEntriesResult {
  23. nextRemoteSessions: RemoteWorkspaceSessionEntry[];
  24. credentialKeysToDelete: string[];
  25. }
  26. function buildRemoteWorkspacePasswordCredentialKey(workspaceKey: string): string {
  27. return `remote-workspace:${workspaceKey}:password`;
  28. }
  29. function buildRemoteWorkspacePrivateKeyPassphraseCredentialKey(workspaceKey: string): string {
  30. return `remote-workspace:${workspaceKey}:private-key-passphrase`;
  31. }
  32. function buildRemoteWorkspaceServerTokenCredentialKey(workspaceKey: string): string {
  33. return `remote-workspace:${workspaceKey}:server-token`;
  34. }
  35. function collectRemoteWorkspaceCredentialKeys(snapshot: RemoteTargetSnapshot): string[] {
  36. if (snapshot.kind === "ssh") {
  37. return [snapshot.passwordCredentialKey, snapshot.privateKeyPassphraseCredentialKey].filter(
  38. (key): key is string => typeof key === "string" && key.length > 0,
  39. );
  40. }
  41. if (snapshot.kind === "server") {
  42. return [snapshot.tokenCredentialKey].filter(
  43. (key): key is string => typeof key === "string" && key.length > 0,
  44. );
  45. }
  46. return [];
  47. }
  48. export function getWorkspaceDisplayLabel(workspacePath: string): string {
  49. const normalized = workspacePath.replace(/\\/g, "/");
  50. const segments = normalized.split("/").filter(Boolean);
  51. return segments[segments.length - 1] ?? workspacePath;
  52. }
  53. export function hasRemoteWorkspaceIdentity(entry: {
  54. remoteSessionId?: string;
  55. remoteTarget?: RemoteTarget;
  56. workspaceIdentity?: string;
  57. }): boolean {
  58. return Boolean(entry.remoteSessionId || entry.remoteTarget || entry.workspaceIdentity);
  59. }
  60. export function isSshRemoteWorkspaceIdentity(workspaceIdentity?: string | null): boolean {
  61. return workspaceIdentity?.trim().startsWith("remote:ssh:") === true;
  62. }
  63. type WslRemoteTargetLike = Extract<RemoteTarget | RemoteTargetSnapshot, { kind: "wsl" }>;
  64. function getWslRemoteTargetUser(target: WslRemoteTargetLike): string | undefined {
  65. return target.user?.trim() || undefined;
  66. }
  67. function formatWslRemoteTargetAuthority(target: WslRemoteTargetLike): string {
  68. const user = getWslRemoteTargetUser(target);
  69. if (target.distro) {
  70. return user ? `wsl:${target.distro}:${user}` : `wsl:${target.distro}`;
  71. }
  72. return user ? `wsl:default:${user}` : "wsl";
  73. }
  74. function getServerRemoteTargetDisplayName(
  75. target: Extract<RemoteTarget | RemoteTargetSnapshot, { kind: "server" }>,
  76. ): string {
  77. return target.name?.trim() || target.serverId?.trim() || formatServerRemoteTargetHost(target);
  78. }
  79. function formatServerRemoteTargetHost(
  80. target: Extract<RemoteTarget | RemoteTargetSnapshot, { kind: "server" }>,
  81. ): string {
  82. try {
  83. return new URL(target.url.trim()).host;
  84. } catch {
  85. return target.url.trim();
  86. }
  87. }
  88. export function formatRemoteWorkspaceTargetSubtitle(
  89. target: RemoteTarget | RemoteTargetSnapshot,
  90. ): string {
  91. switch (target.kind) {
  92. case "ssh":
  93. return `SSH · ${target.username}@${target.host}${target.port ? `:${target.port}` : ""}`;
  94. case "wsl": {
  95. const user = getWslRemoteTargetUser(target);
  96. return ["WSL", target.distro, user].filter(Boolean).join(" · ");
  97. }
  98. case "docker":
  99. return `Docker · ${target.container}`;
  100. case "server":
  101. return `Server · ${getServerRemoteTargetDisplayName(target)}`;
  102. }
  103. }
  104. export function formatRemoteWorkspaceHeaderHostLabel(
  105. target: RemoteTarget | RemoteTargetSnapshot,
  106. ): string {
  107. switch (target.kind) {
  108. case "ssh":
  109. return target.port && target.port !== 22 ? `${target.host}:${target.port}` : target.host;
  110. case "wsl":
  111. return formatWslRemoteTargetAuthority(target);
  112. case "docker":
  113. return `docker:${target.container}`;
  114. case "server":
  115. return formatServerRemoteTargetHost(target);
  116. }
  117. }
  118. export function formatRemoteWorkspaceDisplayLabel(
  119. label: string,
  120. target?: RemoteTarget | RemoteTargetSnapshot,
  121. ): string {
  122. if (target?.kind !== "ssh") {
  123. return label;
  124. }
  125. const sshConfigAlias = target.sshConfigAlias?.trim();
  126. return sshConfigAlias ? `${label} [SSH: ${sshConfigAlias}]` : label;
  127. }
  128. function normalizeWorkspacePathForIdentity(path: string): string {
  129. // 远程目录可能出现符号链接别名(例如 /dev 与 /home/dev)。
  130. // 身份计算前统一做分隔符归一化与收尾斜杠清理,避免同一路径文本噪声导致身份漂移。
  131. const normalized = path.replace(/\\/g, "/").replace(/\/+$/, "");
  132. return normalized.length > 0 ? normalized : "/";
  133. }
  134. function getRemoteWorkspaceAuthorityKey(target: RemoteTarget | RemoteTargetSnapshot): string {
  135. switch (target.kind) {
  136. case "ssh": {
  137. const normalizedHost = target.host.trim().toLowerCase();
  138. const normalizedUsername = target.username.trim();
  139. const normalizedPort = target.port ?? 22;
  140. return ["ssh", normalizedHost, normalizedPort, normalizedUsername].join(":");
  141. }
  142. case "wsl": {
  143. // WSL 默认用户与 root/其他显式用户的文件权限边界不同,
  144. // workspace identity 必须区分显式 user,避免 session、缓存和队列串用。
  145. const user = getWslRemoteTargetUser(target);
  146. const base = ["wsl", target.distro ?? "default"];
  147. return user ? [...base, user].join(":") : base.join(":");
  148. }
  149. case "docker":
  150. return ["docker", target.container].join(":");
  151. case "server": {
  152. const identity = buildServerRemoteWorkspaceIdentity({
  153. serverId: getServerRemoteTargetIdentityId(target),
  154. workspacePath: "/",
  155. });
  156. return identity.slice("remote:".length, -":/".length);
  157. }
  158. }
  159. }
  160. export function buildRemoteWorkspaceIdentity(
  161. workspacePath: string,
  162. target: RemoteTarget | RemoteTargetSnapshot,
  163. ): string {
  164. if (target.kind === "server") {
  165. return buildServerRemoteWorkspaceIdentity({
  166. serverId: getServerRemoteTargetIdentityId(target),
  167. workspacePath,
  168. });
  169. }
  170. const authority = getRemoteWorkspaceAuthorityKey(target);
  171. const normalizedPath = normalizeWorkspacePathForIdentity(workspacePath);
  172. return `remote:${authority}:${normalizedPath}`;
  173. }
  174. function getServerRemoteTargetIdentityId(
  175. target: Extract<RemoteTarget | RemoteTargetSnapshot, { kind: "server" }>,
  176. ): string {
  177. return target.serverId?.trim() || target.name?.trim() || formatServerRemoteTargetHost(target);
  178. }
  179. export function resolveRemoteWorkspaceSessionIdentity(
  180. entry: Pick<RemoteWorkspaceSessionEntry, "workspacePath" | "target" | "workspaceIdentity">,
  181. ): string {
  182. return entry.workspaceIdentity || buildRemoteWorkspaceIdentity(entry.workspacePath, entry.target);
  183. }
  184. export function buildWorkspaceSessionKey(entry: {
  185. workspacePath: string;
  186. workspaceIdentity?: string;
  187. }): string {
  188. return entry.workspaceIdentity?.trim() || entry.workspacePath;
  189. }
  190. function normalizeOptionalPath(path: string | undefined): string | undefined {
  191. const trimmed = path?.trim();
  192. return trimmed ? trimmed : undefined;
  193. }
  194. export function findMatchingRemoteWorkspaceSessionEntry(
  195. sessions: RemoteWorkspaceSessionEntry[],
  196. workspacePath: string,
  197. target: RemoteTarget | RemoteTargetSnapshot,
  198. ): RemoteWorkspaceSessionEntry | null {
  199. const workspaceIdentity = buildRemoteWorkspaceIdentity(workspacePath, target);
  200. return (
  201. sessions.find((entry) => resolveRemoteWorkspaceSessionIdentity(entry) === workspaceIdentity) ??
  202. null
  203. );
  204. }
  205. export function createRemoteTargetSnapshot(
  206. workspaceKey: string,
  207. target: RemoteTarget,
  208. previousSnapshot?: RemoteTargetSnapshot,
  209. ): RemoteTargetSnapshot {
  210. switch (target.kind) {
  211. case "ssh":
  212. return {
  213. kind: "ssh",
  214. host: target.host,
  215. port: target.port,
  216. username: target.username,
  217. ...(target.sshConfigAlias?.trim() ? { sshConfigAlias: target.sshConfigAlias.trim() } : {}),
  218. assetInstallMode: target.assetInstallMode,
  219. privateKeyPath: target.privateKeyPath,
  220. passwordCredentialKey:
  221. target.password && target.password.length > 0
  222. ? previousSnapshot?.kind === "ssh" && previousSnapshot.passwordCredentialKey
  223. ? previousSnapshot.passwordCredentialKey
  224. : buildRemoteWorkspacePasswordCredentialKey(workspaceKey)
  225. : undefined,
  226. privateKeyPassphraseCredentialKey:
  227. target.privateKeyPassphrase && target.privateKeyPassphrase.length > 0
  228. ? previousSnapshot?.kind === "ssh" && previousSnapshot.privateKeyPassphraseCredentialKey
  229. ? previousSnapshot.privateKeyPassphraseCredentialKey
  230. : buildRemoteWorkspacePrivateKeyPassphraseCredentialKey(workspaceKey)
  231. : undefined,
  232. };
  233. case "wsl": {
  234. const user = target.user?.trim();
  235. return {
  236. kind: "wsl",
  237. distro: target.distro,
  238. ...(user ? { user } : {}),
  239. };
  240. }
  241. case "docker":
  242. return {
  243. kind: "docker",
  244. container: target.container,
  245. };
  246. case "server":
  247. return {
  248. kind: "server",
  249. url: target.url,
  250. ...(target.name?.trim() ? { name: target.name.trim() } : {}),
  251. ...(target.workspacePath?.trim() ? { workspacePath: target.workspacePath.trim() } : {}),
  252. ...(target.serverId?.trim() ? { serverId: target.serverId.trim() } : {}),
  253. tokenCredentialKey:
  254. target.token && target.token.length > 0
  255. ? previousSnapshot?.kind === "server" && previousSnapshot.tokenCredentialKey
  256. ? previousSnapshot.tokenCredentialKey
  257. : buildRemoteWorkspaceServerTokenCredentialKey(workspaceKey)
  258. : undefined,
  259. };
  260. }
  261. }
  262. export function createRemoteTargetFromSnapshot(
  263. snapshot: RemoteTargetSnapshot,
  264. credentials: {
  265. password: string | null;
  266. privateKeyPassphrase: string | null;
  267. token?: string | null;
  268. },
  269. ): RemoteTarget {
  270. switch (snapshot.kind) {
  271. case "ssh":
  272. return {
  273. kind: "ssh",
  274. host: snapshot.host,
  275. port: snapshot.port,
  276. username: snapshot.username,
  277. ...(snapshot.sshConfigAlias ? { sshConfigAlias: snapshot.sshConfigAlias } : {}),
  278. ...(snapshot.assetInstallMode ? { assetInstallMode: snapshot.assetInstallMode } : {}),
  279. ...(snapshot.privateKeyPath ? { privateKeyPath: snapshot.privateKeyPath } : {}),
  280. ...(credentials.password ? { password: credentials.password } : {}),
  281. ...(credentials.privateKeyPassphrase
  282. ? { privateKeyPassphrase: credentials.privateKeyPassphrase }
  283. : {}),
  284. };
  285. case "wsl":
  286. return {
  287. kind: "wsl",
  288. distro: snapshot.distro,
  289. ...(snapshot.user ? { user: snapshot.user } : {}),
  290. };
  291. case "docker":
  292. return {
  293. kind: "docker",
  294. container: snapshot.container,
  295. };
  296. case "server":
  297. return {
  298. kind: "server",
  299. url: snapshot.url,
  300. ...(snapshot.name ? { name: snapshot.name } : {}),
  301. ...(snapshot.workspacePath ? { workspacePath: snapshot.workspacePath } : {}),
  302. ...(snapshot.serverId ? { serverId: snapshot.serverId } : {}),
  303. ...(credentials.token ? { token: credentials.token } : {}),
  304. };
  305. }
  306. }
  307. export function upsertRemoteWorkspaceSessionEntries(
  308. sessions: RemoteWorkspaceSessionEntry[],
  309. nextEntry: RemoteWorkspaceSessionEntry,
  310. ): RemoteWorkspaceSessionEntry[] {
  311. const nextWorkspaceKey = buildWorkspaceSessionKey(nextEntry);
  312. return [
  313. nextEntry,
  314. ...sessions.filter((entry) => buildWorkspaceSessionKey(entry) !== nextWorkspaceKey),
  315. ]
  316. .sort((left, right) => right.lastOpenedAt - left.lastOpenedAt)
  317. .slice(0, REMOTE_WORKSPACE_SESSION_LIMIT);
  318. }
  319. export function removeRemoteWorkspaceSessionEntries(
  320. sessions: readonly RemoteWorkspaceSessionEntry[],
  321. workspaceKeys: readonly string[],
  322. ): RemoveRemoteWorkspaceSessionEntriesResult {
  323. const workspaceKeySet = new Set(
  324. workspaceKeys.map((workspaceKey) => workspaceKey.trim()).filter(Boolean),
  325. );
  326. const credentialKeysToDelete = new Set<string>();
  327. const nextRemoteSessions: RemoteWorkspaceSessionEntry[] = [];
  328. for (const session of sessions) {
  329. const sessionWorkspaceKey = buildWorkspaceSessionKey(session);
  330. if (!workspaceKeySet.has(sessionWorkspaceKey)) {
  331. nextRemoteSessions.push(session);
  332. continue;
  333. }
  334. for (const credentialKey of collectRemoteWorkspaceCredentialKeys(session.target)) {
  335. credentialKeysToDelete.add(credentialKey);
  336. }
  337. }
  338. return {
  339. nextRemoteSessions,
  340. credentialKeysToDelete: [...credentialKeysToDelete],
  341. };
  342. }
  343. export function buildRemoteWorkspaceSessionMutation(params: {
  344. remoteSessions: RemoteWorkspaceSessionEntry[];
  345. workspacePath: string;
  346. localWorkspacePath?: string;
  347. workspaceIdentity?: string;
  348. target: RemoteTarget;
  349. lastConnectionStatus: RemoteWorkspaceSessionEntry["lastConnectionStatus"];
  350. lastConnectionError?: string;
  351. touchOpenedAt: boolean;
  352. }): RemoteWorkspaceSessionMutation {
  353. const currentEntry =
  354. findMatchingRemoteWorkspaceSessionEntry(
  355. params.remoteSessions,
  356. params.workspacePath,
  357. params.target,
  358. ) ?? null;
  359. const resolvedWorkspaceIdentity =
  360. params.workspaceIdentity ??
  361. currentEntry?.workspaceIdentity ??
  362. buildRemoteWorkspaceIdentity(params.workspacePath, params.target);
  363. const workspaceKey = resolvedWorkspaceIdentity?.trim() || params.workspacePath;
  364. const nextSnapshot =
  365. params.lastConnectionStatus === "failed" && currentEntry
  366. ? currentEntry.target
  367. : createRemoteTargetSnapshot(workspaceKey, params.target, currentEntry?.target);
  368. const localWorkspacePath = normalizeOptionalPath(
  369. params.localWorkspacePath ?? currentEntry?.localWorkspacePath,
  370. );
  371. const nextEntry: RemoteWorkspaceSessionEntry = {
  372. kind: "remote",
  373. workspacePath: params.workspacePath,
  374. // filesystem MCP 同步需要用“本机 workspace -> 远端 workspace”映射。
  375. // 远端历史之前只保存远端路径,已连接后的 Settings/Header 入口无法再恢复本机基准路径。
  376. ...(localWorkspacePath ? { localWorkspacePath } : {}),
  377. workspaceIdentity: resolvedWorkspaceIdentity,
  378. target: nextSnapshot,
  379. lastOpenedAt: params.touchOpenedAt ? Date.now() : (currentEntry?.lastOpenedAt ?? Date.now()),
  380. lastConnectionStatus: params.lastConnectionStatus,
  381. lastConnectionError:
  382. params.lastConnectionStatus === "failed"
  383. ? (params.lastConnectionError ?? currentEntry?.lastConnectionError)
  384. : undefined,
  385. };
  386. const nextRemoteSessions = upsertRemoteWorkspaceSessionEntries(params.remoteSessions, nextEntry);
  387. const nextRemoteWorkspaceKeys = new Set(
  388. nextRemoteSessions.map((entry) => buildWorkspaceSessionKey(entry)),
  389. );
  390. const credentialKeysToDelete = new Set<string>();
  391. const previousCredentialKeys = new Set(
  392. currentEntry ? collectRemoteWorkspaceCredentialKeys(currentEntry.target) : [],
  393. );
  394. const nextCredentialKeys = new Set(collectRemoteWorkspaceCredentialKeys(nextSnapshot));
  395. for (const previousCredentialKey of previousCredentialKeys) {
  396. if (!nextCredentialKeys.has(previousCredentialKey)) {
  397. credentialKeysToDelete.add(previousCredentialKey);
  398. }
  399. }
  400. for (const removedEntry of params.remoteSessions) {
  401. if (nextRemoteWorkspaceKeys.has(buildWorkspaceSessionKey(removedEntry))) {
  402. continue;
  403. }
  404. for (const credentialKey of collectRemoteWorkspaceCredentialKeys(removedEntry.target)) {
  405. credentialKeysToDelete.add(credentialKey);
  406. }
  407. }
  408. const credentialsToSave: { key: string; value: string }[] = [];
  409. if (
  410. params.target.kind === "ssh" &&
  411. nextSnapshot.kind === "ssh" &&
  412. params.target.password &&
  413. nextSnapshot.passwordCredentialKey
  414. ) {
  415. credentialsToSave.push({
  416. key: nextSnapshot.passwordCredentialKey,
  417. value: params.target.password,
  418. });
  419. }
  420. if (
  421. params.target.kind === "ssh" &&
  422. nextSnapshot.kind === "ssh" &&
  423. params.target.privateKeyPassphrase &&
  424. nextSnapshot.privateKeyPassphraseCredentialKey
  425. ) {
  426. credentialsToSave.push({
  427. key: nextSnapshot.privateKeyPassphraseCredentialKey,
  428. value: params.target.privateKeyPassphrase,
  429. });
  430. }
  431. if (
  432. params.target.kind === "server" &&
  433. nextSnapshot.kind === "server" &&
  434. params.target.token &&
  435. nextSnapshot.tokenCredentialKey
  436. ) {
  437. credentialsToSave.push({
  438. key: nextSnapshot.tokenCredentialKey,
  439. value: params.target.token,
  440. });
  441. }
  442. return {
  443. entry: nextEntry,
  444. nextRemoteSessions,
  445. credentialsToSave,
  446. credentialKeysToDelete: [...credentialKeysToDelete],
  447. };
  448. }
  449. export function buildPersistedWorkspaceSessionEntries(
  450. tabs: WindowTabState[],
  451. remoteSessionsByWorkspaceKey: ReadonlyMap<string, RemoteWorkspaceSessionEntry>,
  452. ): PersistedWorkspaceSessionEntry[] {
  453. return tabs.reduce<PersistedWorkspaceSessionEntry[]>((entries, tab) => {
  454. if (!isWorkspaceTab(tab)) {
  455. return entries;
  456. }
  457. if (hasRemoteWorkspaceIdentity(tab)) {
  458. const workspaceKey = buildWorkspaceSessionKey(tab);
  459. const remoteEntry = remoteSessionsByWorkspaceKey.get(workspaceKey);
  460. // lastWorkspaceSession 现在是远端 workspace 的唯一持久化来源。
  461. // 如果这里因为 tab 断连就把 remote 项漏掉,下次启动会直接丢失“手动重连”的入口。
  462. // 因此只要当前 tab 具有远端身份,就必须写回完整 remote 条目。
  463. if (!remoteEntry) {
  464. return entries;
  465. }
  466. entries.push(remoteEntry);
  467. return entries;
  468. }
  469. entries.push({
  470. kind: "local",
  471. workspacePath: tab.workspacePath,
  472. ...(tab.workspacePurpose
  473. ? { workspacePurpose: tab.workspacePurpose }
  474. : {}),
  475. });
  476. return entries;
  477. }, []);
  478. }
  479. export function readPersistedWorkspaceSessionEntries(
  480. settings: Pick<AppSettings, "lastWorkspaceSession">,
  481. ): PersistedWorkspaceSessionEntry[] {
  482. return settings.lastWorkspaceSession ?? [];
  483. }
  484. export function getRemoteWorkspaceSessionEntries(
  485. settings: Pick<AppSettings, "lastWorkspaceSession">,
  486. ): RemoteWorkspaceSessionEntry[] {
  487. return (settings.lastWorkspaceSession ?? []).flatMap((entry) =>
  488. entry.kind === "remote" ? [entry] : [],
  489. );
  490. }
  491. export function buildRemoteWorkspaceSessionEntryMap(
  492. entries: readonly RemoteWorkspaceSessionEntry[],
  493. ): Map<string, RemoteWorkspaceSessionEntry> {
  494. return new Map(entries.map((entry) => [buildWorkspaceSessionKey(entry), entry] as const));
  495. }