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(nav): send the agent/group sidebar back button to the page it was opened from (#23127)

Rdmclin292d3d251f698
diff --git a/src/features/AgentSidebar/Header/index.tsx b/src/features/AgentSidebar/Header/index.tsx
index 47bcb4fdcca..95243592efa 100644
--- a/src/features/AgentSidebar/Header/index.tsx
+++ b/src/features/AgentSidebar/Header/index.tsx
@@ -2,15 +2,18 @@
import { type PropsWithChildren } from 'react';
+import { useBackButtonProps } from '@/features/NavPanel/backOrigin';
import SideBarHeaderLayout from '@/features/NavPanel/SideBarHeaderLayout';
import Agent from './Agent';
import Nav from './Nav';
const HeaderInfo = (_props: PropsWithChildren) => {
+ const back = useBackButtonProps();
+
return (
<>
- <SideBarHeaderLayout left={<Agent />} />
+ <SideBarHeaderLayout {...back} left={<Agent />} />
<Nav />
</>
);
diff --git a/src/features/NavPanel/Shell.tsx b/src/features/NavPanel/Shell.tsx
index bf67dcfef2d..110fdb86c39 100644
--- a/src/features/NavPanel/Shell.tsx
+++ b/src/features/NavPanel/Shell.tsx
@@ -2,6 +2,7 @@
import HomeNavPanelPortal from '@/features/HomeSidebar';
+import BackOriginTracker from './backOrigin/Tracker';
import NavPanel from './index';
// The Home portal is owned by the shell, not by the Home route layout: routes
@@ -12,6 +13,7 @@ import NavPanel from './index';
// no `home` entry at all, so the panel is stuck on the loading skeleton.
const NavPanelShell = () => (
<>
+ <BackOriginTracker />
<HomeNavPanelPortal />
<NavPanel />
</>
diff --git a/src/features/NavPanel/SideBarHeaderLayout.tsx b/src/features/NavPanel/SideBarHeaderLayout.tsx
index 3f95a06a317..830128f7df4 100644
--- a/src/features/NavPanel/SideBarHeaderLayout.tsx
+++ b/src/features/NavPanel/SideBarHeaderLayout.tsx
@@ -9,7 +9,7 @@ import {
Text,
} from '@lobehub/ui';
import { ChevronRightIcon, HomeIcon } from 'lucide-react';
-import type { ReactNode } from 'react';
+import type { MouseEvent, ReactNode } from 'react';
import { memo } from 'react';
import { flushSync } from 'react-dom';
@@ -39,11 +39,15 @@ const styles = createStaticStyles(({ css, cssVar }) => ({
}));
interface SideBarHeaderLayoutProps {
+ /** `backTo` is a literal path that already carries its workspace scope. */
+ backEscape?: boolean;
backTo?: string;
breadcrumb?: BreadcrumbItem[];
/** Override the leading home breadcrumb item (defaults to home icon β†’ `/`). */
homeItem?: BreadcrumbItem;
left?: ReactNode;
+ /** Runs before the back navigation; `preventDefault()` cancels it. */
+ onBack?: (event: MouseEvent) => void;
right?: ReactNode;
showBack?: boolean;
showTogglePanelButton?: boolean;
@@ -54,6 +58,8 @@ const SideBarHeaderLayout = memo<SideBarHeaderLayoutProps>(
left,
right,
backTo = '/',
+ backEscape,
+ onBack,
showBack = true,
breadcrumb = [],
homeItem,
@@ -70,7 +76,14 @@ const SideBarHeaderLayout = memo<SideBarHeaderLayoutProps>(
overflow: 'hidden',
}}
>
- {showBack && <BackButton size={DESKTOP_HEADER_ICON_SMALL_SIZE} to={backTo} />}
+ {showBack && (
+ <BackButton
+ escape={backEscape}
+ size={DESKTOP_HEADER_ICON_SMALL_SIZE}
+ to={backTo}
+ onClick={onBack}
+ />
+ )}
{left && typeof left === 'string' ? (
<Text ellipsis fontSize={16} weight={500}>
{left}
diff --git a/src/features/NavPanel/backOrigin/Tracker.tsx b/src/features/NavPanel/backOrigin/Tracker.tsx
new file mode 100644
index 00000000000..bd5b48cc42c
--- /dev/null
+++ b/src/features/NavPanel/backOrigin/Tracker.tsx
@@ -0,0 +1,36 @@
+'use client';
+
+import { useEffect, useRef, useState } from 'react';
+
+import { useActiveLocation } from '@/hooks/useActiveLocation';
+
+import { readHistoryIndex } from './historyIndex';
+import { closedOwnersBetween, createBackOriginRecorder, pruneBackOwners } from './index';
+import { parseOpenOwners, useLocationOwner, useOpenOwnersKey } from './useLocationOwner';
+
+/** Feeds every in-app navigation to the back-origin store. Renders nothing. */
+const BackOriginTracker = () => {
+ const { hash, key, pathname, search } = useActiveLocation();
+ const owner = useLocationOwner();
+ const openOwnersKey = useOpenOwnersKey();
+ const [record] = useState(createBackOriginRecorder);
+
+ const openOwnersKeyRef = useRef(openOwnersKey);
+
+ useEffect(() => {
+ const previous = parseOpenOwners(openOwnersKeyRef.current);
+ pruneBackOwners(closedOwnersBetween(previous, parseOpenOwners(openOwnersKey)));
+ openOwnersKeyRef.current = openOwnersKey;
+ }, [openOwnersKey]);
+
+ useEffect(() => {
+ // Desktop tab urls carry no hash; on web it brings back a section anchor.
+ record(owner, `${pathname}${search}${hash}`, readHistoryIndex());
+ // `key` changes when the same url is pushed or popped again (a new history
+ // entry with a new index).
+ }, [owner, pathname, search, hash, key, record]);
+
+ return null;
+};
+
+export default BackOriginTracker;
diff --git a/src/features/NavPanel/backOrigin/historyIndex.desktop.ts b/src/features/NavPanel/backOrigin/historyIndex.desktop.ts
new file mode 100644
index 00000000000..d11f78b5eef
--- /dev/null
+++ b/src/features/NavPanel/backOrigin/historyIndex.desktop.ts
@@ -0,0 +1,5 @@
+/**
+ * Desktop tabs keep their own histories outside `window.history`, so the back
+ * button always navigates to the origin there.
+ */
+export const readHistoryIndex = (): number | undefined => undefined;
diff --git a/src/features/NavPanel/backOrigin/historyIndex.ts b/src/features/NavPanel/backOrigin/historyIndex.ts
new file mode 100644
index 00000000000..bd33997e360
--- /dev/null
+++ b/src/features/NavPanel/backOrigin/historyIndex.ts
@@ -0,0 +1,8 @@
+/**
+ * The react-router index of the current browser history entry, used to walk
+ * back to an origin instead of pushing it again.
+ */
+export const readHistoryIndex = (): number | undefined => {
+ const index = (window.history.state as { idx?: unknown } | null)?.idx;
+ return typeof index === 'number' ? index : undefined;
+};
diff --git a/src/features/NavPanel/backOrigin/index.test.ts b/src/features/NavPanel/backOrigin/index.test.ts
new file mode 100644
index 00000000000..483f89e4aba
--- /dev/null
+++ b/src/features/NavPanel/backOrigin/index.test.ts
@@ -0,0 +1,226 @@
+import { afterEach, describe, expect, it } from 'vitest';
+
+import {
+ closedOwnersBetween,
+ createBackOriginRecorder,
+ getBackOrigin,
+ historyDeltaTo,
+ pruneBackOwners,
+ recordBackLocation,
+ resetBackOrigins,
+ resolveBackScope,
+} from './index';
+
+const walk = (...paths: string[]) => {
+ for (const path of paths) recordBackLocation('main', path);
+};
+
+afterEach(() => {
+ resetBackOrigins();
+});
+
+describe('resolveBackScope', () => {
+ it('scopes agent and group pages by id', () => {
+ expect(resolveBackScope('/agent/agt_1')).toBe('agent:agt_1');
+ expect(resolveBackScope('/agent/agt_1/tpc_2?x=1')).toBe('agent:agt_1');
+ expect(resolveBackScope('/group/grp_1/settings')).toBe('group:grp_1');
+ });
+
+ it('strips a workspace slug prefix', () => {
+ expect(resolveBackScope('/lobehub/agent/agt_1')).toBe('agent:agt_1');
+ expect(resolveBackScope('/lobehub/group/grp_1')).toBe('group:grp_1');
+ });
+
+ it('leaves every other page unscoped', () => {
+ expect(resolveBackScope('/')).toBeNull();
+ expect(resolveBackScope('/agents')).toBeNull();
+ expect(resolveBackScope('/agent')).toBeNull();
+ expect(resolveBackScope('/lobehub/tasks')).toBeNull();
+ expect(resolveBackScope('/lobehub')).toBeNull();
+ });
+});
+
+describe('recordBackLocation', () => {
+ it('remembers the page an agent was opened from', () => {
+ walk('/tasks', '/agent/agt_1');
+ expect(getBackOrigin('main', '/agent/agt_1')).toBe('/tasks');
+ });
+
+ it('keeps the origin while moving inside the agent', () => {
+ walk('/agents', '/agent/agt_1', '/agent/agt_1/tpc_1', '/agent/agt_1/profile');
+ expect(getBackOrigin('main', '/agent/agt_1/profile')).toBe('/agents');
+ });
+
+ it('keeps the query string of the origin', () => {
+ walk('/resource?mode=list', '/lobehub/group/grp_1');
+ expect(getBackOrigin('main', '/lobehub/group/grp_1')).toBe('/resource?mode=list');
+ });
+
+ it('steps back one level at a time through nested entries', () => {
+ walk('/tasks', '/agent/agt_1', '/agent/agt_1/tpc_1', '/group/grp_1');
+ // group β†’ the agent (at the topic it was left on) β†’ the page it was opened from
+ expect(getBackOrigin('main', '/group/grp_1')).toBe('/agent/agt_1/tpc_1');
+ walk('/agent/agt_1/tpc_1');
+ expect(getBackOrigin('main', '/agent/agt_1/tpc_1')).toBe('/tasks');
+ });
+
+ it('cuts the trail when re-entering an entry instead of ping-ponging', () => {
+ walk('/project/p1', '/agent/agt_1', '/agent/agt_2', '/agent/agt_1');
+ expect(getBackOrigin('main', '/agent/agt_1')).toBe('/project/p1');
+ expect(getBackOrigin('main', '/agent/agt_2')).toBeUndefined();
+ });
+
+ it('returns to the same origin after repeated enter / back rounds', () => {
+ for (let round = 0; round < 3; round++) {
+ walk('/tasks', '/agent/agt_1', '/group/grp_1');
+ expect(getBackOrigin('main', '/group/grp_1')).toBe('/agent/agt_1');
+ walk('/agent/agt_1');
+ expect(getBackOrigin('main', '/agent/agt_1')).toBe('/tasks');
+ }
+ });
+
+ it('has no origin when the agent is the first page', () => {
+ walk('/agent/agt_1');
+ expect(getBackOrigin('main', '/agent/agt_1')).toBeUndefined();
+ });
+
+ it('replaces a stale origin on the next entry', () => {
+ walk('/tasks', '/agent/agt_1', '/memory', '/agent/agt_1');
+ expect(getBackOrigin('main', '/agent/agt_1')).toBe('/memory');
+ });
+
+ it('keeps the literal personal origin when an escaped link hops into a workspace', () => {
+ walk('/tasks', '/acme/agent/agt_2');
+ // Not rebased onto `/acme/tasks`: the back button navigates to it as-is.
+ expect(getBackOrigin('main', '/acme/agent/agt_2')).toBe('/tasks');
+ });
+
+ it('returns nothing for unscoped pages', () => {
+ walk('/tasks', '/agent/agt_1');
+ expect(getBackOrigin('main', '/tasks')).toBeUndefined();
+ });
+
+ it('caps the trail length', () => {
+ walk('/tasks', ...Array.from({ length: 80 }, (_, i) => `/agent/agt_${i}`));
+ expect(getBackOrigin('main', '/agent/agt_79')).toBe('/agent/agt_78');
+ });
+});
+
+describe('createBackOriginRecorder', () => {
+ it('records navigations within one owner', () => {
+ const record = createBackOriginRecorder();
+ record('tab-1', '/tasks');
+ record('tab-1', '/agent/agt_1');
+ expect(getBackOrigin('tab-1', '/agent/agt_1')).toBe('/tasks');
+ });
+
+ it('does not treat switching to another tab as a navigation', () => {
+ const record = createBackOriginRecorder();
+ record('tab-1', '/projects');
+ record('tab-1', '/agent/agt_1');
+ record('tab-2', '/tasks');
+ record('tab-1', '/agent/agt_1');
+ expect(getBackOrigin('tab-1', '/agent/agt_1')).toBe('/projects');
+ });
+
+ it('keeps a separate origin for the same agent open in two tabs', () => {
+ const record = createBackOriginRecorder();
+ record('tab-1', '/projects');
+ record('tab-1', '/agent/agt_1');
+ record('tab-2', '/tasks');
+ record('tab-2', '/agent/agt_1');
+ expect(getBackOrigin('tab-1', '/agent/agt_1')).toBe('/projects');
+ expect(getBackOrigin('tab-2', '/agent/agt_1')).toBe('/tasks');
+ });
+
+ it('gives an agent first seen in a fresh tab no origin', () => {
+ const record = createBackOriginRecorder();
+ record('tab-1', '/tasks');
+ record('tab-2', '/agent/agt_1');
+ record('tab-1', '/tasks');
+ record('tab-2', '/agent/agt_1');
+ expect(getBackOrigin('tab-2', '/agent/agt_1')).toBeUndefined();
+ });
+
+ it('gives a tab duplicated from another one the source origin', () => {
+ const record = createBackOriginRecorder();
+ record('tab-1', '/projects');
+ record('tab-1', '/agent/agt_1');
+ record('tab-2', '/agent/agt_1');
+ expect(getBackOrigin('tab-2', '/agent/agt_1')).toBe('/projects');
+ });
+
+ it('keeps the hash of the origin page', () => {
+ const record = createBackOriginRecorder();
+ record('main', '/page/docs_1#notes');
+ record('main', '/agent/agt_1');
+ expect(getBackOrigin('main', '/agent/agt_1')).toBe('/page/docs_1#notes');
+ });
+});
+
+describe('history walk-back', () => {
+ it('steps back over the entries opened inside the agent', () => {
+ recordBackLocation('main', '/tasks', 3);
+ recordBackLocation('main', '/agent/agt_1', 4);
+ recordBackLocation('main', '/agent/agt_1/tpc_1', 5);
+ const origin = { historyIndex: 3, location: '/tasks' };
+ expect(historyDeltaTo(origin, 5)).toBe(-2);
+ });
+
+ it('falls back to pushing when the origin is not an earlier history entry', () => {
+ // replaced into the agent, unknown indexes (desktop tabs), or a later entry
+ expect(historyDeltaTo({ historyIndex: 4, location: '/tasks' }, 4)).toBeUndefined();
+ expect(historyDeltaTo({ location: '/tasks' }, 4)).toBeUndefined();
+ expect(historyDeltaTo({ historyIndex: 2, location: '/tasks' }, undefined)).toBeUndefined();
+ expect(historyDeltaTo({ historyIndex: 6, location: '/tasks' }, 4)).toBeUndefined();
+ });
+
+ it('records a revisit of the same location at a new history index', () => {
+ recordBackLocation('main', '/tasks', 1);
+ recordBackLocation('main', '/tasks', 3);
+ recordBackLocation('main', '/agent/agt_1', 4);
+ expect(getBackOrigin('main', '/agent/agt_1')).toBe('/tasks');
+ });
+});
+
+describe('pruneBackOwners', () => {
+ it('drops the trails of closed tabs and keeps open ones however many there are', () => {
+ const record = createBackOriginRecorder();
+ for (let tab = 0; tab < 30; tab++) {
+ record(`tab-${tab}`, `/page/${tab}`);
+ record(`tab-${tab}`, '/agent/agt_1');
+ }
+ pruneBackOwners(['tab-0']);
+
+ expect(getBackOrigin('tab-0', '/agent/agt_1')).toBeUndefined();
+ expect(getBackOrigin('tab-1', '/agent/agt_1')).toBe('/page/1');
+ expect(getBackOrigin('tab-29', '/agent/agt_1')).toBe('/page/29');
+ });
+
+ it('always keeps the main owner', () => {
+ walk('/tasks', '/agent/agt_1');
+ pruneBackOwners(['main']);
+ expect(getBackOrigin('main', '/agent/agt_1')).toBe('/tasks');
+ });
+});
+
+describe('closedOwnersBetween', () => {
+ it('reports tabs that left the list within one scope', () => {
+ expect(
+ closedOwnersBetween(
+ { ids: ['tab-1', 'tab-2'], scope: 'personal' },
+ { ids: ['tab-2'], scope: 'personal' },
+ ),
+ ).toEqual(['tab-1']);
+ });
+
+ it('closes nothing when the scope switches', () => {
+ expect(
+ closedOwnersBetween(
+ { ids: ['tab-1', 'tab-2'], scope: 'personal' },
+ { ids: ['tab-3'], scope: 'workspace:acme' },
+ ),
+ ).toEqual([]);
+ expect(closedOwnersBetween(null, { ids: ['tab-3'], scope: 'personal' })).toEqual([]);
+ });
+});
diff --git a/src/features/NavPanel/backOrigin/index.ts b/src/features/NavPanel/backOrigin/index.ts
new file mode 100644
index 00000000000..ee42a02b1b1
--- /dev/null
+++ b/src/features/NavPanel/backOrigin/index.ts
@@ -0,0 +1,216 @@
+import { type MouseEvent, useSyncExternalStore } from 'react';
+
+import { RESERVED_ROOT_SEGMENTS } from '@/features/Workspace/rootSegments';
+import { useActiveLocation } from '@/hooks/useActiveLocation';
+
+import { readHistoryIndex } from './historyIndex';
+import { MAIN_OWNER, type OpenOwners, useLocationOwner } from './useLocationOwner';
+
+/**
+ * Sidebars that own a back button for one entity (an agent or a group) send it
+ * to the page the user opened that entity from, instead of always going home.
+ * Opened straight from a link (nothing before it), back falls back to home.
+ */
+const SCOPED_ROOT_SEGMENTS: ReadonlySet<string> = new Set(['agent', 'group']);
+
+/**
+ * The entity a path belongs to (`agent:<id>` / `group:<id>`), with an optional
+ * `/:workspaceSlug` prefix stripped. Any other page has no scope.
+ */
+export const resolveBackScope = (pathname: string): string | null => {
+ const segments = pathname.split(/[?#]/)[0].split('/').filter(Boolean);
+ const routeSegments =
+ segments.length > 0 && !RESERVED_ROOT_SEGMENTS.has(segments[0]) ? segments.slice(1) : segments;
+ const [root, id] = routeSegments;
+
+ if (!root || !id || !SCOPED_ROOT_SEGMENTS.has(root)) return null;
+ return `${root}:${id}`;
+};
+
+type Listener = () => void;
+
+/** One step of a trail: where the user was, and its browser history index when known. */
+export interface BackEntry {
+ /** `history.state.idx` of that location on web; unknown on desktop tabs. */
+ historyIndex?: number;
+ location: string;
+}
+
+type Stacks = Readonly<Record<string, readonly BackEntry[]>>;
+
+/** Stacks never grow past this many entries; the oldest are dropped first. */
+const MAX_STACK = 50;
+
+/**
+ * Per owner (an Electron tab, or `main` on web), the trail that led to the
+ * current page: the last unscoped page, then each agent / group entered from it
+ * in order, each holding the latest location seen inside it.
+ */
+let stacks: Stacks = {};
+const listeners = new Set<Listener>();
+
+const subscribe = (listener: Listener) => {
+ listeners.add(listener);
+ return () => {
+ listeners.delete(listener);
+ };
+};
+
+const getStacks = () => stacks;
+
+const setStack = (owner: string, stack: readonly BackEntry[]) => {
+ stacks = { ...stacks, [owner]: stack.slice(-MAX_STACK) };
+ listeners.forEach((listener) => listener());
+};
+
+/**
+ * Forget the trails of owners that were closed (Electron tabs). `main` (the web
+ * router, or desktop without tabs) is always kept.
+ */
+export const pruneBackOwners = (closedOwners: Iterable<string>): void => {
+ const closed = new Set(closedOwners);
+ closed.delete(MAIN_OWNER);
+ if (![...closed].some((owner) => owner in stacks)) return;
+
+ stacks = Object.fromEntries(Object.entries(stacks).filter(([owner]) => !closed.has(owner)));
+ listeners.forEach((listener) => listener());
+};
+
+/**
+ * The owners closed between two snapshots of the open owners. A snapshot taken
+ * in another scope (personal vs a workspace) lists that scope's tabs instead, so
+ * a scope switch closes nothing: those tabs come back when the user returns.
+ */
+export const closedOwnersBetween = (
+ previous: OpenOwners | null,
+ next: OpenOwners | null,
+): string[] => {
+ if (!previous || !next || previous.scope !== next.scope) return [];
+ const open = new Set(next.ids);
+ return previous.ids.filter((id) => !open.has(id));
+};
+
+const findScope = (stack: readonly BackEntry[], scope: string): number =>
+ stack.findLastIndex((entry) => resolveBackScope(entry.location) === scope);
+
+/**
+ * Record that `owner` is now at `location`.
+ *
+ * - An unscoped page starts a new trail.
+ * - Moving inside the current agent / group (topics, sub pages) only updates
+ * where that entry points.
+ * - Entering an agent / group pushes it, so back steps out one level at a time
+ * (page β†’ agent β†’ group goes back to the agent, then to the page).
+ * - Re-entering one already on the trail cuts the trail back to it, so hopping
+ * A β†’ B β†’ A and pressing back leaves for the page A was opened from instead
+ * of bouncing between A and B.
+ */
+export const recordBackLocation = (
+ owner: string,
+ location: string,
+ historyIndex?: number,
+): void => {
+ const stack = stacks[owner] ?? [];
+ const top = stack.at(-1);
+ if (top?.location === location && top.historyIndex === historyIndex) return;
+
+ const entry: BackEntry = { historyIndex, location };
+ const scope = resolveBackScope(location);
+ if (!scope) return setStack(owner, [entry]);
+
+ const index = findScope(stack, scope);
+ setStack(owner, index === -1 ? [...stack, entry] : [...stack.slice(0, index), entry]);
+};
+
+/**
+ * Feeds locations to {@link recordBackLocation}. Switching to another owner is
+ * not a navigation: each owner keeps its own trail. An owner first seen at the
+ * location the previously active owner was on is a duplicate of it (a tab split
+ * into a new pane) and starts from a copy of its trail.
+ */
+export const createBackOriginRecorder = () => {
+ let lastOwner: string | null = null;
+
+ return (owner: string, location: string, historyIndex?: number): void => {
+ const sourceOwner = lastOwner;
+ lastOwner = owner;
+
+ const source = sourceOwner ? stacks[sourceOwner] : undefined;
+ if (!stacks[owner] && source?.at(-1)?.location === location) {
+ setStack(owner, source);
+ return;
+ }
+ recordBackLocation(owner, location, historyIndex);
+ };
+};
+
+const selectOrigin = (all: Stacks, owner: string, pathname: string): BackEntry | undefined => {
+ const scope = resolveBackScope(pathname);
+ const stack = all[owner];
+ if (!scope || !stack) return undefined;
+
+ const index = findScope(stack, scope);
+ return index > 0 ? stack[index - 1] : undefined;
+};
+
+export const getBackOrigin = (owner: string, pathname: string): string | undefined =>
+ selectOrigin(stacks, owner, pathname)?.location;
+
+/**
+ * How many browser history steps lead back to `origin`, or `undefined` when it
+ * is not an earlier entry of the current history (desktop tabs, a `replace`
+ * into the agent, a reload that lost the index).
+ */
+export const historyDeltaTo = (
+ origin: BackEntry,
+ currentIndex: number | undefined,
+): number | undefined => {
+ if (origin.historyIndex === undefined || currentIndex === undefined) return undefined;
+ const delta = origin.historyIndex - currentIndex;
+ return delta < 0 ? delta : undefined;
+};
+
+/** Test-only: forget every recorded trail. */
+export const resetBackOrigins = (): void => {
+ stacks = {};
+ listeners.forEach((listener) => listener());
+};
+
+/**
+ * Back button props for the agent / group sidebar header.
+ *
+ * The origin is the literal location the user was on, so it already carries its
+ * own personal or workspace scope: it is navigated to as-is instead of being
+ * rebased onto the active workspace (an escaped cross-workspace link would
+ * otherwise send a personal `/tasks` origin to `/<slug>/tasks`).
+ *
+ * When the origin is still an earlier entry of the browser history, a plain
+ * click walks the history back to it instead of pushing it again, so the
+ * browser back button and the in-page one stay in step. Without an origin
+ * (opened straight from a link) back goes home.
+ */
+export const useBackButtonProps = (): {
+ backEscape: boolean;
+ backTo: string;
+ onBack?: (event: MouseEvent) => void;
+} => {
+ const { pathname } = useActiveLocation();
+ const owner = useLocationOwner();
+ const all = useSyncExternalStore(subscribe, getStacks, getStacks);
+ const origin = selectOrigin(all, owner, pathname);
+
+ if (!origin) return { backEscape: false, backTo: '/' };
+
+ return {
+ backEscape: true,
+ backTo: origin.location,
+ onBack: (event) => {
+ if (event.metaKey || event.ctrlKey || event.shiftKey || event.altKey || event.button !== 0)
+ return;
+ const delta = historyDeltaTo(origin, readHistoryIndex());
+ if (delta === undefined) return;
+ event.preventDefault();
+ window.history.go(delta);
+ },
+ };
+};
diff --git a/src/features/NavPanel/backOrigin/useLocationOwner.desktop.ts b/src/features/NavPanel/backOrigin/useLocationOwner.desktop.ts
new file mode 100644
index 00000000000..2a39ee16044
--- /dev/null
+++ b/src/features/NavPanel/backOrigin/useLocationOwner.desktop.ts
@@ -0,0 +1,18 @@
+import { tabScopeKey } from '@/features/Electron/titlebar/TabBar/scope';
+import { useElectronStore } from '@/store/electron';
+
+import { MAIN_OWNER } from './useLocationOwner';
+
+export { MAIN_OWNER, type OpenOwners, parseOpenOwners } from './useLocationOwner';
+
+/**
+ * Which history a location belongs to: each Electron tab (or split pane) keeps
+ * its own, so focusing another tab is not a navigation.
+ */
+export const useLocationOwner = (): string => useElectronStore((s) => s.activeTabId) ?? MAIN_OWNER;
+
+/** The active tab scope, then its open tab ids, joined by `\n`. */
+export const useOpenOwnersKey = (): string | null =>
+ useElectronStore((s) =>
+ [tabScopeKey(s.activeTabScope), ...s.tabs.map((tab) => tab.id)].join('\n'),
+ );
diff --git a/src/features/NavPanel/backOrigin/useLocationOwner.ts b/src/features/NavPanel/backOrigin/useLocationOwner.ts
new file mode 100644
index 00000000000..97db4c38b62
--- /dev/null
+++ b/src/features/NavPanel/backOrigin/useLocationOwner.ts
@@ -0,0 +1,23 @@
+/** The owner of locations that do not belong to an Electron tab. */
+export const MAIN_OWNER = 'main';
+
+/** The owners open in one tab scope (personal or a workspace). */
+export interface OpenOwners {
+ ids: string[];
+ scope: string;
+}
+
+/** Which history a location belongs to. The web app has one router. */
+export const useLocationOwner = (): string => MAIN_OWNER;
+
+/**
+ * The open owners as a stable string key (see `parseOpenOwners`), or `null`
+ * when owners never close.
+ */
+export const useOpenOwnersKey = (): string | null => null;
+
+export const parseOpenOwners = (key: string | null): OpenOwners | null => {
+ if (key === null) return null;
+ const [scope, ...ids] = key.split('\n');
+ return { ids, scope };
+};
diff --git a/src/features/NavPanel/components/BackButton.tsx b/src/features/NavPanel/components/BackButton.tsx
index a385c75c2bf..4698953c051 100644
--- a/src/features/NavPanel/components/BackButton.tsx
+++ b/src/features/NavPanel/components/BackButton.tsx
@@ -9,9 +9,15 @@ import { buildWorkspaceAwarePath } from '@/features/Workspace/workspaceAwarePath
export const BACK_BUTTON_ID = 'lobe-back-button';
-const BackButton = memo<ActionIconProps & { to?: string }>(({ to = '/', onClick, ...rest }) => {
+interface BackButtonProps extends ActionIconProps {
+ /** Go to the literal `to` without applying the active workspace prefix. */
+ escape?: boolean;
+ to?: string;
+}
+
+const BackButton = memo<BackButtonProps>(({ to = '/', escape, onClick, ...rest }) => {
const activeSlug = useActiveWorkspaceSlug();
- const resolvedTo = buildWorkspaceAwarePath(to, activeSlug);
+ const resolvedTo = buildWorkspaceAwarePath(to, activeSlug, { escape });
const handleClick = (event: MouseEvent<HTMLAnchorElement>) => {
onClick?.(event as never);
diff --git a/src/routes/(main)/group/_layout/Sidebar/Header/index.tsx b/src/routes/(main)/group/_layout/Sidebar/Header/index.tsx
index 47bcb4fdcca..95243592efa 100644
--- a/src/routes/(main)/group/_layout/Sidebar/Header/index.tsx
+++ b/src/routes/(main)/group/_layout/Sidebar/Header/index.tsx
@@ -2,15 +2,18 @@
import { type PropsWithChildren } from 'react';
+import { useBackButtonProps } from '@/features/NavPanel/backOrigin';
import SideBarHeaderLayout from '@/features/NavPanel/SideBarHeaderLayout';
import Agent from './Agent';
import Nav from './Nav';
const HeaderInfo = (_props: PropsWithChildren) => {
+ const back = useBackButtonProps();
+
return (
<>
- <SideBarHeaderLayout left={<Agent />} />
+ <SideBarHeaderLayout {...back} left={<Agent />} />
<Nav />
</>
);