remoteWorkspaceHistory.ts 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850
  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, parseRemoteWorkspaceIdentity } 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 collectOwnedRemoteWorkspaceCredentialKeys(snapshot: RemoteTargetSnapshot): string[] {
  36. // 历史快照可引用 Profile 凭据,但引用不转移所有权。此前重投影移除引用时
  37. // 把 Profile 密码也加入删除列表,导致冷启动后失去认证;所有历史清理只收集自有 key。
  38. const isOwned = (key: string | undefined): key is string =>
  39. typeof key === "string" && key.startsWith("remote-workspace:");
  40. if (snapshot.kind === "ssh") {
  41. return [snapshot.passwordCredentialKey, snapshot.privateKeyPassphraseCredentialKey].filter(
  42. isOwned,
  43. );
  44. }
  45. if (snapshot.kind === "server") {
  46. return [snapshot.tokenCredentialKey].filter(isOwned);
  47. }
  48. return [];
  49. }
  50. export function getWorkspaceDisplayLabel(workspacePath: string): string {
  51. const normalized = workspacePath.replace(/\\/g, "/");
  52. const segments = normalized.split("/").filter(Boolean);
  53. return segments[segments.length - 1] ?? workspacePath;
  54. }
  55. export function hasRemoteWorkspaceIdentity(entry: {
  56. remoteSessionId?: string;
  57. remoteTarget?: RemoteTarget;
  58. workspaceIdentity?: string;
  59. }): boolean {
  60. return Boolean(entry.remoteSessionId || entry.remoteTarget || entry.workspaceIdentity);
  61. }
  62. export function isSshRemoteWorkspaceIdentity(workspaceIdentity?: string | null): boolean {
  63. return workspaceIdentity?.trim().startsWith("remote:ssh:") === true;
  64. }
  65. type WslRemoteTargetLike = Extract<RemoteTarget | RemoteTargetSnapshot, { kind: "wsl" }>;
  66. function getWslRemoteTargetUser(target: WslRemoteTargetLike): string | undefined {
  67. return target.user?.trim() || undefined;
  68. }
  69. function formatWslRemoteTargetAuthority(target: WslRemoteTargetLike): string {
  70. const user = getWslRemoteTargetUser(target);
  71. if (target.distro) {
  72. return user ? `wsl:${target.distro}:${user}` : `wsl:${target.distro}`;
  73. }
  74. return user ? `wsl:default:${user}` : "wsl";
  75. }
  76. function getServerRemoteTargetDisplayName(
  77. target: Extract<RemoteTarget | RemoteTargetSnapshot, { kind: "server" }>,
  78. ): string {
  79. return target.name?.trim() || target.serverId?.trim() || formatServerRemoteTargetHost(target);
  80. }
  81. function formatServerRemoteTargetHost(
  82. target: Extract<RemoteTarget | RemoteTargetSnapshot, { kind: "server" }>,
  83. ): string {
  84. try {
  85. return new URL(target.url.trim()).host;
  86. } catch {
  87. return target.url.trim();
  88. }
  89. }
  90. export function formatRemoteWorkspaceTargetSubtitle(
  91. target: RemoteTarget | RemoteTargetSnapshot,
  92. ): string {
  93. switch (target.kind) {
  94. case "ssh":
  95. return `SSH · ${target.username}@${target.host}${target.port ? `:${target.port}` : ""}`;
  96. case "wsl": {
  97. const user = getWslRemoteTargetUser(target);
  98. return ["WSL", target.distro, user].filter(Boolean).join(" · ");
  99. }
  100. case "docker":
  101. return `Docker · ${target.container}`;
  102. case "server":
  103. return `Server · ${getServerRemoteTargetDisplayName(target)}`;
  104. }
  105. }
  106. export function formatRemoteWorkspaceHeaderHostLabel(
  107. target: RemoteTarget | RemoteTargetSnapshot,
  108. ): string {
  109. switch (target.kind) {
  110. case "ssh":
  111. return target.port && target.port !== 22 ? `${target.host}:${target.port}` : target.host;
  112. case "wsl":
  113. return formatWslRemoteTargetAuthority(target);
  114. case "docker":
  115. return `docker:${target.container}`;
  116. case "server":
  117. return formatServerRemoteTargetHost(target);
  118. }
  119. }
  120. export function formatRemoteWorkspaceDisplayLabel(
  121. label: string,
  122. target?: RemoteTarget | RemoteTargetSnapshot,
  123. ): string {
  124. // 线路信息属于设备原子/悬浮详情,不能把硬编码 SSH alias 拼进项目名称;
  125. // 这样既避免窄侧栏截断,也让标题可本地化。target 参数保留兼容旧调用方。
  126. void target;
  127. return label;
  128. }
  129. function normalizeWorkspacePathForIdentity(path: string): string {
  130. // 远程目录可能出现符号链接别名(例如 /dev 与 /home/dev)。
  131. // 身份计算前统一做分隔符归一化与收尾斜杠清理,避免同一路径文本噪声导致身份漂移。
  132. const normalized = path.replace(/\\/g, "/").replace(/\/+$/, "");
  133. return normalized.length > 0 ? normalized : "/";
  134. }
  135. function getRemoteWorkspaceAuthorityKey(target: RemoteTarget | RemoteTargetSnapshot): string {
  136. switch (target.kind) {
  137. case "ssh": {
  138. const normalizedHost = target.host.trim().toLowerCase();
  139. const normalizedUsername = target.username.trim();
  140. const normalizedPort = target.port ?? 22;
  141. return ["ssh", normalizedHost, normalizedPort, normalizedUsername].join(":");
  142. }
  143. case "wsl": {
  144. // WSL 默认用户与 root/其他显式用户的文件权限边界不同,
  145. // workspace identity 必须区分显式 user,避免 session、缓存和队列串用。
  146. const user = getWslRemoteTargetUser(target);
  147. const base = ["wsl", target.distro ?? "default"];
  148. return user ? [...base, user].join(":") : base.join(":");
  149. }
  150. case "docker":
  151. return ["docker", target.container].join(":");
  152. case "server": {
  153. const identity = buildServerRemoteWorkspaceIdentity({
  154. serverId: getServerRemoteTargetIdentityId(target),
  155. workspacePath: "/",
  156. });
  157. return identity.slice("remote:".length, -":/".length);
  158. }
  159. }
  160. }
  161. export function buildRemoteWorkspaceIdentity(
  162. workspacePath: string,
  163. target: RemoteTarget | RemoteTargetSnapshot,
  164. ): string {
  165. if (target.kind === "server") {
  166. return buildServerRemoteWorkspaceIdentity({
  167. serverId: getServerRemoteTargetIdentityId(target),
  168. workspacePath,
  169. });
  170. }
  171. const authority = getRemoteWorkspaceAuthorityKey(target);
  172. const normalizedPath = normalizeWorkspacePathForIdentity(workspacePath);
  173. return `remote:${authority}:${normalizedPath}`;
  174. }
  175. function getServerRemoteTargetIdentityId(
  176. target: Extract<RemoteTarget | RemoteTargetSnapshot, { kind: "server" }>,
  177. ): string {
  178. return target.serverId?.trim() || target.name?.trim() || formatServerRemoteTargetHost(target);
  179. }
  180. export function resolveRemoteWorkspaceSessionIdentity(
  181. entry: Pick<RemoteWorkspaceSessionEntry, "workspacePath" | "target" | "workspaceIdentity">,
  182. ): string {
  183. return entry.workspaceIdentity || buildRemoteWorkspaceIdentity(entry.workspacePath, entry.target);
  184. }
  185. export function buildWorkspaceSessionKey(entry: {
  186. workspacePath: string;
  187. workspaceIdentity?: string;
  188. }): string {
  189. return entry.workspaceIdentity?.trim() || entry.workspacePath;
  190. }
  191. function normalizeOptionalPath(path: string | undefined): string | undefined {
  192. const trimmed = path?.trim();
  193. return trimmed ? trimmed : undefined;
  194. }
  195. export function findMatchingRemoteWorkspaceSessionEntry(
  196. sessions: RemoteWorkspaceSessionEntry[],
  197. workspacePath: string,
  198. target: RemoteTarget | RemoteTargetSnapshot,
  199. preferredWorkspaceIdentity?: string,
  200. ): RemoteWorkspaceSessionEntry | null {
  201. const preferredWorkspaceKey = preferredWorkspaceIdentity?.trim();
  202. if (preferredWorkspaceKey) {
  203. const preferred = sessions.find(
  204. (entry) =>
  205. entry.workspacePath === workspacePath &&
  206. buildWorkspaceSessionKey(entry) === preferredWorkspaceKey,
  207. );
  208. if (preferred) return preferred;
  209. }
  210. const workspaceIdentity = buildRemoteWorkspaceIdentity(workspacePath, target);
  211. return (
  212. sessions.find((entry) => resolveRemoteWorkspaceSessionIdentity(entry) === workspaceIdentity) ??
  213. null
  214. );
  215. }
  216. export function createRemoteTargetSnapshot(
  217. workspaceKey: string,
  218. target: RemoteTarget,
  219. previousSnapshot?: RemoteTargetSnapshot,
  220. ): RemoteTargetSnapshot {
  221. const sourceServerOwnedCredentials =
  222. parseRemoteWorkspaceIdentity(workspaceKey)?.kind === "server";
  223. switch (target.kind) {
  224. case "ssh":
  225. return {
  226. kind: "ssh",
  227. host: target.host,
  228. port: target.port,
  229. username: target.username,
  230. ...(target.sshConfigAlias?.trim() ? { sshConfigAlias: target.sshConfigAlias.trim() } : {}),
  231. assetInstallMode: target.assetInstallMode,
  232. privateKeyPath: target.privateKeyPath,
  233. passwordCredentialKey:
  234. !sourceServerOwnedCredentials && target.password && target.password.length > 0
  235. ? previousSnapshot?.kind === "ssh" && previousSnapshot.passwordCredentialKey
  236. ? previousSnapshot.passwordCredentialKey
  237. : buildRemoteWorkspacePasswordCredentialKey(workspaceKey)
  238. : undefined,
  239. privateKeyPassphraseCredentialKey:
  240. !sourceServerOwnedCredentials &&
  241. target.privateKeyPassphrase &&
  242. target.privateKeyPassphrase.length > 0
  243. ? previousSnapshot?.kind === "ssh" && previousSnapshot.privateKeyPassphraseCredentialKey
  244. ? previousSnapshot.privateKeyPassphraseCredentialKey
  245. : buildRemoteWorkspacePrivateKeyPassphraseCredentialKey(workspaceKey)
  246. : undefined,
  247. };
  248. case "wsl": {
  249. const user = target.user?.trim();
  250. return {
  251. kind: "wsl",
  252. distro: target.distro,
  253. ...(user ? { user } : {}),
  254. };
  255. }
  256. case "docker":
  257. return {
  258. kind: "docker",
  259. container: target.container,
  260. };
  261. case "server":
  262. return {
  263. kind: "server",
  264. url: target.url,
  265. ...(target.name?.trim() ? { name: target.name.trim() } : {}),
  266. ...(target.workspacePath?.trim() ? { workspacePath: target.workspacePath.trim() } : {}),
  267. ...(target.serverId?.trim() ? { serverId: target.serverId.trim() } : {}),
  268. tokenCredentialKey:
  269. target.token && target.token.length > 0
  270. ? previousSnapshot?.kind === "server" && previousSnapshot.tokenCredentialKey
  271. ? previousSnapshot.tokenCredentialKey
  272. : buildRemoteWorkspaceServerTokenCredentialKey(workspaceKey)
  273. : undefined,
  274. };
  275. }
  276. }
  277. export function createRemoteTargetFromSnapshot(
  278. snapshot: RemoteTargetSnapshot,
  279. credentials: {
  280. password: string | null;
  281. privateKeyPassphrase: string | null;
  282. token?: string | null;
  283. },
  284. ): RemoteTarget {
  285. switch (snapshot.kind) {
  286. case "ssh":
  287. return {
  288. kind: "ssh",
  289. host: snapshot.host,
  290. port: snapshot.port,
  291. username: snapshot.username,
  292. ...(snapshot.sshConfigAlias ? { sshConfigAlias: snapshot.sshConfigAlias } : {}),
  293. ...(snapshot.assetInstallMode ? { assetInstallMode: snapshot.assetInstallMode } : {}),
  294. ...(snapshot.privateKeyPath ? { privateKeyPath: snapshot.privateKeyPath } : {}),
  295. ...(credentials.password ? { password: credentials.password } : {}),
  296. ...(credentials.privateKeyPassphrase
  297. ? { privateKeyPassphrase: credentials.privateKeyPassphrase }
  298. : {}),
  299. };
  300. case "wsl":
  301. return {
  302. kind: "wsl",
  303. distro: snapshot.distro,
  304. ...(snapshot.user ? { user: snapshot.user } : {}),
  305. };
  306. case "docker":
  307. return {
  308. kind: "docker",
  309. container: snapshot.container,
  310. };
  311. case "server":
  312. return {
  313. kind: "server",
  314. url: snapshot.url,
  315. ...(snapshot.name ? { name: snapshot.name } : {}),
  316. ...(snapshot.workspacePath ? { workspacePath: snapshot.workspacePath } : {}),
  317. ...(snapshot.serverId ? { serverId: snapshot.serverId } : {}),
  318. ...(credentials.token ? { token: credentials.token } : {}),
  319. };
  320. }
  321. }
  322. export function upsertRemoteWorkspaceSessionEntries(
  323. sessions: RemoteWorkspaceSessionEntry[],
  324. nextEntry: RemoteWorkspaceSessionEntry,
  325. ): RemoteWorkspaceSessionEntry[] {
  326. const nextWorkspaceKey = buildWorkspaceSessionKey(nextEntry);
  327. return [
  328. nextEntry,
  329. ...sessions.filter((entry) => buildWorkspaceSessionKey(entry) !== nextWorkspaceKey),
  330. ]
  331. .sort((left, right) => right.lastOpenedAt - left.lastOpenedAt)
  332. .slice(0, REMOTE_WORKSPACE_SESSION_LIMIT);
  333. }
  334. export function removeRemoteWorkspaceSessionEntries(
  335. sessions: readonly RemoteWorkspaceSessionEntry[],
  336. workspaceKeys: readonly string[],
  337. ): RemoveRemoteWorkspaceSessionEntriesResult {
  338. const workspaceKeySet = new Set(
  339. workspaceKeys.map((workspaceKey) => workspaceKey.trim()).filter(Boolean),
  340. );
  341. const credentialKeysToDelete = new Set<string>();
  342. const nextRemoteSessions: RemoteWorkspaceSessionEntry[] = [];
  343. for (const session of sessions) {
  344. const sessionWorkspaceKey = buildWorkspaceSessionKey(session);
  345. if (!workspaceKeySet.has(sessionWorkspaceKey)) {
  346. nextRemoteSessions.push(session);
  347. continue;
  348. }
  349. for (const credentialKey of collectOwnedRemoteWorkspaceCredentialKeys(session.target)) {
  350. credentialKeysToDelete.add(credentialKey);
  351. }
  352. }
  353. return {
  354. nextRemoteSessions,
  355. credentialKeysToDelete: [...credentialKeysToDelete],
  356. };
  357. }
  358. export function buildRemoteWorkspaceSessionMutation(params: {
  359. remoteSessions: RemoteWorkspaceSessionEntry[];
  360. workspacePath: string;
  361. localWorkspacePath?: string;
  362. workspaceIdentity?: string;
  363. target: RemoteTarget;
  364. workspacePurpose?: "project" | "conversation";
  365. lastConnectionStatus: RemoteWorkspaceSessionEntry["lastConnectionStatus"];
  366. lastConnectionError?: string;
  367. lastConnectionErrorCode?: string;
  368. touchOpenedAt: boolean;
  369. }): RemoteWorkspaceSessionMutation {
  370. const currentEntry =
  371. findMatchingRemoteWorkspaceSessionEntry(
  372. params.remoteSessions,
  373. params.workspacePath,
  374. params.target,
  375. params.workspaceIdentity,
  376. ) ?? null;
  377. const resolvedWorkspaceIdentity =
  378. params.workspaceIdentity ??
  379. currentEntry?.workspaceIdentity ??
  380. buildRemoteWorkspaceIdentity(params.workspacePath, params.target);
  381. const workspaceKey = resolvedWorkspaceIdentity?.trim() || params.workspacePath;
  382. const nextSnapshot =
  383. params.lastConnectionStatus === "failed" && currentEntry
  384. ? currentEntry.target
  385. : createRemoteTargetSnapshot(workspaceKey, params.target, currentEntry?.target);
  386. const localWorkspacePath = normalizeOptionalPath(
  387. params.localWorkspacePath ?? currentEntry?.localWorkspacePath,
  388. );
  389. // 错误码与文案同写同清:新失败只用自己的码(可以没有),只更新状态时沿用原记录。
  390. const lastConnectionErrorCode =
  391. params.lastConnectionStatus !== "failed"
  392. ? undefined
  393. : params.lastConnectionError !== undefined
  394. ? params.lastConnectionErrorCode
  395. : currentEntry?.lastConnectionErrorCode;
  396. const nextEntry: RemoteWorkspaceSessionEntry = {
  397. kind: "remote",
  398. workspacePath: params.workspacePath,
  399. ...(params.workspacePurpose || currentEntry?.workspacePurpose
  400. ? {
  401. workspacePurpose: params.workspacePurpose ?? currentEntry?.workspacePurpose,
  402. }
  403. : {}),
  404. // Bugfix: filesystem MCP 同步需要用“本机 workspace -> 远端 workspace”映射。
  405. // 远端历史之前只保存远端路径,已连接后的 Settings/Header 入口无法再恢复本机基准路径。
  406. ...(localWorkspacePath ? { localWorkspacePath } : {}),
  407. workspaceIdentity: resolvedWorkspaceIdentity,
  408. target: nextSnapshot,
  409. lastOpenedAt: params.touchOpenedAt ? Date.now() : (currentEntry?.lastOpenedAt ?? Date.now()),
  410. lastConnectionStatus: params.lastConnectionStatus,
  411. lastConnectionError:
  412. params.lastConnectionStatus === "failed"
  413. ? (params.lastConnectionError ?? currentEntry?.lastConnectionError)
  414. : undefined,
  415. ...(lastConnectionErrorCode ? { lastConnectionErrorCode } : {}),
  416. };
  417. // Bug 原因:Host 绑定 stable identity 后,旧 route entry 与新 entry 的 key 不同,
  418. // 通用 upsert 会把两条都保留。已经通过 target/alias 证明的 currentEntry 就是被换代对象,
  419. // 必须先移除再按 stable key 插入。
  420. const nextRemoteSessions = upsertRemoteWorkspaceSessionEntries(
  421. currentEntry
  422. ? params.remoteSessions.filter((entry) => entry !== currentEntry)
  423. : params.remoteSessions,
  424. nextEntry,
  425. );
  426. const nextRemoteWorkspaceKeys = new Set(
  427. nextRemoteSessions.map((entry) => buildWorkspaceSessionKey(entry)),
  428. );
  429. const credentialKeysToDelete = new Set<string>();
  430. const previousCredentialKeys = new Set(
  431. currentEntry ? collectOwnedRemoteWorkspaceCredentialKeys(currentEntry.target) : [],
  432. );
  433. const nextCredentialKeys = new Set(collectOwnedRemoteWorkspaceCredentialKeys(nextSnapshot));
  434. const sourceServerOwnedCredentials =
  435. parseRemoteWorkspaceIdentity(workspaceKey)?.kind === "server";
  436. const preservesRollbackCredential = (credentialKey: string): boolean =>
  437. sourceServerOwnedCredentials &&
  438. credentialKey.startsWith("remote-workspace:remote:") &&
  439. !credentialKey.includes(":remote:server:");
  440. for (const previousCredentialKey of previousCredentialKeys) {
  441. if (
  442. !nextCredentialKeys.has(previousCredentialKey) &&
  443. !preservesRollbackCredential(previousCredentialKey)
  444. ) {
  445. credentialKeysToDelete.add(previousCredentialKey);
  446. }
  447. }
  448. for (const removedEntry of params.remoteSessions) {
  449. if (removedEntry === currentEntry) {
  450. // currentEntry 的凭据差异已在 previousCredentialKeys 分支处理;
  451. // 无显式 identity 的旧 entry 不能再被当成「被容量裁剪」重复删除凭据。
  452. continue;
  453. }
  454. if (nextRemoteWorkspaceKeys.has(buildWorkspaceSessionKey(removedEntry))) {
  455. continue;
  456. }
  457. for (const credentialKey of collectOwnedRemoteWorkspaceCredentialKeys(removedEntry.target)) {
  458. if (!preservesRollbackCredential(credentialKey)) {
  459. credentialKeysToDelete.add(credentialKey);
  460. }
  461. }
  462. }
  463. const credentialsToSave: { key: string; value: string }[] = [];
  464. if (
  465. params.target.kind === "ssh" &&
  466. nextSnapshot.kind === "ssh" &&
  467. params.target.password &&
  468. nextSnapshot.passwordCredentialKey
  469. ) {
  470. credentialsToSave.push({
  471. key: nextSnapshot.passwordCredentialKey,
  472. value: params.target.password,
  473. });
  474. }
  475. if (
  476. params.target.kind === "ssh" &&
  477. nextSnapshot.kind === "ssh" &&
  478. params.target.privateKeyPassphrase &&
  479. nextSnapshot.privateKeyPassphraseCredentialKey
  480. ) {
  481. credentialsToSave.push({
  482. key: nextSnapshot.privateKeyPassphraseCredentialKey,
  483. value: params.target.privateKeyPassphrase,
  484. });
  485. }
  486. if (
  487. params.target.kind === "server" &&
  488. nextSnapshot.kind === "server" &&
  489. params.target.token &&
  490. nextSnapshot.tokenCredentialKey
  491. ) {
  492. credentialsToSave.push({
  493. key: nextSnapshot.tokenCredentialKey,
  494. value: params.target.token,
  495. });
  496. }
  497. return {
  498. entry: nextEntry,
  499. nextRemoteSessions,
  500. credentialsToSave,
  501. credentialKeysToDelete: [...credentialKeysToDelete],
  502. };
  503. }
  504. export function buildPersistedWorkspaceSessionEntries(
  505. tabs: WindowTabState[],
  506. remoteSessionsByWorkspaceKey: ReadonlyMap<string, RemoteWorkspaceSessionEntry>,
  507. ): PersistedWorkspaceSessionEntry[] {
  508. return tabs.reduce<PersistedWorkspaceSessionEntry[]>((entries, tab) => {
  509. if (!isWorkspaceTab(tab)) {
  510. return entries;
  511. }
  512. if (hasRemoteWorkspaceIdentity(tab)) {
  513. const workspaceKey = buildWorkspaceSessionKey(tab);
  514. const remoteEntry = remoteSessionsByWorkspaceKey.get(workspaceKey);
  515. // lastWorkspaceSession 现在是远端 workspace 的唯一持久化来源。
  516. // 如果这里因为 tab 断连就把 remote 项漏掉,下次启动会直接丢失“手动重连”的入口。
  517. // 因此只要当前 tab 具有远端身份,就必须写回完整 remote 条目。
  518. if (!remoteEntry) {
  519. return entries;
  520. }
  521. entries.push(remoteEntry);
  522. return entries;
  523. }
  524. entries.push({
  525. kind: "local",
  526. workspacePath: tab.workspacePath,
  527. ...(tab.workspacePurpose ? { workspacePurpose: tab.workspacePurpose } : {}),
  528. });
  529. return entries;
  530. }, []);
  531. }
  532. export function readPersistedWorkspaceSessionEntries(
  533. settings: Pick<
  534. AppSettings,
  535. | "lastWorkspaceSession"
  536. | "lastActiveWorkspace"
  537. | "sourceServerWorkspaceHistory"
  538. | "connectionProfiles"
  539. | "remoteConversationWorkspaceBySourceServerId"
  540. >,
  541. ): PersistedWorkspaceSessionEntry[] {
  542. // 新版只恢复活动执行目录;旧字段仅供首次导入或连接旧 Server 使用。
  543. if (settings.lastActiveWorkspace !== undefined) {
  544. return settings.lastActiveWorkspace ? [settings.lastActiveWorkspace] : [];
  545. }
  546. const projectAliases = mergeIdentityAliases([
  547. buildSourceServerWorkspaceIdentityAliases(settings.sourceServerWorkspaceHistory ?? []),
  548. buildSourceProfileWorkspaceIdentityAliases(
  549. settings.sourceServerWorkspaceHistory ?? [],
  550. settings.connectionProfiles ?? [],
  551. ),
  552. ]);
  553. const conversationAliases = buildSourceConversationWorkspaceIdentityAliases(settings);
  554. const result: PersistedWorkspaceSessionEntry[] = [];
  555. const remoteIndexByKey = new Map<string, number>();
  556. for (const entry of settings.lastWorkspaceSession ?? []) {
  557. if (entry.kind === "local") {
  558. result.push(entry);
  559. continue;
  560. }
  561. const currentIdentity = resolveRemoteWorkspaceSessionIdentity(entry);
  562. const aliasKey = `${entry.workspacePath}\0${currentIdentity}`;
  563. const projectAlias = projectAliases.get(aliasKey);
  564. const conversationAlias = conversationAliases.get(aliasKey);
  565. // project history 与 device conversation map 理论上不会声明同一路径;旧数据若冲突,
  566. // 保持 legacy identity fail-closed,不能把 workspace 猜到任一 Source。
  567. const stableAlias =
  568. projectAlias && conversationAlias && projectAlias !== conversationAlias
  569. ? undefined
  570. : (projectAlias ?? conversationAlias);
  571. const normalized = stableAlias
  572. ? {
  573. ...entry,
  574. workspaceIdentity: stableAlias,
  575. ...(conversationAlias === stableAlias
  576. ? { workspacePurpose: "conversation" as const }
  577. : {}),
  578. }
  579. : entry;
  580. const workspaceKey = buildWorkspaceSessionKey(normalized);
  581. const existingIndex = remoteIndexByKey.get(workspaceKey);
  582. if (existingIndex === undefined) {
  583. remoteIndexByKey.set(workspaceKey, result.length);
  584. result.push(normalized);
  585. continue;
  586. }
  587. const existing = result[existingIndex];
  588. if (existing?.kind === "remote" && normalized.lastOpenedAt > existing.lastOpenedAt) {
  589. result[existingIndex] = {
  590. ...existing,
  591. ...normalized,
  592. localWorkspacePath: normalized.localWorkspacePath ?? existing.localWorkspacePath,
  593. };
  594. }
  595. }
  596. return result;
  597. }
  598. function buildSourceServerWorkspaceIdentityAliases(
  599. historyEntries: NonNullable<AppSettings["sourceServerWorkspaceHistory"]>,
  600. ): Map<string, string> {
  601. const aliases = new Map<string, string>();
  602. for (const history of historyEntries) {
  603. const legacyIdentity = history.legacyWorkspaceIdentity?.trim();
  604. const stableIdentity = history.workspaceIdentity?.trim();
  605. if (legacyIdentity && stableIdentity && legacyIdentity !== stableIdentity) {
  606. aliases.set(`${history.workspacePath}\0${legacyIdentity}`, stableIdentity);
  607. }
  608. }
  609. return aliases;
  610. }
  611. function buildSourceConversationWorkspaceIdentityAliases(
  612. settings: Pick<AppSettings, "connectionProfiles" | "remoteConversationWorkspaceBySourceServerId">,
  613. ): Map<string, string> {
  614. const candidatesByAlias = new Map<string, Set<string>>();
  615. for (const profile of settings.connectionProfiles ?? []) {
  616. const sourceServerId = profile.sourceServerId?.trim();
  617. if (!sourceServerId || profile.lifecycleState === "retired") {
  618. continue;
  619. }
  620. const workspacePath =
  621. settings.remoteConversationWorkspaceBySourceServerId?.[sourceServerId]?.workspacePath;
  622. if (!workspacePath) continue;
  623. // Bug 原因:rollback writer 必须为旧 Desktop 写 route identity,但 conversation
  624. // 按合同不进入 project history,reader 过去没有逆映射来源,重启后只能恢复成 pending tab。
  625. // 这里同时要求已绑定 Profile 的精确 authority 与设备级 canonical path,且只接受唯一 Source。
  626. const legacyIdentity = buildRemoteWorkspaceIdentity(workspacePath, profile.target);
  627. const stableIdentity = buildServerRemoteWorkspaceIdentity({
  628. serverId: sourceServerId,
  629. workspacePath,
  630. });
  631. const aliasKey = `${workspacePath}\0${legacyIdentity}`;
  632. const candidates = candidatesByAlias.get(aliasKey) ?? new Set<string>();
  633. candidates.add(stableIdentity);
  634. candidatesByAlias.set(aliasKey, candidates);
  635. }
  636. const aliases = new Map<string, string>();
  637. for (const [aliasKey, candidates] of candidatesByAlias) {
  638. if (candidates.size !== 1) continue;
  639. const stableIdentity = candidates.values().next().value;
  640. if (stableIdentity) aliases.set(aliasKey, stableIdentity);
  641. }
  642. return aliases;
  643. }
  644. function buildSourceProfileWorkspaceIdentityAliases(
  645. historyEntries: NonNullable<AppSettings["sourceServerWorkspaceHistory"]>,
  646. profiles: NonNullable<AppSettings["connectionProfiles"]>,
  647. ): Map<string, string> {
  648. const candidatesByAlias = new Map<string, Set<string>>();
  649. for (const history of historyEntries) {
  650. const sourceServerId = history.sourceServerId?.trim();
  651. if (!sourceServerId) continue;
  652. const stableIdentity = buildServerRemoteWorkspaceIdentity({
  653. serverId: sourceServerId,
  654. workspacePath: history.workspacePath,
  655. });
  656. for (const profile of profiles) {
  657. if (
  658. profile.lifecycleState === "retired" ||
  659. profile.sourceServerId?.trim() !== sourceServerId
  660. ) {
  661. continue;
  662. }
  663. const legacyIdentity = buildRemoteWorkspaceIdentity(history.workspacePath, profile.target);
  664. if (legacyIdentity === stableIdentity) continue;
  665. const aliasKey = `${history.workspacePath}\0${legacyIdentity}`;
  666. const candidates = candidatesByAlias.get(aliasKey) ?? new Set<string>();
  667. candidates.add(stableIdentity);
  668. candidatesByAlias.set(aliasKey, candidates);
  669. }
  670. }
  671. const aliases = new Map<string, string>();
  672. for (const [aliasKey, candidates] of candidatesByAlias) {
  673. if (candidates.size !== 1) continue;
  674. const stableIdentity = candidates.values().next().value;
  675. if (stableIdentity) aliases.set(aliasKey, stableIdentity);
  676. }
  677. return aliases;
  678. }
  679. function mergeIdentityAliases(
  680. aliasMaps: readonly ReadonlyMap<string, string>[],
  681. ): Map<string, string> {
  682. const candidatesByAlias = new Map<string, Set<string>>();
  683. for (const aliasMap of aliasMaps) {
  684. for (const [aliasKey, stableIdentity] of aliasMap) {
  685. const candidates = candidatesByAlias.get(aliasKey) ?? new Set<string>();
  686. candidates.add(stableIdentity);
  687. candidatesByAlias.set(aliasKey, candidates);
  688. }
  689. }
  690. const aliases = new Map<string, string>();
  691. for (const [aliasKey, candidates] of candidatesByAlias) {
  692. if (candidates.size !== 1) continue;
  693. const stableIdentity = candidates.values().next().value;
  694. if (stableIdentity) aliases.set(aliasKey, stableIdentity);
  695. }
  696. return aliases;
  697. }
  698. export interface RemoteWorkspaceSessionIdentityRekey {
  699. workspacePath: string;
  700. previousWorkspaceIdentity: string;
  701. workspaceIdentity: string;
  702. }
  703. export function projectRemoteWorkspaceSessionIdentityAliases(
  704. remoteSessions: readonly RemoteWorkspaceSessionEntry[],
  705. sourceServerWorkspaceHistoryOrSettings:
  706. | NonNullable<AppSettings["sourceServerWorkspaceHistory"]>
  707. | Pick<
  708. AppSettings,
  709. | "sourceServerWorkspaceHistory"
  710. | "connectionProfiles"
  711. | "remoteConversationWorkspaceBySourceServerId"
  712. >,
  713. ): {
  714. remoteSessions: RemoteWorkspaceSessionEntry[];
  715. identityRekeys: RemoteWorkspaceSessionIdentityRekey[];
  716. } {
  717. const sourceServerWorkspaceHistory = Array.isArray(sourceServerWorkspaceHistoryOrSettings)
  718. ? sourceServerWorkspaceHistoryOrSettings
  719. : (sourceServerWorkspaceHistoryOrSettings.sourceServerWorkspaceHistory ?? []);
  720. const settings: Pick<
  721. AppSettings,
  722. | "sourceServerWorkspaceHistory"
  723. | "connectionProfiles"
  724. | "remoteConversationWorkspaceBySourceServerId"
  725. > = Array.isArray(sourceServerWorkspaceHistoryOrSettings)
  726. ? {}
  727. : sourceServerWorkspaceHistoryOrSettings;
  728. const aliases = mergeIdentityAliases([
  729. buildSourceServerWorkspaceIdentityAliases(sourceServerWorkspaceHistory),
  730. buildSourceProfileWorkspaceIdentityAliases(
  731. sourceServerWorkspaceHistory,
  732. settings.connectionProfiles ?? [],
  733. ),
  734. buildSourceConversationWorkspaceIdentityAliases({
  735. connectionProfiles: settings.connectionProfiles ?? [],
  736. remoteConversationWorkspaceBySourceServerId:
  737. settings.remoteConversationWorkspaceBySourceServerId,
  738. }),
  739. ]);
  740. const identityRekeys = remoteSessions.flatMap((entry) => {
  741. const previousWorkspaceIdentity = resolveRemoteWorkspaceSessionIdentity(entry);
  742. const workspaceIdentity = aliases.get(`${entry.workspacePath}\0${previousWorkspaceIdentity}`);
  743. return workspaceIdentity
  744. ? [
  745. {
  746. workspacePath: entry.workspacePath,
  747. previousWorkspaceIdentity,
  748. workspaceIdentity,
  749. },
  750. ]
  751. : [];
  752. });
  753. const projectedEntries = readPersistedWorkspaceSessionEntries({
  754. lastWorkspaceSession: [...remoteSessions],
  755. sourceServerWorkspaceHistory,
  756. ...(settings.connectionProfiles ? { connectionProfiles: settings.connectionProfiles } : {}),
  757. ...(settings.remoteConversationWorkspaceBySourceServerId
  758. ? {
  759. remoteConversationWorkspaceBySourceServerId:
  760. settings.remoteConversationWorkspaceBySourceServerId,
  761. }
  762. : {}),
  763. });
  764. return {
  765. remoteSessions: projectedEntries.flatMap((entry) => (entry.kind === "remote" ? [entry] : [])),
  766. identityRekeys,
  767. };
  768. }
  769. export function getRemoteWorkspaceSessionEntries(
  770. settings: Pick<
  771. AppSettings,
  772. | "lastWorkspaceSession"
  773. | "sourceServerWorkspaceHistory"
  774. | "connectionProfiles"
  775. | "remoteConversationWorkspaceBySourceServerId"
  776. >,
  777. ): RemoteWorkspaceSessionEntry[] {
  778. return readPersistedWorkspaceSessionEntries(settings).flatMap((entry) =>
  779. entry.kind === "remote" ? [entry] : [],
  780. );
  781. }
  782. export function buildRemoteWorkspaceSessionEntryMap(
  783. entries: readonly RemoteWorkspaceSessionEntry[],
  784. ): Map<string, RemoteWorkspaceSessionEntry> {
  785. return new Map(entries.map((entry) => [buildWorkspaceSessionKey(entry), entry] as const));
  786. }