tabStore.ts 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655
  1. /* oxlint-disable eslint(max-lines) */
  2. /**
  3. * Tab Store —— 多标签页状态管理
  4. *
  5. * 每个窗口拥有独立的 tab store(不跨窗口广播)。
  6. * 标签页状态通过 settingService 持久化(见 useTabPersistence)。
  7. */
  8. import { create } from "zustand";
  9. import {
  10. createUuid,
  11. type RemoteTarget,
  12. type TabId,
  13. type TabState,
  14. type WorkspacePurpose,
  15. } from "@zcode/shared";
  16. import {
  17. persistWorkspaceExpandedPreference,
  18. readWorkspaceExpansionState,
  19. resolveExpandedWorkspacePaths,
  20. type WorkspaceExpansionState,
  21. } from "@/lib/workspaceExpansionPreference.js";
  22. import { isSameWorkspaceTab } from "@/store/tabWorkspaceIdentity.js";
  23. export const SETTINGS_TAB_ID = "__settings__" satisfies TabId;
  24. export type WorkspaceAvailability = "available" | "unavailable-local-directory";
  25. export interface SettingsTabState {
  26. id: typeof SETTINGS_TAB_ID;
  27. kind: "settings";
  28. label: "settings";
  29. }
  30. export interface WorkspaceTabState extends TabState {
  31. kind: "workspace";
  32. /** 启动期一次性校验结果;不持久化,运行期间不重检。 */
  33. availability?: WorkspaceAvailability;
  34. remoteSessionId?: string;
  35. remoteTarget?: RemoteTarget;
  36. remoteHistoryId?: string;
  37. workspaceIdentity?: string;
  38. localWorkspacePath?: string;
  39. workspacePurpose?: WorkspacePurpose;
  40. }
  41. export interface WorkspaceTabOptions {
  42. availability?: WorkspaceAvailability;
  43. remoteSessionId?: string;
  44. remoteTarget?: RemoteTarget;
  45. remoteHistoryId?: string;
  46. workspaceIdentity?: string;
  47. localWorkspacePath?: string;
  48. workspacePurpose?: WorkspacePurpose;
  49. }
  50. export interface RestorableWorkspaceTab {
  51. workspacePath: string;
  52. availability?: WorkspaceAvailability;
  53. remoteSessionId?: string;
  54. remoteTarget?: RemoteTarget;
  55. workspaceIdentity?: string;
  56. localWorkspacePath?: string;
  57. workspacePurpose?: WorkspacePurpose;
  58. }
  59. export type WindowTabState = WorkspaceTabState | SettingsTabState;
  60. export function isWorkspaceTab(tab: WindowTabState): tab is WorkspaceTabState {
  61. return tab.kind === "workspace";
  62. }
  63. export function isWorkspaceTabReadOnly(tab: WindowTabState): tab is WorkspaceTabState & {
  64. availability: "unavailable-local-directory";
  65. } {
  66. return isWorkspaceTab(tab) && tab.availability === "unavailable-local-directory";
  67. }
  68. export function isWorkspaceReadOnly(
  69. state: Pick<TabStoreState, "tabs">,
  70. workspacePath: string,
  71. workspaceIdentity?: string,
  72. ): boolean {
  73. const workspaceKey = workspaceIdentity?.trim() || workspacePath;
  74. return state.tabs.some(
  75. (tab) =>
  76. isWorkspaceTabReadOnly(tab) &&
  77. (tab.workspaceIdentity?.trim() || tab.workspacePath) === workspaceKey,
  78. );
  79. }
  80. export function isSettingsTab(tab: WindowTabState): tab is SettingsTabState {
  81. return tab.kind === "settings";
  82. }
  83. // ============================================================================
  84. // State 定义
  85. // ============================================================================
  86. export interface TabStoreState {
  87. /** 当前窗口所有打开的标签页(有序) */
  88. tabs: WindowTabState[];
  89. /** 当前激活的标签页 ID,null 表示无激活标签 */
  90. activeTabId: TabId | null;
  91. /** 当前或最近一次激活的 workspace 路径 */
  92. activeWorkspacePath: string | null;
  93. /** 当前或最近一次激活的 workspace identity(远端同路径隔离) */
  94. activeWorkspaceIdentity: string | null;
  95. /** 左侧侧边栏中已展开的 workspace 路径集合 */
  96. expandedWorkspacePaths: Set<string>;
  97. /** 新增标签页,返回新 tab 的 ID */
  98. addTab: (workspacePath: string, options?: WorkspaceTabOptions) => TabId;
  99. /** 确保 workspace 出现在任务区数据源中,但不抢走当前焦点 */
  100. ensureWorkspaceTab: (workspacePath: string, options?: WorkspaceTabOptions) => TabId;
  101. /** 关闭标签页 */
  102. closeTab: (tabId: TabId) => void;
  103. /** 激活指定标签页 */
  104. activateTab: (tabId: TabId) => void;
  105. /** 拖拽排序:将 fromIndex 位置的 tab 移动到 toIndex */
  106. reorderTabs: (fromIndex: number, toIndex: number) => void;
  107. /** 仅按 workspace 子序列重排,保留设置页等非 workspace tab 的位置槽位 */
  108. reorderWorkspaceTabs: (fromIndex: number, toIndex: number) => void;
  109. /** 打开设置标签页(窗口内唯一) */
  110. openSettingsTab: () => void;
  111. /** 通过 workspace 路径激活 tab(跨窗口 focus 用),返回是否找到 */
  112. activateTabByPath: (path: string, options?: { workspaceIdentity?: string }) => boolean;
  113. /** 切换 workspace 的展开/收起态 */
  114. toggleWorkspaceExpanded: (path: string) => void;
  115. /** 展开当前任务区里的全部 workspace */
  116. expandAllWorkspaceTabs: (paths: string[]) => void;
  117. /** 收起当前任务区里的全部 workspace */
  118. collapseAllWorkspaceTabs: (paths: string[]) => void;
  119. /** 批量恢复标签页(启动时从持久化数据恢复用) */
  120. restoreTabs: (tabs: Array<string | RestorableWorkspaceTab>, activeIndex: number) => void;
  121. /** 启动首帧后补齐持久化标签页;保留当前 active identity 和用户在此期间新增的标签页。 */
  122. completeTabRestore: (tabs: Array<string | RestorableWorkspaceTab>) => void;
  123. }
  124. // ============================================================================
  125. // 工具函数
  126. // ============================================================================
  127. /** 从路径提取文件夹名作为标签显示名 */
  128. function labelFromPath(path: string): string {
  129. // 兼容 Windows 反斜杠和 Unix 正斜杠
  130. const segments = path.replace(/\\/g, "/").split("/").filter(Boolean);
  131. return segments[segments.length - 1] ?? path;
  132. }
  133. function createWorkspaceTab(
  134. workspacePath: string,
  135. options?: WorkspaceTabOptions,
  136. ): WorkspaceTabState {
  137. return {
  138. id: createUuid(),
  139. kind: "workspace",
  140. workspacePath,
  141. label: labelFromPath(workspacePath),
  142. availability: options?.availability,
  143. remoteSessionId: options?.remoteSessionId,
  144. remoteTarget: options?.remoteTarget,
  145. workspaceIdentity: options?.workspaceIdentity,
  146. localWorkspacePath: options?.localWorkspacePath,
  147. workspacePurpose: options?.workspacePurpose,
  148. };
  149. }
  150. function mergeWorkspaceTabOptions(
  151. tab: WorkspaceTabState,
  152. options?: WorkspaceTabOptions,
  153. ): WorkspaceTabState {
  154. return {
  155. ...tab,
  156. availability: options?.availability ?? tab.availability,
  157. remoteSessionId: options?.remoteSessionId ?? tab.remoteSessionId,
  158. remoteTarget: options?.remoteTarget ?? tab.remoteTarget,
  159. remoteHistoryId: options?.remoteHistoryId ?? tab.remoteHistoryId,
  160. workspaceIdentity: options?.workspaceIdentity ?? tab.workspaceIdentity,
  161. localWorkspacePath: options?.localWorkspacePath ?? tab.localWorkspacePath,
  162. workspacePurpose: options?.workspacePurpose ?? tab.workspacePurpose,
  163. };
  164. }
  165. function normalizeRestorableWorkspaceTab(
  166. tab: string | RestorableWorkspaceTab,
  167. ): RestorableWorkspaceTab {
  168. if (typeof tab === "string") {
  169. return {
  170. workspacePath: tab,
  171. };
  172. }
  173. return tab;
  174. }
  175. function createSettingsTab(): SettingsTabState {
  176. return {
  177. id: SETTINGS_TAB_ID,
  178. kind: "settings",
  179. label: "settings",
  180. };
  181. }
  182. function moveItem<T>(items: readonly T[], fromIndex: number, toIndex: number): T[] {
  183. const nextItems = [...items];
  184. const [movedItem] = nextItems.splice(fromIndex, 1);
  185. if (!movedItem) {
  186. return nextItems;
  187. }
  188. nextItems.splice(toIndex, 0, movedItem);
  189. return nextItems;
  190. }
  191. function ensureWorkspaceExpanded(
  192. expandedWorkspacePaths: Set<string>,
  193. workspacePath: string,
  194. ): Set<string> {
  195. if (expandedWorkspacePaths.has(workspacePath)) {
  196. return expandedWorkspacePaths;
  197. }
  198. const next = new Set(expandedWorkspacePaths);
  199. next.add(workspacePath);
  200. return next;
  201. }
  202. function pruneExpandedWorkspace(
  203. expandedWorkspacePaths: Set<string>,
  204. workspacePath: string,
  205. ): Set<string> {
  206. if (!expandedWorkspacePaths.has(workspacePath)) {
  207. return expandedWorkspacePaths;
  208. }
  209. const next = new Set(expandedWorkspacePaths);
  210. next.delete(workspacePath);
  211. return next;
  212. }
  213. // ============================================================================
  214. // Store 创建
  215. // ============================================================================
  216. interface StorageLike {
  217. getItem(key: string): string | null;
  218. setItem(key: string, value: string): void;
  219. }
  220. export function createTabStore(storage: StorageLike | null | undefined = undefined) {
  221. return create<TabStoreState>()((set, get) => ({
  222. tabs: [],
  223. activeTabId: null,
  224. activeWorkspacePath: null,
  225. activeWorkspaceIdentity: null,
  226. expandedWorkspacePaths: new Set<string>(),
  227. addTab: (workspacePath: string, options) => {
  228. // 之前复用 tab 只按 workspacePath + history/session 片段判断,
  229. // 同路径不同远端(例如 10.0.0.1:/home/dev 与 10.0.0.2:/home/dev)会被当成一个 tab。
  230. // 这里优先按 workspaceIdentity(authority + canonicalPath)匹配,路径只作为最后兜底。
  231. const existing = get().tabs.find(
  232. (tab): tab is WorkspaceTabState =>
  233. isWorkspaceTab(tab) && isSameWorkspaceTab(tab, workspacePath, options),
  234. );
  235. if (existing) {
  236. persistWorkspaceExpandedPreference(existing.workspacePath, true, storage);
  237. set((state) => ({
  238. // 远程 workspace 手动重连成功后会再次走 addTab,
  239. // 但这里之前命中已有 tab 只做激活,不把新的 remoteSessionId 等元数据写回旧 tab。
  240. // 结果 UI 仍然读到“remoteSessionId 还没更新”的旧状态,
  241. // reconnect 按钮就会一直显示,像是还没连上。这里在复用 tab 时同步覆盖远程会话字段。
  242. tabs: state.tabs.map((tab) =>
  243. tab.id !== existing.id || !isWorkspaceTab(tab)
  244. ? tab
  245. : mergeWorkspaceTabOptions(tab, options),
  246. ),
  247. activeTabId: existing.id,
  248. activeWorkspacePath: existing.workspacePath,
  249. // Settings 页的插件管理要按“最近激活 workspace”的 identity 继续命中同一远端。
  250. // 之前这里只保存路径,切到 settings tab 后 identity 会丢失,导致同路径远端隔离失效。
  251. activeWorkspaceIdentity: options?.workspaceIdentity ?? existing.workspaceIdentity ?? null,
  252. expandedWorkspacePaths: ensureWorkspaceExpanded(
  253. state.expandedWorkspacePaths,
  254. existing.workspacePath,
  255. ),
  256. }));
  257. return existing.id;
  258. }
  259. const tab = createWorkspaceTab(workspacePath, options);
  260. persistWorkspaceExpandedPreference(workspacePath, true, storage);
  261. set((state) => ({
  262. // 左侧 workspace 列表现在支持手动排序,但新打开项目仍然默认追加到底部,
  263. // 连续开新项目时最新 workspace 总要滚到下面找,和侧栏“最新上下文优先”的浏览方式不一致。
  264. // 这里改成把新 workspace 插到最前面,让新打开的项目直接出现在列表顶部。
  265. tabs: [tab, ...state.tabs],
  266. activeTabId: tab.id,
  267. activeWorkspacePath: workspacePath,
  268. activeWorkspaceIdentity: tab.workspaceIdentity ?? null,
  269. expandedWorkspacePaths: ensureWorkspaceExpanded(
  270. state.expandedWorkspacePaths,
  271. workspacePath,
  272. ),
  273. }));
  274. return tab.id;
  275. },
  276. ensureWorkspaceTab: (workspacePath: string, options) => {
  277. const existing = get().tabs.find(
  278. (tab): tab is WorkspaceTabState =>
  279. isWorkspaceTab(tab) && isSameWorkspaceTab(tab, workspacePath, options),
  280. );
  281. if (existing) {
  282. persistWorkspaceExpandedPreference(existing.workspacePath, true, storage);
  283. set((state) => ({
  284. tabs: state.tabs.map((tab) =>
  285. tab.id !== existing.id || !isWorkspaceTab(tab)
  286. ? tab
  287. : mergeWorkspaceTabOptions(tab, options),
  288. ),
  289. expandedWorkspacePaths: ensureWorkspaceExpanded(
  290. state.expandedWorkspacePaths,
  291. existing.workspacePath,
  292. ),
  293. }));
  294. return existing.id;
  295. }
  296. const tab = createWorkspaceTab(workspacePath, options);
  297. persistWorkspaceExpandedPreference(workspacePath, true, storage);
  298. set((state) => ({
  299. // Claude 历史导入可能把任务写入一个“当前窗口从未打开过”的 workspace。
  300. // 任务区只遍历 workspace tabs;如果这里只 bump 任务列表版本而不补 tab,
  301. // 新任务虽然已经持久化成功,侧边栏里仍然没有对应分组可渲染。这里补一个仅确保可见的入口,
  302. // 既让目标 workspace 进入任务区数据源,又不打断用户当前正在看的 tab / settings 上下文。
  303. tabs: [tab, ...state.tabs],
  304. expandedWorkspacePaths: ensureWorkspaceExpanded(
  305. state.expandedWorkspacePaths,
  306. workspacePath,
  307. ),
  308. }));
  309. return tab.id;
  310. },
  311. closeTab: (tabId: TabId) => {
  312. const stateBefore = get();
  313. const { tabs, activeTabId } = stateBefore;
  314. const index = tabs.findIndex((t) => t.id === tabId);
  315. if (index === -1) {
  316. return;
  317. }
  318. const closingTab = tabs[index] ?? null;
  319. const newTabs = tabs.filter((t) => t.id !== tabId);
  320. // 如果关闭的是当前激活的 tab,需要切换到相邻 tab
  321. let newActiveTabId = activeTabId;
  322. if (activeTabId === tabId) {
  323. if (newTabs.length === 0) {
  324. newActiveTabId = null;
  325. } else {
  326. // 优先激活右边的 tab,如果是最后一个则激活左边
  327. const newIndex = Math.min(index, newTabs.length - 1);
  328. newActiveTabId = newTabs[newIndex]!.id;
  329. }
  330. }
  331. const nextWorkspaceTab = newTabs.find((tab) => tab.id === newActiveTabId);
  332. const fallbackWorkspacePath = (() => {
  333. if (nextWorkspaceTab && isWorkspaceTab(nextWorkspaceTab)) {
  334. return nextWorkspaceTab.workspacePath;
  335. }
  336. if (closingTab && isWorkspaceTab(closingTab)) {
  337. const replacementWorkspace = newTabs.find(isWorkspaceTab);
  338. return replacementWorkspace?.workspacePath ?? null;
  339. }
  340. return stateBefore.activeWorkspacePath;
  341. })();
  342. const fallbackWorkspaceIdentity = (() => {
  343. if (nextWorkspaceTab && isWorkspaceTab(nextWorkspaceTab)) {
  344. return nextWorkspaceTab.workspaceIdentity ?? null;
  345. }
  346. if (closingTab && isWorkspaceTab(closingTab)) {
  347. const replacementWorkspace = newTabs.find(isWorkspaceTab);
  348. return replacementWorkspace?.workspaceIdentity ?? null;
  349. }
  350. return stateBefore.activeWorkspaceIdentity;
  351. })();
  352. const nextState = {
  353. tabs: newTabs,
  354. activeTabId: newActiveTabId,
  355. activeWorkspacePath: fallbackWorkspacePath,
  356. activeWorkspaceIdentity: fallbackWorkspaceIdentity,
  357. expandedWorkspacePaths: (() => {
  358. const prunedExpandedWorkspacePaths =
  359. closingTab && isWorkspaceTab(closingTab)
  360. ? pruneExpandedWorkspace(stateBefore.expandedWorkspacePaths, closingTab.workspacePath)
  361. : stateBefore.expandedWorkspacePaths;
  362. // 关闭当前 workspace 后,主内容会自动切到相邻 tab。
  363. // 之前侧边栏把展开态放在组件本地状态时,会在 workspacePath 变化后顺手把接替项展开;
  364. // 现在改由 store 托管后,这个兜底也要一起搬过来,否则“关闭当前 tab”会留下一个已激活但折叠的 workspace。
  365. return fallbackWorkspacePath
  366. ? ensureWorkspaceExpanded(prunedExpandedWorkspacePaths, fallbackWorkspacePath)
  367. : prunedExpandedWorkspacePaths;
  368. })(),
  369. };
  370. if (fallbackWorkspacePath) {
  371. persistWorkspaceExpandedPreference(fallbackWorkspacePath, true, storage);
  372. }
  373. set(nextState);
  374. },
  375. activateTab: (tabId: TabId) => {
  376. const stateBefore = get();
  377. const tab = stateBefore.tabs.find((t) => t.id === tabId);
  378. if (!tab) {
  379. return;
  380. }
  381. const nextState = {
  382. activeTabId: tabId,
  383. activeWorkspacePath: isWorkspaceTab(tab)
  384. ? tab.workspacePath
  385. : stateBefore.activeWorkspacePath,
  386. activeWorkspaceIdentity: isWorkspaceTab(tab)
  387. ? (tab.workspaceIdentity ?? null)
  388. : stateBefore.activeWorkspaceIdentity,
  389. expandedWorkspacePaths: isWorkspaceTab(tab)
  390. ? ensureWorkspaceExpanded(stateBefore.expandedWorkspacePaths, tab.workspacePath)
  391. : stateBefore.expandedWorkspacePaths,
  392. };
  393. if (isWorkspaceTab(tab)) {
  394. persistWorkspaceExpandedPreference(tab.workspacePath, true, storage);
  395. }
  396. set(nextState);
  397. },
  398. reorderTabs: (fromIndex: number, toIndex: number) => {
  399. set((state) => {
  400. if (
  401. fromIndex < 0 ||
  402. toIndex < 0 ||
  403. fromIndex >= state.tabs.length ||
  404. toIndex >= state.tabs.length ||
  405. fromIndex === toIndex
  406. ) {
  407. return state;
  408. }
  409. const newTabs = moveItem(state.tabs, fromIndex, toIndex);
  410. return { tabs: newTabs };
  411. });
  412. },
  413. reorderWorkspaceTabs: (fromIndex: number, toIndex: number) => {
  414. set((state) => {
  415. const workspaceTabs = state.tabs.filter(isWorkspaceTab);
  416. if (
  417. fromIndex < 0 ||
  418. toIndex < 0 ||
  419. fromIndex >= workspaceTabs.length ||
  420. toIndex >= workspaceTabs.length ||
  421. fromIndex === toIndex
  422. ) {
  423. return state;
  424. }
  425. const reorderedWorkspaceTabs = moveItem(workspaceTabs, fromIndex, toIndex);
  426. let workspaceIndex = 0;
  427. const newTabs = state.tabs.map((tab) => {
  428. if (!isWorkspaceTab(tab)) {
  429. return tab;
  430. }
  431. return reorderedWorkspaceTabs[workspaceIndex++] ?? tab;
  432. });
  433. return { tabs: newTabs };
  434. });
  435. },
  436. openSettingsTab: () => {
  437. const existing = get().tabs.find(isSettingsTab);
  438. if (existing) {
  439. set({ activeTabId: existing.id });
  440. return;
  441. }
  442. const settingsTab = createSettingsTab();
  443. set((state) => ({
  444. tabs: [...state.tabs, settingsTab],
  445. activeTabId: settingsTab.id,
  446. }));
  447. },
  448. toggleWorkspaceExpanded: (path: string) => {
  449. set((state) => {
  450. const expandedWorkspacePaths = new Set(state.expandedWorkspacePaths);
  451. const nextExpanded = !expandedWorkspacePaths.has(path);
  452. if (expandedWorkspacePaths.has(path)) {
  453. expandedWorkspacePaths.delete(path);
  454. } else {
  455. expandedWorkspacePaths.add(path);
  456. }
  457. persistWorkspaceExpandedPreference(path, nextExpanded, storage);
  458. return { expandedWorkspacePaths };
  459. });
  460. },
  461. expandAllWorkspaceTabs: (paths: string[]) => {
  462. set((state) => {
  463. const expandedWorkspacePaths = new Set(state.expandedWorkspacePaths);
  464. for (const path of paths) {
  465. expandedWorkspacePaths.add(path);
  466. persistWorkspaceExpandedPreference(path, true, storage);
  467. }
  468. return { expandedWorkspacePaths };
  469. });
  470. },
  471. collapseAllWorkspaceTabs: (paths: string[]) => {
  472. set((state) => {
  473. const expandedWorkspacePaths = new Set(state.expandedWorkspacePaths);
  474. for (const path of paths) {
  475. expandedWorkspacePaths.delete(path);
  476. persistWorkspaceExpandedPreference(path, false, storage);
  477. }
  478. return { expandedWorkspacePaths };
  479. });
  480. },
  481. activateTabByPath: (path: string, options) => {
  482. const stateBefore = get();
  483. const tab = stateBefore.tabs.find((currentTab): currentTab is WorkspaceTabState => {
  484. if (!isWorkspaceTab(currentTab) || currentTab.workspacePath !== path) {
  485. return false;
  486. }
  487. if (options?.workspaceIdentity) {
  488. return currentTab.workspaceIdentity === options.workspaceIdentity;
  489. }
  490. return true;
  491. });
  492. if (!tab) {
  493. return false;
  494. }
  495. const nextState = {
  496. activeTabId: tab.id,
  497. activeWorkspacePath: path,
  498. activeWorkspaceIdentity: tab.workspaceIdentity ?? null,
  499. expandedWorkspacePaths: ensureWorkspaceExpanded(stateBefore.expandedWorkspacePaths, path),
  500. };
  501. persistWorkspaceExpandedPreference(path, true, storage);
  502. set(nextState);
  503. return true;
  504. },
  505. restoreTabs: (tabsInput, activeIndex: number) => {
  506. if (tabsInput.length === 0) return;
  507. const tabs = tabsInput.map((tab) => {
  508. const normalized = normalizeRestorableWorkspaceTab(tab);
  509. return createWorkspaceTab(normalized.workspacePath, {
  510. remoteSessionId: normalized.remoteSessionId,
  511. remoteTarget: normalized.remoteTarget,
  512. workspaceIdentity: normalized.workspaceIdentity,
  513. workspacePurpose: normalized.workspacePurpose,
  514. availability: normalized.availability,
  515. });
  516. });
  517. const safeIndex = Math.min(Math.max(activeIndex, 0), tabs.length - 1);
  518. const activeWorkspaceTab = tabs[safeIndex];
  519. if (!activeWorkspaceTab || !isWorkspaceTab(activeWorkspaceTab)) {
  520. return;
  521. }
  522. const expansionState: WorkspaceExpansionState = readWorkspaceExpansionState(storage);
  523. set({
  524. tabs,
  525. activeTabId: activeWorkspaceTab.id,
  526. activeWorkspacePath: activeWorkspaceTab.workspacePath,
  527. activeWorkspaceIdentity: activeWorkspaceTab.workspaceIdentity ?? null,
  528. expandedWorkspacePaths: resolveExpandedWorkspacePaths(
  529. tabs.map((tab) => tab.workspacePath),
  530. expansionState,
  531. ),
  532. });
  533. },
  534. completeTabRestore: (tabsInput) => {
  535. if (tabsInput.length === 0) return;
  536. set((state) => {
  537. const consumedTabIds = new Set<TabId>();
  538. const completedTabs = tabsInput.map((tabInput) => {
  539. const normalized = normalizeRestorableWorkspaceTab(tabInput);
  540. const options: WorkspaceTabOptions = {
  541. remoteSessionId: normalized.remoteSessionId,
  542. remoteTarget: normalized.remoteTarget,
  543. workspaceIdentity: normalized.workspaceIdentity,
  544. localWorkspacePath: normalized.localWorkspacePath,
  545. workspacePurpose: normalized.workspacePurpose,
  546. availability: normalized.availability,
  547. };
  548. const existing = state.tabs.find(
  549. (tab): tab is WorkspaceTabState =>
  550. isWorkspaceTab(tab) &&
  551. !consumedTabIds.has(tab.id) &&
  552. isSameWorkspaceTab(tab, normalized.workspacePath, options),
  553. );
  554. if (existing) {
  555. consumedTabIds.add(existing.id);
  556. return mergeWorkspaceTabOptions(existing, options);
  557. }
  558. return createWorkspaceTab(normalized.workspacePath, options);
  559. });
  560. const extraWorkspaceTabs = state.tabs.filter(
  561. (tab): tab is WorkspaceTabState => isWorkspaceTab(tab) && !consumedTabIds.has(tab.id),
  562. );
  563. const nonWorkspaceTabs = state.tabs.filter((tab) => !isWorkspaceTab(tab));
  564. const tabs = [...extraWorkspaceTabs, ...completedTabs, ...nonWorkspaceTabs];
  565. const expansionState = readWorkspaceExpansionState(storage);
  566. // active-first 的第二阶段若再次调用 restoreTabs,会重建 active tab id,
  567. // 让已经挂载的会话视图丢失 identity;用户在首帧后新开的 tab 也会被覆盖。
  568. // 补齐阶段只合并缺失 tab,明确保留当前焦点和 active workspace 投影。
  569. return {
  570. tabs,
  571. activeTabId: state.activeTabId,
  572. activeWorkspacePath: state.activeWorkspacePath,
  573. activeWorkspaceIdentity: state.activeWorkspaceIdentity,
  574. expandedWorkspacePaths: resolveExpandedWorkspacePaths(
  575. tabs.filter(isWorkspaceTab).map((tab) => tab.workspacePath),
  576. expansionState,
  577. ),
  578. };
  579. });
  580. },
  581. }));
  582. }
  583. export type TabStore = ReturnType<typeof createTabStore>;