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.

⚑️ perf(desktop): switch topics instantly, stop tab flashes and close the last tab (#21001)

Innei79818b29683e
diff --git a/src/features/AgentSidebar/Topic/List/Item/index.tsx b/src/features/AgentSidebar/Topic/List/Item/index.tsx
index fe0ae2cd190..c8382696d43 100644
--- a/src/features/AgentSidebar/Topic/List/Item/index.tsx
+++ b/src/features/AgentSidebar/Topic/List/Item/index.tsx
@@ -11,7 +11,7 @@ import { createStaticStyles, cssVar, useTheme } from 'antd-style';
import dayjs from 'dayjs';
import isEqual from 'fast-deep-equal';
import { MessageSquareDashed } from 'lucide-react';
-import type { CSSProperties, DragEvent, RefObject } from 'react';
+import type { CSSProperties, DragEvent, MouseEvent, RefObject } from 'react';
import { memo, Suspense, useCallback, useEffect, useMemo, useRef, useState } from 'react';
import { useTranslation } from 'react-i18next';
@@ -37,7 +37,6 @@ import { agentSelectors, builtinAgentSelectors } from '@/store/agent/selectors';
import { useChatStore } from '@/store/chat';
import { operationSelectors } from '@/store/chat/selectors';
import { messageMapKey } from '@/store/chat/utils/messageMapKey';
-import { useElectronStore } from '@/store/electron';
import { useTopicNavigation } from '../../hooks/useTopicNavigation';
import ThreadList from '../../TopicListContent/ThreadList';
@@ -52,6 +51,7 @@ import {
PR_STATE_VISUAL,
} from './metaCardData';
import MetaHoverCard from './MetaHoverCard';
+import { openTopicInNewTab, recordTopicClickOrigin } from './openTopicTab';
// Base UI Popover plays an opacity/scale enter+exit transition driven by these
// CSS vars on the positioner. Zero them so the meta hover card appears instantly
@@ -111,11 +111,6 @@ const styles = createStaticStyles(({ css }) => ({
`,
}));
-// Module-scoped so a click on any topic cancels a pending click on another.
-// Per-item refs can't do that, which lets rapid clicks across items all
-// fire β€” each racing to write activeTopicId (see ).
-let pendingSingleClickTimer: ReturnType<typeof setTimeout> | null = null;
-
/**
* The mobile surface renders its topic list in a modal and never mounts the
* working sidebar β€” the desktop host of a topic's thread list. Without nesting
@@ -133,13 +128,6 @@ const isMobileSurface = () => typeof __MOBILE__ !== 'undefined' && __MOBILE__;
// Nesting cue: keeps the rows visually under their topic row.
const NESTED_THREAD_LIST_INDENT = 32;
-const cancelPendingSingleClick = () => {
- if (pendingSingleClickTimer) {
- clearTimeout(pendingSingleClickTimer);
- pendingSingleClickTimer = null;
- }
-};
-
const getWorkingDirectoryDisplay = (metadata: ChatTopicMetadata | undefined) => {
const config = metadata?.workingDirectoryConfig;
const workingDirectory = getTopicMetadataWorkingDirectoryEffectivePath(metadata);
@@ -322,29 +310,24 @@ const TopicItemRow = memo<TopicItemRowProps>(
const handleDragStart = useCallback(
(event: DragEvent) => {
if (!id) return;
- cancelPendingSingleClick();
startTopicDrag(event, { topicId: id, topicTitle: title });
},
[id, title],
);
- const handleClick = useCallback(() => {
- if (isDesktop) {
- cancelPendingSingleClick();
- pendingSingleClickTimer = setTimeout(() => {
- pendingSingleClickTimer = null;
- void navRef.current.navigateToTopic(id);
- }, 250);
- } else {
+ const handleClick = useCallback(
+ (event?: MouseEvent) => {
+ if (event && event.detail > 1) return;
+ if (isDesktop && id) recordTopicClickOrigin(id);
void navRef.current.navigateToTopic(id);
- }
- }, [id, navRef]);
+ },
+ [id, navRef],
+ );
const handleDoubleClick = useCallback(async () => {
if (!id || !activeAgentId || !isDesktop) return;
- cancelPendingSingleClick();
if (scope && href) {
- useElectronStore.getState().addTab(href);
+ openTopicInNewTab(id, href);
void navRef.current.navigateToTopic(id);
return;
}
@@ -352,11 +335,10 @@ const TopicItemRow = memo<TopicItemRowProps>(
void navRef.current.navigateToTopic(id, { skipPopupFocus: true });
return;
}
- useElectronStore
- .getState()
- .addTab(
- buildWorkspaceAwarePath(AGENT_CHAT_TOPIC_URL(activeAgentId, id), activeWorkspaceSlug),
- );
+ openTopicInNewTab(
+ id,
+ buildWorkspaceAwarePath(AGENT_CHAT_TOPIC_URL(activeAgentId, id), activeWorkspaceSlug),
+ );
void navRef.current.navigateToTopic(id);
}, [id, activeAgentId, activeWorkspaceSlug, navRef, scope, href]);
diff --git a/src/features/AgentSidebar/Topic/List/Item/openTopicTab.test.ts b/src/features/AgentSidebar/Topic/List/Item/openTopicTab.test.ts
new file mode 100644
index 00000000000..0291219424d
--- /dev/null
+++ b/src/features/AgentSidebar/Topic/List/Item/openTopicTab.test.ts
@@ -0,0 +1,86 @@
+import { createMemoryRouter } from 'react-router';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { flushHiddenTabRestores } from '@/features/Electron/TabHost/hiddenTabRestore';
+import {
+ getOrCreateTabRouter,
+ resetTabRouterManager,
+} from '@/features/Electron/TabHost/tabRouterManager';
+import { useElectronStore } from '@/store/electron';
+import { initialState } from '@/store/electron/initialState';
+
+import { openTopicInNewTab, recordTopicClickOrigin } from './openTopicTab';
+
+const makeRouter = (url: string) =>
+ createMemoryRouter([{ element: null, path: '*' }], { initialEntries: [url] });
+
+const seedActiveTab = (url: string) => {
+ useElectronStore.setState({
+ ...initialState,
+ activeTabId: 'origin',
+ tabs: [{ id: 'origin', lastVisited: 1, url }],
+ });
+ return getOrCreateTabRouter('origin', url, makeRouter);
+};
+
+beforeEach(() => {
+ window.localStorage.clear();
+ resetTabRouterManager();
+});
+
+afterEach(() => {
+ resetTabRouterManager();
+ useElectronStore.setState(initialState);
+});
+
+describe('openTopicInNewTab', () => {
+ it('opens the topic in a new tab and puts the clicked tab back where it was', async () => {
+ const router = seedActiveTab('/agent/a/tpc_before');
+
+ recordTopicClickOrigin('tpc_next');
+ await router.navigate('/agent/a/tpc_next', { replace: true });
+ useElectronStore.getState().reportTabLocation('origin', '/agent/a/tpc_next');
+
+ openTopicInNewTab('tpc_next', '/agent/a/tpc_next');
+
+ const { activeTabId, tabs } = useElectronStore.getState();
+ expect(tabs).toHaveLength(2);
+ expect(activeTabId).not.toBe('origin');
+ expect(tabs.find((tab) => tab.id === activeTabId)!.url).toBe('/agent/a/tpc_next');
+
+ flushHiddenTabRestores([activeTabId!]);
+ await vi.waitFor(() => expect(router.state.location.pathname).toBe('/agent/a/tpc_before'));
+ expect(useElectronStore.getState().tabs.find((tab) => tab.id === 'origin')!.url).toBe(
+ '/agent/a/tpc_before',
+ );
+ });
+
+ it('keeps the single tab when the topic was already open in it', () => {
+ seedActiveTab('/agent/a/tpc_same');
+
+ recordTopicClickOrigin('tpc_same');
+ openTopicInNewTab('tpc_same', '/agent/a/tpc_same');
+
+ const { activeTabId, tabs } = useElectronStore.getState();
+ expect(tabs).toHaveLength(1);
+ expect(activeTabId).toBe('origin');
+ });
+
+ it('activates another tab that already holds the topic instead of duplicating it', () => {
+ seedActiveTab('/agent/a/tpc_before');
+ useElectronStore.setState({
+ tabs: [
+ ...useElectronStore.getState().tabs,
+ { id: 'existing', lastVisited: 0, url: '/agent/a/tpc_next' },
+ ],
+ });
+
+ recordTopicClickOrigin('tpc_next');
+ useElectronStore.getState().reportTabLocation('origin', '/agent/a/tpc_next');
+ openTopicInNewTab('tpc_next', '/agent/a/tpc_next');
+
+ const { activeTabId, tabs } = useElectronStore.getState();
+ expect(tabs).toHaveLength(2);
+ expect(activeTabId).toBe('existing');
+ });
+});
diff --git a/src/features/AgentSidebar/Topic/List/Item/openTopicTab.ts b/src/features/AgentSidebar/Topic/List/Item/openTopicTab.ts
new file mode 100644
index 00000000000..8bdd6cb0b96
--- /dev/null
+++ b/src/features/AgentSidebar/Topic/List/Item/openTopicTab.ts
@@ -0,0 +1,50 @@
+import { restoreTabWhenHidden } from '@/features/Electron/TabHost/hiddenTabRestore';
+import { getTabRouter } from '@/features/Electron/TabHost/tabRouterManager';
+import { normalizeTabUrl } from '@/features/Electron/titlebar/TabBar/url';
+import { useElectronStore } from '@/store/electron';
+
+interface ClickOrigin {
+ tabId: string;
+ topicId: string;
+ url: string;
+}
+
+let lastClickOrigin: ClickOrigin | null = null;
+
+// A single click navigates the active tab at once, so by the time the double
+// click arrives that tab already shows the topic. Remember where it was so the
+// double click can open the topic in a new tab and put the clicked tab back.
+export const recordTopicClickOrigin = (topicId: string): void => {
+ const { activeTabId } = useElectronStore.getState();
+ const location = activeTabId ? getTabRouter(activeTabId)?.state.location : undefined;
+
+ lastClickOrigin =
+ activeTabId && location
+ ? {
+ tabId: activeTabId,
+ topicId,
+ url: `${location.pathname}${location.search}${location.hash}`,
+ }
+ : null;
+};
+
+export const openTopicInNewTab = (topicId: string, url: string): void => {
+ const origin = lastClickOrigin?.topicId === topicId ? lastClickOrigin : null;
+ lastClickOrigin = null;
+
+ const electron = useElectronStore.getState();
+ const target = normalizeTabUrl(url);
+
+ if (!origin || normalizeTabUrl(origin.url) === target) {
+ electron.addTab(url);
+ return;
+ }
+
+ const existing = electron.tabs.find(
+ (tab) => tab.id !== origin.tabId && normalizeTabUrl(tab.url) === target,
+ );
+ if (existing) electron.activateTab(existing.id);
+ else electron.addNewTab(url);
+
+ restoreTabWhenHidden(origin.tabId, { from: url, to: origin.url });
+};
diff --git a/src/features/Electron/TabHost/TabHost.test.ts b/src/features/Electron/TabHost/TabHost.test.ts
index 31bce5fef57..6cc137efe74 100644
--- a/src/features/Electron/TabHost/TabHost.test.ts
+++ b/src/features/Electron/TabHost/TabHost.test.ts
@@ -8,6 +8,8 @@ import { useElectronStore } from '@/store/electron';
import { initialState } from '@/store/electron/initialState';
import { useUserStore } from '@/store/user';
+import { useDisplayedTabStore } from './displayedTab';
+import { restoreTabWhenHidden } from './hiddenTabRestore';
import { useLiveTabRouterCap } from './liveTabRouterCap';
import TabHost from './TabHost';
import TabLocationReporter from './TabLocationReporter';
@@ -487,4 +489,98 @@ describe('TabHost', () => {
expect(useElectronStore.getState().tabs.find((t) => t.id === 'b')!.url).toBe('/agent/moved');
expect(getTabHistorySnapshot('b').canGoBack).toBe(true);
});
+
+ it('keeps the outgoing tab on screen until a cold tab finishes its first load', async () => {
+ let releaseColdLoader!: () => void;
+ const coldLoader = new Promise<null>((resolve) => {
+ releaseColdLoader = () => resolve(null);
+ });
+ const createLoadingRouter = (url: string): TabRouter => {
+ const router = createMemoryRouter(
+ [
+ {
+ element: React.createElement(TestRoute),
+ loader: () => (url === '/item/cold' ? coldLoader : null),
+ path: '/item/:id',
+ },
+ ],
+ { initialEntries: [url] },
+ );
+ created.push({ dispose: vi.spyOn(router, 'dispose'), router, url });
+ return router;
+ };
+ setStore(
+ [
+ { id: 'warm', lastVisited: 2, url: '/item/warm' },
+ { id: 'cold', lastVisited: 1, url: '/item/cold' },
+ ],
+ 'warm',
+ );
+ render(React.createElement(TabHost, { createRouter: createLoadingRouter }));
+ expect(await screen.findByTestId('param-warm')).toBeVisible();
+
+ act(() => useElectronStore.setState({ activeTabId: 'cold' }));
+ await vi.waitFor(() => expect(getTabRouter('cold')).toBeDefined());
+
+ expect(screen.getByTestId('param-warm')).toBeVisible();
+ expect(useDisplayedTabStore.getState().tabId).toBe('warm');
+
+ await act(async () => {
+ releaseColdLoader();
+ await coldLoader;
+ });
+
+ expect(await screen.findByTestId('param-cold')).toBeVisible();
+ expect(screen.getByTestId('param-warm')).not.toBeVisible();
+ expect(useDisplayedTabStore.getState().tabId).toBe('cold');
+ });
+
+ it('restores a tab to its earlier location once another tab takes its slot', async () => {
+ setStore(
+ [
+ { id: 'origin', lastVisited: 2, url: '/item/clicked' },
+ { id: 'other', lastVisited: 1, url: '/item/other' },
+ ],
+ 'origin',
+ );
+ renderHost();
+ await screen.findByTestId('param-clicked');
+
+ restoreTabWhenHidden('origin', { from: '/item/clicked', to: '/item/before' });
+ await act(async () => {});
+ expect(getTabRouter('origin')!.state.location.pathname).toBe('/item/clicked');
+
+ act(() => useElectronStore.setState({ activeTabId: 'other' }));
+ await screen.findByTestId('param-other');
+
+ await vi.waitFor(() =>
+ expect(getTabRouter('origin')!.state.location.pathname).toBe('/item/before'),
+ );
+ expect(useElectronStore.getState().tabs.find((t) => t.id === 'origin')!.url).toBe(
+ '/item/before',
+ );
+ });
+
+ it('drops the restore when the tab already left the location it was meant to undo', async () => {
+ setStore(
+ [
+ { id: 'origin', lastVisited: 2, url: '/item/clicked' },
+ { id: 'other', lastVisited: 1, url: '/item/other' },
+ ],
+ 'origin',
+ );
+ renderHost();
+ await screen.findByTestId('param-clicked');
+
+ restoreTabWhenHidden('origin', { from: '/item/clicked', to: '/item/before' });
+ await act(async () => {
+ await getTabRouter('origin')!.navigate('/item/elsewhere');
+ });
+
+ act(() => useElectronStore.setState({ activeTabId: 'other' }));
+ await screen.findByTestId('param-other');
+ await act(async () => {});
+
+ expect(getTabRouter('origin')!.state.location.pathname).toBe('/item/elsewhere');
+ });
});
diff --git a/src/features/Electron/TabHost/TabHost.tsx b/src/features/Electron/TabHost/TabHost.tsx
index 44f1b25ac24..95522edfbe0 100644
--- a/src/features/Electron/TabHost/TabHost.tsx
+++ b/src/features/Electron/TabHost/TabHost.tsx
@@ -9,6 +9,7 @@ import {
type ReactNode,
useDeferredValue,
useEffect,
+ useLayoutEffect,
useMemo,
useRef,
} from 'react';
@@ -21,6 +22,8 @@ import { useElectronStore } from '@/store/electron';
import { useUserStore } from '@/store/user';
import { labPreferSelectors, preferenceSelectors } from '@/store/user/selectors';
+import { useDisplayedTabStore } from './displayedTab';
+import { flushHiddenTabRestores } from './hiddenTabRestore';
import { useLiveTabRouterCap } from './liveTabRouterCap';
import { resolveLiveTabIds } from './resolveLiveTabIds';
import { TabIdContext } from './TabIdContext';
@@ -31,6 +34,7 @@ import {
syncTabRouters,
type TabRouter,
} from './tabRouterManager';
+import { useDisplayedTabIds } from './useDisplayedTabIds';
import { useTabPreviewCapture } from './useTabPreviewCapture';
interface TabHostProps {
@@ -158,21 +162,49 @@ const TabHost = ({ createRouter = createTabRouter }: TabHostProps) => {
[activeTabId, effectiveSplitView],
);
+ const existingTabIds = useMemo(() => tabs.map((tab) => tab.id), [tabs]);
+ const requestedRouters = useMemo(
+ () =>
+ visibleTabIds.flatMap((id) => {
+ const tab = tabs.find((item) => item.id === id);
+ return tab ? [getOrCreateTabRouter(id, tab.url, createRouter)] : [];
+ }),
+ [createRouter, tabs, visibleTabIds],
+ );
+ const displayedTabIds = useDisplayedTabIds({
+ canHold: !effectiveSplitView,
+ existingTabIds,
+ requestedRouters,
+ requestedTabIds: visibleTabIds,
+ });
+
useEffect(() => {
if (isPreferenceInit && !splitViewEnabled && splitView) closeSplitView();
}, [closeSplitView, isPreferenceInit, splitView, splitViewEnabled]);
- const liveIds = useMemo(
- () =>
- resolveLiveTabIds(
- // Persisted tabs are cold until first shown; only retain already-created routers.
- tabs.filter((tab) => visibleTabIds.includes(tab.id) || getTabRouter(tab.id)),
- activeTabId,
- liveTabCap,
- visibleTabIds,
- ),
- [tabs, activeTabId, liveTabCap, visibleTabIds],
- );
+ const liveIds = useMemo(() => {
+ const retainedTabIds = [...visibleTabIds, ...displayedTabIds];
+ return resolveLiveTabIds(
+ // Persisted tabs are cold until first shown; only retain already-created routers.
+ tabs.filter((tab) => retainedTabIds.includes(tab.id) || getTabRouter(tab.id)),
+ activeTabId,
+ liveTabCap,
+ retainedTabIds,
+ );
+ }, [tabs, activeTabId, liveTabCap, visibleTabIds, displayedTabIds]);
+
+ const displayedActiveTabId =
+ activeTabId && displayedTabIds.includes(activeTabId)
+ ? activeTabId
+ : (displayedTabIds[0] ?? null);
+
+ useLayoutEffect(() => {
+ useDisplayedTabStore.setState({ tabId: displayedActiveTabId });
+ }, [displayedActiveTabId]);
+
+ useEffect(() => {
+ flushHiddenTabRestores(displayedTabIds);
+ }, [displayedTabIds]);
useEffect(() => {
const liveSet = new Set(liveIds);
@@ -187,7 +219,10 @@ const TabHost = ({ createRouter = createTabRouter }: TabHostProps) => {
}, [liveIds]);
const liveSet = new Set(liveIds);
- const visibleSet = new Set(visibleTabIds);
+ const visibleSet = new Set(displayedTabIds);
+ // A held tab must not pre-mount: a hidden RouterProvider has no subscription,
+ // so it would reveal its pre-load (empty) state once the router initializes.
+ const heldSet = new Set(visibleTabIds.filter((id) => !visibleSet.has(id)));
const handleDividerPointerMove = (event: PointerEvent<HTMLDivElement>) => {
if (!event.currentTarget.hasPointerCapture(event.pointerId)) return;
@@ -206,7 +241,7 @@ const TabHost = ({ createRouter = createTabRouter }: TabHostProps) => {
return (
<div style={rootStyle}>
{tabs
- .filter((tab) => liveSet.has(tab.id))
+ .filter((tab) => liveSet.has(tab.id) && !heldSet.has(tab.id))
.map((tab) => {
const isVisible = visibleSet.has(tab.id);
const isPrimary = effectiveSplitView?.primaryTabId === tab.id;
diff --git a/src/features/Electron/TabHost/displayedTab.ts b/src/features/Electron/TabHost/displayedTab.ts
new file mode 100644
index 00000000000..81125665cd1
--- /dev/null
+++ b/src/features/Electron/TabHost/displayedTab.ts
@@ -0,0 +1,21 @@
+import { create } from 'zustand';
+
+import { selectActiveTabUrl } from '@/features/Electron/shell/activeTabUrl';
+import { useElectronStore } from '@/store/electron';
+
+interface DisplayedTabState {
+ tabId: string | null;
+}
+
+// `activeTabId` flips as soon as a tab is clicked, but TabHost reveals the pane
+// later (deferred, or held until a cold router loads). Chrome that must match
+// the pane on screen, like the nav panel, follows this id instead.
+export const useDisplayedTabStore = create<DisplayedTabState>(() => ({ tabId: null }));
+
+export const useDisplayedTabUrl = (): string | null => {
+ const tabId = useDisplayedTabStore((s) => s.tabId);
+
+ return useElectronStore(
+ (s) => (tabId && s.tabs.find((tab) => tab.id === tabId)?.url) || selectActiveTabUrl(s),
+ );
+};
diff --git a/src/features/Electron/TabHost/hiddenTabRestore.ts b/src/features/Electron/TabHost/hiddenTabRestore.ts
new file mode 100644
index 00000000000..af2a2c04a28
--- /dev/null
+++ b/src/features/Electron/TabHost/hiddenTabRestore.ts
@@ -0,0 +1,34 @@
+import { navigateTab } from '@/features/Electron/navigation/activeTabNavigate';
+import { normalizeTabUrl } from '@/features/Electron/titlebar/TabBar/url';
+import { useElectronStore } from '@/store/electron';
+
+import { getTabRouter } from './tabRouterManager';
+
+interface TabRestore {
+ from: string;
+ to: string;
+}
+
+const pendingRestores = new Map<string, TabRestore>();
+
+// Undoing a navigation on a tab that is still on screen would flash the old page
+// before the replacement tab paints, so the restore waits until TabHost hides it.
+export const restoreTabWhenHidden = (tabId: string, restore: TabRestore): void => {
+ pendingRestores.set(tabId, restore);
+};
+
+export const flushHiddenTabRestores = (displayedTabIds: readonly string[]): void => {
+ for (const [tabId, { from, to }] of pendingRestores) {
+ if (displayedTabIds.includes(tabId)) continue;
+ pendingRestores.delete(tabId);
+
+ const state = getTabRouter(tabId)?.state;
+ if (!state) continue;
+
+ const { hash, pathname, search } = state.navigation.location ?? state.location;
+ if (normalizeTabUrl(`${pathname}${search}${hash}`) !== normalizeTabUrl(from)) continue;
+
+ navigateTab(tabId, to, { replace: true });
+ useElectronStore.getState().snapshotTabLocation(tabId, to);
+ }
+};
diff --git a/src/features/Electron/TabHost/resolveBootAction.ts b/src/features/Electron/TabHost/resolveBootAction.ts
index 27a3f2cbb84..f2a811ec004 100644
--- a/src/features/Electron/TabHost/resolveBootAction.ts
+++ b/src/features/Electron/TabHost/resolveBootAction.ts
@@ -1,15 +1,14 @@
-import { isSameTabTarget, resolveTabScope } from '@/features/Electron/titlebar/TabBar/scope';
+import {
+ isSameTabTarget,
+ resolveTabScope,
+ tabScopeHomeUrl,
+} from '@/features/Electron/titlebar/TabBar/scope';
import { type TabItem } from '@/features/Electron/titlebar/TabBar/types';
import { normalizeTabUrl } from '@/features/Electron/titlebar/TabBar/url';
export type BootAction =
{ type: 'keep' } | { id: string; type: 'activate'; url?: string } | { type: 'add'; url: string };
-const scopeRootUrl = (bootUrl: string): string => {
- const scope = resolveTabScope(bootUrl);
- return scope.type === 'workspace' ? `/${scope.slug}` : '/';
-};
-
export const resolveBootAction = (
tabs: TabItem[],
activeTabId: string | null,
@@ -18,7 +17,7 @@ export const resolveBootAction = (
// A scope-root boot url (`/`, or `/{slug}` when the main process restores the
// last workspace) is a plain launch, not a deep link: keep the scope's last
// active tab instead of forcing its home tab to the front.
- const isDefaultLaunch = normalizeTabUrl(bootUrl) === scopeRootUrl(bootUrl);
+ const isDefaultLaunch = normalizeTabUrl(bootUrl) === tabScopeHomeUrl(resolveTabScope(bootUrl));
const activeTabExists = !!activeTabId && tabs.some((tab) => tab.id === activeTabId);
if (isDefaultLaunch && activeTabExists) return { type: 'keep' };
diff --git a/src/features/Electron/TabHost/useDisplayedTabIds.ts b/src/features/Electron/TabHost/useDisplayedTabIds.ts
new file mode 100644
index 00000000000..a09135b35f1
--- /dev/null
+++ b/src/features/Electron/TabHost/useDisplayedTabIds.ts
@@ -0,0 +1,45 @@
+import { useCallback, useState, useSyncExternalStore } from 'react';
+
+import { type TabRouter } from './tabRouterManager';
+
+interface UseDisplayedTabIdsOptions {
+ canHold: boolean;
+ existingTabIds: readonly string[];
+ requestedRouters: readonly TabRouter[];
+ requestedTabIds: string[];
+}
+
+const isSameIds = (a: readonly string[], b: readonly string[]) =>
+ a.length === b.length && a.every((id, index) => id === b[index]);
+
+// A cold tab router renders nothing until its first loaders settle (no
+// HydrateFallback), and the route layout that registers the sidebar has not
+// mounted yet. Showing it immediately blanks both the pane and the nav panel,
+// so the previously displayed tab stays on screen until the new one is ready.
+export const useDisplayedTabIds = ({
+ canHold,
+ existingTabIds,
+ requestedRouters,
+ requestedTabIds,
+}: UseDisplayedTabIdsOptions): string[] => {
+ const subscribe = useCallback(
+ (onChange: () => void) => {
+ const unsubscribes = requestedRouters.map((router) => router.subscribe(onChange));
+ return () => unsubscribes.forEach((unsubscribe) => unsubscribe());
+ },
+ [requestedRouters],
+ );
+ const getReady = () => requestedRouters.every((router) => router.state.initialized);
+ const isReady = useSyncExternalStore(subscribe, getReady, getReady);
+
+ const [displayed, setDisplayed] = useState(requestedTabIds);
+ const shouldHold =
+ canHold &&
+ !isReady &&
+ displayed.length > 0 &&
+ displayed.every((id) => existingTabIds.includes(id));
+
+ if (!shouldHold && !isSameIds(displayed, requestedTabIds)) setDisplayed(requestedTabIds);
+
+ return shouldHold ? displayed : requestedTabIds;
+};
diff --git a/src/features/Electron/titlebar/TabBar/TabItem.tsx b/src/features/Electron/titlebar/TabBar/TabItem.tsx
index aaf5c2e6204..fecaedb104d 100644
--- a/src/features/Electron/titlebar/TabBar/TabItem.tsx
+++ b/src/features/Electron/titlebar/TabBar/TabItem.tsx
@@ -104,10 +104,9 @@ const TabItem = memo<TabItemProps>(
const showUnreadDot = !isRunning && isUnread;
const pinned = !!tab.pinned;
// Which tiers actually show the button is settled in CSS so that it can fade rather
- // than unmount; a lone tab is the one case with no button to fade at all. Staying
- // mounted below the compact tier would otherwise leave an invisible button in the
- // focus order, so those tiers are made inert rather than merely transparent.
- const closable = totalCount > 1;
+ // than unmount. Staying mounted below the compact tier would otherwise leave an
+ // invisible button in the focus order, so those tiers are made inert rather than
+ // merely transparent.
const closeInert = tier !== 'full' && tier !== 'compact';
const isDragging = !!drag;
@@ -209,11 +208,11 @@ const TabItem = memo<TabItemProps>(
const handleAuxClick = useCallback(
(e: React.MouseEvent) => {
- if (e.button !== 1 || totalCount === 1) return;
+ if (e.button !== 1) return;
e.preventDefault();
onClose(id);
},
- [onClose, id, totalCount],
+ [onClose, id],
);
const contextMenuItems = useCallback(
@@ -306,17 +305,15 @@ const TabItem = memo<TabItemProps>(
<span data-tab-title className={styles.tabTitle}>
{meta.title}
</span>
- {closable && (
- <ActionIcon
- data-tab-close
- className={styles.closeIcon}
- icon={X}
- inert={closeInert}
- size="small"
- style={CLOSE_BUTTON_STYLE}
- onClick={handleClose}
- />
- )}
+ <ActionIcon
+ data-tab-close
+ className={styles.closeIcon}
+ icon={X}
+ inert={closeInert}
+ size="small"
+ style={CLOSE_BUTTON_STYLE}
+ onClick={handleClose}
+ />
</m.div>
);
diff --git a/src/features/Electron/titlebar/TabBar/index.tsx b/src/features/Electron/titlebar/TabBar/index.tsx
index a3187af07b1..1a5441694b2 100644
--- a/src/features/Electron/titlebar/TabBar/index.tsx
+++ b/src/features/Electron/titlebar/TabBar/index.tsx
@@ -25,6 +25,7 @@ import { useResolvedTabs } from './hooks/useResolvedTabs';
import { useStripWidth } from './hooks/useStripWidth';
import { useTabDrag } from './hooks/useTabDrag';
import { TAB_SPRING } from './motion';
+import { resolveCloseShortcut } from './resolveCloseShortcut';
import { resolveTabScope } from './scope';
import { useStyles } from './styles';
import TabItem from './TabItem';
@@ -207,11 +208,11 @@ const TabBar = () => {
);
useWatchBroadcast('closeCurrentTabOrWindow', () => {
- if (tabs.length > 1 && activeTabId) {
- handleClose(activeTabId);
- } else {
- void electronSystemService.closeWindow();
- }
+ const state = useElectronStore.getState();
+ const action = resolveCloseShortcut(state.tabs, state.activeTabId, state.activeTabScope);
+
+ if (action.type === 'closeTab') handleClose(action.id);
+ else void electronSystemService.closeWindow();
});
const handleNewTab = useCallback(
diff --git a/src/features/Electron/titlebar/TabBar/resolveCloseShortcut.test.ts b/src/features/Electron/titlebar/TabBar/resolveCloseShortcut.test.ts
new file mode 100644
index 00000000000..9ac6fe6c222
--- /dev/null
+++ b/src/features/Electron/titlebar/TabBar/resolveCloseShortcut.test.ts
@@ -0,0 +1,49 @@
+import { describe, expect, it } from 'vitest';
+
+import { resolveCloseShortcut } from './resolveCloseShortcut';
+import { PERSONAL_TAB_SCOPE } from './scope';
+import { type TabItem } from './types';
+
+const tab = (id: string, url: string): TabItem => ({ id, lastVisited: 1, url });
+
+describe('resolveCloseShortcut', () => {
+ it('closes the active tab when several are open', () => {
+ const tabs = [tab('a', '/agent/a1'), tab('b', '/')];
+
+ expect(resolveCloseShortcut(tabs, 'a', PERSONAL_TAB_SCOPE)).toEqual({
+ id: 'a',
+ type: 'closeTab',
+ });
+ });
+
+ it('closes a lone tab that is not at home, so it lands on the home tab', () => {
+ const tabs = [tab('a', '/agent/a1?topic=t1')];
+
+ expect(resolveCloseShortcut(tabs, 'a', PERSONAL_TAB_SCOPE)).toEqual({
+ id: 'a',
+ type: 'closeTab',
+ });
+ });
+
+ it('closes the window when the lone tab is already at home', () => {
+ expect(resolveCloseShortcut([tab('a', '/')], 'a', PERSONAL_TAB_SCOPE)).toEqual({
+ type: 'closeWindow',
+ });
+ });
+
+ it('treats the workspace root as home inside a workspace scope', () => {
+ const scope = { slug: 'acme', type: 'workspace' } as const;
+
+ expect(resolveCloseShortcut([tab('a', '/acme')], 'a', scope)).toEqual({
+ type: 'closeWindow',
+ });
+ expect(resolveCloseShortcut([tab('a', '/')], 'a', scope)).toEqual({
+ id: 'a',
+ type: 'closeTab',
+ });
+ });
+
+ it('closes the window when no tab is active', () => {
+ expect(resolveCloseShortcut([], null, PERSONAL_TAB_SCOPE)).toEqual({ type: 'closeWindow' });
+ });
+});
diff --git a/src/features/Electron/titlebar/TabBar/resolveCloseShortcut.ts b/src/features/Electron/titlebar/TabBar/resolveCloseShortcut.ts
new file mode 100644
index 00000000000..9c5372cecc2
--- /dev/null
+++ b/src/features/Electron/titlebar/TabBar/resolveCloseShortcut.ts
@@ -0,0 +1,21 @@
+import { isSameTabTarget, type TabScope, tabScopeHomeUrl } from './scope';
+import { type TabItem } from './types';
+
+export type CloseShortcutAction = { id: string; type: 'closeTab' } | { type: 'closeWindow' };
+
+// Closing the last tab lands on a fresh home tab, so a lone tab already at home has
+// nowhere further to go; there the shortcut falls back to closing the window, or it
+// would never close it at all.
+export const resolveCloseShortcut = (
+ tabs: TabItem[],
+ activeTabId: string | null,
+ scope: TabScope,
+): CloseShortcutAction => {
+ const active = tabs.find((tab) => tab.id === activeTabId);
+ if (!active) return { type: 'closeWindow' };
+
+ const isLoneHomeTab = tabs.length === 1 && isSameTabTarget(active, tabScopeHomeUrl(scope));
+ if (isLoneHomeTab) return { type: 'closeWindow' };
+
+ return { id: active.id, type: 'closeTab' };
+};
diff --git a/src/features/Electron/titlebar/TabBar/scope.ts b/src/features/Electron/titlebar/TabBar/scope.ts
index 6bc6291d444..65b90b82678 100644
--- a/src/features/Electron/titlebar/TabBar/scope.ts
+++ b/src/features/Electron/titlebar/TabBar/scope.ts
@@ -51,6 +51,9 @@ export const resolveTabScope = (url: string): TabScope => {
return { slug: firstSegment, type: 'workspace' };
};
+export const tabScopeHomeUrl = (scope: TabScope): string =>
+ scope.type === 'workspace' ? `/${scope.slug}` : '/';
+
export const tabScopeKey = (scope: TabScope): string =>
scope.type === 'personal' ? 'personal' : `workspace:${encodeURIComponent(scope.slug)}`;
diff --git a/src/features/Electron/titlebar/TabBar/styles.ts b/src/features/Electron/titlebar/TabBar/styles.ts
index fd33124a8e5..f77a3ac6b4e 100644
--- a/src/features/Electron/titlebar/TabBar/styles.ts
+++ b/src/features/Electron/titlebar/TabBar/styles.ts
@@ -134,19 +134,14 @@ export const useStyles = createStaticStyles(({ css, cssVar }) => ({
too. The button stays mounted at every tier and fades; unmounting it made it vanish
mid-pin.
- A lone tab never mounts the button (the last tab cannot close), so :has([data-
- tab-close]) keeps the title margin from opening a hole for a control that is not
- there β€” which otherwise still ran the mask gradient in as if a close affordance
- were arriving.
-
- :has() also carries the keyboard path β€” the button is focusable at these tiers, so
+ :has() carries the keyboard path β€” the button is focusable at these tiers, so
without it a tabbing user would land on something invisible.
Reservation is 20px button + 3px inset - the tab's own 6px end padding. Margin
rather than padding: the mask applies to the padding box, so padding would put the
gradient inside the reservation instead of at the text's edge. */
- &[data-tier='full']:hover:has([data-tab-close]),
- &[data-tier='compact']:hover:has([data-tab-close]),
+ &[data-tier='full']:hover,
+ &[data-tier='compact']:hover,
&[data-tier='full']:has([data-tab-close]:focus-visible),
&[data-tier='compact']:has([data-tab-close]:focus-visible) {
[data-tab-close] {
diff --git a/src/features/Electron/titlebar/TabBar/tabContextMenu.test.ts b/src/features/Electron/titlebar/TabBar/tabContextMenu.test.ts
index bb4fd415b8f..8bb4c9867e7 100644
--- a/src/features/Electron/titlebar/TabBar/tabContextMenu.test.ts
+++ b/src/features/Electron/titlebar/TabBar/tabContextMenu.test.ts
@@ -37,11 +37,22 @@ describe('tab context menu ownership', () => {
expect(toNativeTemplate(items).template).toMatchSnapshot();
});
- it('stays native-eligible in the fully disabled single-tab state', () => {
+ it('stays native-eligible in the single-tab state', () => {
expect(canGoNative(build(0, 1))).toBe(true);
});
});
+describe('close entries', () => {
+ it('lets a lone tab close itself while the bulk closes have nothing to reach', () => {
+ const items = build(0, 1);
+
+ expect(isDisabled(items, 'closeCurrentTab')).toBe(false);
+ expect(isDisabled(items, 'closeOtherTabs')).toBe(true);
+ expect(isDisabled(items, 'closeLeftTabs')).toBe(true);
+ expect(isDisabled(items, 'closeRightTabs')).toBe(true);
+ });
+});
+
describe('pin entry', () => {
it('offers pinning for an unpinned tab and unpinning for a pinned one', () => {
const labelOf = (pinned: boolean) => {
@@ -55,7 +66,7 @@ describe('pin entry', () => {
expect(labelOf(true)).toBe('tab.unpin');
});
- it('stays available when closing is not β€” a lone tab can still be pinned', () => {
+ it('stays available for a lone tab', () => {
const items = build(0, 1);
const pin = items.find((item) => !!item && 'key' in item && item.key === 'togglePin');
diff --git a/src/features/Electron/titlebar/TabBar/tabContextMenu.ts b/src/features/Electron/titlebar/TabBar/tabContextMenu.ts
index 68c6207274b..23ec721c587 100644
--- a/src/features/Electron/titlebar/TabBar/tabContextMenu.ts
+++ b/src/features/Electron/titlebar/TabBar/tabContextMenu.ts
@@ -67,7 +67,6 @@ export const buildTabContextMenuItems = ({
: null,
{ type: 'divider' },
{
- disabled: totalCount === 1,
key: 'closeCurrentTab',
label: t('tab.closeCurrentTab'),
onClick: () => onClose(id),
diff --git a/src/features/NavPanel/useActiveNavKey.desktop.test.ts b/src/features/NavPanel/useActiveNavKey.desktop.test.ts
new file mode 100644
index 00000000000..a0972230e3d
--- /dev/null
+++ b/src/features/NavPanel/useActiveNavKey.desktop.test.ts
@@ -0,0 +1,52 @@
+import { act, renderHook } from '@testing-library/react';
+import { afterEach, describe, expect, it, vi } from 'vitest';
+
+import { useDisplayedTabStore } from '@/features/Electron/TabHost/displayedTab';
+import { useElectronStore } from '@/store/electron';
+
+import { useActiveNavKey } from './useActiveNavKey.desktop';
+
+vi.mock('@/business/client/hooks/useActiveWorkspaceSlug', () => ({
+ useActiveWorkspaceSlug: () => null,
+}));
+
+const tab = (id: string, url: string) => ({ id, lastVisited: 0, url });
+
+afterEach(() => {
+ useElectronStore.setState({ activeTabId: null, tabs: [] });
+ useDisplayedTabStore.setState({ tabId: null });
+});
+
+describe('useActiveNavKey (desktop)', () => {
+ it('keeps the panel of the tab on screen until the clicked tab is revealed', () => {
+ useElectronStore.setState({
+ activeTabId: 'topic',
+ tabs: [tab('home', '/'), tab('topic', '/agent/agt_a/tpc_a')],
+ });
+ useDisplayedTabStore.setState({ tabId: 'home' });
+
+ const { result } = renderHook(() => useActiveNavKey());
+ expect(result.current).toBe('home');
+
+ act(() => useDisplayedTabStore.setState({ tabId: 'topic' }));
+ expect(result.current).toBe('agent');
+ });
+
+ it('follows in-tab navigation of the displayed tab', () => {
+ useElectronStore.setState({ activeTabId: 'only', tabs: [tab('only', '/')] });
+ useDisplayedTabStore.setState({ tabId: 'only' });
+
+ const { result } = renderHook(() => useActiveNavKey());
+ act(() => useElectronStore.getState().reportTabLocation('only', '/agent/agt_a?thread=x'));
+
+ expect(result.current).toBe('agent');
+ });
+
+ it('falls back to the active tab before any tab is displayed', () => {
+ useElectronStore.setState({ activeTabId: 'only', tabs: [tab('only', '/community')] });
+
+ const { result } = renderHook(() => useActiveNavKey());
+
+ expect(result.current).toBe('discover');
+ });
+});
diff --git a/src/features/NavPanel/useActiveNavKey.desktop.ts b/src/features/NavPanel/useActiveNavKey.desktop.ts
new file mode 100644
index 00000000000..8dfa57184a6
--- /dev/null
+++ b/src/features/NavPanel/useActiveNavKey.desktop.ts
@@ -0,0 +1,15 @@
+import { useActiveWorkspaceSlug } from '@/business/client/hooks/useActiveWorkspaceSlug';
+import { useDisplayedTabUrl } from '@/features/Electron/TabHost/displayedTab';
+
+import { resolveNavPanelKey } from './routeKey';
+
+// The route-owned panel registers from inside the tab's layout, so keying the
+// panel by the clicked tab before its pane is on screen finds no entry and
+// paints the skeleton.
+export const useActiveNavKey = () => {
+ const url = useDisplayedTabUrl() ?? '/';
+ const activeWorkspaceSlug = useActiveWorkspaceSlug();
+ const pathname = url.split(/[#?]/)[0] || '/';
+
+ return resolveNavPanelKey(pathname, activeWorkspaceSlug);
+};
diff --git a/src/store/electron/actions/tabPages.closeLastTab.test.ts b/src/store/electron/actions/tabPages.closeLastTab.test.ts
new file mode 100644
index 00000000000..db14880c1dc
--- /dev/null
+++ b/src/store/electron/actions/tabPages.closeLastTab.test.ts
@@ -0,0 +1,79 @@
+import { act, renderHook } from '@testing-library/react';
+import { beforeEach, describe, expect, it } from 'vitest';
+
+import { PERSONAL_TAB_SCOPE, type TabScope } from '@/features/Electron/titlebar/TabBar/scope';
+import { getTabPages } from '@/features/Electron/titlebar/TabBar/storage';
+import { type TabItem } from '@/features/Electron/titlebar/TabBar/types';
+import { useElectronStore } from '@/store/electron';
+import { initialState } from '@/store/electron/initialState';
+
+const seed = (tab: TabItem, activeTabScope: TabScope = PERSONAL_TAB_SCOPE) => {
+ const { result } = renderHook(() => useElectronStore());
+ act(() => {
+ useElectronStore.setState({ activeTabId: tab.id, activeTabScope, tabs: [tab] });
+ });
+ return result;
+};
+
+const topicTab: TabItem = { id: 'topic', lastVisited: 1, url: '/agent/a1?topic=t1' };
+
+describe('closing the last tab', () => {
+ beforeEach(() => {
+ window.localStorage.clear();
+ useElectronStore.setState({ ...initialState, activeTabId: null, tabs: [] });
+ });
+
+ it('replaces it with a fresh home tab and focuses it', () => {
+ const result = seed(topicTab);
+
+ let returned: string | null = null;
+ act(() => {
+ returned = result.current.removeTab('topic');
+ });
+
+ const { activeTabId, splitView, tabs } = result.current;
+ expect(tabs).toHaveLength(1);
+ expect(tabs[0].url).toBe('/');
+ expect(tabs[0].id).not.toBe('topic');
+ expect(activeTabId).toBe(tabs[0].id);
+ expect(returned).toBe(tabs[0].id);
+ expect(splitView).toBeNull();
+ });
+
+ it('lands on the workspace home inside a workspace scope', () => {
+ const result = seed(
+ { id: 'ws-topic', lastVisited: 1, url: '/acme/agent/a1' },
+ { slug: 'acme', type: 'workspace' },
+ );
+
+ act(() => {
+ result.current.removeTab('ws-topic');
+ });
+
+ expect(result.current.tabs.map((tab) => tab.url)).toEqual(['/acme']);
+ });
+
+ it('closes a pinned last tab too', () => {
+ const result = seed({ ...topicTab, pinned: true });
+
+ act(() => {
+ result.current.removeTab('topic');
+ });
+
+ expect(result.current.tabs).toHaveLength(1);
+ expect(result.current.tabs[0]).toMatchObject({ url: '/' });
+ expect(result.current.tabs[0].pinned).toBeUndefined();
+ });
+
+ it('persists the home tab so a relaunch does not restore the closed one', () => {
+ const result = seed(topicTab);
+
+ act(() => {
+ result.current.removeTab('topic');
+ });
+
+ const persisted = getTabPages(PERSONAL_TAB_SCOPE);
+ expect(persisted.tabs.map((tab) => tab.url)).toEqual(['/']);
+ expect(persisted.activeTabId).toBe(result.current.activeTabId);
+ });
+});
diff --git a/src/store/electron/actions/tabPages.ts b/src/store/electron/actions/tabPages.ts
index 157c7166573..bb9f7338eb4 100644
--- a/src/store/electron/actions/tabPages.ts
+++ b/src/store/electron/actions/tabPages.ts
@@ -7,6 +7,7 @@ import {
PERSONAL_TAB_SCOPE,
resolveTabScope,
type TabScope,
+ tabScopeHomeUrl,
tabScopeKey,
} from '@/features/Electron/titlebar/TabBar/scope';
import { getTabPages, saveTabPages } from '@/features/Electron/titlebar/TabBar/storage';
@@ -233,17 +234,28 @@ export class TabPagesActionImpl {
};
removeTab = (id: string): string | null => {
- const { tabs, activeTabId } = this.#get();
+ const { activeTabScope, tabs, activeTabId } = this.#get();
const index = tabs.findIndex((t) => t.id === id);
if (index < 0) return null;
const newTabs = tabs.filter((t) => t.id !== id);
+ // With no tab left TabHost has nothing to render, so the last close lands on a fresh
+ // home tab instead β€” a new id, because a live router is never re-pointed at a new url.
+ if (newTabs.length === 0) {
+ const home: TabItem = {
+ id: generateTabId(),
+ lastVisited: Date.now(),
+ url: tabScopeHomeUrl(activeTabScope),
+ };
+ this.#set({ activeTabId: home.id, splitView: null, tabs: [home] }, false, 'removeTab');
+ this.#persist();
+ return home.id;
+ }
+
let newActiveId = activeTabId;
if (activeTabId === id) {
- if (newTabs.length === 0) {
- newActiveId = null;
- } else if (index >= newTabs.length) {
+ if (index >= newTabs.length) {
newActiveId = newTabs.at(-1)!.id;
} else {
newActiveId = newTabs[index].id;