Skip to content

🤯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.

🐛 fix(desktop): isolate tabbar data by scope (#16224)

Innei260f9ef1c29c
diff --git a/src/features/Electron/navigation/tabNavigation.test.ts b/src/features/Electron/navigation/tabNavigation.test.ts
index 30552e93cd2..c181acb28ef 100644
--- a/src/features/Electron/navigation/tabNavigation.test.ts
+++ b/src/features/Electron/navigation/tabNavigation.test.ts
@@ -1,6 +1,5 @@
import { describe, expect, it } from 'vitest';
-import { resolveTabScope } from '@/features/Electron/titlebar/TabBar/scope';
import { type TabItem } from '@/features/Electron/titlebar/TabBar/types';
import { resolveTabNavigationAction } from './tabNavigation';
@@ -8,32 +7,21 @@ import { resolveTabNavigationAction } from './tabNavigation';
const tab = (id: string, url: string): TabItem => ({
id,
lastVisited: 1,
- scope: resolveTabScope(url),
url,
});
describe('resolveTabNavigationAction', () => {
- it('opens a new tab when navigation crosses from personal to workspace scope', () => {
+ it('adds a tab when the active bucket has no active tab', () => {
expect(
resolveTabNavigationAction({
- activeTabId: 'personal',
- currentUrl: '/acme/agent/workspace-agent',
- tabs: [tab('personal', '/agent/personal-agent')],
- }),
- ).toEqual({ type: 'add', url: '/acme/agent/workspace-agent' });
- });
-
- it('opens a new tab when navigation crosses from workspace to personal scope', () => {
- expect(
- resolveTabNavigationAction({
- activeTabId: 'workspace',
+ activeTabId: null,
currentUrl: '/agent/personal-agent',
- tabs: [tab('workspace', '/acme/agent/workspace-agent')],
+ tabs: [],
}),
).toEqual({ type: 'add', url: '/agent/personal-agent' });
});
- it('updates the active tab for same-scope navigation', () => {
+ it('updates the active tab when the current bucket has no matching target', () => {
expect(
resolveTabNavigationAction({
activeTabId: 'workspace',
@@ -43,7 +31,7 @@ describe('resolveTabNavigationAction', () => {
).toEqual({ id: 'workspace', type: 'update', url: '/acme/group/g1' });
});
- it('activates an existing tab with the same scoped target', () => {
+ it('activates an existing tab with the same target inside the active bucket', () => {
expect(
resolveTabNavigationAction({
activeTabId: 'personal',
diff --git a/src/features/Electron/navigation/tabNavigation.ts b/src/features/Electron/navigation/tabNavigation.ts
index fe4ba29133a..ee864202d71 100644
--- a/src/features/Electron/navigation/tabNavigation.ts
+++ b/src/features/Electron/navigation/tabNavigation.ts
@@ -1,9 +1,4 @@
-import {
- isSameTabScope,
- isSameTabTarget,
- normalizeTabScope,
- resolveTabScope,
-} from '@/features/Electron/titlebar/TabBar/scope';
+import { isSameTabTarget } from '@/features/Electron/titlebar/TabBar/scope';
import { type TabItem } from '@/features/Electron/titlebar/TabBar/types';
export type TabNavigationAction =
@@ -35,22 +30,18 @@ export const resolveTabNavigationAction = ({
currentUrl,
tabs,
}: ResolveTabNavigationActionInput): TabNavigationAction => {
- const currentScope = resolveTabScope(currentUrl);
const activeTab = activeTabId ? tabs.find((t) => t.id === activeTabId) : null;
- if (activeTab && isSameTabTarget(activeTab, currentUrl, currentScope)) {
+ if (activeTab && isSameTabTarget(activeTab, currentUrl)) {
return activeTab.url === currentUrl
? { type: 'none' }
: { id: activeTab.id, type: 'update', url: currentUrl };
}
- const existing = tabs.find((t) => isSameTabTarget(t, currentUrl, currentScope));
+ const existing = tabs.find((t) => isSameTabTarget(t, currentUrl));
if (existing) return { id: existing.id, type: 'activate' };
if (!activeTab) return { type: 'add', url: currentUrl };
- const activeScope = normalizeTabScope(activeTab.scope, activeTab.url);
- if (!isSameTabScope(activeScope, currentScope)) return { type: 'add', url: currentUrl };
-
return { id: activeTab.id, type: 'update', url: currentUrl };
};
diff --git a/src/features/Electron/navigation/useTabNavigation.ts b/src/features/Electron/navigation/useTabNavigation.ts
index bb7620ee78d..ebacbf7d269 100644
--- a/src/features/Electron/navigation/useTabNavigation.ts
+++ b/src/features/Electron/navigation/useTabNavigation.ts
@@ -3,7 +3,7 @@
import { useEffect, useRef } from 'react';
import { useLocation } from 'react-router';
-import { isSameTabTarget } from '@/features/Electron/titlebar/TabBar/scope';
+import { isSameTabTarget, resolveTabScopeKey } from '@/features/Electron/titlebar/TabBar/scope';
import { useElectronStore } from '@/store/electron';
import { resolveTabNavigationAction } from './tabNavigation';
@@ -20,18 +20,16 @@ export const useTabNavigation = () => {
const currentRouteMetaUrl = useElectronStore((s) => s.currentRouteMetaUrl);
const prevLocationRef = useRef<string | null>(null);
- const loadedRef = useRef(false);
-
- useEffect(() => {
- if (!loadedRef.current) {
- loadTabs();
- loadedRef.current = true;
- }
- }, [loadTabs]);
+ const loadedScopeKeyRef = useRef<string | null>(null);
useEffect(() => {
const currentUrl = location.pathname + location.search;
+ const currentScopeKey = resolveTabScopeKey(currentUrl);
+ if (loadedScopeKeyRef.current !== currentScopeKey) {
+ loadTabs(currentUrl);
+ loadedScopeKeyRef.current = currentScopeKey;
+ }
if (prevLocationRef.current === currentUrl) return;
prevLocationRef.current = currentUrl;
@@ -52,7 +50,7 @@ export const useTabNavigation = () => {
break;
}
}
- }, [location.pathname, location.search, activateTab, addTab, updateTab]);
+ }, [location.pathname, location.search, activateTab, addTab, updateTab, loadTabs]);
useEffect(() => {
if (!currentRouteMeta || !currentRouteMetaUrl) return;
diff --git a/src/features/Electron/titlebar/RecentlyViewed/index.tsx b/src/features/Electron/titlebar/RecentlyViewed/index.tsx
index 4d9e95de427..a77dff0f01e 100644
--- a/src/features/Electron/titlebar/RecentlyViewed/index.tsx
+++ b/src/features/Electron/titlebar/RecentlyViewed/index.tsx
@@ -3,6 +3,7 @@
import { Flexbox } from '@lobehub/ui';
import { memo, useEffect } from 'react';
import { useTranslation } from 'react-i18next';
+import { useLocation } from 'react-router';
import { useElectronStore } from '@/store/electron';
@@ -16,6 +17,7 @@ interface RecentlyViewedProps {
const RecentlyViewed = memo<RecentlyViewedProps>(({ onClose }) => {
const { t } = useTranslation('electron');
+ const location = useLocation();
const styles = useStyles;
const loadPinnedPages = useElectronStore((s) => s.loadPinnedPages);
@@ -23,8 +25,8 @@ const RecentlyViewed = memo<RecentlyViewedProps>(({ onClose }) => {
const { pinnedPages, recentPages } = useResolvedPages();
useEffect(() => {
- loadPinnedPages();
- }, [loadPinnedPages]);
+ loadPinnedPages(location.pathname + location.search);
+ }, [loadPinnedPages, location.pathname, location.search]);
const isEmpty = pinnedPages.length === 0 && recentPages.length === 0;
diff --git a/src/features/Electron/titlebar/RecentlyViewed/storage.ts b/src/features/Electron/titlebar/RecentlyViewed/storage.ts
index 275e1caf395..1ccb88d3ff1 100644
--- a/src/features/Electron/titlebar/RecentlyViewed/storage.ts
+++ b/src/features/Electron/titlebar/RecentlyViewed/storage.ts
@@ -1,7 +1,11 @@
-import { normalizeTabScope } from '../TabBar/scope';
+import { type TabScope, tabScopeKey } from '../TabBar/scope';
import { type TabItem } from '../TabBar/types';
-export const PINNED_PAGES_STORAGE_KEY = 'lobechat:desktop:pinned-pages:v3';
+export const PINNED_PAGES_STORAGE_KEY_V3 = 'lobechat:desktop:pinned-pages:v3';
+export const PINNED_PAGES_STORAGE_KEY_PREFIX = 'lobechat:desktop:pinned-pages:v4';
+
+export const pinnedPagesStorageKey = (scope: TabScope): string =>
+ `${PINNED_PAGES_STORAGE_KEY_PREFIX}:${tabScopeKey(scope)}`;
const isTabItem = (item: unknown): item is TabItem =>
!!item &&
@@ -10,49 +14,38 @@ const isTabItem = (item: unknown): item is TabItem =>
typeof (item as TabItem).url === 'string' &&
typeof (item as TabItem).lastVisited === 'number';
-const reviveTabItem = (item: unknown): TabItem | null => {
- if (!isTabItem(item)) return null;
-
- return {
- ...item,
- scope: normalizeTabScope((item as Partial<TabItem>).scope, item.url),
- };
-};
-
-const isRevivedTabItem = (item: TabItem | null): item is TabItem => !!item;
-
-export const getPinnedPages = (): TabItem[] => {
+export const getPinnedPages = (scope: TabScope): TabItem[] => {
if (typeof window === 'undefined') return [];
try {
- const data = window.localStorage.getItem(PINNED_PAGES_STORAGE_KEY);
+ const data = window.localStorage.getItem(pinnedPagesStorageKey(scope));
if (!data) return [];
const parsed = JSON.parse(data);
if (!Array.isArray(parsed)) return [];
- return parsed.map(reviveTabItem).filter(isRevivedTabItem);
+ return parsed.filter(isTabItem);
} catch {
return [];
}
};
-export const savePinnedPages = (pages: TabItem[]): boolean => {
+export const savePinnedPages = (scope: TabScope, pages: TabItem[]): boolean => {
if (typeof window === 'undefined') return false;
try {
- window.localStorage.setItem(PINNED_PAGES_STORAGE_KEY, JSON.stringify(pages));
+ window.localStorage.setItem(pinnedPagesStorageKey(scope), JSON.stringify(pages));
return true;
} catch {
return false;
}
};
-export const clearPinnedPages = (): boolean => {
+export const clearPinnedPages = (scope: TabScope): boolean => {
if (typeof window === 'undefined') return false;
try {
- window.localStorage.removeItem(PINNED_PAGES_STORAGE_KEY);
+ window.localStorage.removeItem(pinnedPagesStorageKey(scope));
return true;
} catch {
return false;
diff --git a/src/features/Electron/titlebar/TabBar/TabCacheBridges.test.tsx b/src/features/Electron/titlebar/TabBar/TabCacheBridges.test.tsx
index ff3ea91290f..54a31d66851 100644
--- a/src/features/Electron/titlebar/TabBar/TabCacheBridges.test.tsx
+++ b/src/features/Electron/titlebar/TabBar/TabCacheBridges.test.tsx
@@ -5,7 +5,6 @@ import { afterEach, describe, expect, it, vi } from 'vitest';
import { type DynamicRouteMeta, type RouteMeta } from '@/spa/router/routeMeta';
-import { resolveTabScope } from './scope';
import TabCacheBridges from './TabCacheBridges';
import { type TabItem } from './types';
@@ -72,7 +71,6 @@ const buildRoutes = (): RouteObject[] => [
const tab = (url: string): TabItem => ({
id: url,
lastVisited: 1,
- scope: resolveTabScope(url),
url,
});
diff --git a/src/features/Electron/titlebar/TabBar/resolveTab.test.ts b/src/features/Electron/titlebar/TabBar/resolveTab.test.ts
index bfb0fa669c6..1a0985244b2 100644
--- a/src/features/Electron/titlebar/TabBar/resolveTab.test.ts
+++ b/src/features/Electron/titlebar/TabBar/resolveTab.test.ts
@@ -5,7 +5,6 @@ import { describe, expect, it } from 'vitest';
import { type RouteMeta } from '@/spa/router/routeMeta';
import { resolveTab } from './hooks/useResolvedTabs';
-import { resolveTabScope } from './scope';
import { type TabItem } from './types';
const agentMeta: RouteMeta = { icon: MessageSquare, titleKey: 'navigation.chat' };
@@ -23,7 +22,6 @@ const tab = (url: string, cached?: TabItem['cached']): TabItem => ({
cached,
id: url,
lastVisited: 1,
- scope: resolveTabScope(url),
url,
});
diff --git a/src/features/Electron/titlebar/TabBar/scope.test.ts b/src/features/Electron/titlebar/TabBar/scope.test.ts
index 750f7b62dea..ba3c55f289a 100644
--- a/src/features/Electron/titlebar/TabBar/scope.test.ts
+++ b/src/features/Electron/titlebar/TabBar/scope.test.ts
@@ -26,17 +26,10 @@ describe('desktop tab scope', () => {
});
});
- it('requires both normalized URL and scope to match', () => {
- expect(
- isSameTabTarget({ scope: { type: 'personal' }, url: '/agent/a?b=2&a=1' }, '/agent/a?a=1&b=2'),
- ).toBe(true);
+ it('matches tab targets by normalized URL inside the active scope bucket', () => {
+ expect(isSameTabTarget({ url: '/agent/a?b=2&a=1' }, '/agent/a?a=1&b=2')).toBe(true);
- expect(
- isSameTabTarget(
- { scope: { slug: 'acme', type: 'workspace' }, url: '/acme/agent/a' },
- '/beta/agent/a',
- ),
- ).toBe(false);
+ expect(isSameTabTarget({ url: '/acme/agent/a' }, '/beta/agent/a')).toBe(false);
});
it('keeps the historical recent/pinned id as the normalized URL', () => {
diff --git a/src/features/Electron/titlebar/TabBar/scope.ts b/src/features/Electron/titlebar/TabBar/scope.ts
index 1e941005aae..b08c625a99d 100644
--- a/src/features/Electron/titlebar/TabBar/scope.ts
+++ b/src/features/Electron/titlebar/TabBar/scope.ts
@@ -51,6 +51,11 @@ export const resolveTabScope = (url: string): TabScope => {
return { slug: firstSegment, type: 'workspace' };
};
+export const tabScopeKey = (scope: TabScope): string =>
+ scope.type === 'personal' ? 'personal' : `workspace:${encodeURIComponent(scope.slug)}`;
+
+export const resolveTabScopeKey = (url: string): string => tabScopeKey(resolveTabScope(url));
+
export const normalizeTabScope = (scope: unknown, url: string): TabScope => {
if (!scope || typeof scope !== 'object') return resolveTabScope(url);
@@ -73,12 +78,7 @@ export const isSameTabScope = (a: TabScope, b: TabScope): boolean => {
return a.type === 'personal' || a.slug === (b as Extract<TabScope, { type: 'workspace' }>).slug;
};
-export const isSameTabTarget = (
- target: ScopedTabTarget,
- url: string,
- scope: TabScope = resolveTabScope(url),
-): boolean =>
- normalizeTabUrl(target.url) === normalizeTabUrl(url) &&
- isSameTabScope(normalizeTabScope(target.scope, target.url), scope);
+export const isSameTabTarget = (target: ScopedTabTarget, url: string): boolean =>
+ normalizeTabUrl(target.url) === normalizeTabUrl(url);
export const tabTargetId = (url: string): string => normalizeTabUrl(url);
diff --git a/src/features/Electron/titlebar/TabBar/storage.test.ts b/src/features/Electron/titlebar/TabBar/storage.test.ts
index b101af718a0..2141ca41b43 100644
--- a/src/features/Electron/titlebar/TabBar/storage.test.ts
+++ b/src/features/Electron/titlebar/TabBar/storage.test.ts
@@ -1,13 +1,16 @@
import { afterEach, beforeEach, describe, expect, it } from 'vitest';
-import { resolveTabScope } from './scope';
import {
getTabPages,
saveTabPages,
- TAB_PAGES_STORAGE_KEY,
TAB_PAGES_STORAGE_KEY_V1,
+ TAB_PAGES_STORAGE_KEY_V2,
+ tabPagesStorageKey,
} from './storage';
+const personalScope = { type: 'personal' } as const;
+const acmeScope = { slug: 'acme', type: 'workspace' } as const;
+
describe('TabBar storage', () => {
beforeEach(() => {
window.localStorage.clear();
@@ -17,130 +20,60 @@ describe('TabBar storage', () => {
window.localStorage.clear();
});
- it('returns empty when nothing is stored', () => {
- expect(getTabPages()).toEqual({ activeTabId: null, tabs: [] });
+ it('returns empty scoped data when nothing is stored', () => {
+ expect(getTabPages(personalScope)).toEqual({ activeTabId: null, tabs: [] });
+ expect(getTabPages(acmeScope)).toEqual({ activeTabId: null, tabs: [] });
});
- it('round-trips v2 tab items', () => {
+ it('round-trips personal and workspace tab buckets independently', () => {
+ saveTabPages(
+ personalScope,
+ [{ id: 'personal-tab', lastVisited: 1, url: '/agent/abc' }],
+ 'personal-tab',
+ );
saveTabPages(
- [
- {
- id: '/agent/abc',
- lastVisited: 1,
- scope: resolveTabScope('/agent/abc'),
- url: '/agent/abc',
- },
- ],
- '/agent/abc',
+ acmeScope,
+ [{ id: 'workspace-tab', lastVisited: 2, url: '/acme/agent/abc' }],
+ 'workspace-tab',
);
- const loaded = getTabPages();
- expect(loaded.tabs).toHaveLength(1);
- expect(loaded.tabs[0].url).toBe('/agent/abc');
- expect(loaded.tabs[0].scope).toEqual({ type: 'personal' });
- expect(loaded.activeTabId).toBe('/agent/abc');
+
+ expect(getTabPages(personalScope)).toEqual({
+ activeTabId: 'personal-tab',
+ tabs: [{ id: 'personal-tab', lastVisited: 1, url: '/agent/abc' }],
+ });
+ expect(getTabPages(acmeScope)).toEqual({
+ activeTabId: 'workspace-tab',
+ tabs: [{ id: 'workspace-tab', lastVisited: 2, url: '/acme/agent/abc' }],
+ });
});
- it('revives old v2 tab items without persisted scope', () => {
+ it('does not read legacy global tab storage keys', () => {
window.localStorage.setItem(
- TAB_PAGES_STORAGE_KEY,
+ TAB_PAGES_STORAGE_KEY_V1,
JSON.stringify({
- activeTabId: '/acme/agent/abc',
- tabs: [{ id: '/acme/agent/abc', lastVisited: 1, url: '/acme/agent/abc' }],
+ activeTabId: 'agent:abc',
+ tabs: [{ id: 'agent:abc', lastVisited: 1, params: { agentId: 'abc' }, type: 'agent' }],
+ }),
+ );
+ window.localStorage.setItem(
+ TAB_PAGES_STORAGE_KEY_V2,
+ JSON.stringify({
+ activeTabId: '/agent/abc',
+ tabs: [{ id: '/agent/abc', lastVisited: 1, url: '/agent/abc' }],
}),
);
- const loaded = getTabPages();
- expect(loaded.tabs[0].scope).toEqual({ slug: 'acme', type: 'workspace' });
+ expect(getTabPages(personalScope)).toEqual({ activeTabId: null, tabs: [] });
});
- describe('v1 -> v2 migration', () => {
- it('reconstructs urls from old type + params', () => {
- window.localStorage.setItem(
- TAB_PAGES_STORAGE_KEY_V1,
- JSON.stringify({
- activeTabId: 'agent:abc',
- tabs: [
- {
- cached: { avatar: 'a.png', title: 'Claude' },
- id: 'agent:abc',
- lastVisited: 10,
- params: { agentId: 'abc' },
- type: 'agent',
- },
- {
- id: 'agent-topic:abc:tpc_1',
- lastVisited: 20,
- params: { agentId: 'abc', topicId: 'tpc_1' },
- type: 'agent-topic',
- },
- {
- id: 'home',
- lastVisited: 5,
- params: {},
- type: 'home',
- },
- ],
- }),
- );
-
- const migrated = getTabPages();
- expect(migrated.tabs.map((t) => t.url)).toEqual(['/agent/abc', '/agent/abc/tpc_1', '/']);
- expect(migrated.tabs.map((t) => t.scope)).toEqual([
- { type: 'personal' },
- { type: 'personal' },
- { type: 'personal' },
- ]);
- expect(migrated.activeTabId).toBe('/agent/abc');
- expect(migrated.tabs[0].cached).toEqual({ avatar: 'a.png', title: 'Claude' });
- });
-
- it('drops tabs whose url cannot be reconstructed', () => {
- window.localStorage.setItem(
- TAB_PAGES_STORAGE_KEY_V1,
- JSON.stringify({
- activeTabId: null,
- tabs: [
- { id: 'agent:', lastVisited: 1, params: {}, type: 'agent' },
- { id: 'mystery', lastVisited: 1, params: {}, type: 'unknown-type' },
- { id: 'home', lastVisited: 1, params: {}, type: 'home' },
- ],
- }),
- );
-
- const migrated = getTabPages();
- expect(migrated.tabs).toHaveLength(1);
- expect(migrated.tabs[0].url).toBe('/');
- });
-
- it('removes the v1 key after migration', () => {
- window.localStorage.setItem(
- TAB_PAGES_STORAGE_KEY_V1,
- JSON.stringify({ activeTabId: null, tabs: [] }),
- );
- getTabPages();
- expect(window.localStorage.getItem(TAB_PAGES_STORAGE_KEY_V1)).toBeNull();
- });
-
- it('does not migrate when v2 data already exists', () => {
- window.localStorage.setItem(
- TAB_PAGES_STORAGE_KEY,
- JSON.stringify({
- activeTabId: '/page/p1',
- tabs: [{ id: '/page/p1', lastVisited: 1, url: '/page/p1' }],
- }),
- );
- window.localStorage.setItem(
- TAB_PAGES_STORAGE_KEY_V1,
- JSON.stringify({
- activeTabId: 'agent:abc',
- tabs: [{ id: 'agent:abc', lastVisited: 1, params: { agentId: 'abc' }, type: 'agent' }],
- }),
- );
+ it('stores workspace buckets under their own key', () => {
+ saveTabPages(
+ acmeScope,
+ [{ id: 'workspace-tab', lastVisited: 1, url: '/acme' }],
+ 'workspace-tab',
+ );
- const loaded = getTabPages();
- expect(loaded.tabs).toHaveLength(1);
- expect(loaded.tabs[0].url).toBe('/page/p1');
- expect(loaded.tabs[0].scope).toEqual({ type: 'personal' });
- });
+ expect(window.localStorage.getItem(tabPagesStorageKey(personalScope))).toBeNull();
+ expect(window.localStorage.getItem(tabPagesStorageKey(acmeScope))).toContain('workspace-tab');
});
});
diff --git a/src/features/Electron/titlebar/TabBar/storage.ts b/src/features/Electron/titlebar/TabBar/storage.ts
index 6fb0fd37278..b3ca7e3812a 100644
--- a/src/features/Electron/titlebar/TabBar/storage.ts
+++ b/src/features/Electron/titlebar/TabBar/storage.ts
@@ -1,19 +1,20 @@
-import { type DynamicRouteMeta } from '@/spa/router/routeMeta';
-
-import { normalizeTabScope } from './scope';
+import { type TabScope, tabScopeKey } from './scope';
import { type TabItem } from './types';
-import { normalizeTabUrl } from './url';
export const TAB_PAGES_STORAGE_KEY_V1 = 'lobechat:desktop:tab-pages:v1';
-export const TAB_PAGES_STORAGE_KEY = 'lobechat:desktop:tab-pages:v2';
+export const TAB_PAGES_STORAGE_KEY_V2 = 'lobechat:desktop:tab-pages:v2';
+export const TAB_PAGES_STORAGE_KEY_PREFIX = 'lobechat:desktop:tab-pages:v3';
-interface TabPagesStorageData {
+export interface TabPagesStorageData {
activeTabId: string | null;
tabs: TabItem[];
}
const EMPTY: TabPagesStorageData = { activeTabId: null, tabs: [] };
+export const tabPagesStorageKey = (scope: TabScope): string =>
+ `${TAB_PAGES_STORAGE_KEY_PREFIX}:${tabScopeKey(scope)}`;
+
const isTabItem = (item: unknown): item is TabItem =>
!!item &&
typeof item === 'object' &&
@@ -21,124 +22,17 @@ const isTabItem = (item: unknown): item is TabItem =>
typeof (item as TabItem).url === 'string' &&
typeof (item as TabItem).lastVisited === 'number';
-const reviveTabItem = (item: unknown): TabItem | null => {
- if (!isTabItem(item)) return null;
-
- return {
- ...item,
- scope: normalizeTabScope((item as Partial<TabItem>).scope, item.url),
- };
-};
-
-const isRevivedTabItem = (item: TabItem | null): item is TabItem => !!item;
-
-const reconstructUrlFromV1 = (type: unknown, params: unknown): string | null => {
- if (typeof type !== 'string' || !params || typeof params !== 'object') return null;
- const p = params as Record<string, string | undefined>;
-
- switch (type) {
- case 'home': {
- return '/';
- }
- case 'agent': {
- return p.agentId ? `/agent/${p.agentId}` : null;
- }
- case 'agent-topic': {
- return p.agentId && p.topicId ? `/agent/${p.agentId}/${p.topicId}` : null;
- }
- case 'group': {
- return p.groupId ? `/group/${p.groupId}` : null;
- }
- case 'group-topic': {
- return p.groupId && p.topicId ? `/group/${p.groupId}?topic=${p.topicId}` : null;
- }
- case 'page': {
- return p.pageId ? `/page/${p.pageId}` : null;
- }
- case 'settings': {
- return p.section ? `/settings/${p.section}` : '/settings';
- }
- case 'community': {
- return p.section ? `/community/${p.section}` : '/community';
- }
- case 'resource': {
- return p.section ? `/resource/${p.section}` : '/resource';
- }
- case 'memory': {
- return p.section ? `/memory/${p.section}` : '/memory';
- }
- case 'image': {
- return '/image';
- }
- default: {
- return null;
- }
- }
-};
-
-const migrateV1 = (): TabPagesStorageData => {
- if (typeof window === 'undefined') return EMPTY;
-
- try {
- const raw = window.localStorage.getItem(TAB_PAGES_STORAGE_KEY_V1);
- if (!raw) return EMPTY;
-
- const parsed = JSON.parse(raw);
- if (!parsed || typeof parsed !== 'object' || !Array.isArray(parsed.tabs)) return EMPTY;
-
- const seen = new Set<string>();
- const tabs: TabItem[] = [];
- let activeTabId: string | null = null;
-
- for (const old of parsed.tabs) {
- if (!old || typeof old !== 'object') continue;
- const url = reconstructUrlFromV1(old.type, old.params);
- if (!url) continue;
-
- const id = normalizeTabUrl(url);
- if (seen.has(id)) continue;
- seen.add(id);
-
- const cached =
- old.cached && typeof old.cached === 'object' ? (old.cached as DynamicRouteMeta) : undefined;
-
- tabs.push({
- cached,
- id,
- lastVisited: typeof old.lastVisited === 'number' ? old.lastVisited : Date.now(),
- scope: normalizeTabScope(undefined, url),
- url,
- visitCount: typeof old.visitCount === 'number' ? old.visitCount : undefined,
- });
-
- if (old.id === parsed.activeTabId) activeTabId = id;
- }
-
- return { activeTabId, tabs };
- } catch {
- return EMPTY;
- } finally {
- try {
- window.localStorage.removeItem(TAB_PAGES_STORAGE_KEY_V1);
- } catch {
- // ignore
- }
- }
-};
-
-export const getTabPages = (): TabPagesStorageData => {
+export const getTabPages = (scope: TabScope): TabPagesStorageData => {
if (typeof window === 'undefined') return EMPTY;
try {
- const data = window.localStorage.getItem(TAB_PAGES_STORAGE_KEY);
- if (!data) return migrateV1();
+ const data = window.localStorage.getItem(tabPagesStorageKey(scope));
+ if (!data) return EMPTY;
const parsed = JSON.parse(data);
if (!parsed || typeof parsed !== 'object') return EMPTY;
- const tabs = Array.isArray(parsed.tabs)
- ? parsed.tabs.map(reviveTabItem).filter(isRevivedTabItem)
- : [];
+ const tabs = Array.isArray(parsed.tabs) ? parsed.tabs.filter(isTabItem) : [];
return {
activeTabId: typeof parsed.activeTabId === 'string' ? parsed.activeTabId : null,
@@ -149,11 +43,15 @@ export const getTabPages = (): TabPagesStorageData => {
}
};
-export const saveTabPages = (tabs: TabItem[], activeTabId: string | null): boolean => {
+export const saveTabPages = (
+ scope: TabScope,
+ tabs: TabItem[],
+ activeTabId: string | null,
+): boolean => {
if (typeof window === 'undefined') return false;
try {
- window.localStorage.setItem(TAB_PAGES_STORAGE_KEY, JSON.stringify({ activeTabId, tabs }));
+ window.localStorage.setItem(tabPagesStorageKey(scope), JSON.stringify({ activeTabId, tabs }));
return true;
} catch {
return false;
diff --git a/src/features/Electron/titlebar/TabBar/types.ts b/src/features/Electron/titlebar/TabBar/types.ts
index 9abf782dde5..b2cdd3f41ad 100644
--- a/src/features/Electron/titlebar/TabBar/types.ts
+++ b/src/features/Electron/titlebar/TabBar/types.ts
@@ -1,12 +1,9 @@
import { type DynamicRouteMeta } from '@/spa/router/routeMeta';
-import { type TabScope } from './scope';
-
export interface TabItem {
cached?: DynamicRouteMeta;
id: string;
lastVisited: number;
- scope: TabScope;
url: string;
visitCount?: number;
}
diff --git a/src/store/electron/actions/__tests__/recentPages.test.ts b/src/store/electron/actions/__tests__/recentPages.test.ts
index 5c6e5ba3cfc..980dfe65c8d 100644
--- a/src/store/electron/actions/__tests__/recentPages.test.ts
+++ b/src/store/electron/actions/__tests__/recentPages.test.ts
@@ -1,7 +1,7 @@
import { act, renderHook } from '@testing-library/react';
import { beforeEach, describe, expect, it, vi } from 'vitest';
-import { resolveTabScope } from '@/features/Electron/titlebar/TabBar/scope';
+import { PINNED_PAGES_STORAGE_KEY_V3 } from '@/features/Electron/titlebar/RecentlyViewed/storage';
import { type TabItem } from '@/features/Electron/titlebar/TabBar/types';
import { useElectronStore } from '@/store/electron';
import { initialState } from '@/store/electron/initialState';
@@ -14,7 +14,6 @@ const buildTab = (url: string, cached?: TabItem['cached']): TabItem => ({
cached,
id: url,
lastVisited: 1,
- scope: resolveTabScope(url),
url,
});
@@ -22,11 +21,17 @@ describe('recentPages actions', () => {
beforeEach(() => {
vi.clearAllMocks();
window.localStorage.clear();
- useElectronStore.setState({ ...initialState, pinnedPages: [], recentPages: [] });
+ useElectronStore.setState({
+ ...initialState,
+ pinnedPageBuckets: {},
+ pinnedPages: [],
+ recentPageBuckets: {},
+ recentPages: [],
+ });
});
describe('addRecentPage', () => {
- it('keeps personal and workspace URLs as separate recent entries', () => {
+ it('switches between personal and workspace recent buckets', () => {
const { result } = renderHook(() => useElectronStore());
act(() => {
@@ -34,17 +39,18 @@ describe('recentPages actions', () => {
result.current.addRecentPage('/acme/agent/abc');
});
- expect(result.current.recentPages.map((page) => page.id)).toEqual([
- '/acme/agent/abc',
- '/agent/abc',
- ]);
- expect(result.current.recentPages.map((page) => page.scope)).toEqual([
- { slug: 'acme', type: 'workspace' },
- { type: 'personal' },
- ]);
+ expect(result.current.activeRecentScope).toEqual({ slug: 'acme', type: 'workspace' });
+ expect(result.current.recentPages.map((page) => page.id)).toEqual(['/acme/agent/abc']);
+
+ act(() => {
+ result.current.loadPinnedPages('/agent/abc');
+ });
+
+ expect(result.current.activeRecentScope).toEqual({ type: 'personal' });
+ expect(result.current.recentPages.map((page) => page.id)).toEqual(['/agent/abc']);
});
- it('dedupes only within the same normalized workspace URL', () => {
+ it('dedupes within the active workspace bucket', () => {
const { result } = renderHook(() => useElectronStore());
act(() => {
@@ -54,16 +60,12 @@ describe('recentPages actions', () => {
expect(result.current.recentPages).toHaveLength(1);
expect(result.current.recentPages[0].id).toBe('/acme/agent/abc?a=1&b=2');
- expect(result.current.recentPages[0].scope).toEqual({
- slug: 'acme',
- type: 'workspace',
- });
expect(result.current.recentPages[0].visitCount).toBe(2);
});
});
describe('pinPage', () => {
- it('pins personal and workspace URLs independently', () => {
+ it('pins personal and workspace URLs into independent buckets', () => {
const { result } = renderHook(() => useElectronStore());
act(() => {
@@ -71,13 +73,18 @@ describe('recentPages actions', () => {
result.current.pinPage(buildTab('/acme/agent/abc'));
});
- expect(result.current.pinnedPages.map((page) => page.id)).toEqual([
- '/agent/abc',
- '/acme/agent/abc',
- ]);
+ expect(result.current.activeRecentScope).toEqual({ slug: 'acme', type: 'workspace' });
+ expect(result.current.pinnedPages.map((page) => page.id)).toEqual(['/acme/agent/abc']);
+
+ act(() => {
+ result.current.loadPinnedPages('/agent/abc');
+ });
+
+ expect(result.current.activeRecentScope).toEqual({ type: 'personal' });
+ expect(result.current.pinnedPages.map((page) => page.id)).toEqual(['/agent/abc']);
});
- it('removes only the matching scoped recent entry when pinning', () => {
+ it('removes only the matching recent entry from the active bucket when pinning', () => {
const { result } = renderHook(() => useElectronStore());
act(() => {
@@ -87,7 +94,28 @@ describe('recentPages actions', () => {
});
expect(result.current.pinnedPages.map((page) => page.id)).toEqual(['/acme/agent/abc']);
+ expect(result.current.recentPages.map((page) => page.id)).toEqual([]);
+
+ act(() => {
+ result.current.loadPinnedPages('/agent/abc');
+ });
+
+ expect(result.current.pinnedPages.map((page) => page.id)).toEqual([]);
expect(result.current.recentPages.map((page) => page.id)).toEqual(['/agent/abc']);
});
+
+ it('does not load legacy global pinned data', () => {
+ window.localStorage.setItem(
+ PINNED_PAGES_STORAGE_KEY_V3,
+ JSON.stringify([{ id: '/agent/abc', lastVisited: 1, url: '/agent/abc' }]),
+ );
+ const { result } = renderHook(() => useElectronStore());
+
+ act(() => {
+ result.current.loadPinnedPages('/agent/abc');
+ });
+
+ expect(result.current.pinnedPages).toEqual([]);
+ });
});
});
diff --git a/src/store/electron/actions/__tests__/tabPages.test.ts b/src/store/electron/actions/__tests__/tabPages.test.ts
index cb044cbbaf0..31751bea82d 100644
--- a/src/store/electron/actions/__tests__/tabPages.test.ts
+++ b/src/store/electron/actions/__tests__/tabPages.test.ts
@@ -1,7 +1,6 @@
import { act, renderHook } from '@testing-library/react';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
-import { resolveTabScope } from '@/features/Electron/titlebar/TabBar/scope';
import { type TabItem } from '@/features/Electron/titlebar/TabBar/types';
import { useElectronStore } from '@/store/electron';
import { initialState } from '@/store/electron/initialState';
@@ -25,7 +24,6 @@ const buildTab = (url: string, cached?: TabItem['cached']): TabItem => ({
cached,
id: url,
lastVisited: 1,
- scope: resolveTabScope(url),
url,
});
@@ -50,19 +48,28 @@ describe('tabPages actions', () => {
expect(result.current.tabs).toHaveLength(1);
expect(result.current.tabs[0].id).toBe(createdId);
- expect(result.current.tabs[0].scope).toEqual({ type: 'personal' });
expect(result.current.tabs[0].url).toBe('/agent/abc?b=2&a=1');
+ expect(result.current.activeTabScope).toEqual({ type: 'personal' });
expect(result.current.activeTabId).toBe(createdId);
});
- it('records workspace scope on workspace tabs', () => {
+ it('switches the visible tab bucket when the URL moves into a workspace', () => {
const { result } = renderHook(() => useElectronStore());
act(() => {
+ result.current.addTab('/agent/abc');
result.current.addTab('/acme/agent/abc');
});
- expect(result.current.tabs[0].scope).toEqual({ slug: 'acme', type: 'workspace' });
+ expect(result.current.activeTabScope).toEqual({ slug: 'acme', type: 'workspace' });
+ expect(result.current.tabs.map((page) => page.url)).toEqual(['/acme/agent/abc']);
+
+ act(() => {
+ result.current.loadTabs('/agent/abc');
+ });
+
+ expect(result.current.activeTabScope).toEqual({ type: 'personal' });
+ expect(result.current.tabs.map((page) => page.url)).toEqual(['/agent/abc']);
});
it('dedupes tabs that resolve to the same normalized URL', () => {
@@ -122,12 +129,11 @@ describe('tabPages actions', () => {
const updatedTab = result.current.tabs[0];
expect(updatedTab.id).toBe(agentTab.id);
expect(updatedTab.url).toBe('/');
- expect(updatedTab.scope).toEqual({ type: 'personal' });
expect(updatedTab.cached).toBeUndefined();
expect(result.current.activeTabId).toBe(agentTab.id);
});
- it('updates the stored scope when the tab moves into a workspace URL', () => {
+ it('keeps a tab in the current bucket when updateTab receives a workspace URL directly', () => {
const { result } = renderHook(() => useElectronStore());
const agentTab = buildTab('/agent/abc', { title: 'Claude Code' });
@@ -139,7 +145,8 @@ describe('tabPages actions', () => {
result.current.updateTab(agentTab.id, '/acme/agent/abc');
});
- expect(result.current.tabs[0].scope).toEqual({ slug: 'acme', type: 'workspace' });
+ expect(result.current.activeTabScope).toEqual({ type: 'personal' });
+ expect(result.current.tabs[0].url).toBe('/acme/agent/abc');
expect(result.current.tabs[0].cached).toBeUndefined();
});
diff --git a/src/store/electron/actions/recentPages.ts b/src/store/electron/actions/recentPages.ts
index 7682af31cf9..10b163f1b61 100644
--- a/src/store/electron/actions/recentPages.ts
+++ b/src/store/electron/actions/recentPages.ts
@@ -5,8 +5,10 @@ import {
import { guardedMergeCache } from '@/features/Electron/titlebar/TabBar/resolveRouteMeta';
import {
isSameTabTarget,
- normalizeTabScope,
+ PERSONAL_TAB_SCOPE,
resolveTabScope,
+ type TabScope,
+ tabScopeKey,
tabTargetId,
} from '@/features/Electron/titlebar/TabBar/scope';
import { type TabItem } from '@/features/Electron/titlebar/TabBar/types';
@@ -23,14 +25,20 @@ const PINNED_PAGES_LIMIT = 10;
// ======== Types ======== //
export interface RecentPagesState {
+ activeRecentScope: TabScope;
+ pinnedPageBuckets: Record<string, TabItem[]>;
pinnedPages: TabItem[];
+ recentPageBuckets: Record<string, TabItem[]>;
recentPages: TabItem[];
}
// ======== Initial State ======== //
export const recentPagesInitialState: RecentPagesState = {
+ activeRecentScope: PERSONAL_TAB_SCOPE,
+ pinnedPageBuckets: {},
pinnedPages: [],
+ recentPageBuckets: {},
recentPages: [],
};
@@ -51,30 +59,29 @@ export class RecentPagesActionImpl {
}
addRecentPage = (url: string, cached?: DynamicRouteMeta): void => {
+ this.#ensureScopeForUrl(url);
const { pinnedPages, recentPages } = this.#get();
- const scope = resolveTabScope(url);
const id = tabTargetId(url);
- const pinnedIndex = pinnedPages.findIndex((p) => isSameTabTarget(p, url, scope));
+ const pinnedIndex = pinnedPages.findIndex((p) => isSameTabTarget(p, url));
if (pinnedIndex >= 0) {
const merged = guardedMergeCache(pinnedPages[pinnedIndex].cached, cached);
if (merged === pinnedPages[pinnedIndex].cached) return;
const updatedPinned = [...pinnedPages];
updatedPinned[pinnedIndex] = { ...updatedPinned[pinnedIndex], cached: merged };
- this.#set({ pinnedPages: updatedPinned }, false, 'updatePinnedPageCache');
- savePinnedPages(updatedPinned);
+ this.#set(this.#withActivePinned(updatedPinned), false, 'updatePinnedPageCache');
+ this.#savePinned(updatedPinned);
return;
}
- const existingIndex = recentPages.findIndex((p) => isSameTabTarget(p, url, scope));
+ const existingIndex = recentPages.findIndex((p) => isSameTabTarget(p, url));
const existingEntry = existingIndex >= 0 ? recentPages[existingIndex] : null;
const newEntry: TabItem = {
cached: guardedMergeCache(existingEntry?.cached, cached),
id,
lastVisited: Date.now(),
- scope,
url,
visitCount: (existingEntry?.visitCount || 0) + 1,
};
@@ -84,63 +91,61 @@ export class RecentPagesActionImpl {
const newRecent = [newEntry, ...filtered].slice(0, RECENT_PAGES_LIMIT);
- this.#set({ recentPages: newRecent }, false, 'addRecentPage');
+ this.#set(this.#withActiveRecent(newRecent), false, 'addRecentPage');
};
clearRecentPages = (): void => {
- this.#set({ recentPages: [] }, false, 'clearRecentPages');
+ this.#set(this.#withActiveRecent([]), false, 'clearRecentPages');
};
isPagePinned = (id: string): boolean => {
return this.#get().pinnedPages.some((p) => p.id === id);
};
- loadPinnedPages = (): void => {
- const pinned = getPinnedPages();
- const { recentPages } = this.#get();
-
- const filteredRecent = recentPages.filter(
- (recentPage) =>
- !pinned.some((pinnedPage) =>
- isSameTabTarget(
- recentPage,
- pinnedPage.url,
- normalizeTabScope(pinnedPage.scope, pinnedPage.url),
- ),
- ),
- );
-
- this.#set({ pinnedPages: pinned, recentPages: filteredRecent }, false, 'loadPinnedPages');
+ loadPinnedPages = (url?: string): void => {
+ this.#loadScope(url ? resolveTabScope(url) : this.#get().activeTabScope, true);
};
pinPage = (page: TabItem): void => {
+ this.#ensureScopeForUrl(page.url);
const { pinnedPages, recentPages } = this.#get();
- const scope = normalizeTabScope(page.scope, page.url);
const id = tabTargetId(page.url);
- if (pinnedPages.some((p) => isSameTabTarget(p, page.url, scope))) return;
+ if (pinnedPages.some((p) => isSameTabTarget(p, page.url))) return;
if (pinnedPages.length >= PINNED_PAGES_LIMIT) return;
- const existingRecent = recentPages.find((p) => isSameTabTarget(p, page.url, scope));
+ const existingRecent = recentPages.find((p) => isSameTabTarget(p, page.url));
const newEntry: TabItem = {
...page,
cached: page.cached ?? existingRecent?.cached,
id,
lastVisited: Date.now(),
- scope,
};
const newPinned = [...pinnedPages, newEntry];
- const newRecent = recentPages.filter((p) => !isSameTabTarget(p, page.url, scope));
+ const filteredRecent = recentPages.filter(
+ (recentPage) => !isSameTabTarget(recentPage, page.url),
+ );
- this.#set({ pinnedPages: newPinned, recentPages: newRecent }, false, 'pinPage');
- savePinnedPages(newPinned);
+ this.#set(
+ {
+ ...this.#withActivePinned(newPinned),
+ ...this.#withActiveRecent(filteredRecent),
+ },
+ false,
+ 'pinPage',
+ );
+ this.#savePinned(newPinned);
};
removeRecentPage = (id: string): void => {
const { recentPages } = this.#get();
- this.#set({ recentPages: recentPages.filter((p) => p.id !== id) }, false, 'removeRecentPage');
+ this.#set(
+ this.#withActiveRecent(recentPages.filter((p) => p.id !== id)),
+ false,
+ 'removeRecentPage',
+ );
};
unpinPage = (id: string): void => {
@@ -152,8 +157,73 @@ export class RecentPagesActionImpl {
const newPinned = pinnedPages.filter((p) => p.id !== id);
const newRecent = [page, ...recentPages].slice(0, RECENT_PAGES_LIMIT);
- this.#set({ pinnedPages: newPinned, recentPages: newRecent }, false, 'unpinPage');
- savePinnedPages(newPinned);
+ this.#set(
+ {
+ ...this.#withActivePinned(newPinned),
+ ...this.#withActiveRecent(newRecent),
+ },
+ false,
+ 'unpinPage',
+ );
+ this.#savePinned(newPinned);
+ };
+
+ #ensureScopeForUrl = (url: string): void => {
+ this.#loadScope(resolveTabScope(url));
+ };
+
+ #loadScope = (scope: TabScope, force = false): void => {
+ const { activeRecentScope, pinnedPageBuckets, pinnedPages, recentPageBuckets, recentPages } =
+ this.#get();
+ const currentKey = tabScopeKey(activeRecentScope);
+ const nextKey = tabScopeKey(scope);
+ if (!force && currentKey === nextKey) return;
+
+ const nextRecentBuckets = {
+ ...recentPageBuckets,
+ [currentKey]: recentPages,
+ };
+ const nextPinnedBuckets = {
+ ...pinnedPageBuckets,
+ [currentKey]: pinnedPages,
+ };
+
+ const nextPinned = force
+ ? getPinnedPages(scope)
+ : (nextPinnedBuckets[nextKey] ?? getPinnedPages(scope));
+ const nextRecent = nextRecentBuckets[nextKey] ?? [];
+
+ this.#set(
+ {
+ activeRecentScope: scope,
+ pinnedPageBuckets: { ...nextPinnedBuckets, [nextKey]: nextPinned },
+ pinnedPages: nextPinned,
+ recentPageBuckets: { ...nextRecentBuckets, [nextKey]: nextRecent },
+ recentPages: nextRecent,
+ },
+ false,
+ 'loadPinnedPages',
+ );
+ };
+
+ #savePinned = (pages: TabItem[]): void => {
+ savePinnedPages(this.#get().activeRecentScope, pages);
+ };
+
+ #withActivePinned = (pages: TabItem[]) => {
+ const key = tabScopeKey(this.#get().activeRecentScope);
+ return {
+ pinnedPageBuckets: { ...this.#get().pinnedPageBuckets, [key]: pages },
+ pinnedPages: pages,
+ };
+ };
+
+ #withActiveRecent = (pages: TabItem[]) => {
+ const key = tabScopeKey(this.#get().activeRecentScope);
+ return {
+ recentPageBuckets: { ...this.#get().recentPageBuckets, [key]: pages },
+ recentPages: pages,
+ };
};
}
diff --git a/src/store/electron/actions/tabPages.ts b/src/store/electron/actions/tabPages.ts
index 24670b9c6f9..98b95a7c5eb 100644
--- a/src/store/electron/actions/tabPages.ts
+++ b/src/store/electron/actions/tabPages.ts
@@ -2,10 +2,11 @@ import { nanoid } from 'nanoid';
import { guardedMergeCache } from '@/features/Electron/titlebar/TabBar/resolveRouteMeta';
import {
- isSameTabScope,
isSameTabTarget,
- normalizeTabScope,
+ PERSONAL_TAB_SCOPE,
resolveTabScope,
+ type TabScope,
+ tabScopeKey,
} from '@/features/Electron/titlebar/TabBar/scope';
import { getTabPages, saveTabPages } from '@/features/Electron/titlebar/TabBar/storage';
import { type TabItem } from '@/features/Electron/titlebar/TabBar/types';
@@ -21,12 +22,14 @@ const generateTabId = (): string => `tab_${nanoid(8)}`;
export interface TabPagesState {
activeTabId: string | null;
+ activeTabScope: TabScope;
tabs: TabItem[];
}
// ======== Initial State ======== //
export const tabPagesInitialState: TabPagesState = {
+ activeTabScope: PERSONAL_TAB_SCOPE,
activeTabId: null,
tabs: [],
};
@@ -56,9 +59,9 @@ export class TabPagesActionImpl {
};
addTab = (url: string, cached?: DynamicRouteMeta, activate = true): string => {
- const scope = resolveTabScope(url);
+ this.#ensureScopeForUrl(url);
const { tabs } = this.#get();
- const existing = tabs.find((t) => isSameTabTarget(t, url, scope));
+ const existing = tabs.find((t) => isSameTabTarget(t, url));
if (existing) {
if (activate) {
@@ -68,11 +71,12 @@ export class TabPagesActionImpl {
return existing.id;
}
- return this.#createTab(url, cached, activate, scope);
+ return this.#createTab(url, cached, activate);
};
addNewTab = (url: string, cached?: DynamicRouteMeta): string => {
- return this.#createTab(url, cached, true, resolveTabScope(url));
+ this.#ensureScopeForUrl(url);
+ return this.#createTab(url, cached, true);
};
getActiveTab = (): TabItem | null => {
@@ -81,9 +85,8 @@ export class TabPagesActionImpl {
return tabs.find((t) => t.id === activeTabId) ?? null;
};
- loadTabs = (): void => {
- const { tabs, activeTabId } = getTabPages();
- this.#set({ activeTabId, tabs }, false, 'loadTabs');
+ loadTabs = (url = '/'): void => {
+ this.#loadScope(resolveTabScope(url), true);
};
removeTab = (id: string): string | null => {
@@ -162,17 +165,13 @@ export class TabPagesActionImpl {
if (index < 0) return id;
const prev = tabs[index];
- const scope = resolveTabScope(url);
- const previousScope = normalizeTabScope(prev.scope, prev.url);
- const sameTarget =
- normalizeTabUrl(url) === normalizeTabUrl(prev.url) && isSameTabScope(scope, previousScope);
+ const sameTarget = normalizeTabUrl(url) === normalizeTabUrl(prev.url);
const newTabs = [...tabs];
newTabs[index] = {
...prev,
cached: sameTarget ? prev.cached : undefined,
lastVisited: Date.now(),
- scope,
url,
};
@@ -196,19 +195,13 @@ export class TabPagesActionImpl {
this.#persist();
};
- #createTab = (
- url: string,
- cached: DynamicRouteMeta | undefined,
- activate: boolean,
- scope = resolveTabScope(url),
- ): string => {
+ #createTab = (url: string, cached: DynamicRouteMeta | undefined, activate: boolean): string => {
const { tabs, activeTabId } = this.#get();
const id = generateTabId();
const newTab: TabItem = {
cached,
id,
lastVisited: Date.now(),
- scope,
url,
};
@@ -222,8 +215,24 @@ export class TabPagesActionImpl {
};
#persist = (): void => {
- const { tabs, activeTabId } = this.#get();
- saveTabPages(tabs, activeTabId);
+ const { activeTabScope, tabs, activeTabId } = this.#get();
+ saveTabPages(activeTabScope, tabs, activeTabId);
+ };
+
+ #ensureScopeForUrl = (url: string): void => {
+ const scope = resolveTabScope(url);
+ const { activeTabScope } = this.#get();
+ if (tabScopeKey(activeTabScope) === tabScopeKey(scope)) return;
+
+ this.#loadScope(scope);
+ };
+
+ #loadScope = (scope: TabScope, force = false): void => {
+ const { activeTabScope } = this.#get();
+ if (!force && tabScopeKey(activeTabScope) === tabScopeKey(scope)) return;
+
+ const { tabs, activeTabId } = getTabPages(scope);
+ this.#set({ activeTabId, activeTabScope: scope, tabs }, false, 'loadTabs');
};
}