π€― 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.
TypeScript agentagent-collaborationagent-harnessloop-engineeringmcppersonal-assistantproactive-agentskillssuper-agenttask-management
β»οΈ refactor(desktop): route Electron shell through per-tab keep-alive routers (#17595)
Innei8333b61729c2
diff --git a/.agents/acceptance/common-mistakes.md b/.agents/acceptance/common-mistakes.mdindex 23ea4c954ed..a8c4506e460 100644--- a/.agents/acceptance/common-mistakes.md+++ b/.agents/acceptance/common-mistakes.md@@ -138,6 +138,28 @@ together and visually verify their side-by-side rendering.## Environment safety+### L-S2 β Trusting `vite build` exit 0 as proof the desktop renderer boots++**Wrong approach:** accept a green `vite build --config vite.renderer.config.ts`+(plus green vitest) as blank-screen insurance for a routing/module-graph+refactor, skipping a real Electron boot.++**Why it fails:** bundlers serialize import cycles at build time; a+module-initialization-order TDZ (`Cannot access 'X' before initialization`)+only fires at runtime, and vitest's module runner resolves cycles differently+from browser ESM, so both stay green while the packaged renderer white-screens+at boot. Observed on the per-tab-router branch: `utils/router.tsx β+NavigatorRegistrar.desktop β β¦ β tabRouterManager β tabRouter β+desktopRouter.config.desktop` cycle crashed boot with `_jsxDEV` TDZ; a second+runtime-only crash (react-router's nested-`<Router>` invariant) hid behind it+because unit tests mounted TabHost without an outer router.++**Correct approach:** for any change touching the desktop module graph or+router composition, boot the real instance (`electron-dev.sh start`) and gate+on `app-probe.sh ready` returning `ok:true` with a non-error UI screenshot+before publishing. Component tests for router-hosting components must include+an outer-router mounting variant.+### L-S1 β Acquiring Electron auth through OAuth**Wrong approach:** click Sign in or call `requestAuthorization` on a dev instance.@@ -346,4 +368,4 @@ full incident narratives and old Case numbers for earlier cross-references.- **Wrong approach**: attach `agent-browser --cdp 9222` and evaluate DOM/state assuming it is the LobeHub dev Electron.- **Why**: 9222 is a universal default; other projects' dev Electrons (e.g. unrelated repos) claim it first. A user-started LobeHub dev instance often has NO `--remote-debugging-port` at all.- **What it breaks**: all collected evidence (DOM, localStorage, console) silently describes a different product.-- **Correct approach**: before any eval, verify identity β check the process command line (`ps ax | rg Electron` β path must be under this repo) and probe the renderer (e.g. script srcs / a known global). If the user's instance has no CDP, start a pool instance (`electron-dev.sh start <n>`, distinct port) instead of guessing; note a user-started instance may die when the pool instance boots (observed once, causality unverified) β warn the user first.\ No newline at end of file+- **Correct approach**: before any eval, verify identity β check the process command line (`ps ax | rg Electron` β path must be under this repo) and probe the renderer (e.g. script srcs / a known global). If the user's instance has no CDP, start a pool instance (`electron-dev.sh start <n>`, distinct port) instead of guessing; note a user-started instance may die when the pool instance boots (observed once, causality unverified) β warn the user first.diff --git a/.agents/acceptance/probe-mock-patterns.md b/.agents/acceptance/probe-mock-patterns.mdindex 5d65eaf6cc9..2d37bced522 100644--- a/.agents/acceptance/probe-mock-patterns.md+++ b/.agents/acceptance/probe-mock-patterns.md@@ -200,6 +200,101 @@ in the renderer graph, which makes Vite optimize and execute `vitest` in the appimport the locale resource there. Restart the isolated Electron instance after abad scan because the optimized dependency graph can remain poisoned.+### Desktop tab switching is not `activateTab` alone β drive the real tab element++**Situation:** benchmarking or driving a desktop tab switch from an `eval`+payload, using `window.__LOBE_STORES.electron().activateTab(id)`.++**Doesn't work:** on the single-router shell, `activateTab` only writes+`activeTabId`; navigation is a second step performed by the TabBar+(`handleActivate` = `activateTab(id)` + `startTransition(navigate(url))`). Calling+the store action alone leaves `location.pathname` on the previous route, so the+run measures a no-op β visible as a tiny settle time, \~4 DOM mutations, and zero+long tasks, which reads like an impossibly fast surface rather than a broken+probe. The per-tab-router shell does switch content from the store action alone,+so the same payload is a real switch on one build and a no-op on the other:+any A/B built on it is invalid.++**Works:** drive the tab element the user actually clicks, and assert the+navigation happened.++```js+const all = [...document.querySelectorAll('[data-insp-path*="TabBar/TabItem.tsx"]')].filter(+ (e) => e.getBoundingClientRect().width > 100,+);+// two nested nodes per tab match β keep only the outermost+const roots = all+ .filter((e) => !all.some((o) => o !== e && o.contains(e)))+ .sort((a, b) => a.getBoundingClientRect().x - b.getBoundingClientRect().x);+// roots[i] aligns 1:1 with store tabs[i]; verify roots.length === tabs.length+roots[idx].click();+```++`el.click()` reaches the React `onClick` here (this is not a controlled input, so+the generic D11 trusted-input caveat does not apply). Always record+`location.pathname` before and after and keep a `navigated` flag on every sample β+that flag is what catches a payload that silently stopped switching.++### Clicking an already-active tab is a no-op β a desynced tab can never be re-entered by clicking++**Situation:** a probe adds a tab with `addTab(url)` and then clicks it to enter that route.++**Doesn't work:** `addTab` already activates the new tab, so the later click lands on the _active_ tab+and the shell does nothing. On the single-router shell this can leave `activeTabId` pointing at a tab+whose URL names one topic while `location.pathname` and `chat().activeTopicId` still name another β+after which no amount of clicking recovers it, and every downstream assertion reads the wrong page.+Symptom: the probe's final `location.pathname` is not the tab you clicked, with no error anywhere.++**Works:** after `addTab`, enter the route with a full navigation+(`app-probe.sh goto <url>`) before starting the trials, and assert the three values agree before+measuring:++```js+const st = window.__LOBE_STORES.electron();+const chat = window.__LOBE_STORES.chat();+const tab = (st.tabs || []).find((t) => t.id === st.activeTabId);+// tab.url, location.pathname and chat.activeTopicId must all point at the same topic+```++### Attributing switch work to hidden keep-alive trees β classify on BOTH sides of the action++**Situation:** measuring what a per-tab keep-alive shell costs while a tab is hidden.++**Doesn't work:** collecting the hidden slots (the `display: none` children of the TabHost root) _before_+the switch and classifying every mutation against that list. The switch is precisely what makes the+target tab visible, and that tab was hidden when the list was captured β so the incoming tab's own+render, which is necessary user-visible work, is counted as hidden-tree work. This produced a confident+"\~44% of switch work happens off-screen" that was pure artefact, and it survived review because the+number looked plausible.++**Works:** classify against the intersection β slots hidden **before** the switch that are **still+hidden after** it:++```js+const before = hiddenSlots(); // display:none children of the TabHost root+/* click the tab, observe mutations */+const after = hiddenSlots();+const stillHidden = before.filter((s) => after.includes(s));+```++Measured this way, still-hidden slots produced **0** mutations in 6/6 switches: React+`<Activity mode="hidden">` keeps state, tears down effects, and commits nothing while hidden.++**General rule:** when a measurement classifies work by a property that the measured action itself+changes (visible/hidden, active/inactive, mounted/unmounted), capture the classification on both sides+and use the intersection. Otherwise the action's own effect lands in the wrong bucket.++### `eval` declarations persist in the page global scope++**Situation:** running several `agent-browser eval` payloads against one renderer.++**Doesn't work:** a bare top-level `const els = β¦` in a second payload fails with+`SyntaxError: Identifier 'els' has already been declared`, because each `eval`+shares the page's global scope.++**Works:** wrap every payload in an IIFE (`(() => { β¦ })()`), or attach state to a+single namespaced `window.__X` object.+### Shared agent-browser session names can cross-wire concurrent acceptance runs**Situation:** a Web acceptance run uses the adapter's default `lobehub-dev`diff --git a/AGENTS.md b/AGENTS.mdindex edd220a7057..97bc1e6d3ab 100644--- a/AGENTS.md+++ b/AGENTS.md@@ -62,7 +62,7 @@ When adding or changing SPA routes:1. In `src/routes/`, add only the route segment files (layout + page) that delegate to features.2. Implement layout and page content under `src/features/<Domain>/` and export from there.3. In route files, use `import { X } from '@/features/<Domain>'` (or `import Y from '@/features/<Domain>/...'`). Do not add new `features/` folders inside `src/routes/`.-4. **Register the desktop route tree in both configs:** `src/spa/router/desktopRouter.config.tsx` and `src/spa/router/desktopRouter.config.desktop.tsx` must stay in sync (same paths and nesting). Updating only one can cause **blank screens** if the other build path expects the route. `desktopRouter.sync.test.tsx` guards this invariant β keep it passing.+4. **Register desktop content routes in the `createMainAreaChildren()` twins:** the main-area content tree is built by `createMainAreaChildren()`, which exists in both `src/spa/router/desktopRouter.config.tsx` and `src/spa/router/desktopRouter.config.desktop.tsx` and must stay in sync (same paths and nesting). Web mounts these children under the root router; electron mounts them in per-tab memory routers via `src/spa/router/tabRouter.tsx`, so the electron root config's `/` children are intentionally slim stubs. Updating only one twin can cause **blank screens**. `desktopRouter.sync.test.tsx` guards builder parity β keep it passing.See the **spa-routes** skill for the full convention and file-division rules.diff --git a/changelog/v2.json b/changelog/v2.jsonindex 059848a244d..90abf1ec630 100644--- a/changelog/v2.json+++ b/changelog/v2.json@@ -91,12 +91,8 @@},{"children": {- "fixes": [- "hide runtime-only model aliases."- ],- "features": [- "set OSS default model to DeepSeek V4 Pro."- ]+ "fixes": ["hide runtime-only model aliases."],+ "features": ["set OSS default model to DeepSeek V4 Pro."]},"date": "2026-05-09","version": "2.1.57"@@ -113,9 +109,7 @@},{"children": {- "fixes": [- "clear stale topic when switching agents from a topic route."- ]+ "fixes": ["clear stale topic when switching agents from a topic route."]},"date": "2026-04-27","version": "2.1.54"@@ -127,10 +121,7 @@},{"children": {- "fixes": [- "fix minify cli.",- "recent delete."- ]+ "fixes": ["fix minify cli.", "recent delete."]},"date": "2026-04-16","version": "2.1.51"@@ -142,21 +133,15 @@},{"children": {- "improvements": [- "add agent task system database schema."- ]+ "improvements": ["add agent task system database schema."]},"date": "2026-03-26","version": "2.1.45"},{"children": {- "fixes": [- "misc UI/UX improvements and bug fixes."- ],- "improvements": [- "add image/video switch."- ]+ "fixes": ["misc UI/UX improvements and bug fixes."],+ "improvements": ["add image/video switch."]},"date": "2026-03-20","version": "2.1.44"@@ -188,27 +173,21 @@},{"children": {- "improvements": [- "add api key hash column migration."- ]+ "improvements": ["add api key hash column migration."]},"date": "2026-03-09","version": "2.1.39"},{"children": {- "fixes": [- "when use trustclient not register market m2m token."- ]+ "fixes": ["when use trustclient not register market m2m token."]},"date": "2026-03-06","version": "2.1.38"},{"children": {- "improvements": [- "Update i18n."- ]+ "improvements": ["Update i18n."]},"date": "2026-02-10","version": "2.1.26"@@ -220,9 +199,7 @@},{"children": {- "fixes": [- "Fix multimodal content_part images rendered as base64 text."- ]+ "fixes": ["Fix multimodal content_part images rendered as base64 text."]},"date": "2026-02-09","version": "2.1.24"@@ -232,18 +209,14 @@"fixes": ["Fix editor content missing when send error, use custom avatar for group chat in sidebar."],- "improvements": [- "Update i18n."- ]+ "improvements": ["Update i18n."]},"date": "2026-02-09","version": "2.1.23"},{"children": {- "fixes": [- "Register Notebook tool in server runtime."- ]+ "fixes": ["Register Notebook tool in server runtime."]},"date": "2026-02-08","version": "2.1.22"@@ -268,9 +241,7 @@},{"children": {- "fixes": [- "Fixed in community pluings tab the lobehub skills not display."- ]+ "fixes": ["Fixed in community pluings tab the lobehub skills not display."]},"date": "2026-02-06","version": "2.1.19"@@ -287,27 +258,21 @@},{"children": {- "fixes": [- "Add the preview publish to market button preview check."- ]+ "fixes": ["Add the preview publish to market button preview check."]},"date": "2026-02-04","version": "2.1.16"},{"children": {- "fixes": [- "Fixed the agents list the show updateAt time error."- ]+ "fixes": ["Fixed the agents list the show updateAt time error."]},"date": "2026-02-04","version": "2.1.15"},{"children": {- "fixes": [- "Fix cannot uncompressed messages."- ]+ "fixes": ["Fix cannot uncompressed messages."]},"date": "2026-02-04","version": "2.1.14"@@ -324,9 +289,7 @@},{"children": {- "fixes": [- "Hide password features when AUTH_DISABLE_EMAIL_PASSWORD is set."- ]+ "fixes": ["Hide password features when AUTH_DISABLE_EMAIL_PASSWORD is set."]},"date": "2026-02-02","version": "2.1.11"@@ -338,54 +301,42 @@},{"children": {- "fixes": [- "Use oauth2.link for generic OIDC provider account linking."- ]+ "fixes": ["Use oauth2.link for generic OIDC provider account linking."]},"date": "2026-02-02","version": "2.1.9"},{"children": {- "improvements": [- "Improve tasks display."- ]+ "improvements": ["Improve tasks display."]},"date": "2026-02-01","version": "2.1.8"},{"children": {- "fixes": [- "Add missing description parameter docs in Notebook system prompt."- ]+ "fixes": ["Add missing description parameter docs in Notebook system prompt."]},"date": "2026-02-01","version": "2.1.7"},{"children": {- "improvements": [- "Improve local-system tool implement."- ]+ "improvements": ["Improve local-system tool implement."]},"date": "2026-02-01","version": "2.1.6"},{"children": {- "fixes": [- "Slove the group member agents cant set skills problem."- ]+ "fixes": ["Slove the group member agents cant set skills problem."]},"date": "2026-01-31","version": "2.1.5"},{"children": {- "improvements": [- "Update i18n, Update Kimi K2.5 & Qwen3 Max Thinking models."- ]+ "improvements": ["Update i18n, Update Kimi K2.5 & Qwen3 Max Thinking models."]},"date": "2026-01-31","version": "2.1.4"@@ -397,63 +348,49 @@},{"children": {- "fixes": [- "Fix feishu sso provider."- ]+ "fixes": ["Fix feishu sso provider."]},"date": "2026-01-30","version": "2.1.2"},{"children": {- "fixes": [- "Correct desktop download URL path."- ]+ "fixes": ["Correct desktop download URL path."]},"date": "2026-01-30","version": "2.1.1"},{"children": {- "features": [- "Refactor cron job UI and use runtime enableBusinessFeatures flag."- ]+ "features": ["Refactor cron job UI and use runtime enableBusinessFeatures flag."]},"date": "2026-01-30","version": "2.1.0"},{"children": {- "improvements": [- "Fix usage table display issues."- ]+ "improvements": ["Fix usage table display issues."]},"date": "2026-01-29","version": "2.0.13"},{"children": {- "fixes": [- "Group publish to market should set local group market identifer."- ]+ "fixes": ["Group publish to market should set local group market identifer."]},"date": "2026-01-29","version": "2.0.12"},{"children": {- "improvements": [- "Fix group task render."- ]+ "improvements": ["Fix group task render."]},"date": "2026-01-29","version": "2.0.11"},{"children": {- "fixes": [- "Add ExtendParamsTypeSchema for enhanced model settings."- ]+ "fixes": ["Add ExtendParamsTypeSchema for enhanced model settings."]},"date": "2026-01-29","version": "2.0.10"@@ -465,9 +402,7 @@},{"children": {- "fixes": [- "Fix inbox agent in mobile."- ]+ "fixes": ["Fix inbox agent in mobile."]},"date": "2026-01-28","version": "2.0.8"@@ -479,27 +414,21 @@},{"children": {- "fixes": [- "The klavis in onboarding connect timeout fixed."- ]+ "fixes": ["The klavis in onboarding connect timeout fixed."]},"date": "2026-01-27","version": "2.0.6"},{"children": {- "fixes": [- "Update the artifact prompt."- ]+ "fixes": ["Update the artifact prompt."]},"date": "2026-01-27","version": "2.0.5"},{"children": {- "fixes": [- "Rename docker image and update docs for v2."- ]+ "fixes": ["Rename docker image and update docs for v2."]},"date": "2026-01-27","version": "2.0.4"@@ -515,9 +444,7 @@},{"children": {- "fixes": [- "Slove the recentTopicLinkError."- ]+ "fixes": ["Slove the recentTopicLinkError."]},"date": "2026-01-27","version": "2.0.2"diff --git a/src/components/CollapsibleContent/index.tsx b/src/components/CollapsibleContent/index.tsxindex 0570dd6d9c8..33a5c8c0a67 100644--- a/src/components/CollapsibleContent/index.tsx+++ b/src/components/CollapsibleContent/index.tsx@@ -3,9 +3,11 @@import { createStaticStyles } from 'antd-style';import { ChevronDownIcon, ChevronUpIcon } from 'lucide-react';import type { CSSProperties, MouseEvent, ReactNode } from 'react';-import { memo, useCallback, useEffect, useLayoutEffect, useRef, useState } from 'react';+import { memo, useCallback, useEffect, useRef, useState } from 'react';import { useTranslation } from 'react-i18next';+import { useNaturalHeight } from './useNaturalHeight';+const DEFAULT_MAX_HEIGHT = 280;const DEFAULT_FADE_HEIGHT = 48;// The fade must stay under one line-height, or the last visible line is a ghost@@ -97,25 +99,9 @@ const CollapsibleContent = memo<CollapsibleContentProps>(const contentRef = useRef<HTMLDivElement | null>(null);const [maxHeight, setMaxHeight] = useState(() => computeThreshold(maxHeightLimit));- const [naturalHeight, setNaturalHeight] = useState(0);const [collapsed, setCollapsed] = useState(true);- // Measure content's natural (unconstrained) height. We read scrollHeight so- // the value is unaffected by our own max-height clamp.- useLayoutEffect(() => {- const el = contentRef.current;- if (!el) return;-- const measure = () => {- setNaturalHeight(el.scrollHeight);- };- measure();-- if (typeof ResizeObserver === 'undefined') return;- const observer = new ResizeObserver(measure);- observer.observe(el);- return () => observer.disconnect();- }, []);+ const naturalHeight = useNaturalHeight(contentRef);useEffect(() => {if (typeof window === 'undefined') return;diff --git a/src/components/CollapsibleContent/useNaturalHeight.test.ts b/src/components/CollapsibleContent/useNaturalHeight.test.tsnew file mode 100644index 00000000000..77381d0ae39--- /dev/null+++ b/src/components/CollapsibleContent/useNaturalHeight.test.ts@@ -0,0 +1,86 @@+import { act, renderHook } from '@testing-library/react';+import { type RefObject } from 'react';+import { afterEach, beforeEach, describe, expect, it } from 'vitest';++import { useNaturalHeight } from './useNaturalHeight';++type ObserverEntry = { contentRect: { height: number; width: number } };++let notify: ((entries: ObserverEntry[]) => void) | undefined;+let observed = 0;+let disconnected = 0;++const originalResizeObserver = globalThis.ResizeObserver;++const elementWithScrollHeight = (initial: number) => {+ const el = { scrollHeight: initial };+ return { el, ref: { current: el as unknown as HTMLElement } as RefObject<HTMLElement | null> };+};++beforeEach(() => {+ notify = undefined;+ observed = 0;+ disconnected = 0;+ globalThis.ResizeObserver = class {+ constructor(cb: (entries: ObserverEntry[]) => void) {+ notify = cb;+ }+ disconnect() {+ disconnected += 1;+ }+ observe() {+ observed += 1;+ }+ unobserve() {}+ } as unknown as typeof ResizeObserver;+});++afterEach(() => {+ globalThis.ResizeObserver = originalResizeObserver;+});++describe('useNaturalHeight', () => {+ it('measures the element on mount and observes it', () => {+ const { ref } = elementWithScrollHeight(900);++ const { result } = renderHook(() => useNaturalHeight(ref));++ expect(result.current).toBe(900);+ expect(observed).toBe(1);+ });++ it('ignores a zero box so a hidden subtree keeps its last real height', () => {+ const { el, ref } = elementWithScrollHeight(900);+ const { result } = renderHook(() => useNaturalHeight(ref));++ // An inactive desktop tab kept alive behind `display: none` reports a zero+ // box and a zero scrollHeight.+ el.scrollHeight = 0;+ act(() => {+ notify?.([{ contentRect: { height: 0, width: 0 } }]);+ });++ expect(result.current).toBe(900);+ });++ it('re-measures on a real size change', () => {+ const { el, ref } = elementWithScrollHeight(900);+ const { result } = renderHook(() => useNaturalHeight(ref));++ el.scrollHeight = 120;+ act(() => {+ notify?.([{ contentRect: { height: 120, width: 600 } }]);+ });++ expect(result.current).toBe(120);+ });++ it('disconnects the observer on unmount', () => {+ const { ref } = elementWithScrollHeight(400);+ const { unmount } = renderHook(() => useNaturalHeight(ref));++ unmount();++ expect(disconnected).toBe(1);+ });+});diff --git a/src/components/CollapsibleContent/useNaturalHeight.ts b/src/components/CollapsibleContent/useNaturalHeight.tsnew file mode 100644index 00000000000..09ac1755066--- /dev/null+++ b/src/components/CollapsibleContent/useNaturalHeight.ts@@ -0,0 +1,38 @@+import { type RefObject, useLayoutEffect, useState } from 'react';++/**+ * Tracks an element's natural (unconstrained) height, read from `scrollHeight`+ * so a `max-height` clamp on the element itself does not affect it.+ */+export const useNaturalHeight = (ref: RefObject<HTMLElement | null>) => {+ const [naturalHeight, setNaturalHeight] = useState(0);++ useLayoutEffect(() => {+ const el = ref.current;+ if (!el) return;++ const measure = () => {+ const next = el.scrollHeight;+ setNaturalHeight((prev) => (prev === next ? prev : next));+ };+ measure();++ if (typeof ResizeObserver === 'undefined') return;++ // A subtree that stops being rendered β an inactive desktop tab kept alive+ // behind `display: none` β reports a zero box, and its `scrollHeight` reads+ // 0. Measuring that would drop the height to zero and restore it on reveal,+ // costing two forced layouts and a visible flip for content that never+ // changed. Keep the last real measurement instead.+ const observer = new ResizeObserver((entries) => {+ const box = entries.at(-1)?.contentRect;+ if (box && box.width === 0 && box.height === 0) return;+ measure();+ });+ observer.observe(el);++ return () => observer.disconnect();+ }, [ref]);++ return naturalHeight;+};diff --git a/src/features/AgentRoute/useResolvedAgentRouteId.ts b/src/features/AgentRoute/useResolvedAgentRouteId.tsnew file mode 100644index 00000000000..27e46224224--- /dev/null+++ b/src/features/AgentRoute/useResolvedAgentRouteId.ts@@ -0,0 +1,19 @@+import { BUILTIN_AGENT_SLUGS } from '@lobechat/builtin-agents';++import { useAgentStore } from '@/store/agent';+import { builtinAgentSelectors } from '@/store/agent/selectors';++const builtinAgentSlugs = new Set<string>(Object.values(BUILTIN_AGENT_SLUGS));++export const useResolvedAgentRouteId = (routeAgentId?: string) => {+ const isBuiltinSlug = !!routeAgentId && builtinAgentSlugs.has(routeAgentId);+ const resolvedAgentId = useAgentStore(+ builtinAgentSelectors.getBuiltinAgentId(isBuiltinSlug ? routeAgentId! : ''),+ );++ return {+ agentId: isBuiltinSlug ? resolvedAgentId || routeAgentId : routeAgentId,+ isBuiltinSlug,+ resolvedAgentId,+ };+};diff --git a/src/features/AgentSidebar/Header/Nav.test.tsx b/src/features/AgentSidebar/Header/Nav.test.tsxindex 537ff4f436a..3ae0ca76b12 100644--- a/src/features/AgentSidebar/Header/Nav.test.tsx+++ b/src/features/AgentSidebar/Header/Nav.test.tsx@@ -80,8 +80,8 @@ vi.mock('@/hooks/useQueryRoute', () => ({}),}));-vi.mock('@/libs/router/navigation', () => ({- usePathname: usePathnameMock,+vi.mock('@/hooks/useActiveLocation', () => ({+ useActiveLocation: () => ({ hash: '', pathname: usePathnameMock(), search: '' }),}));vi.mock('@/libs/swr', () => ({diff --git a/src/features/AgentSidebar/Header/Nav.tsx b/src/features/AgentSidebar/Header/Nav.tsxindex 779d208595a..aa292b2c3fe 100644--- a/src/features/AgentSidebar/Header/Nav.tsx+++ b/src/features/AgentSidebar/Header/Nav.tsx@@ -10,14 +10,14 @@ import {} from 'lucide-react';import { memo } from 'react';import { useTranslation } from 'react-i18next';-import { useParams } from 'react-router';import urlJoin from 'url-join';import NavItem from '@/features/NavPanel/components/NavItem';import { useResourceAccess } from '@/features/ResourcePermission/useResourceAccess';+import { useActiveLocation } from '@/hooks/useActiveLocation';+import { useActiveRouteParams } from '@/hooks/useActiveRouteParams';import { usePermission } from '@/hooks/usePermission';import { useQueryRoute } from '@/hooks/useQueryRoute';-import { usePathname } from '@/libs/router/navigation';import { useActionSWR } from '@/libs/swr';import { topicActionKeys } from '@/libs/swr/keys';import { useAgentStore } from '@/store/agent';@@ -30,9 +30,9 @@ import { featureFlagsSelectors, useServerConfigStore } from '@/store/serverConficonst Nav = memo(() => {const { t } = useTranslation('chat');const { t: tTopic } = useTranslation('topic');- const params = useParams();+ const params = useActiveRouteParams();const agentId = params.aid;- const pathname = usePathname();+ const { pathname } = useActiveLocation();const isProfileActive = pathname.includes('/profile');const isChannelActive = pathname.includes('/channel');// Topic IDs are prefixed `topics_`, so /agent/:aid/topics_abc would also matchdiff --git a/src/features/AgentSidebar/Task/StatusGroup.tsx b/src/features/AgentSidebar/Task/StatusGroup.tsxindex f2626215105..6d11aa4b5d0 100644--- a/src/features/AgentSidebar/Task/StatusGroup.tsx+++ b/src/features/AgentSidebar/Task/StatusGroup.tsx@@ -4,9 +4,9 @@ import { AccordionItem, Center, Flexbox, Icon, Text } from '@lobehub/ui';import { cssVar } from 'antd-style';import { memo } from 'react';import { useTranslation } from 'react-i18next';-import { useParams } from 'react-router';import { EXECUTION_STATUS_VISUALS, type ExecutionStatusVisual } from '@/components/ExecutionStatus';+import { useActiveRouteParams } from '@/hooks/useActiveRouteParams';import type { TaskGroupItem } from '@/store/task/slices/list/initialState';import TaskItem from './TaskItem';@@ -26,7 +26,7 @@ interface StatusGroupProps {const StatusGroup = memo<StatusGroupProps>(({ group }) => {const { t } = useTranslation('chat');- const { taskId } = useParams<{ taskId?: string }>();+ const { taskId } = useActiveRouteParams<{ taskId?: string }>();const meta = STATUS_META[group.key];if (!meta) return null;diff --git a/src/features/AgentSidebar/Topic/TopicListContent/ByProjectMode/GroupItem.test.tsx b/src/features/AgentSidebar/Topic/TopicListContent/ByProjectMode/GroupItem.test.tsxindex 93780d4d9fa..d2cd9fd2782 100644--- a/src/features/AgentSidebar/Topic/TopicListContent/ByProjectMode/GroupItem.test.tsx+++ b/src/features/AgentSidebar/Topic/TopicListContent/ByProjectMode/GroupItem.test.tsx@@ -111,8 +111,8 @@ vi.mock('@/hooks/useQueryRoute', () => ({}),}));-vi.mock('@/libs/router/navigation', () => ({- usePathname: () => '/lobehub/agent/agent-1/profile',+vi.mock('@/hooks/useActiveLocation', () => ({+ useActiveLocation: () => ({ hash: '', pathname: '/lobehub/agent/agent-1/profile', search: '' }),}));vi.mock('@/store/agent', () => ({diff --git a/src/features/AgentSidebar/Topic/TopicListContent/ByProjectMode/GroupItem.tsx b/src/features/AgentSidebar/Topic/TopicListContent/ByProjectMode/GroupItem.tsxindex ddf601be180..191be9e6cd5 100644--- a/src/features/AgentSidebar/Topic/TopicListContent/ByProjectMode/GroupItem.tsx+++ b/src/features/AgentSidebar/Topic/TopicListContent/ByProjectMode/GroupItem.tsx@@ -4,7 +4,6 @@ import { createStaticStyles, cssVar, cx } from 'antd-style';import { FolderClosedIcon, FolderOpenIcon, type LucideIcon, PlusIcon } from 'lucide-react';import { memo, useCallback, useMemo } from 'react';import { useTranslation } from 'react-i18next';-import { useParams } from 'react-router';import { useActiveWorkspaceSlug } from '@/business/client/hooks/useActiveWorkspaceSlug';import { TOPIC_STATUS_VISUALS } from '@/components/ExecutionStatus';@@ -14,8 +13,9 @@ import { isDesktop } from '@/const/version';import { useCommitWorkingDirectory } from '@/features/ChatInput/ControlBar/useCommitWorkingDirectory';import { resolveExecutionTarget } from '@/helpers/executionTarget';import { useIsGatewayModeEnabled } from '@/helpers/gatewayMode';+import { useActiveLocation } from '@/hooks/useActiveLocation';+import { useActiveRouteParams } from '@/hooks/useActiveRouteParams';import { useQueryRoute } from '@/hooks/useQueryRoute';-import { usePathname } from '@/libs/router/navigation';import { useAgentStore } from '@/store/agent';import { agentByIdSelectors } from '@/store/agent/selectors';import { useChatStore } from '@/store/chat';@@ -166,8 +166,8 @@ const GroupItem = memo<GroupItemComponentProps>();const agentId = useAgentStore((s) => s.activeAgentId);- const { aid: routeAgentId } = useParams<{ aid?: string }>();- const pathname = usePathname();+ const { aid: routeAgentId } = useActiveRouteParams<{ aid?: string }>();+ const { pathname } = useActiveLocation();const agentRoute = useMemo(() => parseAgentPathname(pathname), [pathname]);const targetAgentId = routeAgentId ?? agentRoute?.agentId ?? agentId;const currentAgentId = targetAgentId ?? agentId;diff --git a/src/features/AgentSidebar/Topic/hooks/useThreadNavigation.ts b/src/features/AgentSidebar/Topic/hooks/useThreadNavigation.tsindex 37ad65ec6e9..476aa5df12e 100644--- a/src/features/AgentSidebar/Topic/hooks/useThreadNavigation.ts+++ b/src/features/AgentSidebar/Topic/hooks/useThreadNavigation.ts@@ -1,9 +1,9 @@import { AGENT_CHAT_TOPIC_URL, AGENT_CHAT_URL } from '@lobechat/const';import { useCallback } from 'react';-import { useParams } from 'react-router';+import { useActiveLocation } from '@/hooks/useActiveLocation';+import { useActiveRouteParams } from '@/hooks/useActiveRouteParams';import { useQueryRoute } from '@/hooks/useQueryRoute';-import { usePathname } from '@/libs/router/navigation';import { useChatStore } from '@/store/chat';import { useGlobalStore } from '@/store/global';@@ -12,8 +12,8 @@ import { useGlobalStore } from '@/store/global';* If in agent sub-route (e.g., /agent/:aid/profile), navigate back to chat first*/export const useThreadNavigation = () => {- const pathname = usePathname();- const params = useParams<{ aid?: string; topicId?: string }>();+ const { pathname } = useActiveLocation();+ const params = useActiveRouteParams<{ aid?: string; topicId?: string }>();const router = useQueryRoute();const toggleConfig = useGlobalStore((s) => s.toggleMobileTopic);const switchThread = useChatStore((s) => s.switchThread);diff --git a/src/features/AgentSidebar/Topic/hooks/useTopicNavigation.test.tsx b/src/features/AgentSidebar/Topic/hooks/useTopicNavigation.test.tsxindex 82f3c14c938..ace1f215a6b 100644--- a/src/features/AgentSidebar/Topic/hooks/useTopicNavigation.test.tsx+++ b/src/features/AgentSidebar/Topic/hooks/useTopicNavigation.test.tsx@@ -31,8 +31,8 @@ vi.mock('@/hooks/useQueryRoute', () => ({}),}));-vi.mock('@/libs/router/navigation', () => ({- usePathname: pathnameMock,+vi.mock('@/hooks/useActiveLocation', () => ({+ useActiveLocation: () => ({ hash: '', pathname: pathnameMock(), search: '' }),}));vi.mock('@/store/chat', () => ({diff --git a/src/features/AgentSidebar/Topic/hooks/useTopicNavigation.ts b/src/features/AgentSidebar/Topic/hooks/useTopicNavigation.tsindex f01f329b758..5794fbb49a5 100644--- a/src/features/AgentSidebar/Topic/hooks/useTopicNavigation.ts+++ b/src/features/AgentSidebar/Topic/hooks/useTopicNavigation.ts@@ -1,12 +1,12 @@import { AGENT_CHAT_TOPIC_URL, AGENT_CHAT_URL } from '@lobechat/const';import { useCallback, useMemo } from 'react';-import { useParams } from 'react-router';import urlJoin from 'url-join';import { useActiveWorkspaceSlug } from '@/business/client/hooks/useActiveWorkspaceSlug';import { useFocusTopicPopup } from '@/features/TopicPopupGuard/useTopicPopupsRegistry';+import { useActiveLocation } from '@/hooks/useActiveLocation';+import { useActiveRouteParams } from '@/hooks/useActiveRouteParams';import { useQueryRoute } from '@/hooks/useQueryRoute';-import { usePathname } from '@/libs/router/navigation';import { useChatStore } from '@/store/chat';import { useGlobalStore } from '@/store/global';@@ -21,9 +21,9 @@ interface NavigateToTopicOptions {}export const useTopicNavigation = () => {- const pathname = usePathname();+ const { pathname } = useActiveLocation();const agentRoute = useMemo(() => parseAgentPathname(pathname), [pathname]);- const params = useParams<{ aid?: string; topicId?: string }>();+ const params = useActiveRouteParams<{ aid?: string; topicId?: string }>();const [activeAgentId, activeTopicId] = useChatStore((s) => [s.activeAgentId, s.activeTopicId]);const router = useQueryRoute();const toggleConfig = useGlobalStore((s) => s.toggleMobileTopic);diff --git a/src/features/CommandMenu/index.tsx b/src/features/CommandMenu/index.tsxindex 5a28422bf68..d6188c9d40b 100644--- a/src/features/CommandMenu/index.tsx+++ b/src/features/CommandMenu/index.tsx@@ -6,8 +6,8 @@ import { CornerDownLeft } from 'lucide-react';import { memo, useCallback, useEffect, useRef, useState } from 'react';import { createPortal } from 'react-dom';import { useTranslation } from 'react-i18next';-import { useLocation } from 'react-router';+import { useActiveLocation } from '@/hooks/useActiveLocation';import { useGlobalStore } from '@/store/global';import AskAgentCommands from './AskAgentCommands';@@ -202,7 +202,7 @@ const CommandMenu = memo(() => {const [appRoot, setAppRoot] = useState<HTMLElement | null>(null);const [isClosing, setIsClosing] = useState(false);const [isVisible, setIsVisible] = useState(false);- const location = useLocation();+ const location = useActiveLocation();const pathname = location.pathname;// Ensure we're mounted on the clientdiff --git a/src/features/Conversation/WorkingSidebar/Review/index.tsx b/src/features/Conversation/WorkingSidebar/Review/index.tsxindex e20125b9536..eba75ff6d02 100644--- a/src/features/Conversation/WorkingSidebar/Review/index.tsx+++ b/src/features/Conversation/WorkingSidebar/Review/index.tsx@@ -224,477 +224,487 @@ const styles = createStaticStyles(({ css, cssVar }) => ({`,}));-const Review = memo<ReviewProps>(({ active, deviceId, onToggleTree, showTree, workingDirectory }) => {- const { t } = useTranslation('chat');- const [mode, setMode] = useLocalStorageState<ReviewMode>(REVIEW_MODE_STORAGE_KEY, 'unstaged');- // Per-repo base-ref override β when set, the branch diff compares against- // this ref instead of `origin/HEAD`. Stored as a single keyed object so we- // don't proliferate localStorage keys across repos.- const [baseOverrides, setBaseOverrides] = useLocalStorageState<Record<string, string>>(- BASE_REF_OVERRIDES_STORAGE_KEY,- {},- );- const baseOverride = baseOverrides[workingDirectory];- const setBaseOverride = (next: string | undefined) => {- setBaseOverrides((prev) => {- const updated = { ...prev };- if (next === undefined) delete updated[workingDirectory];- else updated[workingDirectory] = next;- return updated;- });- };-- const { data, isLoading, isValidating } = useReviewPatches(- workingDirectory,- mode,- baseOverride,- deviceId,- active,- );- const invalidateReviewData = useCallback(- async () =>- invalidateGitReviewCaches({- baseRef: baseOverride,- deviceId,- dirPath: workingDirectory,- mode,- }),- [baseOverride, deviceId, mode, workingDirectory],- );-- useEffect(() => {- if (!active) return;- void invalidateReviewData();- }, [active, invalidateReviewData]);- // Lazy: only fetch remote branches list once the user opens the picker.- const [basePickerOpen, setBasePickerOpen] = useState(false);- const { data: remoteBranches } = useGitRemoteBranches(- workingDirectory,- mode === 'branch' && basePickerOpen,- deviceId,- );- // Memo-stabilise the fallback so downstream useMemo deps don't flap on- // every render while the SWR result is undefined.- const patches = useMemo(() => data?.patches ?? [], [data]);- const submoduleGroups = useMemo(() => data?.submodules ?? [], [data]);- const baseRef = data?.mode === 'branch' ? data.baseRef : undefined;- const headRef = data?.mode === 'branch' ? data.headRef : undefined;- // Parent branch β only needed for the group header label, so we only fetch- // it when there's at least one submodule group to render alongside it.- // SWR-deduped under the hood by `useFetchGitBranch`'s own cache key. Routes- // through the target device so remote repos resolve the same way.- const { data: parentGitInfo } = useFetchGitBranch(- deviceId,- submoduleGroups.length > 0 ? workingDirectory : undefined,- );- const [viewMode, setViewMode] = useLocalStorageState<'unified' | 'split'>(- VIEW_MODE_STORAGE_KEY,- 'unified',- );- const [wordWrap, setWordWrap] = useLocalStorageState<boolean>(WORD_WRAP_STORAGE_KEY, false);- // pierre/diffs default lineDiffType is 'word-alt' (text-level highlighting on),- // so we default the persisted toggle to true to preserve current behaviour.- const [textDiff, setTextDiff] = useLocalStorageState<boolean>(TEXT_DIFF_STORAGE_KEY, true);-- // Build the per-repo group list. The parent always comes first; submodules- // follow in the order the IPC returned them (which is the order they appear- // in `git status`). The parent group is dropped when it has zero patches- // *and* at least one submodule exists β we don't want an empty parent- // header hovering above the submodule rows. Submodule groups with zero- // patches (pointer-only bumps) are intentionally kept so the user still- // sees the submodule surfaced.- const groups = useMemo<RepoGroup[]>(() => {- const result: RepoGroup[] = [];- if (patches.length > 0 || submoduleGroups.length === 0) {- result.push({- absolutePath: workingDirectory,- branch: parentGitInfo?.branch,- detached: parentGitInfo?.detached,- isParent: true,- name: path.basename(workingDirectory) || workingDirectory,- patches,+const Review = memo<ReviewProps>(+ ({ active, deviceId, onToggleTree, showTree, workingDirectory }) => {+ const { t } = useTranslation('chat');+ const [mode, setMode] = useLocalStorageState<ReviewMode>(REVIEW_MODE_STORAGE_KEY, 'unstaged');+ // Per-repo base-ref override β when set, the branch diff compares against+ // this ref instead of `origin/HEAD`. Stored as a single keyed object so we+ // don't proliferate localStorage keys across repos.+ const [baseOverrides, setBaseOverrides] = useLocalStorageState<Record<string, string>>(+ BASE_REF_OVERRIDES_STORAGE_KEY,+ {},+ );+ const baseOverride = baseOverrides[workingDirectory];+ const setBaseOverride = (next: string | undefined) => {+ setBaseOverrides((prev) => {+ const updated = { ...prev };+ if (next === undefined) delete updated[workingDirectory];+ else updated[workingDirectory] = next;+ return updated;});- }- for (const sub of submoduleGroups) {- result.push({- absolutePath: sub.absolutePath,- branch: sub.branch,- detached: sub.detached,- isParent: false,- name: sub.name,- patches: sub.patches,+ };++ const { data, isLoading, isValidating } = useReviewPatches(+ workingDirectory,+ mode,+ baseOverride,+ deviceId,+ active,+ );+ const invalidateReviewData = useCallback(+ async () =>+ invalidateGitReviewCaches({+ baseRef: baseOverride,+ deviceId,+ dirPath: workingDirectory,+ mode,+ }),+ [baseOverride, deviceId, mode, workingDirectory],+ );++ useEffect(() => {+ if (!active) return;+ void invalidateReviewData();+ }, [active, invalidateReviewData]);+ // Lazy: only fetch remote branches list once the user opens the picker.+ const [basePickerOpen, setBasePickerOpen] = useState(false);+ const { data: remoteBranches } = useGitRemoteBranches(+ workingDirectory,+ mode === 'branch' && basePickerOpen,+ deviceId,+ );+ // Memo-stabilise the fallback so downstream useMemo deps don't flap on+ // every render while the SWR result is undefined.+ const patches = useMemo(() => data?.patches ?? [], [data]);+ const submoduleGroups = useMemo(() => data?.submodules ?? [], [data]);+ const baseRef = data?.mode === 'branch' ? data.baseRef : undefined;+ const headRef = data?.mode === 'branch' ? data.headRef : undefined;+ // Parent branch β only needed for the group header label, so we only fetch+ // it when there's at least one submodule group to render alongside it.+ // SWR-deduped under the hood by `useFetchGitBranch`'s own cache key. Routes+ // through the target device so remote repos resolve the same way.+ const { data: parentGitInfo } = useFetchGitBranch(+ deviceId,+ submoduleGroups.length > 0 ? workingDirectory : undefined,+ );+ const [viewMode, setViewMode] = useLocalStorageState<'unified' | 'split'>(+ VIEW_MODE_STORAGE_KEY,+ 'unified',+ );+ const [wordWrap, setWordWrap] = useLocalStorageState<boolean>(WORD_WRAP_STORAGE_KEY, false);+ // pierre/diffs default lineDiffType is 'word-alt' (text-level highlighting on),+ // so we default the persisted toggle to true to preserve current behaviour.+ const [textDiff, setTextDiff] = useLocalStorageState<boolean>(TEXT_DIFF_STORAGE_KEY, true);++ // Build the per-repo group list. The parent always comes first; submodules+ // follow in the order the IPC returned them (which is the order they appear+ // in `git status`). The parent group is dropped when it has zero patches+ // *and* at least one submodule exists β we don't want an empty parent+ // header hovering above the submodule rows. Submodule groups with zero+ // patches (pointer-only bumps) are intentionally kept so the user still+ // sees the submodule surfaced.+ const groups = useMemo<RepoGroup[]>(() => {+ const result: RepoGroup[] = [];+ if (patches.length > 0 || submoduleGroups.length === 0) {+ result.push({+ absolutePath: workingDirectory,+ branch: parentGitInfo?.branch,+ detached: parentGitInfo?.detached,+ isParent: true,+ name: path.basename(workingDirectory) || workingDirectory,+ patches,+ });+ }+ for (const sub of submoduleGroups) {+ result.push({+ absolutePath: sub.absolutePath,+ branch: sub.branch,+ detached: sub.detached,+ isParent: false,+ name: sub.name,+ patches: sub.patches,+ });+ }+ return result;+ }, [+ workingDirectory,+ parentGitInfo?.branch,+ parentGitInfo?.detached,+ patches,+ submoduleGroups,+ ]);+ const showGroupHeaders = submoduleGroups.length > 0;+ const allEntries = useMemo(+ () => groups.flatMap((g) => g.patches.map((p) => ({ group: g, patch: p }))),+ [groups],+ );+ // Per-group collapse state β ephemeral (not persisted across reloads).+ // Stored as a set of repo absolutePaths; entries linger if a group later+ // disappears, which is harmless since nothing renders for missing paths.+ const [collapsedGroupPaths, setCollapsedGroupPaths] = useState<Set<string>>(() => new Set());+ const toggleGroupCollapsed = (absolutePath: string) => {+ setCollapsedGroupPaths((prev) => {+ const next = new Set(prev);+ if (next.has(absolutePath)) next.delete(absolutePath);+ else next.add(absolutePath);+ return next;});+ };++ // Default-expand by patch-size budget: take entries (across all groups in+ // order) until cumulative patch bytes exceed DEFAULT_EXPAND_BYTE_BUDGET,+ // capped at DEFAULT_EXPAND_MAX_COUNT. Every PatchDiff mounts a Shiki+ // tokenizer synchronously, so expanding too much at once locks the renderer;+ // size-based budget keeps small-diff cases generous while clamping repos+ // with a few large refactors. Re-syncing on signature change auto-expands+ // new entries within the cap; panels the user manually closed earlier stay+ // closed because their key is already absent.+ const signature = useMemo(+ () => allEntries.map(({ group, patch }) => itemKey(group.absolutePath, patch)).join('|'),+ [allEntries],+ );+ const [seenSignature, setSeenSignature] = useState('');+ const [activeKeys, setActiveKeys] = useState<string[]>([]);+ if (signature !== seenSignature) {+ setSeenSignature(signature);+ const initialKeys: string[] = [];+ let budget = DEFAULT_EXPAND_BYTE_BUDGET;+ for (const { group, patch } of allEntries) {+ if (initialKeys.length >= DEFAULT_EXPAND_MAX_COUNT) break;+ const cost = patch.patch?.length ?? 0;+ if (initialKeys.length > 0 && cost > budget) break;+ initialKeys.push(itemKey(group.absolutePath, patch));+ budget -= cost;+ }+ setActiveKeys(initialKeys);}- return result;- }, [workingDirectory, parentGitInfo?.branch, parentGitInfo?.detached, patches, submoduleGroups]);- const showGroupHeaders = submoduleGroups.length > 0;- const allEntries = useMemo(- () => groups.flatMap((g) => g.patches.map((p) => ({ group: g, patch: p }))),- [groups],- );- // Per-group collapse state β ephemeral (not persisted across reloads).- // Stored as a set of repo absolutePaths; entries linger if a group later- // disappears, which is harmless since nothing renders for missing paths.- const [collapsedGroupPaths, setCollapsedGroupPaths] = useState<Set<string>>(() => new Set());- const toggleGroupCollapsed = (absolutePath: string) => {- setCollapsedGroupPaths((prev) => {- const next = new Set(prev);- if (next.has(absolutePath)) next.delete(absolutePath);- else next.add(absolutePath);- return next;- });- };-- // Default-expand by patch-size budget: take entries (across all groups in- // order) until cumulative patch bytes exceed DEFAULT_EXPAND_BYTE_BUDGET,- // capped at DEFAULT_EXPAND_MAX_COUNT. Every PatchDiff mounts a Shiki- // tokenizer synchronously, so expanding too much at once locks the renderer;- // size-based budget keeps small-diff cases generous while clamping repos- // with a few large refactors. Re-syncing on signature change auto-expands- // new entries within the cap; panels the user manually closed earlier stay- // closed because their key is already absent.- const signature = useMemo(- () => allEntries.map(({ group, patch }) => itemKey(group.absolutePath, patch)).join('|'),- [allEntries],- );- const [seenSignature, setSeenSignature] = useState('');- const [activeKeys, setActiveKeys] = useState<string[]>([]);- if (signature !== seenSignature) {- setSeenSignature(signature);- const initialKeys: string[] = [];- let budget = DEFAULT_EXPAND_BYTE_BUDGET;- for (const { group, patch } of allEntries) {- if (initialKeys.length >= DEFAULT_EXPAND_MAX_COUNT) break;- const cost = patch.patch?.length ?? 0;- if (initialKeys.length > 0 && cost > budget) break;- initialKeys.push(itemKey(group.absolutePath, patch));- budget -= cost;++ // The file whose diff the tree-nav last scrolled to β highlighted in the rail.+ const [activeFileKey, setActiveFileKey] = useState<string | undefined>();+ // Scroll container for the left diff list; tree-nav clicks scroll it to the+ // matching `[data-file-key]` row.+ const listRef = useRef<HTMLDivElement>(null);+ const toggleFileKey = (key: string) =>+ setActiveKeys((prev) =>+ prev.includes(key) ? prev.filter((k) => k !== key) : [...prev, key],+ );+ // Tree-nav β diff list: reveal the group, expand the file, scroll it into view.+ const handleSelectFile = (key: string) => {+ setActiveFileKey(key);+ const groupPath = key.slice(0, key.indexOf('|'));+ setCollapsedGroupPaths((prev) => {+ if (!prev.has(groupPath)) return prev;+ const next = new Set(prev);+ next.delete(groupPath);+ return next;+ });+ setActiveKeys((prev) => (prev.includes(key) ? prev : [...prev, key]));+ // Defer until the row is mounted/uncollapsed, then scroll it to the top.+ requestAnimationFrame(() => {+ const el = listRef.current?.querySelector(`[data-file-key="${CSS.escape(key)}"]`);+ el?.scrollIntoView({ block: 'start' });+ });+ };++ if (!data && isLoading) {+ return (+ <Center flex={1}>+ <NeuralNetworkLoading size={48} />+ </Center>+ );}- setActiveKeys(initialKeys);- }-- // The file whose diff the tree-nav last scrolled to β highlighted in the rail.- const [activeFileKey, setActiveFileKey] = useState<string | undefined>();- // Scroll container for the left diff list; tree-nav clicks scroll it to the- // matching `[data-file-key]` row.- const listRef = useRef<HTMLDivElement>(null);- const toggleFileKey = (key: string) =>- setActiveKeys((prev) => (prev.includes(key) ? prev.filter((k) => k !== key) : [...prev, key]));- // Tree-nav β diff list: reveal the group, expand the file, scroll it into view.- const handleSelectFile = (key: string) => {- setActiveFileKey(key);- const groupPath = key.slice(0, key.indexOf('|'));- setCollapsedGroupPaths((prev) => {- if (!prev.has(groupPath)) return prev;- const next = new Set(prev);- next.delete(groupPath);- return next;- });- setActiveKeys((prev) => (prev.includes(key) ? prev : [...prev, key]));- // Defer until the row is mounted/uncollapsed, then scroll it to the top.- requestAnimationFrame(() => {- const el = listRef.current?.querySelector(`[data-file-key="${CSS.escape(key)}"]`);- el?.scrollIntoView({ block: 'start' });- });- };-- if (!data && isLoading) {- return (- <Center flex={1}>- <NeuralNetworkLoading size={48} />- </Center>- );- }- const totalEntryCount = allEntries.length;- const allExpanded = totalEntryCount > 0 && activeKeys.length === totalEntryCount;- const handleToggleAll = () => {- setActiveKeys(- allExpanded ? [] : allEntries.map(({ group, patch }) => itemKey(group.absolutePath, patch)),+ const totalEntryCount = allEntries.length;+ const allExpanded = totalEntryCount > 0 && activeKeys.length === totalEntryCount;+ const handleToggleAll = () => {+ setActiveKeys(+ allExpanded ? [] : allEntries.map(({ group, patch }) => itemKey(group.absolutePath, patch)),+ );+ };++ const totals = allEntries.reduce(+ (acc, { patch }) => {+ acc.additions += patch.additions ?? 0;+ acc.deletions += patch.deletions ?? 0;+ return acc;+ },+ { additions: 0, deletions: 0 },);- };-- const totals = allEntries.reduce(- (acc, { patch }) => {- acc.additions += patch.additions ?? 0;- acc.deletions += patch.deletions ?? 0;- return acc;- },- { additions: 0, deletions: 0 },- );-- const moreMenuItems: DropdownItem[] = [- {- icon: <RefreshCwIcon size={14} />,- key: 'refresh',- label: t('workingPanel.review.refresh'),- onClick: () => void invalidateReviewData(),- },- { type: 'divider' },- {- icon: <WrapTextIcon size={14} />,- key: 'wordWrap',- label: wordWrap- ? t('workingPanel.review.wordWrap.disable')- : t('workingPanel.review.wordWrap.enable'),- onClick: () => setWordWrap((w) => !w),- },- {- icon: <WholeWordIcon size={14} />,- key: 'textDiff',- label: textDiff- ? t('workingPanel.review.textDiff.disable')- : t('workingPanel.review.textDiff.enable'),- onClick: () => setTextDiff((v) => !v),- },- {- icon: viewMode === 'unified' ? <Columns2Icon size={14} /> : <Rows2Icon size={14} />,- key: 'viewMode',- label:- viewMode === 'unified'- ? t('workingPanel.review.viewMode.split')- : t('workingPanel.review.viewMode.unified'),- onClick: () => setViewMode((m) => (m === 'unified' ? 'split' : 'unified')),- },- ];-- const modeMenuItems: DropdownItem[] = [- {- key: 'unstaged',- label: t('workingPanel.review.mode.unstaged'),- onClick: () => setMode('unstaged'),- },- {- key: 'branch',- label: t('workingPanel.review.mode.branch'),- onClick: () => setMode('branch'),- },- ];-- // Branches are only loaded after the user opens the picker (see- // `basePickerOpen`). While loading, render a single disabled placeholder- // so the menu doesn't pop empty + jump to its final size.- const baseRefMenuItems: DropdownItem[] = remoteBranches- ? [- ...remoteBranches.map((branch) => ({- key: branch.name,- label: branch.isDefault- ? `${branch.name} Β· ${t('workingPanel.review.baseRef.default')}`- : branch.name,- onClick: () =>- setBaseOverride(branch.isDefault && !baseOverride ? undefined : branch.name),- })),- ...(baseOverride- ? [- { type: 'divider' as const },- {- icon: <RotateCcwIcon size={14} />,- key: 'reset',- label: t('workingPanel.review.baseRef.reset'),- onClick: () => setBaseOverride(undefined),- },- ]- : []),- ]- : [- {- disabled: true,- key: 'loading',- label: t('workingPanel.review.baseRef.loading'),- },- ];-- // A pointer-only submodule bump produces a group with no file patches but is- // still worth surfacing (the GroupHeader + "submodule clean" line), so don't- // collapse into the global empty state when any submodule group is present.- const isEmpty = totalEntryCount === 0 && submoduleGroups.length === 0;- const emptyText =- mode === 'branch'- ? baseRef- ? t('workingPanel.review.empty.branch', { baseRef })- : t('workingPanel.review.empty.noBaseRef')- : t('workingPanel.review.empty');-- return (- <Flexbox style={{ overflow: 'hidden' }} width={'100%'}>- <div className={styles.subheader}>- <Flexbox- horizontal- align={'center'}- gap={8}- style={{ flex: '1 1 auto', minWidth: 0, overflow: 'hidden' }}- >- <DropdownMenu items={modeMenuItems} placement={'bottomLeft'}>- <span className={styles.scopeChip} role={'button'} tabIndex={0}>- {mode === 'branch'- ? t('workingPanel.review.mode.branch')- : t('workingPanel.review.mode.unstaged')}- <ChevronDownIcon className={styles.caret} size={12} />- </span>- </DropdownMenu>- {mode === 'branch' && (baseRef || headRef) && (- <span className={styles.compareChip}>- <DropdownMenu- items={baseRefMenuItems}- placement={'bottomLeft'}- onOpenChange={setBasePickerOpen}- >- <span className={styles.basePicker} role={'button'} tabIndex={0}>- <span className={styles.refName}>- {baseRef ?? t('workingPanel.review.baseRef.unresolved')}- </span>- <ChevronDownIcon className={styles.caret} size={12} />- </span>- </DropdownMenu>- {headRef && (- <>- <ArrowLeftIcon className={styles.arrow} size={12} />- <span className={styles.headRefText}>{headRef}</span>- </>- )}- </span>- )}- {(totals.additions > 0 || totals.deletions > 0) && (- <span className={styles.totalStats}>- {totals.additions > 0 && (- <span className={styles.totalAdditions}>+{totals.additions}</span>- )}- {totals.deletions > 0 && (- <span className={styles.totalDeletions}>-{totals.deletions}</span>- )}- </span>- )}- </Flexbox>- <Flexbox horizontal align={'center'} gap={2}>- {totalEntryCount > 0 && (- <ActionIcon- icon={allExpanded ? FoldVerticalIcon : UnfoldVerticalIcon}- size={'small'}- title={- allExpanded- ? t('workingPanel.review.collapseAll')- : t('workingPanel.review.expandAll')- }- onClick={handleToggleAll}- />- )}- {totalEntryCount > 0 && (- <ActionIcon- active={showTree}- icon={showTree ? PanelRightCloseIcon : PanelRightOpenIcon}- size={'small'}- title={- showTree ? t('workingPanel.review.tree.hide') : t('workingPanel.review.tree.show')- }- onClick={onToggleTree}- />- )}- <DropdownMenu items={moreMenuItems} placement={'bottomRight'}>- <ActionIcon- icon={MoreHorizontalIcon}- loading={isValidating}- size={'small'}- title={t('workingPanel.review.more')}- />- </DropdownMenu>- </Flexbox>- </div>- {isEmpty ? (- <Center flex={1} gap={8} paddingBlock={24}>- <Empty description={emptyText} icon={GitCompareIcon} />- </Center>- ) : (- <Flexbox horizontal className={styles.body} flex={1} width={'100%'}>- <Flexbox className={styles.list} flex={1} ref={listRef} style={{ overflow: 'auto' }}>- {groups.map((group) => {- const groupTotals = group.patches.reduce(- (acc, p) => {- acc.additions += p.additions ?? 0;- acc.deletions += p.deletions ?? 0;- return acc;++ const moreMenuItems: DropdownItem[] = [+ {+ icon: <RefreshCwIcon size={14} />,+ key: 'refresh',+ label: t('workingPanel.review.refresh'),+ onClick: () => void invalidateReviewData(),+ },+ { type: 'divider' },+ {+ icon: <WrapTextIcon size={14} />,+ key: 'wordWrap',+ label: wordWrap+ ? t('workingPanel.review.wordWrap.disable')+ : t('workingPanel.review.wordWrap.enable'),+ onClick: () => setWordWrap((w) => !w),+ },+ {+ icon: <WholeWordIcon size={14} />,+ key: 'textDiff',+ label: textDiff+ ? t('workingPanel.review.textDiff.disable')+ : t('workingPanel.review.textDiff.enable'),+ onClick: () => setTextDiff((v) => !v),+ },+ {+ icon: viewMode === 'unified' ? <Columns2Icon size={14} /> : <Rows2Icon size={14} />,+ key: 'viewMode',+ label:+ viewMode === 'unified'+ ? t('workingPanel.review.viewMode.split')+ : t('workingPanel.review.viewMode.unified'),+ onClick: () => setViewMode((m) => (m === 'unified' ? 'split' : 'unified')),+ },+ ];++ const modeMenuItems: DropdownItem[] = [+ {+ key: 'unstaged',+ label: t('workingPanel.review.mode.unstaged'),+ onClick: () => setMode('unstaged'),+ },+ {+ key: 'branch',+ label: t('workingPanel.review.mode.branch'),+ onClick: () => setMode('branch'),+ },+ ];++ // Branches are only loaded after the user opens the picker (see+ // `basePickerOpen`). While loading, render a single disabled placeholder+ // so the menu doesn't pop empty + jump to its final size.+ const baseRefMenuItems: DropdownItem[] = remoteBranches+ ? [+ ...remoteBranches.map((branch) => ({+ key: branch.name,+ label: branch.isDefault+ ? `${branch.name} Β· ${t('workingPanel.review.baseRef.default')}`+ : branch.name,+ onClick: () =>+ setBaseOverride(branch.isDefault && !baseOverride ? undefined : branch.name),+ })),+ ...(baseOverride+ ? [+ { type: 'divider' as const },+ {+ icon: <RotateCcwIcon size={14} />,+ key: 'reset',+ label: t('workingPanel.review.baseRef.reset'),+ onClick: () => setBaseOverride(undefined),},- { additions: 0, deletions: 0 },- );- const groupCollapsed = collapsedGroupPaths.has(group.absolutePath);- const groupItemKeys = group.patches.map((p) => itemKey(group.absolutePath, p));- const groupAllExpanded =- groupItemKeys.length > 0 && groupItemKeys.every((k) => activeKeys.includes(k));- const toggleGroupDiffs = () => {- setActiveKeys((prev) => {- if (groupAllExpanded) {- const set = new Set(groupItemKeys);- return prev.filter((k) => !set.has(k));- }- const next = new Set(prev);- for (const k of groupItemKeys) next.add(k);- return Array.from(next);- });- };- return (- <Fragment key={group.absolutePath}>- {showGroupHeaders && (- <GroupHeader- branch={group.branch}- collapsed={groupCollapsed}- diffsAllExpanded={groupAllExpanded}- hideFoldButton={groupCollapsed || group.patches.length === 0}- name={group.name}- patchCount={group.patches.length}- totalAdditions={groupTotals.additions}- totalDeletions={groupTotals.deletions}- onToggleCollapsed={() => toggleGroupCollapsed(group.absolutePath)}- onToggleDiffs={toggleGroupDiffs}- />- )}- {showGroupHeaders &&- !groupCollapsed &&- !group.isParent &&- group.patches.length === 0 && (- <div className={styles.groupEmpty}>- {t('workingPanel.review.group.submoduleClean')}- </div>- )}- {!groupCollapsed &&- group.patches.length > 0 &&- group.patches.map((entry) => {- const key = itemKey(group.absolutePath, entry);- const expanded = activeKeys.includes(key);- return (- <FileRow- dataFileKey={key}- deviceId={deviceId}- entry={entry}- expanded={expanded}- key={key}- mode={mode}- repoAbsolutePath={group.absolutePath}- textDiff={textDiff}- viewMode={viewMode}- wordWrap={wordWrap}- onReverted={() => void invalidateReviewData()}- onToggle={() => toggleFileKey(key)}- />- );- })}- </Fragment>- );- })}+ ]+ : []),+ ]+ : [+ {+ disabled: true,+ key: 'loading',+ label: t('workingPanel.review.baseRef.loading'),+ },+ ];++ // A pointer-only submodule bump produces a group with no file patches but is+ // still worth surfacing (the GroupHeader + "submodule clean" line), so don't+ // collapse into the global empty state when any submodule group is present.+ const isEmpty = totalEntryCount === 0 && submoduleGroups.length === 0;+ const emptyText =+ mode === 'branch'+ ? baseRef+ ? t('workingPanel.review.empty.branch', { baseRef })+ : t('workingPanel.review.empty.noBaseRef')+ : t('workingPanel.review.empty');++ return (+ <Flexbox style={{ overflow: 'hidden' }} width={'100%'}>+ <div className={styles.subheader}>+ <Flexbox+ horizontal+ align={'center'}+ gap={8}+ style={{ flex: '1 1 auto', minWidth: 0, overflow: 'hidden' }}+ >+ <DropdownMenu items={modeMenuItems} placement={'bottomLeft'}>+ <span className={styles.scopeChip} role={'button'} tabIndex={0}>+ {mode === 'branch'+ ? t('workingPanel.review.mode.branch')+ : t('workingPanel.review.mode.unstaged')}+ <ChevronDownIcon className={styles.caret} size={12} />+ </span>+ </DropdownMenu>+ {mode === 'branch' && (baseRef || headRef) && (+ <span className={styles.compareChip}>+ <DropdownMenu+ items={baseRefMenuItems}+ placement={'bottomLeft'}+ onOpenChange={setBasePickerOpen}+ >+ <span className={styles.basePicker} role={'button'} tabIndex={0}>+ <span className={styles.refName}>+ {baseRef ?? t('workingPanel.review.baseRef.unresolved')}+ </span>+ <ChevronDownIcon className={styles.caret} size={12} />+ </span>+ </DropdownMenu>+ {headRef && (+ <>+ <ArrowLeftIcon className={styles.arrow} size={12} />+ <span className={styles.headRefText}>{headRef}</span>+ </>+ )}+ </span>+ )}+ {(totals.additions > 0 || totals.deletions > 0) && (+ <span className={styles.totalStats}>+ {totals.additions > 0 && (+ <span className={styles.totalAdditions}>+{totals.additions}</span>+ )}+ {totals.deletions > 0 && (+ <span className={styles.totalDeletions}>-{totals.deletions}</span>+ )}+ </span>+ )}</Flexbox>- {showTree && (- <Flexbox className={styles.treeRail}>- <FileTreeNav- activeFileKey={activeFileKey}- groups={groups}- showGroupHeaders={showGroupHeaders}- onSelectFile={handleSelectFile}+ <Flexbox horizontal align={'center'} gap={2}>+ {totalEntryCount > 0 && (+ <ActionIcon+ icon={allExpanded ? FoldVerticalIcon : UnfoldVerticalIcon}+ size={'small'}+ title={+ allExpanded+ ? t('workingPanel.review.collapseAll')+ : t('workingPanel.review.expandAll')+ }+ onClick={handleToggleAll}+ />+ )}+ {totalEntryCount > 0 && (+ <ActionIcon+ active={showTree}+ icon={showTree ? PanelRightCloseIcon : PanelRightOpenIcon}+ size={'small'}+ title={+ showTree ? t('workingPanel.review.tree.hide') : t('workingPanel.review.tree.show')+ }+ onClick={onToggleTree}/>+ )}+ <DropdownMenu items={moreMenuItems} placement={'bottomRight'}>+ <ActionIcon+ icon={MoreHorizontalIcon}+ loading={isValidating}+ size={'small'}+ title={t('workingPanel.review.more')}+ />+ </DropdownMenu>+ </Flexbox>+ </div>+ {isEmpty ? (+ <Center flex={1} gap={8} paddingBlock={24}>+ <Empty description={emptyText} icon={GitCompareIcon} />+ </Center>+ ) : (+ <Flexbox horizontal className={styles.body} flex={1} width={'100%'}>+ <Flexbox className={styles.list} flex={1} ref={listRef} style={{ overflow: 'auto' }}>+ {groups.map((group) => {+ const groupTotals = group.patches.reduce(+ (acc, p) => {+ acc.additions += p.additions ?? 0;+ acc.deletions += p.deletions ?? 0;+ return acc;+ },+ { additions: 0, deletions: 0 },+ );+ const groupCollapsed = collapsedGroupPaths.has(group.absolutePath);+ const groupItemKeys = group.patches.map((p) => itemKey(group.absolutePath, p));+ const groupAllExpanded =+ groupItemKeys.length > 0 && groupItemKeys.every((k) => activeKeys.includes(k));+ const toggleGroupDiffs = () => {+ setActiveKeys((prev) => {+ if (groupAllExpanded) {+ const set = new Set(groupItemKeys);+ return prev.filter((k) => !set.has(k));+ }+ const next = new Set(prev);+ for (const k of groupItemKeys) next.add(k);+ return Array.from(next);+ });+ };+ return (+ <Fragment key={group.absolutePath}>+ {showGroupHeaders && (+ <GroupHeader+ branch={group.branch}+ collapsed={groupCollapsed}+ diffsAllExpanded={groupAllExpanded}+ hideFoldButton={groupCollapsed || group.patches.length === 0}+ name={group.name}+ patchCount={group.patches.length}+ totalAdditions={groupTotals.additions}+ totalDeletions={groupTotals.deletions}+ onToggleCollapsed={() => toggleGroupCollapsed(group.absolutePath)}+ onToggleDiffs={toggleGroupDiffs}+ />+ )}+ {showGroupHeaders &&+ !groupCollapsed &&+ !group.isParent &&+ group.patches.length === 0 && (+ <div className={styles.groupEmpty}>+ {t('workingPanel.review.group.submoduleClean')}+ </div>+ )}+ {!groupCollapsed &&+ group.patches.length > 0 &&+ group.patches.map((entry) => {+ const key = itemKey(group.absolutePath, entry);+ const expanded = activeKeys.includes(key);+ return (+ <FileRow+ dataFileKey={key}+ deviceId={deviceId}+ entry={entry}+ expanded={expanded}+ key={key}+ mode={mode}+ repoAbsolutePath={group.absolutePath}+ textDiff={textDiff}+ viewMode={viewMode}+ wordWrap={wordWrap}+ onReverted={() => void invalidateReviewData()}+ onToggle={() => toggleFileKey(key)}+ />+ );+ })}+ </Fragment>+ );+ })}</Flexbox>- )}- </Flexbox>- )}- </Flexbox>- );-});+ {showTree && (+ <Flexbox className={styles.treeRail}>+ <FileTreeNav+ activeFileKey={activeFileKey}+ groups={groups}+ showGroupHeaders={showGroupHeaders}+ onSelectFile={handleSelectFile}+ />+ </Flexbox>+ )}+ </Flexbox>+ )}+ </Flexbox>+ );+ },+);Review.displayName = 'AgentWorkingSidebarReview';diff --git a/src/features/Conversation/useAgentContext.ts b/src/features/Conversation/useAgentContext.tsindex 4f4e4dab594..b24577cd1d4 100644--- a/src/features/Conversation/useAgentContext.ts+++ b/src/features/Conversation/useAgentContext.ts@@ -3,9 +3,10 @@import { type ConversationContext } from '@lobechat/types';import { useActiveWorkspaceSlug } from '@/business/client/hooks/useActiveWorkspaceSlug';-import { useChatStore } from '@/store/chat';import { useDocumentStore } from '@/store/document';+import { useAgentConversationCoordinate } from './useAgentConversationCoordinate';+/*** Hook to get agent conversation context*@@ -14,11 +15,7 @@ import { useDocumentStore } from '@/store/document';*/export function useAgentContext(): ConversationContext {const workspaceSlug = useActiveWorkspaceSlug();- const [agentId, topicId, threadId] = useChatStore((s) => [- s.activeAgentId,- s.activeTopicId ?? null,- s.activeThreadId ?? null,- ]);+ const [agentId, topicId, threadId] = useAgentConversationCoordinate();const activeTopicDocumentId = useDocumentStore((s) => {if (!topicId || threadId) return undefined;diff --git a/src/features/Conversation/useAgentConversationCoordinate.desktop.test.ts b/src/features/Conversation/useAgentConversationCoordinate.desktop.test.tsnew file mode 100644index 00000000000..675bd7f098a--- /dev/null+++ b/src/features/Conversation/useAgentConversationCoordinate.desktop.test.ts@@ -0,0 +1,54 @@+/**+ * @vitest-environment happy-dom+ */+import { renderHook } from '@testing-library/react';+import { beforeEach, describe, expect, it, vi } from 'vitest';++import { initialState as initialChatState } from '@/store/chat/initialState';+import { useChatStore } from '@/store/chat/store';++import { useAgentConversationCoordinate } from './useAgentConversationCoordinate.desktop';++const route = vi.hoisted(() => ({+ params: { aid: 'agent-route', topicId: 'topic-route' } as {+ aid?: string;+ topicId?: string;+ },+ search: new URLSearchParams('thread=thread-route'),+}));++vi.mock('react-router', () => ({+ useParams: () => route.params,+ useSearchParams: () => [route.search, vi.fn()],+}));++describe('useAgentConversationCoordinate (desktop)', () => {+ beforeEach(() => {+ route.params = { aid: 'agent-route', topicId: 'topic-route' };+ route.search = new URLSearchParams('thread=thread-route');+ useChatStore.setState(+ {+ ...initialChatState,+ activeAgentId: 'agent-global',+ activeThreadId: 'thread-global',+ activeTopicId: 'topic-global',+ },+ false,+ );+ });++ it('uses its own memory-router coordinate when the global pointer belongs to another tab', () => {+ const { result } = renderHook(() => useAgentConversationCoordinate());++ expect(result.current).toEqual(['agent-route', 'topic-route', 'thread-route']);+ });++ it('returns the blank conversation coordinate from the route without inheriting a global topic', () => {+ route.params = { aid: 'agent-route' };+ route.search = new URLSearchParams();++ const { result } = renderHook(() => useAgentConversationCoordinate());++ expect(result.current).toEqual(['agent-route', null, null]);+ });+});diff --git a/src/features/Conversation/useAgentConversationCoordinate.desktop.ts b/src/features/Conversation/useAgentConversationCoordinate.desktop.tsnew file mode 100644index 00000000000..e7344c69049--- /dev/null+++ b/src/features/Conversation/useAgentConversationCoordinate.desktop.ts@@ -0,0 +1,11 @@+import { useParams, useSearchParams } from 'react-router';++import { useResolvedAgentRouteId } from '@/features/AgentRoute/useResolvedAgentRouteId';++export const useAgentConversationCoordinate = () => {+ const params = useParams<{ aid?: string; topicId?: string }>();+ const [searchParams] = useSearchParams();+ const { agentId } = useResolvedAgentRouteId(params.aid);++ return [agentId, params.topicId ?? null, searchParams.get('thread')] as const;+};diff --git a/src/features/Conversation/useAgentConversationCoordinate.ts b/src/features/Conversation/useAgentConversationCoordinate.tsnew file mode 100644index 00000000000..b1c06130a4b--- /dev/null+++ b/src/features/Conversation/useAgentConversationCoordinate.ts@@ -0,0 +1,7 @@+import { useChatStore } from '@/store/chat';++export const useAgentConversationCoordinate = () =>+ useChatStore(+ (state) =>+ [state.activeAgentId, state.activeTopicId ?? null, state.activeThreadId ?? null] as const,+ );diff --git a/src/features/DevDock/Bar.tsx b/src/features/DevDock/Bar.tsxindex 9b08126dcc4..123180f318b 100644--- a/src/features/DevDock/Bar.tsx+++ b/src/features/DevDock/Bar.tsx@@ -22,13 +22,11 @@ const styles = createStaticStyles(({ css }) => ({width: 100%;height: ${BAR_HEIGHT}px;+ margin-block-start: -8px;padding-inline: 8px;- border-block-start: 1px solid ${cssVar.colorBorderSecondary};font-size: 11px;color: ${cssVar.colorTextSecondary};-- background: ${cssVar.colorBgLayout};`,center: css`display: flex;diff --git a/src/features/DevDock/registerBuiltinItems.ts b/src/features/DevDock/registerBuiltinItems.tsindex 174a18dce66..f3d837cd2af 100644--- a/src/features/DevDock/registerBuiltinItems.ts+++ b/src/features/DevDock/registerBuiltinItems.ts@@ -1,4 +1,5 @@import {+ AppWindow,ArrowUpDown,Bot,Cpu,@@ -154,13 +155,32 @@ export const registerBuiltinDevDockItems = () => {];if (isDesktop) {- items.push({- icon: Terminal,- id: 'open-devtools',- label: 'Open DevTools',- onTrigger: triggerOpenDevtools,- type: 'action',- });+ items.push(+ {+ defaultPinned: true,+ icon: AppWindow,+ id: 'tab-routers-count',+ label: 'Live Tab Routers',+ load: () => import('./widgets/TabRoutersWidget'),+ slot: 'right',+ type: 'readout',+ },+ {+ defaultPinned: true,+ icon: AppWindow,+ id: 'tab-routers',+ label: 'Tab Routers',+ load: () => import('@/features/DevPanel/TabRouters'),+ type: 'panel',+ },+ {+ icon: Terminal,+ id: 'open-devtools',+ label: 'Open DevTools',+ onTrigger: triggerOpenDevtools,+ type: 'action',+ },+ );}registerDevDockItems(items);diff --git a/src/features/DevDock/widgets/BarButton.tsx b/src/features/DevDock/widgets/BarButton.tsxindex a660af05baa..95e3b4c0ba8 100644--- a/src/features/DevDock/widgets/BarButton.tsx+++ b/src/features/DevDock/widgets/BarButton.tsx@@ -37,10 +37,11 @@ interface BarButtonProps {icon: LucideIcon;label: string;onClick: () => void;+ title?: string;}-const BarButton = memo<BarButtonProps>(({ icon: Icon, label, onClick }) => (- <button className={barButtonStyles.button} type={'button'} onClick={onClick}>+const BarButton = memo<BarButtonProps>(({ icon: Icon, label, onClick, title }) => (+ <button className={barButtonStyles.button} title={title} type={'button'} onClick={onClick}><Icon size={11} /><span>{label}</span></button>diff --git a/src/features/DevDock/widgets/RoutePathWidget.tsx b/src/features/DevDock/widgets/RoutePathWidget.tsxindex 786fe7a1395..a7af0cc47f9 100644--- a/src/features/DevDock/widgets/RoutePathWidget.tsx+++ b/src/features/DevDock/widgets/RoutePathWidget.tsx@@ -4,6 +4,10 @@ import { createStaticStyles, cssVar } from 'antd-style';import { memo } from 'react';import { useLocation } from 'react-router';+import { isDesktop } from '@/const/version';+import { selectActiveTabUrl } from '@/features/Electron/shell/activeTabUrl';+import { useElectronStore } from '@/store/electron';+const styles = createStaticStyles(({ css }) => ({path: css`overflow: hidden;@@ -21,9 +25,15 @@ const styles = createStaticStyles(({ css }) => ({const RoutePathWidget = memo(() => {const { pathname } = useLocation();+ const activeTabUrl = useElectronStore(selectActiveTabUrl);++ // The DevDock renders inside the root router, which Electron freezes at the boot+ // url; the page actually on screen belongs to the active tab's per-tab router.+ const path = (isDesktop && activeTabUrl) || pathname;+return (- <span className={styles.path} title={pathname}>- {pathname}+ <span className={styles.path} title={path}>+ {path}</span>);});diff --git a/src/features/DevDock/widgets/TabRoutersWidget.tsx b/src/features/DevDock/widgets/TabRoutersWidget.tsxnew file mode 100644index 00000000000..9c1841c66f5--- /dev/null+++ b/src/features/DevDock/widgets/TabRoutersWidget.tsx@@ -0,0 +1,34 @@+'use client';++import { AppWindow } from 'lucide-react';+import { memo, useEffect, useState } from 'react';++import { getTabRouterIds } from '@/features/Electron/TabHost/tabRouterManager';+import { useElectronStore } from '@/store/electron';++import { useDevDockStore } from '../store';+import BarButton from './BarButton';++const TabRoutersWidget = memo(() => {+ const tabCount = useElectronStore((s) => s.tabs.length);+ const togglePanel = useDevDockStore((s) => s.togglePanel);+ const [liveCount, setLiveCount] = useState(() => getTabRouterIds().length);++ useEffect(() => {+ const timer = setInterval(() => setLiveCount(getTabRouterIds().length), 1000);+ return () => clearInterval(timer);+ }, []);++ return (+ <BarButton+ icon={AppWindow}+ label={`${liveCount}/${tabCount}`}+ title={'Live tab routers / open tabs'}+ onClick={() => togglePanel('tab-routers')}+ />+ );+});++TabRoutersWidget.displayName = 'DevDockTabRoutersWidget';++export default TabRoutersWidget;diff --git a/src/features/DevPanel/TabRouters/index.tsx b/src/features/DevPanel/TabRouters/index.tsxnew file mode 100644index 00000000000..03875d7a349--- /dev/null+++ b/src/features/DevPanel/TabRouters/index.tsx@@ -0,0 +1,201 @@+'use client';++import { Flexbox } from '@lobehub/ui';+import { createStaticStyles, cssVar, cx } from 'antd-style';+import { memo } from 'react';++import { useElectronStore } from '@/store/electron';++import { type TabRouterRow, useTabRouterDebug } from './useTabRouterDebug';++const styles = createStaticStyles(({ css }) => ({+ cell: css`+ overflow: hidden;+ text-overflow: ellipsis;+ white-space: nowrap;+ `,+ cold: css`+ color: ${cssVar.colorTextQuaternary};+ `,+ drift: css`+ color: ${cssVar.colorWarning};+ `,+ empty: css`+ padding: 24px;+ font-size: 12px;+ color: ${cssVar.colorTextTertiary};+ text-align: center;+ `,+ head: css`+ position: sticky;+ z-index: 1;+ inset-block-start: 0;++ color: ${cssVar.colorTextQuaternary};+ text-transform: uppercase;+ letter-spacing: 0.04em;++ background: ${cssVar.colorBgContainer};+ `,+ legend: css`+ padding-block: 8px 12px;+ padding-inline: 12px;++ font-size: 10px;+ line-height: 1.6;+ color: ${cssVar.colorTextQuaternary};+ `,+ muted: css`+ color: ${cssVar.colorTextTertiary};+ `,+ next: css`+ color: ${cssVar.colorError};+ `,+ ok: css`+ color: ${cssVar.colorSuccess};+ `,+ row: css`+ cursor: pointer;++ display: grid;+ grid-template-columns: 24px 96px 68px 1fr 1fr 44px 76px 52px;+ gap: 8px;+ align-items: center;++ padding-block: 5px;+ padding-inline: 12px;+ border-block-end: 1px solid ${cssVar.colorBorderSecondary};++ font-family: ${cssVar.fontFamilyCode};+ font-size: 11px;+ font-feature-settings: 'tnum';++ &:hover {+ background: ${cssVar.colorFillQuaternary};+ }+ `,+ rowActive: css`+ background: ${cssVar.colorFillTertiary};+ `,+ summary: css`+ flex-shrink: 0;++ padding-block: 8px;+ padding-inline: 12px;+ border-block-end: 1px solid ${cssVar.colorBorderSecondary};++ font-family: ${cssVar.fontFamilyCode};+ font-size: 11px;+ color: ${cssVar.colorTextSecondary};+ `,+}));++const formatAge = (timestamp: number): string => {+ const seconds = Math.max(0, Math.round((Date.now() - timestamp) / 1000));+ if (seconds < 60) return `${seconds}s ago`;+ const minutes = Math.round(seconds / 60);+ if (minutes < 60) return `${minutes}m ago`;+ return `${Math.round(minutes / 60)}h ago`;+};++const Row = memo<{ index: number; nextEvicted: boolean; row: TabRouterRow }>(+ ({ index, nextEvicted, row }) => {+ const activateTab = useElectronStore((s) => s.activateTab);+ const state = row.active ? 'ACTIVE' : row.live ? 'LIVE' : 'COLD';++ return (+ <div+ className={cx(styles.row, row.active && styles.rowActive)}+ role={'button'}+ tabIndex={0}+ onClick={() => activateTab(row.id)}+ onKeyDown={(e) => e.key === 'Enter' && activateTab(row.id)}+ >+ <span className={styles.muted}>{index + 1}</span>+ <span className={cx(styles.cell, styles.muted)} title={row.id}>+ {row.id}+ </span>+ <span className={row.live ? styles.ok : styles.cold}>+ {state}+ {row.live !== row.shouldBeLive && '!'}+ </span>+ <span+ className={styles.cell}+ title={row.title ? `${row.title} β ${row.storeUrl}` : row.storeUrl}+ >+ {row.storeUrl}+ </span>+ <span+ className={cx(styles.cell, row.drift ? styles.drift : styles.muted)}+ title={row.routerUrl ?? 'router disposed'}+ >+ {row.live ? (row.drift ? row.routerUrl : '=') : 'β'}+ </span>+ <span className={styles.muted}>+ {row.canGoBack ? 'β' : 'Β·'}+ {row.canGoForward ? 'βΆ' : 'Β·'}+ </span>+ <span className={styles.muted}>{formatAge(row.lastVisited)}</span>+ <span className={nextEvicted ? styles.next : styles.muted}>+ #{row.rank}+ {nextEvicted && 'β'}+ </span>+ </div>+ );+ },+);++Row.displayName = 'DevTabRoutersRow';++const TabRouters = memo(() => {+ const { cap, liveCount, orphanIds, rows, scopeKey } = useTabRouterDebug();++ const evictable = rows.filter((row) => row.live && !row.active);+ const nextEvictedId =+ liveCount >= cap && evictable.length > 0+ ? evictable.reduce((oldest, row) => (row.rank > oldest.rank ? row : oldest)).id+ : null;++ return (+ <Flexbox height={'100%'}>+ <div className={styles.summary}>+ scope <b>{scopeKey}</b> Β· tabs <b>{rows.length}</b> Β· live routers{' '}+ <b className={liveCount > cap ? styles.drift : undefined}>+ {liveCount}/{cap}+ </b>+ {orphanIds.length > 0 && (+ <span className={styles.drift}> Β· orphan routers {orphanIds.join(', ')}</span>+ )}+ </div>+ {rows.length === 0 ? (+ <div className={styles.empty}>No tabs in this scope.</div>+ ) : (+ <div>+ <div className={cx(styles.row, styles.head)}>+ <span>#</span>+ <span>tab id</span>+ <span>state</span>+ <span>store url</span>+ <span>router url</span>+ <span>hist</span>+ <span>visited</span>+ <span>lru</span>+ </div>+ {rows.map((row, index) => (+ <Row index={index} key={row.id} nextEvicted={row.id === nextEvictedId} row={row} />+ ))}+ </div>+ )}+ <div className={styles.legend}>+ ACTIVE / LIVE = keep-alive router in memory, COLD = disposed (next activation cold-starts).+ `!` marks a router whose liveness disagrees with the LRU plan. Router url shows `=` when it+ matches the store url, or the diverging location when a hidden tab navigated. `lru` is the+ recency rank; `β` marks the router evicted next. Click a row to activate that tab.+ </div>+ </Flexbox>+ );+});++TabRouters.displayName = 'DevTabRouters';++export default TabRouters;diff --git a/src/features/DevPanel/TabRouters/useTabRouterDebug.ts b/src/features/DevPanel/TabRouters/useTabRouterDebug.tsnew file mode 100644index 00000000000..b0c04ca8ffb--- /dev/null+++ b/src/features/DevPanel/TabRouters/useTabRouterDebug.ts@@ -0,0 +1,99 @@+'use client';++import { useEffect, useState } from 'react';++// Imported from the concrete modules, not the `TabHost` barrel: that barrel+// re-exports `TabHost.tsx`, which would drag the whole desktop route tree into+// this dev-only chunk.+import {+ MAX_LIVE_TAB_ROUTERS,+ resolveLiveTabIds,+} from '@/features/Electron/TabHost/resolveLiveTabIds';+import {+ getTabHistorySnapshot,+ getTabRouter,+ getTabRouterIds,+} from '@/features/Electron/TabHost/tabRouterManager';+import { tabScopeKey } from '@/features/Electron/titlebar/TabBar/scope';+import { useElectronStore } from '@/store/electron';++export interface TabRouterRow {+ active: boolean;+ canGoBack: boolean;+ canGoForward: boolean;+ drift: boolean;+ id: string;+ lastVisited: number;+ live: boolean;+ rank: number;+ routerUrl: string | null;+ shouldBeLive: boolean;+ storeUrl: string;+ title?: string;+}++export interface TabRouterDebug {+ cap: number;+ liveCount: number;+ orphanIds: string[];+ rows: TabRouterRow[];+ scopeKey: string;+}++// Router-side facts (memory-router location, history depth, which instances the+// manager still holds) live outside React, and a hidden tab can navigate without+// any store write β poll instead of trying to subscribe to each of them.+const useTick = (interval: number): void => {+ const [, setTick] = useState(0);++ useEffect(() => {+ const timer = setInterval(() => setTick((value) => value + 1), interval);+ return () => clearInterval(timer);+ }, [interval]);+};++export const useTabRouterDebug = (): TabRouterDebug => {+ const tabs = useElectronStore((s) => s.tabs);+ const activeTabId = useElectronStore((s) => s.activeTabId);+ const activeTabScope = useElectronStore((s) => s.activeTabScope);++ useTick(1000);++ const shouldBeLive = new Set(resolveLiveTabIds(tabs, activeTabId, MAX_LIVE_TAB_ROUTERS));+ const routerIds = getTabRouterIds();+ const liveIds = new Set(routerIds);++ const evictionOrder = tabs+ .map((tab, index) => ({ id: tab.id, index, lastVisited: tab.lastVisited }))+ .sort((a, b) => b.lastVisited - a.lastVisited || a.index - b.index)+ .map((entry) => entry.id);++ const rows = tabs.map((tab) => {+ const location = liveIds.has(tab.id) ? getTabRouter(tab.id)?.state.location : undefined;+ const routerUrl = location ? `${location.pathname}${location.search}${location.hash}` : null;+ const history = getTabHistorySnapshot(tab.id);++ return {+ active: tab.id === activeTabId,+ canGoBack: history.canGoBack,+ canGoForward: history.canGoForward,+ drift: routerUrl !== null && routerUrl !== tab.url,+ id: tab.id,+ lastVisited: tab.lastVisited,+ live: liveIds.has(tab.id),+ rank: evictionOrder.indexOf(tab.id) + 1,+ routerUrl,+ shouldBeLive: shouldBeLive.has(tab.id),+ storeUrl: tab.url,+ title: tab.cached?.title,+ };+ });++ return {+ cap: MAX_LIVE_TAB_ROUTERS,+ liveCount: routerIds.length,+ orphanIds: routerIds.filter((id) => !tabs.some((tab) => tab.id === id)),+ rows,+ scopeKey: tabScopeKey(activeTabScope),+ };+};diff --git a/src/features/Electron/ActiveConversationBridge/coordinate.test.ts b/src/features/Electron/ActiveConversationBridge/coordinate.test.tsnew file mode 100644index 00000000000..51aca37da33--- /dev/null+++ b/src/features/Electron/ActiveConversationBridge/coordinate.test.ts@@ -0,0 +1,47 @@+import { describe, expect, it } from 'vitest';++import { buildActiveConversationUrl, resolveActiveConversationCoordinate } from './coordinate';++describe('active conversation coordinate', () => {+ it('resolves a workspace topic route and preserves unrelated URL state when changing topic', () => {+ const coordinate = resolveActiveConversationCoordinate({+ params: { aid: 'agent-a', topicId: 'topic-a' },+ resolvedAgentId: 'agent-a',+ url: '/team/agent/agent-a/topic-a?thread=thread-a&mode=single#message-a',+ });++ expect(coordinate).toMatchObject({+ agentBasePath: '/team/agent/agent-a',+ agentId: 'agent-a',+ isConversation: true,+ routeAgentId: 'agent-a',+ threadId: 'thread-a',+ topicId: 'topic-a',+ });+ expect(buildActiveConversationUrl(coordinate, 'topic-b', null)).toBe(+ '/team/agent/agent-a/topic-b?mode=single#message-a',+ );+ });++ it('does not interpret an agent subpage as a conversation route', () => {+ const coordinate = resolveActiveConversationCoordinate({+ params: { aid: 'agent-a' },+ resolvedAgentId: 'agent-a',+ url: '/agent/agent-a/profile?thread=stale',+ });++ expect(coordinate.isConversation).toBe(false);+ expect(coordinate.topicId).toBeNull();+ expect(coordinate.threadId).toBeNull();+ });++ it('ignores non-agent routes even when another segment is named agent', () => {+ const coordinate = resolveActiveConversationCoordinate({+ params: {},+ url: '/community/agent/example',+ });++ expect(coordinate.routeAgentId).toBeUndefined();+ expect(coordinate.isConversation).toBe(false);+ });+});diff --git a/src/features/Electron/ActiveConversationBridge/coordinate.ts b/src/features/Electron/ActiveConversationBridge/coordinate.tsnew file mode 100644index 00000000000..e6331ed65ea--- /dev/null+++ b/src/features/Electron/ActiveConversationBridge/coordinate.ts@@ -0,0 +1,67 @@+export interface ActiveConversationCoordinate {+ agentBasePath?: string;+ agentId?: string;+ hash: string;+ isConversation: boolean;+ pathname: string;+ routeAgentId?: string;+ search: string;+ threadId: string | null;+ topicId: string | null;+}++interface ResolveActiveConversationCoordinateOptions {+ params: { aid?: string; topicId?: string };+ resolvedAgentId?: string;+ url: string;+}++export const resolveActiveConversationCoordinate = ({+ params,+ resolvedAgentId,+ url,+}: ResolveActiveConversationCoordinateOptions): ActiveConversationCoordinate => {+ const location = new URL(url, 'https://desktop.local');+ const segments = location.pathname.split('/').filter(Boolean);+ const agentSegmentIndex = segments.lastIndexOf('agent');+ const suffixLength = agentSegmentIndex < 0 ? -1 : segments.length - agentSegmentIndex - 2;+ const isConversation =+ !!params.aid &&+ agentSegmentIndex >= 0 &&+ (suffixLength === 0 || (suffixLength === 1 && params.topicId !== undefined));+ const agentBasePath =+ agentSegmentIndex >= 0 ? `/${segments.slice(0, agentSegmentIndex + 2).join('/')}` : undefined;++ return {+ agentBasePath,+ agentId: params.aid ? resolvedAgentId || params.aid : undefined,+ hash: location.hash,+ isConversation,+ pathname: location.pathname,+ routeAgentId: params.aid,+ search: location.search,+ threadId: isConversation ? location.searchParams.get('thread') : null,+ topicId: isConversation ? params.topicId || null : null,+ };+};++export const buildActiveConversationUrl = (+ coordinate: ActiveConversationCoordinate,+ topicId: string | null,+ threadId: string | null,+) => {+ if (!coordinate.agentBasePath) {+ return `${coordinate.pathname}${coordinate.search}${coordinate.hash}`;+ }++ const searchParams = new URLSearchParams(coordinate.search);+ searchParams.delete('topic');++ if (threadId) searchParams.set('thread', threadId);+ else searchParams.delete('thread');++ const pathname = topicId ? `${coordinate.agentBasePath}/${topicId}` : coordinate.agentBasePath;+ const search = searchParams.toString();++ return `${pathname}${search ? `?${search}` : ''}${coordinate.hash}`;+};diff --git a/src/features/Electron/ActiveConversationBridge/index.tsx b/src/features/Electron/ActiveConversationBridge/index.tsxnew file mode 100644index 00000000000..b3258ba1cb1--- /dev/null+++ b/src/features/Electron/ActiveConversationBridge/index.tsx@@ -0,0 +1,41 @@+'use client';++import { useLayoutEffect, useMemo, useRef } from 'react';++import { useResolvedAgentRouteId } from '@/features/AgentRoute/useResolvedAgentRouteId';+import { selectActiveTabUrl } from '@/features/Electron/shell/activeTabUrl';+import { useActiveRouteParams } from '@/hooks/useActiveRouteParams';+import { useElectronStore } from '@/store/electron';++import { resolveActiveConversationCoordinate } from './coordinate';+import { subscribeActiveConversationNavigation } from './navigation';+import { projectActiveConversationCoordinate } from './projectCoordinate';++const ActiveConversationBridge = () => {+ const params = useActiveRouteParams<{ aid?: string; topicId?: string }>();+ const url = useElectronStore(selectActiveTabUrl) || '/';+ const { agentId } = useResolvedAgentRouteId(params.aid);+ const coordinate = useMemo(+ () =>+ resolveActiveConversationCoordinate({+ params,+ resolvedAgentId: agentId,+ url,+ }),+ [agentId, params, url],+ );+ const coordinateRef = useRef(coordinate);+ coordinateRef.current = coordinate;++ useLayoutEffect(() => {+ projectActiveConversationCoordinate(coordinate);+ }, [coordinate]);++ useLayoutEffect(() => {+ return subscribeActiveConversationNavigation(() => coordinateRef.current);+ }, []);++ return null;+};++export default ActiveConversationBridge;diff --git a/src/features/Electron/ActiveConversationBridge/navigation.test.ts b/src/features/Electron/ActiveConversationBridge/navigation.test.tsnew file mode 100644index 00000000000..a09fe698138--- /dev/null+++ b/src/features/Electron/ActiveConversationBridge/navigation.test.ts@@ -0,0 +1,75 @@+import { beforeEach, describe, expect, it, vi } from 'vitest';++import { initialState as initialChatState } from '@/store/chat/initialState';+import { useChatStore } from '@/store/chat/store';++import { resolveActiveConversationCoordinate } from './coordinate';+import { subscribeActiveConversationNavigation } from './navigation';+import { projectActiveConversationCoordinate } from './projectCoordinate';++vi.mock('@/features/Electron/navigation/appNavigate', () => ({ appNavigate: vi.fn() }));++describe('active conversation navigation', () => {+ beforeEach(() => {+ useChatStore.setState(+ {+ ...initialChatState,+ activeAgentId: 'agent-a',+ activeThreadId: 'thread-a',+ activeTopicId: 'topic-a',+ },+ false,+ );+ });++ it('turns one atomic topic and thread store change into one active-tab navigation', () => {+ const coordinate = resolveActiveConversationCoordinate({+ params: { aid: 'agent-a', topicId: 'topic-a' },+ resolvedAgentId: 'agent-a',+ url: '/team/agent/agent-a/topic-a?thread=thread-a&mode=single',+ });+ const navigate = vi.fn();+ projectActiveConversationCoordinate(coordinate);+ const unsubscribe = subscribeActiveConversationNavigation(() => coordinate, navigate);++ useChatStore.setState({ activeThreadId: undefined, activeTopicId: 'topic-b' }, false);++ expect(navigate).toHaveBeenCalledTimes(1);+ expect(navigate).toHaveBeenCalledWith('/team/agent/agent-a/topic-b?mode=single', {+ replace: true,+ });+ unsubscribe();+ });++ it('restores the routed topic after a scoped store reset without navigating', () => {+ const coordinate = resolveActiveConversationCoordinate({+ params: { aid: 'agent-a', topicId: 'topic-a' },+ resolvedAgentId: 'agent-a',+ url: '/agent/agent-a/topic-a',+ });+ const navigate = vi.fn();+ projectActiveConversationCoordinate(coordinate);+ const unsubscribe = subscribeActiveConversationNavigation(() => coordinate, navigate);++ useChatStore.setState({ activeTopicId: undefined }, false);++ expect(useChatStore.getState().activeTopicId).toBe('topic-a');+ expect(navigate).not.toHaveBeenCalled();+ unsubscribe();+ });++ it('does not convert a global topic change into navigation from an agent subpage', () => {+ const coordinate = resolveActiveConversationCoordinate({+ params: { aid: 'agent-a' },+ resolvedAgentId: 'agent-a',+ url: '/agent/agent-a/profile',+ });+ const navigate = vi.fn();+ const unsubscribe = subscribeActiveConversationNavigation(() => coordinate, navigate);++ useChatStore.setState({ activeTopicId: 'topic-b' }, false);++ expect(navigate).not.toHaveBeenCalled();+ unsubscribe();+ });+});diff --git a/src/features/Electron/ActiveConversationBridge/navigation.ts b/src/features/Electron/ActiveConversationBridge/navigation.tsnew file mode 100644index 00000000000..e8a6575d7b7--- /dev/null+++ b/src/features/Electron/ActiveConversationBridge/navigation.ts@@ -0,0 +1,37 @@+import { appNavigate } from '@/features/Electron/navigation/appNavigate';+import { useChatStore } from '@/store/chat';++import { type ActiveConversationCoordinate, buildActiveConversationUrl } from './coordinate';++type Navigate = (url: string, options: { replace: true }) => void;++export const subscribeActiveConversationNavigation = (+ getCoordinate: () => ActiveConversationCoordinate,+ navigate: Navigate = appNavigate,+) =>+ useChatStore.subscribe((state, previousState) => {+ if (+ state.activeTopicId === previousState.activeTopicId &&+ state.activeThreadId === previousState.activeThreadId+ ) {+ return;+ }++ const coordinate = getCoordinate();+ if (!coordinate.isConversation || !coordinate.routeAgentId) return;++ if (state.activeTopicId === undefined && coordinate.topicId) {+ useChatStore.setState(+ { activeTopicId: coordinate.topicId },+ false,+ 'ActiveConversationBridge/restoreTopicAfterScopedReset',+ );+ return;+ }++ const topicId = state.activeTopicId || null;+ const threadId = state.activeThreadId || null;+ if (topicId === coordinate.topicId && threadId === coordinate.threadId) return;++ navigate(buildActiveConversationUrl(coordinate, topicId, threadId), { replace: true });+ });diff --git a/src/features/Electron/ActiveConversationBridge/projectCoordinate.test.ts b/src/features/Electron/ActiveConversationBridge/projectCoordinate.test.tsnew file mode 100644index 00000000000..0b93e807ee3--- /dev/null+++ b/src/features/Electron/ActiveConversationBridge/projectCoordinate.test.ts@@ -0,0 +1,73 @@+import { beforeEach, describe, expect, it } from 'vitest';++import { useAgentStore } from '@/store/agent/store';+import { initialState as initialChatState } from '@/store/chat/initialState';+import { useChatStore } from '@/store/chat/store';++import { resolveActiveConversationCoordinate } from './coordinate';+import { projectActiveConversationCoordinate } from './projectCoordinate';++describe('active conversation projection', () => {+ beforeEach(() => {+ useAgentStore.setState({ activeAgentId: 'agent-old' }, false);+ useChatStore.setState(+ {+ ...initialChatState,+ activeAgentId: 'agent-old',+ activeThreadId: 'thread-old',+ activeTopicId: 'topic-old',+ },+ false,+ );+ });++ it('projects the active tab route into both global stores as one conversation coordinate', () => {+ const coordinate = resolveActiveConversationCoordinate({+ params: { aid: 'agent-new', topicId: 'topic-new' },+ resolvedAgentId: 'agent-new',+ url: '/agent/agent-new/topic-new?thread=thread-new',+ });++ projectActiveConversationCoordinate(coordinate);++ expect(useAgentStore.getState().activeAgentId).toBe('agent-new');+ expect(useChatStore.getState()).toMatchObject({+ activeAgentId: 'agent-new',+ activeThreadId: 'thread-new',+ activeTopicId: 'topic-new',+ });+ });++ it('preserves topic state on a subpage of the same agent', () => {+ useAgentStore.setState({ activeAgentId: 'agent-old' }, false);+ const coordinate = resolveActiveConversationCoordinate({+ params: { aid: 'agent-old' },+ resolvedAgentId: 'agent-old',+ url: '/agent/agent-old/profile',+ });++ projectActiveConversationCoordinate(coordinate);++ expect(useChatStore.getState()).toMatchObject({+ activeAgentId: 'agent-old',+ activeThreadId: 'thread-old',+ activeTopicId: 'topic-old',+ });+ });++ it('clears stale conversation state when a different agent subpage becomes active', () => {+ const coordinate = resolveActiveConversationCoordinate({+ params: { aid: 'agent-new' },+ resolvedAgentId: 'agent-new',+ url: '/agent/agent-new/profile',+ });++ projectActiveConversationCoordinate(coordinate);++ expect(useChatStore.getState()).toMatchObject({+ activeAgentId: 'agent-new',+ activeThreadId: undefined,+ activeTopicId: null,+ });+ });+});diff --git a/src/features/Electron/ActiveConversationBridge/projectCoordinate.ts b/src/features/Electron/ActiveConversationBridge/projectCoordinate.tsnew file mode 100644index 00000000000..632c23a599f--- /dev/null+++ b/src/features/Electron/ActiveConversationBridge/projectCoordinate.ts@@ -0,0 +1,69 @@+import { useAgentStore } from '@/store/agent';+import { useChatStore } from '@/store/chat';++import { type ActiveConversationCoordinate } from './coordinate';++export const projectActiveConversationCoordinate = (+ coordinate: ActiveConversationCoordinate,+): void => {+ const currentAgentId = useChatStore.getState().activeAgentId;++ if (!coordinate.routeAgentId) {+ if (useAgentStore.getState().activeAgentId !== undefined) {+ useAgentStore.setState(+ { activeAgentId: undefined },+ false,+ 'ActiveConversationBridge/leaveAgent',+ );+ }+ if (currentAgentId !== undefined || useChatStore.getState().activeTopicId !== undefined) {+ useChatStore.setState(+ { activeAgentId: undefined, activeTopicId: undefined },+ false,+ 'ActiveConversationBridge/leaveAgent',+ );+ }+ return;+ }++ const agentId = coordinate.agentId || coordinate.routeAgentId;+ const agentChanged = currentAgentId !== undefined && currentAgentId !== agentId;++ if (agentChanged) useChatStore.getState().clearPortalStack();++ if (useAgentStore.getState().activeAgentId !== agentId) {+ useAgentStore.setState({ activeAgentId: agentId }, false, 'ActiveConversationBridge/syncAgent');+ }++ const chatState = useChatStore.getState();++ if (coordinate.isConversation) {+ if (+ chatState.activeAgentId !== agentId ||+ chatState.activeTopicId !== coordinate.topicId ||+ chatState.activeThreadId !== coordinate.threadId+ ) {+ useChatStore.setState(+ {+ activeAgentId: agentId,+ activeThreadId: coordinate.threadId!,+ activeTopicId: coordinate.topicId!,+ },+ false,+ 'ActiveConversationBridge/syncConversation',+ );+ }+ return;+ }++ if (chatState.activeAgentId !== agentId || agentChanged) {+ useChatStore.setState(+ {+ activeAgentId: agentId,+ ...(agentChanged ? { activeThreadId: undefined, activeTopicId: null! } : {}),+ },+ false,+ 'ActiveConversationBridge/syncAgent',+ );+ }+};diff --git a/src/features/Electron/TabHost/TabHost.test.ts b/src/features/Electron/TabHost/TabHost.test.tsnew file mode 100644index 00000000000..0d3d5779cb7--- /dev/null+++ b/src/features/Electron/TabHost/TabHost.test.ts@@ -0,0 +1,374 @@+import { act, cleanup, render, screen } from '@testing-library/react';+import React from 'react';+import { createMemoryRouter, Outlet, RouterProvider, useParams } from 'react-router';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';++import { type TabItem } from '@/features/Electron/titlebar/TabBar/types';+import { useElectronStore } from '@/store/electron';+import { initialState } from '@/store/electron/initialState';++import { MAX_LIVE_TAB_ROUTERS } from './resolveLiveTabIds';+import TabHost from './TabHost';+import TabLocationReporter from './TabLocationReporter';+import {+ getTabHistorySnapshot,+ getTabRouter,+ resetTabRouterManager,+ type TabRouter,+} from './tabRouterManager';++const TestRoute = () => {+ const { id } = useParams();+ return React.createElement('div', { 'data-testid': `param-${id}` }, id);+};++interface Creation {+ dispose: ReturnType<typeof vi.spyOn>;+ router: TabRouter;+ url: string;+}++let created: Creation[];++const createTestRouter = (url: string): TabRouter => {+ const router = createMemoryRouter(+ [{ element: React.createElement(TestRoute), path: '/item/:id' }],+ { initialEntries: [url] },+ );+ const dispose = vi.spyOn(router, 'dispose');+ created.push({ dispose, router, url });+ return router;+};++const renderHost = () => render(React.createElement(TabHost, { createRouter: createTestRouter }));++const ReporterRoot = () =>+ React.createElement(+ React.Fragment,+ null,+ React.createElement(Outlet),+ React.createElement(TabLocationReporter),+ );++const createReporterRouter = (url: string): TabRouter => {+ const router = createMemoryRouter(+ [+ {+ children: [{ element: React.createElement(TestRoute), path: 'agent/:id' }],+ element: React.createElement(ReporterRoot),+ path: '/',+ },+ ],+ { initialEntries: [url] },+ );+ const dispose = vi.spyOn(router, 'dispose');+ created.push({ dispose, router, url });+ return router;+};++const createScopedRouter = (url: string): TabRouter => {+ const router = createMemoryRouter([{ element: null, path: '*' }], { initialEntries: [url] });+ const dispose = vi.spyOn(router, 'dispose');+ created.push({ dispose, router, url });+ return router;+};++const setStore = (tabs: TabItem[], activeTabId: string | null) => {+ useElectronStore.setState({ ...initialState, activeTabId, tabs });+};++beforeEach(() => {+ created = [];+ window.localStorage.clear();+ resetTabRouterManager();+ setStore([], null);+});++afterEach(() => {+ cleanup();+ resetTabRouterManager();+});++describe('TabHost', () => {+ it('mounts per-tab routers inside an outer data router without tripping the nested-Router invariant', async () => {+ setStore(+ [+ { id: 'a', lastVisited: 2, url: '/item/a' },+ { id: 'b', lastVisited: 1, url: '/item/b' },+ ],+ 'a',+ );++ const outerRouter = createMemoryRouter(+ [+ {+ element: React.createElement(TabHost, { createRouter: createTestRouter }),+ path: '*',+ },+ ],+ { initialEntries: ['/'] },+ );++ render(React.createElement(RouterProvider, { router: outerRouter }));++ expect(await screen.findByTestId('param-a')).toHaveTextContent('a');+ expect(await screen.findByTestId('param-b')).toHaveTextContent('b');+ });++ it('renders each live tab router at its own location so params never bleed across tabs', async () => {+ setStore(+ [+ { id: 'a', lastVisited: 2, url: '/item/a' },+ { id: 'b', lastVisited: 1, url: '/item/b' },+ ],+ 'a',+ );++ renderHost();++ expect(await screen.findByTestId('param-a')).toHaveTextContent('a');+ expect(await screen.findByTestId('param-b')).toHaveTextContent('b');+ });++ it('toggles slot visibility when the active tab changes without unmounting the deactivated tab', async () => {+ setStore(+ [+ { id: 'a', lastVisited: 2, url: '/item/a' },+ { id: 'b', lastVisited: 1, url: '/item/b' },+ ],+ 'a',+ );++ renderHost();++ const slotA = (await screen.findByTestId('param-a')).parentElement!;+ const slotB = (await screen.findByTestId('param-b')).parentElement!;++ expect(slotA.style.display).toBe('');+ expect(slotB.style.display).toBe('none');++ act(() => {+ useElectronStore.setState({ activeTabId: 'b' });+ });++ expect(screen.getByTestId('param-a')).toBeInTheDocument();+ expect(screen.getByTestId('param-b')).toBeInTheDocument();+ expect(slotA.style.display).toBe('none');+ expect(slotB.style.display).toBe('');+ });++ it('disposes a router evicted past the LRU cap and recreates it fresh when reactivated', async () => {+ const baseTabs: TabItem[] = Array.from({ length: MAX_LIVE_TAB_ROUTERS }, (_, index) => ({+ id: `t${index}`,+ lastVisited: 10 - index,+ url: `/item/t${index}`,+ }));+ const oldest = baseTabs.at(-1)!;++ setStore(baseTabs, 't0');+ renderHost();++ await screen.findByTestId(`param-${oldest.id}`);+ expect(created).toHaveLength(MAX_LIVE_TAB_ROUTERS);++ const withEvictor: TabItem[] = [+ ...baseTabs,+ { id: 'evictor', lastVisited: 20, url: '/item/evictor' },+ ];+ act(() => {+ useElectronStore.setState({ activeTabId: 'evictor', tabs: withEvictor });+ });++ const oldestEntry = created.find((entry) => entry.url === oldest.url)!;+ await vi.waitFor(() => expect(oldestEntry.dispose).toHaveBeenCalled());++ const reactivated: TabItem[] = withEvictor.map((entry) =>+ entry.id === oldest.id ? { ...entry, lastVisited: 30 } : entry,+ );+ act(() => {+ useElectronStore.setState({ activeTabId: oldest.id, tabs: reactivated });+ });++ await screen.findByTestId(`param-${oldest.id}`);++ const oldestCreations = created.filter((entry) => entry.url === oldest.url);+ expect(oldestCreations).toHaveLength(2);+ expect(oldestCreations[1].router).not.toBe(oldestCreations[0].router);+ });++ it('cold-restores an internally-navigated tab at its latest reported url with history reset', async () => {+ const target: TabItem = { id: 'target', lastVisited: 100, url: '/agent/orig' };+ const fillers: TabItem[] = Array.from({ length: 5 }, (_, index) => ({+ id: `f${index}`,+ lastVisited: 10 + index,+ url: `/agent/f${index}`,+ }));++ setStore([target, ...fillers], 'target');+ render(React.createElement(TabHost, { createRouter: createReporterRouter }));++ await screen.findByTestId('param-orig');++ const targetRouter = created.find((entry) => entry.url === '/agent/orig')!.router;+ await act(async () => {+ await targetRouter.navigate('/agent/latest');+ });++ expect(useElectronStore.getState().tabs.find((t) => t.id === 'target')!.url).toBe(+ '/agent/latest',+ );+ expect(getTabHistorySnapshot('target').canGoBack).toBe(true);++ const evicted = useElectronStore+ .getState()+ .tabs.map((t) =>+ t.id === 'target' ? { ...t, lastVisited: 0 } : { ...t, lastVisited: 1000 },+ );+ act(() => {+ useElectronStore.setState({ activeTabId: 'f0', tabs: evicted });+ });++ const targetEntry = created.find((entry) => entry.url === '/agent/orig')!;+ await vi.waitFor(() => expect(targetEntry.dispose).toHaveBeenCalled());++ const reactivated = useElectronStore+ .getState()+ .tabs.map((t) => (t.id === 'target' ? { ...t, lastVisited: 2000 } : t));+ act(() => {+ useElectronStore.setState({ activeTabId: 'target', tabs: reactivated });+ });++ expect(await screen.findByTestId('param-latest')).toHaveTextContent('latest');+ expect(created.filter((entry) => entry.url === '/agent/latest')).toHaveLength(1);+ expect(getTabHistorySnapshot('target').canGoBack).toBe(false);+ });++ it("snapshots a hidden tab's navigated location into the store on LRU eviction", async () => {+ const target: TabItem = { id: 'target', lastVisited: 1, url: '/item/target' };+ const fillers: TabItem[] = Array.from({ length: MAX_LIVE_TAB_ROUTERS - 1 }, (_, index) => ({+ id: `f${index}`,+ lastVisited: 10 + index,+ url: `/item/f${index}`,+ }));++ // The newest filler is active; `target` is hidden but live. `createTestRouter`+ // mounts no reporter, mirroring the real hidden tab whose reporter effect is+ // torn down.+ setStore([target, ...fillers], fillers.at(-1)!.id);+ renderHost();++ await screen.findByTestId('param-target');++ const targetRouter = created.find((entry) => entry.url === '/item/target')!.router;+ await act(async () => {+ await targetRouter.navigate('/item/moved');+ });++ // Reporter never fired for the hidden tab, so the store keeps the pre-nav url.+ expect(useElectronStore.getState().tabs.find((t) => t.id === 'target')!.url).toBe(+ '/item/target',+ );++ // A newly active sixth tab pushes the oldest (`target`) out of the live set.+ const withEvictor: TabItem[] = [+ ...useElectronStore.getState().tabs,+ { id: 'evictor', lastVisited: 100, url: '/item/evictor' },+ ];+ act(() => {+ useElectronStore.setState({ activeTabId: 'evictor', tabs: withEvictor });+ });++ const targetEntry = created.find((entry) => entry.url === '/item/target')!;+ await vi.waitFor(() => expect(targetEntry.dispose).toHaveBeenCalled());++ // Eviction snapshot captured the router's latest location before disposal.+ expect(useElectronStore.getState().tabs.find((t) => t.id === 'target')!.url).toBe(+ '/item/moved',+ );++ const reactivated = useElectronStore+ .getState()+ .tabs.map((t) => (t.id === 'target' ? { ...t, lastVisited: 200 } : t));+ act(() => {+ useElectronStore.setState({ activeTabId: 'target', tabs: reactivated });+ });++ // Cold restore starts a fresh router at the snapshotted url with reset history.+ expect(await screen.findByTestId('param-moved')).toHaveTextContent('moved');+ expect(created.filter((entry) => entry.url === '/item/moved')).toHaveLength(1);+ expect(getTabHistorySnapshot('target').canGoBack).toBe(false);+ });++ it('disposes every old-scope router and cold-starts the new-scope tab on a cross-scope report', async () => {+ setStore(+ [+ { id: 'a', lastVisited: 2, url: '/item/a' },+ { id: 'b', lastVisited: 1, url: '/item/b' },+ ],+ 'a',+ );++ render(React.createElement(TabHost, { createRouter: createScopedRouter }));++ await vi.waitFor(() => {+ expect(getTabRouter('a')).toBeDefined();+ expect(getTabRouter('b')).toBeDefined();+ });++ const navigateA = vi.spyOn(getTabRouter('a')!, 'navigate');+ const navigateB = vi.spyOn(getTabRouter('b')!, 'navigate');++ await act(async () => {+ useElectronStore.getState().reportTabLocation('a', '/team-x/agent/z');+ });++ expect(getTabRouter('a')).toBeUndefined();+ expect(getTabRouter('b')).toBeUndefined();++ expect(navigateA).not.toHaveBeenCalled();+ expect(navigateB).not.toHaveBeenCalled();++ const state = useElectronStore.getState();+ expect(state.activeTabScope).toEqual({ slug: 'team-x', type: 'workspace' });++ const newTab = state.tabs.find((t) => t.url === '/team-x/agent/z')!;+ expect(newTab).toBeDefined();+ expect(newTab.id).not.toBe('a');++ const newRouter = getTabRouter(newTab.id)!;+ expect(newRouter.state.location.pathname).toBe('/team-x/agent/z');+ expect(getTabHistorySnapshot(newTab.id).canGoBack).toBe(false);+ });++ it('replays a navigation that landed while the tab was hidden once it becomes active', async () => {+ setStore(+ [+ { id: 'a', lastVisited: 2, url: '/agent/a' },+ { id: 'b', lastVisited: 1, url: '/agent/b' },+ ],+ 'a',+ );++ render(React.createElement(TabHost, { createRouter: createReporterRouter }));++ await screen.findByTestId('param-b');++ const hiddenRouter = created.find((entry) => entry.url === '/agent/b')!.router;+ await act(async () => {+ await hiddenRouter.navigate('/agent/moved');+ });++ // The hidden tree keeps rendering the pre-navigation match: `<Activity+ // mode="hidden">` tore down `RouterProvider`'s subscription.+ expect(screen.getByTestId('param-b')).toBeInTheDocument();++ act(() => {+ useElectronStore.setState({ activeTabId: 'b' });+ });++ expect(await screen.findByTestId('param-moved')).toHaveTextContent('moved');+ expect(screen.queryByTestId('param-b')).not.toBeInTheDocument();+ expect(useElectronStore.getState().tabs.find((t) => t.id === 'b')!.url).toBe('/agent/moved');+ expect(getTabHistorySnapshot('b').canGoBack).toBe(true);+ });+});diff --git a/src/features/Electron/TabHost/TabHost.tsx b/src/features/Electron/TabHost/TabHost.tsxnew file mode 100644index 00000000000..285efbd1bc0--- /dev/null+++ b/src/features/Electron/TabHost/TabHost.tsx@@ -0,0 +1,80 @@+'use client';++import { Activity, type CSSProperties, useEffect, useMemo } from 'react';+import { UNSAFE_LocationContext } from 'react-router';+import { RouterProvider } from 'react-router/dom';++import { createTabRouter } from '@/spa/router/tabRouter';+import { useElectronStore } from '@/store/electron';++import { MAX_LIVE_TAB_ROUTERS, resolveLiveTabIds } from './resolveLiveTabIds';+import { TabIdContext } from './TabIdContext';+import {+ getOrCreateTabRouter,+ getTabRouter,+ getTabRouterIds,+ syncTabRouters,+ type TabRouter,+} from './tabRouterManager';++interface TabHostProps {+ createRouter?: (url: string) => TabRouter;+}++const rootStyle: CSSProperties = { blockSize: '100%', inlineSize: '100%', position: 'relative' };+const slotStyle: CSSProperties = { inset: 0, position: 'absolute' };+const hiddenSlotStyle: CSSProperties = { ...slotStyle, display: 'none' };++const TabHost = ({ createRouter = createTabRouter }: TabHostProps) => {+ const tabs = useElectronStore((s) => s.tabs);+ const activeTabId = useElectronStore((s) => s.activeTabId);++ const liveIds = useMemo(+ () => resolveLiveTabIds(tabs, activeTabId, MAX_LIVE_TAB_ROUTERS),+ [tabs, activeTabId],+ );++ useEffect(() => {+ const liveSet = new Set(liveIds);+ const { snapshotTabLocation } = useElectronStore.getState();+ for (const id of getTabRouterIds()) {+ if (liveSet.has(id)) continue;+ const location = getTabRouter(id)?.state.location;+ if (location)+ snapshotTabLocation(id, `${location.pathname}${location.search}${location.hash}`);+ }+ syncTabRouters(liveIds);+ }, [liveIds]);++ const liveSet = new Set(liveIds);++ return (+ <div style={rootStyle}>+ {tabs+ .filter((tab) => liveSet.has(tab.id))+ .map((tab) => {+ const isActive = tab.id === activeTabId;++ return (+ <Activity key={tab.id} mode={isActive ? 'visible' : 'hidden'} name={`Tab:${tab.id}`}>+ {/* Activity preserves state but doesn't visually hide the DOM in this React+ version, so force-hide the inactive slot (mirrors home/_layout). */}+ <div style={isActive ? slotStyle : hiddenSlotStyle}>+ <TabIdContext value={tab.id}>+ {/* react-router forbids a data <RouterProvider> inside another Router+ (useInRouterContext invariant). Reset LocationContext so each per-tab+ router mounts as a root; nothing renders between the reset and the+ provider, so no consumer can observe the null gap. */}+ <UNSAFE_LocationContext value={null as never}>+ <RouterProvider router={getOrCreateTabRouter(tab.id, tab.url, createRouter)} />+ </UNSAFE_LocationContext>+ </TabIdContext>+ </div>+ </Activity>+ );+ })}+ </div>+ );+};++export default TabHost;diff --git a/src/features/Electron/TabHost/TabIdContext.ts b/src/features/Electron/TabHost/TabIdContext.tsnew file mode 100644index 00000000000..e10bb875a1b--- /dev/null+++ b/src/features/Electron/TabHost/TabIdContext.ts@@ -0,0 +1,3 @@+import { createContext } from 'react';++export const TabIdContext = createContext<string | null>(null);diff --git a/src/features/Electron/TabHost/TabLocationReporter.test.ts b/src/features/Electron/TabHost/TabLocationReporter.test.tsnew file mode 100644index 00000000000..b262c4f9761--- /dev/null+++ b/src/features/Electron/TabHost/TabLocationReporter.test.ts@@ -0,0 +1,101 @@+import { act, cleanup, render } from '@testing-library/react';+import React from 'react';+import { createMemoryRouter, Outlet } from 'react-router';+import { RouterProvider } from 'react-router/dom';+import { afterEach, beforeEach, describe, expect, it } from 'vitest';++import { type TabItem } from '@/features/Electron/titlebar/TabBar/types';+import { useElectronStore } from '@/store/electron';+import { initialState } from '@/store/electron/initialState';++import { TabIdContext } from './TabIdContext';+import TabLocationReporter from './TabLocationReporter';++const Root = () =>+ React.createElement(+ React.Fragment,+ null,+ React.createElement(Outlet),+ React.createElement(TabLocationReporter),+ );++const createReporterRouter = (url: string) =>+ createMemoryRouter(+ [{ children: [{ element: null, path: '*' }], element: React.createElement(Root), path: '/' }],+ {+ initialEntries: [url],+ },+ );++const setStore = (tabs: TabItem[], activeTabId: string | null) => {+ useElectronStore.setState({+ ...initialState,+ activeTabId,+ activeTabScope: { slug: 'item', type: 'workspace' },+ tabs,+ });+};++const urlOf = (id: string) => useElectronStore.getState().tabs.find((t) => t.id === id)!.url;++const renderTab = (tabId: string, router: ReturnType<typeof createReporterRouter>) =>+ render(+ React.createElement(+ TabIdContext.Provider,+ { value: tabId },+ React.createElement(RouterProvider, { router }),+ ),+ );++beforeEach(() => {+ setStore([], null);+});++afterEach(() => {+ cleanup();+});++describe('TabLocationReporter', () => {+ it('mirrors the active tab internal navigation into the store url', async () => {+ setStore([{ id: 'a', lastVisited: 1, url: '/item/a' }], 'a');+ const router = createReporterRouter('/item/a');+ renderTab('a', router);++ await act(async () => {+ await router.navigate('/item/a2');+ });++ expect(urlOf('a')).toBe('/item/a2');+ });++ it('keeps the anchor so a reload or cold restore still resolves the deep link', async () => {+ setStore([{ id: 'a', lastVisited: 1, url: '/item/a' }], 'a');+ const router = createReporterRouter('/item/a');+ renderTab('a', router);++ await act(async () => {+ await router.navigate('/item/a?q=1#msg_1');+ });++ expect(urlOf('a')).toBe('/item/a?q=1#msg_1');+ });++ it('does not overwrite the store from a hidden (non-active) tab navigation', async () => {+ setStore(+ [+ { id: 'a', lastVisited: 2, url: '/item/a' },+ { id: 'b', lastVisited: 1, url: '/item/b' },+ ],+ 'a',+ );+ const router = createReporterRouter('/item/b');+ renderTab('b', router);++ await act(async () => {+ await router.navigate('/item/bX');+ });++ expect(urlOf('b')).toBe('/item/b');+ expect(urlOf('a')).toBe('/item/a');+ });+});diff --git a/src/features/Electron/TabHost/TabLocationReporter.tsx b/src/features/Electron/TabHost/TabLocationReporter.tsxnew file mode 100644index 00000000000..dcdb642c950--- /dev/null+++ b/src/features/Electron/TabHost/TabLocationReporter.tsx@@ -0,0 +1,41 @@+'use client';++import { use, useEffect } from 'react';+import { useLocation } from 'react-router';++import { useElectronStore } from '@/store/electron';++import { TabIdContext } from './TabIdContext';+import { getTabRouter } from './tabRouterManager';++const TabLocationReporter = () => {+ const tabId = use(TabIdContext);+ const location = useLocation();+ const reportTabLocation = useElectronStore((s) => s.reportTabLocation);++ useEffect(() => {+ if (!tabId) return;+ // `<Activity mode="hidden">` tears down effects in hidden trees, so only the+ // active tab reaches here; the active-id check is belt-and-braces.+ if (useElectronStore.getState().activeTabId !== tabId) return;++ // A hidden tree also loses `RouterProvider`'s subscription, and remounting it+ // only reconnects β it never replays what was missed. So a background+ // `navigateTab` leaves the router ahead of the tree it renders. Re-navigating+ // onto the router's own location pushes that state through instead of+ // reporting (and mirroring into the window url) a stale location.+ const router = getTabRouter(tabId);+ const routerLocation = router?.state.location;+ if (router && routerLocation && routerLocation.key !== location.key) {+ const { hash, pathname, search, state } = routerLocation;+ void router.navigate({ hash, pathname, search }, { replace: true, state });+ return;+ }++ reportTabLocation(tabId, location.pathname + location.search + location.hash);+ }, [tabId, location.key, location.pathname, location.search, location.hash, reportTabLocation]);++ return null;+};++export default TabLocationReporter;diff --git a/src/features/Electron/TabHost/index.ts b/src/features/Electron/TabHost/index.tsnew file mode 100644index 00000000000..4c7dca4a9b0--- /dev/null+++ b/src/features/Electron/TabHost/index.ts@@ -0,0 +1,11 @@+export { type HistorySnapshot } from './tabHistoryTracker';+export { default as TabHost } from './TabHost';+export { TabIdContext } from './TabIdContext';+export {+ getOrCreateTabRouter,+ getTabHistorySnapshot,+ getTabRouter,+ resetTabRouterManager,+ subscribeTabHistory,+} from './tabRouterManager';+export { useSeedTabsOnBoot } from './useSeedTabsOnBoot';diff --git a/src/features/Electron/TabHost/resolveBootAction.test.ts b/src/features/Electron/TabHost/resolveBootAction.test.tsnew file mode 100644index 00000000000..0d30193a1f6--- /dev/null+++ b/src/features/Electron/TabHost/resolveBootAction.test.ts@@ -0,0 +1,68 @@+import { describe, expect, it } from 'vitest';++import { type TabItem } from '@/features/Electron/titlebar/TabBar/types';++import { resolveBootAction } from './resolveBootAction';++const tab = (id: string, url: string): TabItem => ({ id, lastVisited: 1, url });++describe('resolveBootAction', () => {+ it('keeps the persisted active tab on a default `/` launch', () => {+ const tabs = [tab('a', '/agent/x'), tab('b', '/image')];++ expect(resolveBootAction(tabs, 'b', '/')).toEqual({ type: 'keep' });+ });++ it('does not keep when the default launch has no valid persisted active tab', () => {+ const tabs = [tab('a', '/agent/x')];++ // Stale active id β falls through to matching, then add.+ expect(resolveBootAction(tabs, 'missing', '/')).toEqual({ type: 'add', url: '/' });+ });++ it('activates a matching tab that is not the active one for a deep-link boot', () => {+ const tabs = [tab('a', '/agent/x'), tab('b', '/image')];++ expect(resolveBootAction(tabs, 'a', '/image')).toEqual({ id: 'b', type: 'activate' });+ });++ it('carries the launch anchor onto a matching tab parked at another fragment', () => {+ const tabs = [tab('a', '/agent/x#msg_1'), tab('b', '/image')];++ expect(resolveBootAction(tabs, 'b', '/agent/x#msg_2')).toEqual({+ id: 'a',+ type: 'activate',+ url: '/agent/x#msg_2',+ });+ });++ it('carries the launch anchor onto a matching tab that has no fragment', () => {+ const tabs = [tab('a', '/settings/agent')];++ expect(resolveBootAction(tabs, 'a', '/settings/agent#llm')).toEqual({+ id: 'a',+ type: 'activate',+ url: '/settings/agent#llm',+ });+ });++ it('adds a tab when the boot url matches nothing', () => {+ const tabs = [tab('a', '/agent/x')];++ expect(resolveBootAction(tabs, 'a', '/memory')).toEqual({ type: 'add', url: '/memory' });+ });++ it('adds a tab for the boot url when the store is empty', () => {+ expect(resolveBootAction([], null, '/agent/x')).toEqual({ type: 'add', url: '/agent/x' });+ });++ it('adds a home tab on a default launch with an empty store', () => {+ expect(resolveBootAction([], null, '/')).toEqual({ type: 'add', url: '/' });+ });++ it('activates a matching `/` tab when there is no persisted active tab', () => {+ const tabs = [tab('a', '/'), tab('b', '/image')];++ expect(resolveBootAction(tabs, null, '/')).toEqual({ id: 'a', type: 'activate' });+ });+});diff --git a/src/features/Electron/TabHost/resolveBootAction.ts b/src/features/Electron/TabHost/resolveBootAction.tsnew file mode 100644index 00000000000..f7de08dc428--- /dev/null+++ b/src/features/Electron/TabHost/resolveBootAction.ts@@ -0,0 +1,27 @@+import { isSameTabTarget } 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 };++export const resolveBootAction = (+ tabs: TabItem[],+ activeTabId: string | null,+ bootUrl: string,+): BootAction => {+ const isDefaultLaunch = normalizeTabUrl(bootUrl) === '/';+ const activeTabExists = !!activeTabId && tabs.some((tab) => tab.id === activeTabId);++ if (isDefaultLaunch && activeTabExists) return { type: 'keep' };++ // Tab identity ignores the fragment, so a matched tab can still sit at a+ // different anchor than the launch url β carry the exact url over.+ const match = tabs.find((tab) => isSameTabTarget(tab, bootUrl));+ if (match)+ return match.url === bootUrl+ ? { id: match.id, type: 'activate' }+ : { id: match.id, type: 'activate', url: bootUrl };++ return { type: 'add', url: bootUrl };+};diff --git a/src/features/Electron/TabHost/resolveLiveTabIds.test.ts b/src/features/Electron/TabHost/resolveLiveTabIds.test.tsnew file mode 100644index 00000000000..2e68b84b849--- /dev/null+++ b/src/features/Electron/TabHost/resolveLiveTabIds.test.ts@@ -0,0 +1,49 @@+import { describe, expect, it } from 'vitest';++import { MAX_LIVE_TAB_ROUTERS, resolveLiveTabIds } from './resolveLiveTabIds';++type Tab = { id: string; lastVisited: number };++const tab = (id: string, lastVisited: number): Tab => ({ id, lastVisited });++describe('resolveLiveTabIds', () => {+ it('returns every id when the cap exceeds the tab count', () => {+ const tabs = [tab('a', 1), tab('b', 2), tab('c', 3)];++ expect(resolveLiveTabIds(tabs, 'a', 10)).toEqual(['a', 'b', 'c']);+ });++ it('keeps the active tab plus the most recently visited and evicts the oldest', () => {+ const tabs = [tab('a', 1), tab('b', 2), tab('c', 3), tab('d', 4)];++ expect(resolveLiveTabIds(tabs, 'a', 2)).toEqual(['a', 'd']);+ });++ it('always keeps the active tab even when it is the oldest, evicting the next-oldest instead', () => {+ const tabs = [tab('a', 1), tab('b', 2), tab('c', 3)];++ expect(resolveLiveTabIds(tabs, 'a', 2)).toEqual(['a', 'c']);+ });++ it('breaks ties on equal lastVisited by stable input order', () => {+ const tabs = [tab('a', 5), tab('b', 5), tab('c', 5)];++ expect(resolveLiveTabIds(tabs, null, 2)).toEqual(['a', 'b']);+ });++ it('falls back to the most recent cap tabs when there is no active tab', () => {+ const tabs = [tab('a', 1), tab('b', 2), tab('c', 3), tab('d', 4)];++ expect(resolveLiveTabIds(tabs, null, 2)).toEqual(['c', 'd']);+ });++ it('handles degenerate inputs safely', () => {+ expect(resolveLiveTabIds([], 'a', 5)).toEqual([]);+ expect(resolveLiveTabIds([tab('a', 1), tab('b', 2)], 'a', 0)).toEqual(['a']);+ expect(resolveLiveTabIds([tab('a', 1)], null, 0)).toEqual([]);+ });++ it('exposes the default cap', () => {+ expect(MAX_LIVE_TAB_ROUTERS).toBe(3);+ });+});diff --git a/src/features/Electron/TabHost/resolveLiveTabIds.ts b/src/features/Electron/TabHost/resolveLiveTabIds.tsnew file mode 100644index 00000000000..84173e6bbd6--- /dev/null+++ b/src/features/Electron/TabHost/resolveLiveTabIds.ts@@ -0,0 +1,27 @@+import { type TabItem } from '@/features/Electron/titlebar/TabBar/types';++export const MAX_LIVE_TAB_ROUTERS = 3;++export const resolveLiveTabIds = (+ tabs: Pick<TabItem, 'id' | 'lastVisited'>[],+ activeTabId: string | null,+ cap: number,+): string[] => {+ const hasActive = activeTabId !== null && tabs.some((tab) => tab.id === activeTabId);++ if (cap <= 0) return hasActive ? [activeTabId!] : [];++ const ranked = tabs+ .map((tab, index) => ({ id: tab.id, index, lastVisited: tab.lastVisited }))+ .sort((a, b) => b.lastVisited - a.lastVisited || a.index - b.index);++ const live = new Set<string>();+ if (hasActive) live.add(activeTabId!);++ for (const entry of ranked) {+ if (live.size >= cap) break;+ live.add(entry.id);+ }++ return tabs.filter((tab) => live.has(tab.id)).map((tab) => tab.id);+};diff --git a/src/features/Electron/TabHost/tabHistoryTracker.test.ts b/src/features/Electron/TabHost/tabHistoryTracker.test.tsnew file mode 100644index 00000000000..da32483859c--- /dev/null+++ b/src/features/Electron/TabHost/tabHistoryTracker.test.ts@@ -0,0 +1,115 @@+import { createMemoryRouter } from 'react-router';+import { describe, expect, it } from 'vitest';++import {+ createHistoryTracker,+ type HistoryState,+ initHistoryState,+ reduceHistoryState,+ snapshotOf,+} from './tabHistoryTracker';++const apply = (state: HistoryState, action: 'POP' | 'PUSH' | 'REPLACE', key: string) =>+ reduceHistoryState(state, action, key);++describe('reduceHistoryState', () => {+ it('starts at index 0 with a single key and cannot go back or forward', () => {+ const state = initHistoryState('a');+ expect(state).toEqual({ index: 0, keys: ['a'] });+ expect(snapshotOf(state)).toEqual({ canGoBack: false, canGoForward: false });+ });++ it('PUSH appends a key and advances the index', () => {+ let state = initHistoryState('a');+ state = apply(state, 'PUSH', 'b');+ expect(state).toEqual({ index: 1, keys: ['a', 'b'] });+ expect(snapshotOf(state)).toEqual({ canGoBack: true, canGoForward: false });+ });++ it('PUSH then POP-back keeps forward history and enables canGoForward', () => {+ let state = initHistoryState('a');+ state = apply(state, 'PUSH', 'b');+ state = apply(state, 'POP', 'a');+ expect(state).toEqual({ index: 0, keys: ['a', 'b'] });+ expect(snapshotOf(state)).toEqual({ canGoBack: false, canGoForward: true });+ });++ it('PUSH after a POP-back truncates the forward entries', () => {+ let state = initHistoryState('a');+ state = apply(state, 'PUSH', 'b');+ state = apply(state, 'PUSH', 'c');+ state = apply(state, 'POP', 'b');+ // now at index 1 of [a,b,c]; a new PUSH should drop 'c'+ state = apply(state, 'PUSH', 'd');+ expect(state).toEqual({ index: 2, keys: ['a', 'b', 'd'] });+ expect(snapshotOf(state)).toEqual({ canGoBack: true, canGoForward: false });+ });++ it('REPLACE swaps the current key without changing the index or length', () => {+ let state = initHistoryState('a');+ state = apply(state, 'PUSH', 'b');+ state = apply(state, 'REPLACE', 'b2');+ expect(state).toEqual({ index: 1, keys: ['a', 'b2'] });+ expect(snapshotOf(state)).toEqual({ canGoBack: true, canGoForward: false });+ });++ it('POP to an unknown key leaves the state unchanged', () => {+ let state = initHistoryState('a');+ state = apply(state, 'PUSH', 'b');+ const same = apply(state, 'POP', 'zzz');+ expect(same).toBe(state);+ });+});++describe('createHistoryTracker', () => {+ const makeRouter = (url: string) =>+ createMemoryRouter([{ element: null, path: '/p/:id' }], { initialEntries: [url] });++ it('tracks a single router and reflects push/back transitions', async () => {+ const router = makeRouter('/p/a');+ const tracker = createHistoryTracker(router);++ expect(tracker.getSnapshot()).toEqual({ canGoBack: false, canGoForward: false });++ await router.navigate('/p/b');+ expect(tracker.getSnapshot()).toEqual({ canGoBack: true, canGoForward: false });++ await router.navigate(-1);+ expect(tracker.getSnapshot()).toEqual({ canGoBack: false, canGoForward: true });++ tracker.dispose();+ });++ it('notifies subscribers only when the snapshot changes', async () => {+ const router = makeRouter('/p/a');+ const tracker = createHistoryTracker(router);+ let calls = 0;+ const unsub = tracker.subscribe(() => {+ calls += 1;+ });++ await router.navigate('/p/b');+ expect(calls).toBe(1);+ // REPLACE keeps canGoBack/canGoForward the same β no notification+ await router.navigate('/p/b2', { replace: true });+ expect(calls).toBe(1);++ unsub();+ tracker.dispose();+ });++ it('tracks two routers independently', async () => {+ const routerA = makeRouter('/p/a');+ const routerB = makeRouter('/p/x');+ const trackerA = createHistoryTracker(routerA);+ const trackerB = createHistoryTracker(routerB);++ await routerA.navigate('/p/b');++ expect(trackerA.getSnapshot()).toEqual({ canGoBack: true, canGoForward: false });+ expect(trackerB.getSnapshot()).toEqual({ canGoBack: false, canGoForward: false });++ trackerA.dispose();+ trackerB.dispose();+ });+});diff --git a/src/features/Electron/TabHost/tabHistoryTracker.ts b/src/features/Electron/TabHost/tabHistoryTracker.tsnew file mode 100644index 00000000000..063679a889f--- /dev/null+++ b/src/features/Electron/TabHost/tabHistoryTracker.ts@@ -0,0 +1,83 @@+import { type TabRouter } from './tabRouterManager';++export type HistoryAction = 'POP' | 'PUSH' | 'REPLACE';++export interface HistoryState {+ index: number;+ keys: string[];+}++export interface HistorySnapshot {+ canGoBack: boolean;+ canGoForward: boolean;+}++export interface HistoryTracker {+ dispose: () => void;+ getSnapshot: () => HistorySnapshot;+ subscribe: (listener: () => void) => () => void;+}++export const initHistoryState = (key: string): HistoryState => ({ index: 0, keys: [key] });++export const reduceHistoryState = (+ state: HistoryState,+ action: HistoryAction,+ key: string,+): HistoryState => {+ switch (action) {+ case 'PUSH': {+ const keys = [...state.keys.slice(0, state.index + 1), key];+ return { index: keys.length - 1, keys };+ }+ case 'REPLACE': {+ const keys = [...state.keys];+ keys[state.index] = key;+ return { index: state.index, keys };+ }+ case 'POP': {+ const index = state.keys.indexOf(key);+ return index === -1 ? state : { index, keys: state.keys };+ }+ default: {+ return state;+ }+ }+};++export const snapshotOf = (state: HistoryState): HistorySnapshot => ({+ canGoBack: state.index > 0,+ canGoForward: state.index < state.keys.length - 1,+});++export const createHistoryTracker = (router: TabRouter): HistoryTracker => {+ let state = initHistoryState(router.state.location.key);+ let snapshot = snapshotOf(state);+ const listeners = new Set<() => void>();++ const unsubscribeRouter = router.subscribe((routerState) => {+ state = reduceHistoryState(+ state,+ routerState.historyAction as HistoryAction,+ routerState.location.key,+ );+ const next = snapshotOf(state);+ if (next.canGoBack === snapshot.canGoBack && next.canGoForward === snapshot.canGoForward) {+ return;+ }+ snapshot = next;+ listeners.forEach((listener) => listener());+ });++ return {+ dispose: () => {+ unsubscribeRouter();+ listeners.clear();+ },+ getSnapshot: () => snapshot,+ subscribe: (listener) => {+ listeners.add(listener);+ return () => listeners.delete(listener);+ },+ };+};diff --git a/src/features/Electron/TabHost/tabRouterManager.test.ts b/src/features/Electron/TabHost/tabRouterManager.test.tsnew file mode 100644index 00000000000..c236ff81f60--- /dev/null+++ b/src/features/Electron/TabHost/tabRouterManager.test.ts@@ -0,0 +1,37 @@+import { createMemoryRouter } from 'react-router';+import { afterEach, describe, expect, it } from 'vitest';++import {+ getOrCreateTabRouter,+ resetTabRouterManager,+ syncTabRouters,+ type TabRouter,+} from './tabRouterManager';++const makeRouter = (url: string): TabRouter =>+ createMemoryRouter([{ element: null, path: '/item/:id' }], { initialEntries: [url] });++afterEach(() => {+ resetTabRouterManager();+});++describe('tabRouterManager', () => {+ it('returns the same instance for a tabId and ignores the url on later calls', () => {+ const first = getOrCreateTabRouter('t1', '/item/a', makeRouter);+ const again = getOrCreateTabRouter('t1', '/item/b', makeRouter);++ expect(again).toBe(first);+ expect(again.state.location.pathname).toBe('/item/a');+ });++ it('disposes routers absent from the live list and recreates them fresh afterwards', () => {+ const original = getOrCreateTabRouter('t1', '/item/a', makeRouter);++ syncTabRouters([]);++ const recreated = getOrCreateTabRouter('t1', '/item/b', makeRouter);++ expect(recreated).not.toBe(original);+ expect(recreated.state.location.pathname).toBe('/item/b');+ });+});diff --git a/src/features/Electron/TabHost/tabRouterManager.ts b/src/features/Electron/TabHost/tabRouterManager.tsnew file mode 100644index 00000000000..87e6d7cdc99--- /dev/null+++ b/src/features/Electron/TabHost/tabRouterManager.ts@@ -0,0 +1,68 @@+import type { createTabRouter } from '@/spa/router/tabRouter';++import {+ createHistoryTracker,+ type HistorySnapshot,+ type HistoryTracker,+} from './tabHistoryTracker';++export type TabRouter = ReturnType<typeof createTabRouter>;++const routers = new Map<string, TabRouter>();+const trackers = new Map<string, HistoryTracker>();++const DEFAULT_HISTORY_SNAPSHOT: HistorySnapshot = { canGoBack: false, canGoForward: false };+const NOOP = () => {};++// `createRouter` is a required injection, not a `= createTabRouter` default: a+// static import of `createTabRouter` here pulls `desktopRouter.config` into the+// boot-time navigation chain and deadlocks module init (jsx-runtime TDZ).+export const getOrCreateTabRouter = (+ tabId: string,+ url: string,+ createRouter: (url: string) => TabRouter,+): TabRouter => {+ const existing = routers.get(tabId);+ if (existing) return existing;++ const router = createRouter(url);+ routers.set(tabId, router);+ trackers.set(tabId, createHistoryTracker(router));+ return router;+};++export const getTabRouter = (tabId: string): TabRouter | undefined => routers.get(tabId);++export const getTabRouterIds = (): string[] => [...routers.keys()];++export const getTabHistorySnapshot = (tabId: string): HistorySnapshot =>+ trackers.get(tabId)?.getSnapshot() ?? DEFAULT_HISTORY_SNAPSHOT;++export const subscribeTabHistory = (tabId: string, listener: () => void): (() => void) =>+ trackers.get(tabId)?.subscribe(listener) ?? NOOP;++export const disposeTabRouter = (tabId: string): void => {+ const tracker = trackers.get(tabId);+ if (tracker) {+ tracker.dispose();+ trackers.delete(tabId);+ }++ const router = routers.get(tabId);+ if (!router) return;++ router.dispose();+ routers.delete(tabId);+};++export const syncTabRouters = (liveTabIds: string[]): void => {+ const live = new Set(liveTabIds);++ for (const tabId of routers.keys()) {+ if (!live.has(tabId)) disposeTabRouter(tabId);+ }+};++export const resetTabRouterManager = (): void => {+ for (const tabId of routers.keys()) disposeTabRouter(tabId);+};diff --git a/src/features/Electron/TabHost/useSeedTabsOnBoot.test.ts b/src/features/Electron/TabHost/useSeedTabsOnBoot.test.tsnew file mode 100644index 00000000000..011159141d6--- /dev/null+++ b/src/features/Electron/TabHost/useSeedTabsOnBoot.test.ts@@ -0,0 +1,53 @@+import { renderHook } from '@testing-library/react';+import { afterEach, beforeEach, describe, expect, it } from 'vitest';++import { PERSONAL_TAB_SCOPE } from '@/features/Electron/titlebar/TabBar/scope';+import { saveTabPages } from '@/features/Electron/titlebar/TabBar/storage';+import { useElectronStore } from '@/store/electron';+import { initialState } from '@/store/electron/initialState';++import { useSeedTabsOnBoot } from './useSeedTabsOnBoot';++const activeUrl = () => {+ const { activeTabId, tabs } = useElectronStore.getState();+ return tabs.find((tab) => tab.id === activeTabId)?.url ?? null;+};++beforeEach(() => {+ window.localStorage.clear();+ useElectronStore.setState({ ...initialState });+});++afterEach(() => {+ window.history.replaceState(null, '', '/');+});++describe('useSeedTabsOnBoot', () => {+ it('keeps the anchor of a direct launch url so the deep link survives boot', () => {+ window.history.replaceState(null, '', '/agent/a?q=1#msg_1');++ renderHook(() => useSeedTabsOnBoot());++ expect(activeUrl()).toBe('/agent/a?q=1#msg_1');+ });++ it('moves a matching persisted tab to the launch anchor', () => {+ saveTabPages(PERSONAL_TAB_SCOPE, [{ id: 'a', lastVisited: 1, url: '/agent/a' }], null);+ window.history.replaceState(null, '', '/agent/a#msg_2');++ renderHook(() => useSeedTabsOnBoot());++ expect(useElectronStore.getState().tabs).toHaveLength(1);+ expect(activeUrl()).toBe('/agent/a#msg_2');+ });++ it('activates a persisted tab instead of adding one when the boot url matches', () => {+ saveTabPages(PERSONAL_TAB_SCOPE, [{ id: 'a', lastVisited: 1, url: '/agent/a' }], null);+ window.history.replaceState(null, '', '/agent/a');++ renderHook(() => useSeedTabsOnBoot());++ expect(useElectronStore.getState().tabs).toHaveLength(1);+ expect(useElectronStore.getState().activeTabId).toBe('a');+ });+});diff --git a/src/features/Electron/TabHost/useSeedTabsOnBoot.ts b/src/features/Electron/TabHost/useSeedTabsOnBoot.tsnew file mode 100644index 00000000000..bb99c73ac23--- /dev/null+++ b/src/features/Electron/TabHost/useSeedTabsOnBoot.ts@@ -0,0 +1,36 @@+'use client';++import { useEffect, useRef } from 'react';++import { useElectronStore } from '@/store/electron';++import { resolveBootAction } from './resolveBootAction';++export const useSeedTabsOnBoot = () => {+ const seededRef = useRef(false);++ useEffect(() => {+ if (seededRef.current) return;+ seededRef.current = true;++ const bootUrl = window.location.pathname + window.location.search + window.location.hash;++ const { loadTabs } = useElectronStore.getState();+ loadTabs(bootUrl);++ const { tabs, activeTabId, activateTab, addTab, updateTab } = useElectronStore.getState();+ const action = resolveBootAction(tabs, activeTabId, bootUrl);++ switch (action.type) {+ case 'activate': {+ if (action.url) updateTab(action.id, action.url);+ activateTab(action.id);+ break;+ }+ case 'add': {+ addTab(action.url);+ break;+ }+ }+ }, []);+};diff --git a/src/features/Electron/navigation/activeTabNavigate.ts b/src/features/Electron/navigation/activeTabNavigate.tsnew file mode 100644index 00000000000..2aae64c489e--- /dev/null+++ b/src/features/Electron/navigation/activeTabNavigate.ts@@ -0,0 +1,35 @@+import { type NavigateOptions, type To } from 'react-router';++// Import the manager directly, not the `@/features/Electron/TabHost` barrel: the+// barrel re-exports `TabHost`, whose static `createTabRouter` import would drag+// `desktopRouter.config` into the boot navigation chain and TDZ-crash init.+import { getTabRouter } from '@/features/Electron/TabHost/tabRouterManager';+import { useElectronStore } from '@/store/electron';++export const navigateTab = (tabId: string | null, to: To, options?: NavigateOptions): void => {+ const router = tabId ? getTabRouter(tabId) : undefined;+ if (!router) {+ // The active tab always has a live router (never evicted); an originating+ // tab's router may be gone (LRU-disposed, or navigation fired before it+ // mounted) β drop the navigation rather than rewrite the store, which+ // would violate the one-way mirror.+ if (process.env.NODE_ENV !== 'production') {+ console.warn('[appNavigate] tab has no live router; navigation ignored:', tabId, to);+ }+ return;+ }+ void router.navigate(to, options);+};++export const navigateTabByDelta = (tabId: string | null, delta: number): void => {+ if (!tabId) return;+ void getTabRouter(tabId)?.navigate(delta);+};++const getActiveTabId = (): string | null => useElectronStore.getState().activeTabId;++export const navigateActiveTab = (to: To, options?: NavigateOptions): void =>+ navigateTab(getActiveTabId(), to, options);++export const navigateActiveTabByDelta = (delta: number): void =>+ navigateTabByDelta(getActiveTabId(), delta);diff --git a/src/features/Electron/navigation/appNavigate.desktop.test.ts b/src/features/Electron/navigation/appNavigate.desktop.test.tsnew file mode 100644index 00000000000..00743a14d80--- /dev/null+++ b/src/features/Electron/navigation/appNavigate.desktop.test.ts@@ -0,0 +1,80 @@+import { createMemoryRouter } from 'react-router';+import { afterEach, describe, expect, it, vi } from 'vitest';++import * as slugModule from '@/business/client/hooks/useActiveWorkspaceSlug';+import { getOrCreateTabRouter, resetTabRouterManager } from '@/features/Electron/TabHost';++const mocks = vi.hoisted(() => ({+ storeState: { activeTabId: 't1' as string | null, addNewTab: vi.fn() },+}));++vi.mock('@/store/electron', () => ({+ useElectronStore: Object.assign(+ (selector: (s: unknown) => unknown) => selector(mocks.storeState),+ { getState: () => mocks.storeState },+ ),+}));++const { appNavigate } = await import('./appNavigate.desktop');++const makeRouter = (url: string) =>+ createMemoryRouter([{ element: null, path: '*' }], { initialEntries: [url] });++const seedActiveRouter = () => {+ const router = getOrCreateTabRouter('t1', '/', makeRouter);+ const navigate = vi.spyOn(router, 'navigate').mockResolvedValue(undefined);+ return navigate;+};++afterEach(() => {+ resetTabRouterManager();+ vi.restoreAllMocks();+ mocks.storeState.activeTabId = 't1';+ mocks.storeState.addNewTab = vi.fn();+});++describe('appNavigate (desktop)', () => {+ it('navigates the active tab router with the workspace-resolved url', () => {+ vi.spyOn(slugModule, 'getActiveWorkspaceSlug').mockReturnValue('acme');+ const navigate = seedActiveRouter();++ appNavigate('/agent/x');++ expect(navigate).toHaveBeenCalledWith('/acme/agent/x', {});+ });++ it('skips workspace resolution when escape is set', () => {+ vi.spyOn(slugModule, 'getActiveWorkspaceSlug').mockReturnValue('acme');+ const navigate = seedActiveRouter();++ appNavigate('/agent/x', { escape: true });++ expect(navigate).toHaveBeenCalledWith('/agent/x', {});+ });++ it('forwards react-router options (replace) to the active tab router', () => {+ const navigate = seedActiveRouter();++ appNavigate('/settings', { replace: true });++ expect(navigate).toHaveBeenCalledWith('/settings', { replace: true });+ });++ it('opens a new tab via the store without navigating any router', () => {+ vi.spyOn(slugModule, 'getActiveWorkspaceSlug').mockReturnValue('acme');+ const navigate = seedActiveRouter();++ appNavigate('/group/y', { target: 'newTab' });++ expect(mocks.storeState.addNewTab).toHaveBeenCalledWith('/acme/group/y');+ expect(navigate).not.toHaveBeenCalled();+ });++ it('drops the navigation when the active tab has no live router', () => {+ mocks.storeState.activeTabId = 'missing';+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => {});++ expect(() => appNavigate('/agent/x')).not.toThrow();+ expect(warn).toHaveBeenCalled();+ });+});diff --git a/src/features/Electron/navigation/appNavigate.desktop.ts b/src/features/Electron/navigation/appNavigate.desktop.tsnew file mode 100644index 00000000000..abdf0050d76--- /dev/null+++ b/src/features/Electron/navigation/appNavigate.desktop.ts@@ -0,0 +1,18 @@+import { getActiveWorkspaceSlug } from '@/business/client/hooks/useActiveWorkspaceSlug';+import { buildWorkspaceAwarePath } from '@/features/Workspace/workspaceAwarePath';+import { useElectronStore } from '@/store/electron';++import { navigateActiveTab } from './activeTabNavigate';+import type { AppNavigateOptions } from './appNavigate';++export const appNavigate = (to: string, opts: AppNavigateOptions = {}): void => {+ const { target = 'activeTab', escape, ...navOptions } = opts;+ const resolved = buildWorkspaceAwarePath(to, getActiveWorkspaceSlug(), { escape });++ if (target === 'newTab') {+ useElectronStore.getState().addNewTab(resolved);+ return;+ }++ navigateActiveTab(resolved, navOptions);+};diff --git a/src/features/Electron/navigation/appNavigate.ts b/src/features/Electron/navigation/appNavigate.tsnew file mode 100644index 00000000000..23e3bba26f4--- /dev/null+++ b/src/features/Electron/navigation/appNavigate.ts@@ -0,0 +1,15 @@+import { stableWorkspaceAwareNavigate } from '@/features/Workspace/stableWorkspaceAwareNavigate';+import { type WorkspaceAwareNavigateOptions } from '@/features/Workspace/workspaceAwarePath';++export type AppNavigateTarget = 'activeTab' | 'newTab';++export interface AppNavigateOptions extends WorkspaceAwareNavigateOptions {+ target?: AppNavigateTarget;+}++export const appNavigate = (to: string, opts: AppNavigateOptions = {}): void => {+ // Web has a single router; `target` (active vs new tab) is desktop-only.+ const { target: _target, ...rest } = opts;+ void _target;+ stableWorkspaceAwareNavigate(to, rest);+};diff --git a/src/features/Electron/navigation/tabNavigation.test.ts b/src/features/Electron/navigation/tabNavigation.test.tsdeleted file mode 100644index c181acb28ef..00000000000--- a/src/features/Electron/navigation/tabNavigation.test.ts+++ /dev/null@@ -1,43 +0,0 @@-import { describe, expect, it } from 'vitest';--import { type TabItem } from '@/features/Electron/titlebar/TabBar/types';--import { resolveTabNavigationAction } from './tabNavigation';--const tab = (id: string, url: string): TabItem => ({- id,- lastVisited: 1,- url,-});--describe('resolveTabNavigationAction', () => {- it('adds a tab when the active bucket has no active tab', () => {- expect(- resolveTabNavigationAction({- activeTabId: null,- currentUrl: '/agent/personal-agent',- tabs: [],- }),- ).toEqual({ type: 'add', url: '/agent/personal-agent' });- });-- it('updates the active tab when the current bucket has no matching target', () => {- expect(- resolveTabNavigationAction({- activeTabId: 'workspace',- currentUrl: '/acme/group/g1',- tabs: [tab('workspace', '/acme/agent/a1')],- }),- ).toEqual({ id: 'workspace', type: 'update', url: '/acme/group/g1' });- });-- it('activates an existing tab with the same target inside the active bucket', () => {- expect(- resolveTabNavigationAction({- activeTabId: 'personal',- currentUrl: '/acme/agent/a1?b=2&a=1',- tabs: [tab('personal', '/agent/a1'), tab('workspace', '/acme/agent/a1?a=1&b=2')],- }),- ).toEqual({ id: 'workspace', type: 'activate' });- });-});diff --git a/src/features/Electron/navigation/tabNavigation.ts b/src/features/Electron/navigation/tabNavigation.tsdeleted file mode 100644index ee864202d71..00000000000--- a/src/features/Electron/navigation/tabNavigation.ts+++ /dev/null@@ -1,47 +0,0 @@-import { isSameTabTarget } from '@/features/Electron/titlebar/TabBar/scope';-import { type TabItem } from '@/features/Electron/titlebar/TabBar/types';--export type TabNavigationAction =- | {- type: 'activate';- id: string;- }- | {- type: 'add';- url: string;- }- | {- type: 'none';- }- | {- id: string;- type: 'update';- url: string;- };--interface ResolveTabNavigationActionInput {- activeTabId: string | null;- currentUrl: string;- tabs: TabItem[];-}--export const resolveTabNavigationAction = ({- activeTabId,- currentUrl,- tabs,-}: ResolveTabNavigationActionInput): TabNavigationAction => {- const activeTab = activeTabId ? tabs.find((t) => t.id === activeTabId) : null;-- 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));- if (existing) return { id: existing.id, type: 'activate' };-- if (!activeTab) return { type: 'add', url: currentUrl };-- return { id: activeTab.id, type: 'update', url: currentUrl };-};diff --git a/src/features/Electron/navigation/useNavigationHistory.ts b/src/features/Electron/navigation/useNavigationHistory.tsindex bd369c1e975..0f2f49f05a2 100644--- a/src/features/Electron/navigation/useNavigationHistory.ts+++ b/src/features/Electron/navigation/useNavigationHistory.ts@@ -1,125 +1,55 @@'use client';import { useWatchBroadcast } from '@lobechat/electron-client-ipc';-import { useCallback, useEffect, useRef } from 'react';-import { useTranslation } from 'react-i18next';-import { useLocation } from 'react-router';--import { matchRouteMeta } from '@/features/Electron/titlebar/TabBar/resolveRouteMeta';-import { normalizeTabUrl } from '@/features/Electron/titlebar/TabBar/url';-import { useWorkspaceAwareNavigate } from '@/features/Workspace/useWorkspaceAwareNavigate';-import { desktopRoutes } from '@/spa/router/desktopRouter.config';+import { useCallback, useEffect, useRef, useSyncExternalStore } from 'react';++// Import the manager directly, not the `@/features/Electron/TabHost` barrel,+// whose `TabHost` re-export statically drags `desktopRouter.config` into the+// navigation graph (see activeTabNavigate for the boot-init TDZ this avoids).+import type { HistorySnapshot } from '@/features/Electron/TabHost/tabHistoryTracker';+import {+ getTabHistorySnapshot,+ getTabRouter,+ subscribeTabHistory,+} from '@/features/Electron/TabHost/tabRouterManager';+import { useActiveLocation } from '@/hooks/useActiveLocation';import { useElectronStore } from '@/store/electron';-export const useNavigationHistory = () => {- const { t } = useTranslation('electron');- const navigate = useWorkspaceAwareNavigate();- const location = useLocation();+const DEFAULT_SNAPSHOT: HistorySnapshot = { canGoBack: false, canGoForward: false };- const isNavigatingHistory = useElectronStore((s) => s.isNavigatingHistory);- const historyCurrentIndex = useElectronStore((s) => s.historyCurrentIndex);- const historyEntries = useElectronStore((s) => s.historyEntries);- const currentRouteMeta = useElectronStore((s) => s.currentRouteMeta);- const currentRouteMetaUrl = useElectronStore((s) => s.currentRouteMetaUrl);- const pushHistory = useElectronStore((s) => s.pushHistory);- const replaceHistory = useElectronStore((s) => s.replaceHistory);- const setIsNavigatingHistory = useElectronStore((s) => s.setIsNavigatingHistory);- const storeGoBack = useElectronStore((s) => s.goBack);- const storeGoForward = useElectronStore((s) => s.goForward);- const canGoBackFn = useElectronStore((s) => s.canGoBack);- const canGoForwardFn = useElectronStore((s) => s.canGoForward);- const getCurrentEntry = useElectronStore((s) => s.getCurrentEntry);+export const useNavigationHistory = () => {+ const location = useActiveLocation();+ const activeTabId = useElectronStore((s) => s.activeTabId);const addRecentPage = useElectronStore((s) => s.addRecentPage);-- const prevLocationRef = useRef<string | null>(null);-- const canGoBack = historyCurrentIndex > 0;- const canGoForward = historyCurrentIndex < historyEntries.length - 1;+ const prevUrlRef = useRef<string | null>(null);++ const subscribe = useCallback(+ (listener: () => void) => (activeTabId ? subscribeTabHistory(activeTabId, listener) : () => {}),+ [activeTabId],+ );+ const getSnapshot = useCallback(+ () => (activeTabId ? getTabHistorySnapshot(activeTabId) : DEFAULT_SNAPSHOT),+ [activeTabId],+ );+ const { canGoBack, canGoForward } = useSyncExternalStore(subscribe, getSnapshot, getSnapshot);const goBack = useCallback(() => {- if (!canGoBackFn()) return;-- const targetEntry = storeGoBack();- if (targetEntry) navigate(targetEntry.url, { escape: true });- }, [canGoBackFn, storeGoBack, navigate]);+ if (activeTabId) void getTabRouter(activeTabId)?.navigate(-1);+ }, [activeTabId]);const goForward = useCallback(() => {- if (!canGoForwardFn()) return;-- const targetEntry = storeGoForward();- if (targetEntry) navigate(targetEntry.url, { escape: true });- }, [canGoForwardFn, storeGoForward, navigate]);+ if (activeTabId) void getTabRouter(activeTabId)?.navigate(1);+ }, [activeTabId]);useEffect(() => {const currentUrl = location.pathname + location.search;-- if (isNavigatingHistory) {- setIsNavigatingHistory(false);- prevLocationRef.current = currentUrl;- return;- }-- if (prevLocationRef.current === currentUrl) return;-- const currentEntry = getCurrentEntry();- if (currentEntry?.url === currentUrl) {- prevLocationRef.current = currentUrl;- return;- }-- const staticMeta = matchRouteMeta(desktopRoutes, currentUrl).static;- const presetTitle = staticMeta.titleKey- ? (t(staticMeta.titleKey as never) as string)- : (t('navigation.lobehub') as string);-- pushHistory({- metadata: { timestamp: Date.now() },- title: presetTitle,- url: currentUrl,- });-+ if (prevUrlRef.current === currentUrl) return;+ prevUrlRef.current = currentUrl;addRecentPage(currentUrl);+ }, [location.pathname, location.search, addRecentPage]);- prevLocationRef.current = currentUrl;- }, [- location.pathname,- location.search,- isNavigatingHistory,- setIsNavigatingHistory,- getCurrentEntry,- pushHistory,- addRecentPage,- t,- ]);-- useEffect(() => {- const dynamicTitle = currentRouteMeta?.title;- if (!dynamicTitle || !currentRouteMetaUrl) return;-- const currentEntry = getCurrentEntry();- if (!currentEntry) return;- if (normalizeTabUrl(currentEntry.url) !== normalizeTabUrl(currentRouteMetaUrl)) return;- if (currentEntry.title === dynamicTitle) return;-- replaceHistory({ ...currentEntry, title: dynamicTitle });- addRecentPage(currentEntry.url, currentRouteMeta ?? undefined);- }, [currentRouteMeta, currentRouteMetaUrl, getCurrentEntry, replaceHistory, addRecentPage]);-- useWatchBroadcast('historyGoBack', () => {- goBack();- });-- useWatchBroadcast('historyGoForward', () => {- goForward();- });+ useWatchBroadcast('historyGoBack', goBack);+ useWatchBroadcast('historyGoForward', goForward);- return {- canGoBack,- canGoForward,- currentEntry: getCurrentEntry(),- goBack,- goForward,- historyEntries,- historyIndex: historyCurrentIndex,- };+ return { canGoBack, canGoForward, goBack, goForward };};diff --git a/src/features/Electron/navigation/useTabNavigation.ts b/src/features/Electron/navigation/useTabNavigation.tsdeleted file mode 100644index ebacbf7d269..00000000000--- a/src/features/Electron/navigation/useTabNavigation.ts+++ /dev/null@@ -1,66 +0,0 @@-'use client';--import { useEffect, useRef } from 'react';-import { useLocation } from 'react-router';--import { isSameTabTarget, resolveTabScopeKey } from '@/features/Electron/titlebar/TabBar/scope';-import { useElectronStore } from '@/store/electron';--import { resolveTabNavigationAction } from './tabNavigation';--export const useTabNavigation = () => {- const location = useLocation();-- const activateTab = useElectronStore((s) => s.activateTab);- const addTab = useElectronStore((s) => s.addTab);- const updateTab = useElectronStore((s) => s.updateTab);- const updateTabCache = useElectronStore((s) => s.updateTabCache);- const loadTabs = useElectronStore((s) => s.loadTabs);- const currentRouteMeta = useElectronStore((s) => s.currentRouteMeta);- const currentRouteMetaUrl = useElectronStore((s) => s.currentRouteMetaUrl);-- const prevLocationRef = useRef<string | null>(null);- 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;-- const { tabs, activeTabId } = useElectronStore.getState();- const action = resolveTabNavigationAction({ activeTabId, currentUrl, tabs });-- switch (action.type) {- case 'activate': {- activateTab(action.id);- break;- }- case 'add': {- addTab(action.url);- break;- }- case 'update': {- updateTab(action.id, action.url);- break;- }- }- }, [location.pathname, location.search, activateTab, addTab, updateTab, loadTabs]);-- useEffect(() => {- if (!currentRouteMeta || !currentRouteMetaUrl) return;-- const { activeTabId, tabs } = useElectronStore.getState();- if (!activeTabId) return;- const activeTab = tabs.find((t) => t.id === activeTabId);- if (!activeTab) return;- if (!isSameTabTarget(activeTab, currentRouteMetaUrl)) return;-- updateTabCache(activeTabId, currentRouteMeta);- }, [currentRouteMeta, currentRouteMetaUrl, updateTabCache]);-};diff --git a/src/features/Electron/shell/activeTabUrl.ts b/src/features/Electron/shell/activeTabUrl.tsnew file mode 100644index 00000000000..0d6f4e5dfca--- /dev/null+++ b/src/features/Electron/shell/activeTabUrl.ts@@ -0,0 +1,4 @@+import { type ElectronStore } from '@/store/electron';++export const selectActiveTabUrl = (s: ElectronStore): string | null =>+ s.tabs.find((tab) => tab.id === s.activeTabId)?.url ?? null;diff --git a/src/features/Electron/shell/index.ts b/src/features/Electron/shell/index.tsnew file mode 100644index 00000000000..b363a0ac335--- /dev/null+++ b/src/features/Electron/shell/index.ts@@ -0,0 +1,3 @@+export { selectActiveTabUrl } from './activeTabUrl';+export { useDesktopDocumentTitle } from './useDesktopDocumentTitle';+export { useWindowUrlMirror } from './useWindowUrlMirror';diff --git a/src/features/Electron/shell/useDesktopDocumentTitle.test.ts b/src/features/Electron/shell/useDesktopDocumentTitle.test.tsnew file mode 100644index 00000000000..0d87d20c977--- /dev/null+++ b/src/features/Electron/shell/useDesktopDocumentTitle.test.ts@@ -0,0 +1,57 @@+import { BRANDING_NAME } from '@lobechat/business-const';+import { renderHook } from '@testing-library/react';+import { afterEach, describe, expect, it, vi } from 'vitest';++import { useDesktopDocumentTitle } from './useDesktopDocumentTitle';++interface MockResolvedTab {+ isActive: boolean;+ meta: { title: string };+ tab: { id: string };+}++const mocks = vi.hoisted(() => ({+ result: { activeTabId: null as string | null, tabs: [] as unknown[] },+}));++vi.mock('@/features/Electron/titlebar/TabBar/hooks/useResolvedTabs', () => ({+ useResolvedTabs: () => mocks.result,+}));++const resolvedTab = (id: string, title: string): MockResolvedTab => ({+ isActive: false,+ meta: { title },+ tab: { id },+});++afterEach(() => {+ document.title = '';+ mocks.result = { activeTabId: null, tabs: [] };+});++describe('useDesktopDocumentTitle', () => {+ it('sets the active tab title with the branding suffix', () => {+ mocks.result = {+ activeTabId: 't1',+ tabs: [resolvedTab('t1', 'Chat A'), resolvedTab('t2', 'Other')],+ };++ renderHook(() => useDesktopDocumentTitle());++ expect(document.title).toBe(`Chat A Β· ${BRANDING_NAME}`);+ });++ it('emits the bare branding name when the resolved title is the brand fallback', () => {+ mocks.result = { activeTabId: 't1', tabs: [resolvedTab('t1', BRANDING_NAME)] };++ renderHook(() => useDesktopDocumentTitle());++ expect(document.title).toBe(BRANDING_NAME);+ });++ it('emits the bare branding name when there is no active tab', () => {+ renderHook(() => useDesktopDocumentTitle());++ expect(document.title).toBe(BRANDING_NAME);+ });+});diff --git a/src/features/Electron/shell/useDesktopDocumentTitle.ts b/src/features/Electron/shell/useDesktopDocumentTitle.tsnew file mode 100644index 00000000000..7b83b32d99f--- /dev/null+++ b/src/features/Electron/shell/useDesktopDocumentTitle.ts@@ -0,0 +1,18 @@+'use client';++import { BRANDING_NAME } from '@lobechat/business-const';+import { useEffect } from 'react';++import { useResolvedTabs } from '@/features/Electron/titlebar/TabBar/hooks/useResolvedTabs';++export const useDesktopDocumentTitle = (): void => {+ const { activeTabId, tabs } = useResolvedTabs();+ const title = tabs.find((tab) => tab.tab.id === activeTabId)?.meta.title;++ useEffect(() => {+ // `useResolvedTabs` falls back to the brand name for untitled routes β+ // suffixing it would render "LobeHub Β· LobeHub" where web shows the bare name.+ const meaningful = title && title !== BRANDING_NAME;+ document.title = meaningful ? `${title} Β· ${BRANDING_NAME}` : BRANDING_NAME;+ }, [title]);+};diff --git a/src/features/Electron/shell/useWindowUrlMirror.test.ts b/src/features/Electron/shell/useWindowUrlMirror.test.tsnew file mode 100644index 00000000000..fe93ea5e63f--- /dev/null+++ b/src/features/Electron/shell/useWindowUrlMirror.test.ts@@ -0,0 +1,52 @@+import { act, renderHook } from '@testing-library/react';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';++import { useElectronStore } from '@/store/electron';++import { useWindowUrlMirror } from './useWindowUrlMirror';++const tab = (id: string, url: string) => ({ id, lastVisited: 0, url });++let replaceState: ReturnType<typeof vi.spyOn>;++beforeEach(() => {+ replaceState = vi.spyOn(window.history, 'replaceState').mockImplementation(() => {});+});++afterEach(() => {+ vi.restoreAllMocks();+ useElectronStore.setState({ activeTabId: null, tabs: [] });+});++describe('useWindowUrlMirror', () => {+ it('mirrors the active tab url on mount and on tab switch', () => {+ useElectronStore.setState({+ activeTabId: 't1',+ tabs: [tab('t1', '/agent/a'), tab('t2', '/settings')],+ });++ renderHook(() => useWindowUrlMirror());+ expect(replaceState).toHaveBeenLastCalledWith(null, '', '/agent/a');++ act(() => useElectronStore.setState({ activeTabId: 't2' }));+ expect(replaceState).toHaveBeenLastCalledWith(null, '', '/settings');+ });++ it('reflects in-tab navigation (active tab url change)', () => {+ useElectronStore.setState({ activeTabId: 't1', tabs: [tab('t1', '/agent/a')] });++ renderHook(() => useWindowUrlMirror());+ expect(replaceState).toHaveBeenLastCalledWith(null, '', '/agent/a');++ act(() => useElectronStore.setState({ tabs: [tab('t1', '/agent/a/topic/1')] }));+ expect(replaceState).toHaveBeenLastCalledWith(null, '', '/agent/a/topic/1');+ });++ it('never mirrors a falsy url', () => {+ useElectronStore.setState({ activeTabId: null, tabs: [] });++ renderHook(() => useWindowUrlMirror());++ expect(replaceState).not.toHaveBeenCalled();+ });+});diff --git a/src/features/Electron/shell/useWindowUrlMirror.ts b/src/features/Electron/shell/useWindowUrlMirror.tsnew file mode 100644index 00000000000..c38a2216729--- /dev/null+++ b/src/features/Electron/shell/useWindowUrlMirror.ts@@ -0,0 +1,19 @@+'use client';++import { useEffect } from 'react';++import { useElectronStore } from '@/store/electron';++import { selectActiveTabUrl } from './activeTabUrl';++// One-way mirror: reflect the active tab's url into the window address so a real+// reload can re-seed tabs (see `useSeedTabsOnBoot`). The slimmed root router+// ignores `replaceState` (no popstate listener), so this never navigates.+export const useWindowUrlMirror = (): void => {+ const url = useElectronStore(selectActiveTabUrl);++ useEffect(() => {+ if (!url) return;+ window.history.replaceState(null, '', url);+ }, [url]);+};diff --git a/src/features/Electron/titlebar/RecentlyViewed/PageItem.tsx b/src/features/Electron/titlebar/RecentlyViewed/PageItem.tsxindex dab9942b24e..da691e0e380 100644--- a/src/features/Electron/titlebar/RecentlyViewed/PageItem.tsx+++ b/src/features/Electron/titlebar/RecentlyViewed/PageItem.tsx@@ -5,9 +5,9 @@ import { cx } from 'antd-style';import { Pin, PinOff } from 'lucide-react';import React, { memo } from 'react';import { useTranslation } from 'react-i18next';-import { useLocation } from 'react-router';import { useWorkspaceAwareNavigate } from '@/features/Workspace/useWorkspaceAwareNavigate';+import { useActiveLocation } from '@/hooks/useActiveLocation';import { useElectronStore } from '@/store/electron';import { type ResolvedTab } from '../TabBar/hooks/useResolvedTabs';@@ -23,7 +23,7 @@ interface PageItemProps {const PageItem = memo<PageItemProps>(({ item, isPinned, onClose }) => {const { t } = useTranslation('electron');const navigate = useWorkspaceAwareNavigate();- const location = useLocation();+ const location = useActiveLocation();const styles = useStyles;const pinPage = useElectronStore((s) => s.pinPage);diff --git a/src/features/Electron/titlebar/RecentlyViewed/hooks/useResolvedPages.ts b/src/features/Electron/titlebar/RecentlyViewed/hooks/useResolvedPages.tsindex 297976d11a8..503eb0ea87d 100644--- a/src/features/Electron/titlebar/RecentlyViewed/hooks/useResolvedPages.ts+++ b/src/features/Electron/titlebar/RecentlyViewed/hooks/useResolvedPages.ts@@ -3,7 +3,7 @@import { useMemo } from 'react';import { useTranslation } from 'react-i18next';-import { desktopRoutes } from '@/spa/router/desktopRouter.config';+import { mainAreaMetaRoutes } from '@/spa/router/desktopRouter.config';import { useElectronStore } from '@/store/electron';import { type ResolvedTab, resolveTab } from '../../TabBar/hooks/useResolvedTabs';@@ -24,12 +24,12 @@ export const useResolvedPages = (): UseResolvedPagesResult => {const translate = t as unknown as Translate;const pinnedPages = useMemo(- () => pinnedRefs.map((tab) => resolveTab(desktopRoutes, tab, false, translate)),+ () => pinnedRefs.map((tab) => resolveTab(mainAreaMetaRoutes, tab, false, translate)),[pinnedRefs, translate],);const recentPages = useMemo(- () => recentRefs.map((tab) => resolveTab(desktopRoutes, tab, false, translate)),+ () => recentRefs.map((tab) => resolveTab(mainAreaMetaRoutes, tab, false, translate)),[recentRefs, translate],);diff --git a/src/features/Electron/titlebar/RecentlyViewed/index.tsx b/src/features/Electron/titlebar/RecentlyViewed/index.tsxindex a77dff0f01e..1a039b32bb3 100644--- a/src/features/Electron/titlebar/RecentlyViewed/index.tsx+++ b/src/features/Electron/titlebar/RecentlyViewed/index.tsx@@ -3,8 +3,8 @@import { Flexbox } from '@lobehub/ui';import { memo, useEffect } from 'react';import { useTranslation } from 'react-i18next';-import { useLocation } from 'react-router';+import { useActiveLocation } from '@/hooks/useActiveLocation';import { useElectronStore } from '@/store/electron';import { useResolvedPages } from './hooks/useResolvedPages';@@ -17,7 +17,7 @@ interface RecentlyViewedProps {const RecentlyViewed = memo<RecentlyViewedProps>(({ onClose }) => {const { t } = useTranslation('electron');- const location = useLocation();+ const location = useActiveLocation();const styles = useStyles;const loadPinnedPages = useElectronStore((s) => s.loadPinnedPages);diff --git a/src/features/Electron/titlebar/TabBar/TabCacheBridges.test.tsx b/src/features/Electron/titlebar/TabBar/TabCacheBridges.test.tsxindex 4bb1846ed68..726849ab5ad 100644--- a/src/features/Electron/titlebar/TabBar/TabCacheBridges.test.tsx+++ b/src/features/Electron/titlebar/TabBar/TabCacheBridges.test.tsx@@ -44,7 +44,7 @@ const mocks = vi.hoisted(() => {});vi.mock('@/spa/router/desktopRouter.config', () => ({- get desktopRoutes() {+ get mainAreaMetaRoutes() {return mocks.routes.current;},}));diff --git a/src/features/Electron/titlebar/TabBar/TabCacheBridges.tsx b/src/features/Electron/titlebar/TabBar/TabCacheBridges.tsxindex 84c1c036b78..5dc2437609a 100644--- a/src/features/Electron/titlebar/TabBar/TabCacheBridges.tsx+++ b/src/features/Electron/titlebar/TabBar/TabCacheBridges.tsx@@ -3,7 +3,7 @@import { memo, useCallback } from 'react';import DynamicMetaRunner from '@/features/RouteMeta/DynamicMetaRunner';-import { desktopRoutes } from '@/spa/router/desktopRouter.config';+import { mainAreaMetaRoutes } from '@/spa/router/desktopRouter.config';import type { DynamicRouteMeta } from '@/spa/router/routeMeta';import { useElectronStore } from '@/store/electron';@@ -16,7 +16,7 @@ interface TabCacheBridgeProps {const TabCacheBridge = memo<TabCacheBridgeProps>(({ tab }) => {const updateTabCache = useElectronStore((s) => s.updateTabCache);- const matched = matchRouteMeta(desktopRoutes, tab.url);+ const matched = matchRouteMeta(mainAreaMetaRoutes, tab.url);const DynamicMeta = matched.meta?.DynamicMeta;const handleResolve = useCallback(@@ -30,8 +30,8 @@ const TabCacheBridge = memo<TabCacheBridgeProps>(({ tab }) => {return (<DynamicMetaRunner- key={tab.url}DynamicMeta={DynamicMeta}+ key={tab.url}params={matched.params}onResolve={handleResolve}/>diff --git a/src/features/Electron/titlebar/TabBar/hooks/useResolvedTabs.ts b/src/features/Electron/titlebar/TabBar/hooks/useResolvedTabs.tsindex caf892fa44c..8c1768db1c5 100644--- a/src/features/Electron/titlebar/TabBar/hooks/useResolvedTabs.ts+++ b/src/features/Electron/titlebar/TabBar/hooks/useResolvedTabs.ts@@ -4,7 +4,7 @@ import { useMemo } from 'react';import { useTranslation } from 'react-i18next';import { type RouteObject } from 'react-router';-import { desktopRoutes } from '@/spa/router/desktopRouter.config';+import { mainAreaMetaRoutes } from '@/spa/router/desktopRouter.config';import { type DynamicRouteMeta, type ResolvedRouteMeta } from '@/spa/router/routeMeta';import { useElectronStore } from '@/store/electron';@@ -76,7 +76,7 @@ export const useResolvedTabs = (): UseResolvedTabsResult => {() =>tabRefs.map((tab) =>resolveTab(- desktopRoutes,+ mainAreaMetaRoutes,tab,tab.id === activeTabId,translate,diff --git a/src/features/Electron/titlebar/TabBar/index.tsx b/src/features/Electron/titlebar/TabBar/index.tsxindex 3f429b0f8b9..784b27f4bcf 100644--- a/src/features/Electron/titlebar/TabBar/index.tsx+++ b/src/features/Electron/titlebar/TabBar/index.tsx@@ -15,12 +15,11 @@ import { useWatchBroadcast } from '@lobechat/electron-client-ipc';import { ActionIcon, ScrollArea } from '@lobehub/ui';import { cx } from 'antd-style';import { Plus } from 'lucide-react';-import { startTransition, useCallback, useEffect, useMemo, useRef } from 'react';+import { useCallback, useEffect, useMemo, useRef } from 'react';import { useTranslation } from 'react-i18next';-import { useLocation } from 'react-router';-import { useWorkspaceAwareNavigate } from '@/features/Workspace/useWorkspaceAwareNavigate';import { buildWorkspaceAwarePath } from '@/features/Workspace/workspaceAwarePath';+import { useActiveLocation } from '@/hooks/useActiveLocation';import { useRegisterDesktopTabHotkeys } from '@/hooks/useHotkeys/desktopTabScope';import { usePermission } from '@/hooks/usePermission';import { electronSystemService } from '@/services/electron/system';@@ -42,8 +41,7 @@ const restrictToHorizontalAxis: Modifier = ({ transform }) => ({ ...transform, yconst TabBar = () => {const styles = useStyles;- const navigate = useWorkspaceAwareNavigate();- const location = useLocation();+ const location = useActiveLocation();useRegisterDesktopTabHotkeys();const { t } = useTranslation('electron');const { allowed: canCreate, reason } = usePermission('create_content');@@ -87,67 +85,38 @@ const TabBar = () => {);const handleActivate = useCallback(- (id: string, url: string) => {+ (id: string) => {activateTab(id);- startTransition(() => navigate(url, { escape: true }));},- [activateTab, navigate],+ [activateTab],);- const navigateToActive = useCallback(() => {- const { activeTabId: newActiveId, tabs: newTabs } = useElectronStore.getState();- if (newActiveId) {- const target = newTabs.find((tab) => tab.id === newActiveId);- if (target) navigate(target.url, { escape: true });- } else {- navigate('/');- }- }, [navigate]);-const handleClose = useCallback((id: string) => {- const isActive = id === activeTabId;- const nextActiveId = removeTab(id);-- startTransition(() => {- if (isActive && nextActiveId) {- const nextTab = tabs.find((tab) => tab.tab.id === nextActiveId);- if (nextTab) navigate(nextTab.tab.url, { escape: true });- }-- if (!nextActiveId) {- navigate('/');- }- });+ removeTab(id);},- [activeTabId, removeTab, tabs, navigate],+ [removeTab],);const handleCloseOthers = useCallback((id: string) => {closeOtherTabs(id);- startTransition(() => {- const target = tabs.find((tab) => tab.tab.id === id);- if (target) navigate(target.tab.url, { escape: true });- });},- [closeOtherTabs, tabs, navigate],+ [closeOtherTabs],);const handleCloseLeft = useCallback((id: string) => {closeLeftTabs(id);- startTransition(() => navigateToActive());},- [closeLeftTabs, navigateToActive],+ [closeLeftTabs],);const handleCloseRight = useCallback((id: string) => {closeRightTabs(id);- startTransition(() => navigateToActive());},- [closeRightTabs, navigateToActive],+ [closeRightTabs],);useEffect(() => {@@ -188,8 +157,7 @@ const TabBar = () => {// Always open a fresh Home tab, even if a Home tab already exists.addNewTab(newTabUrl);- startTransition(() => navigate(newTabUrl, { escape: true }));- }, [canCreate, addNewTab, navigate, newTabUrl]);+ }, [canCreate, addNewTab, newTabUrl]);useWatchBroadcast('createNewTab', () => {handleNewTab();diff --git a/src/features/Electron/titlebar/TabBar/resolveTabUpdate.test.ts b/src/features/Electron/titlebar/TabBar/resolveTabUpdate.test.tsnew file mode 100644index 00000000000..92d324b3abd--- /dev/null+++ b/src/features/Electron/titlebar/TabBar/resolveTabUpdate.test.ts@@ -0,0 +1,40 @@+import { describe, expect, it } from 'vitest';++import { resolveTabUpdate } from './resolveTabUpdate';+import { PERSONAL_TAB_SCOPE, type TabScope } from './scope';++const workspace = (slug: string): TabScope => ({ slug, type: 'workspace' });++describe('resolveTabUpdate', () => {+ it('rewrites when the reported url stays in the active personal scope', () => {+ expect(resolveTabUpdate(PERSONAL_TAB_SCOPE, '/agent/abc')).toEqual({ type: 'rewrite' });+ });++ it('rewrites when the reported url stays in the same workspace scope', () => {+ expect(resolveTabUpdate(workspace('acme'), '/acme/agent/abc')).toEqual({ type: 'rewrite' });+ });++ it('scope-swaps when a personal tab reports a workspace url', () => {+ expect(resolveTabUpdate(PERSONAL_TAB_SCOPE, '/acme/agent/abc')).toEqual({+ scope: workspace('acme'),+ type: 'scope-swap',+ url: '/acme/agent/abc',+ });+ });++ it('scope-swaps when a workspace tab reports a personal url', () => {+ expect(resolveTabUpdate(workspace('acme'), '/settings')).toEqual({+ scope: PERSONAL_TAB_SCOPE,+ type: 'scope-swap',+ url: '/settings',+ });+ });++ it('scope-swaps between two different workspaces', () => {+ expect(resolveTabUpdate(workspace('acme'), '/globex/agent/abc')).toEqual({+ scope: workspace('globex'),+ type: 'scope-swap',+ url: '/globex/agent/abc',+ });+ });+});diff --git a/src/features/Electron/titlebar/TabBar/resolveTabUpdate.ts b/src/features/Electron/titlebar/TabBar/resolveTabUpdate.tsnew file mode 100644index 00000000000..5687fa0de5d--- /dev/null+++ b/src/features/Electron/titlebar/TabBar/resolveTabUpdate.ts@@ -0,0 +1,10 @@+import { isSameTabScope, resolveTabScope, type TabScope } from './scope';++export type TabUpdate = { type: 'rewrite' } | { scope: TabScope; type: 'scope-swap'; url: string };++export const resolveTabUpdate = (activeTabScope: TabScope, reportedUrl: string): TabUpdate => {+ const scope = resolveTabScope(reportedUrl);+ if (isSameTabScope(activeTabScope, scope)) return { type: 'rewrite' };++ return { scope, type: 'scope-swap', url: reportedUrl };+};diff --git a/src/features/Electron/titlebar/TabBar/url.test.ts b/src/features/Electron/titlebar/TabBar/url.test.tsindex b78b4dabf6b..56e1550af6a 100644--- a/src/features/Electron/titlebar/TabBar/url.test.ts+++ b/src/features/Electron/titlebar/TabBar/url.test.ts@@ -27,6 +27,14 @@ describe('normalizeTabUrl', () => {expect(normalizeTabUrl('/agent/abc?a=1#section')).toBe('/agent/abc?a=1');});+ it('drops the hash fragment when there is no search string', () => {+ expect(normalizeTabUrl('/settings/agent#llm')).toBe('/settings/agent');+ });++ it('treats two anchors of the same page as one tab identity', () => {+ expect(normalizeTabUrl('/agent/abc#msg_1')).toBe(normalizeTabUrl('/agent/abc#msg_2'));+ });+it('makes equivalent URLs collapse to the same id', () => {expect(normalizeTabUrl('/agent/abc?a=1&b=2')).toBe(normalizeTabUrl('/agent/abc?b=2&a=1'));});@@ -75,6 +83,10 @@ describe('parseAgentTabContext', () => {});});+ it('ignores the hash fragment when reading the agent id', () => {+ expect(parseAgentTabContext('/agent/abc#msg_1')).toEqual({ agentId: 'abc', topicId: null });+ });+it('returns null for non-agent urls', () => {expect(parseAgentTabContext('/group/g1')).toBeNull();});diff --git a/src/features/Electron/titlebar/TabBar/url.ts b/src/features/Electron/titlebar/TabBar/url.tsindex 9abae9844ca..4f7292f17ad 100644--- a/src/features/Electron/titlebar/TabBar/url.ts+++ b/src/features/Electron/titlebar/TabBar/url.ts@@ -1,5 +1,9 @@+// Tab identity ignores the fragment: `/settings/agent#llm` and `/settings/agent`+// are the same tab, so an anchor jump keeps the tab's cached meta instead of+// looking like a navigation to a different page.export const normalizeTabUrl = (url: string): string => {- const [rawPath = '', rawQuery = ''] = url.split('?');+ const [withoutHash = ''] = url.split('#');+ const [rawPath = '', rawQuery = ''] = withoutHash.split('?');let pathname = rawPath || '/';if (pathname.length > 1 && pathname.endsWith('/')) {@@ -7,7 +11,7 @@ export const normalizeTabUrl = (url: string): string => {}if (!pathname.startsWith('/')) pathname = `/${pathname}`;- const queryString = rawQuery.split('#')[0] ?? '';+ const queryString = rawQuery;if (!queryString) return pathname;const params = new URLSearchParams(queryString);@@ -32,7 +36,8 @@ const AGENT_TOPIC_PATH = /^\/agent\/([^/]+)\/(tpc_[^/]+)(?:\/|$)/;const AGENT_PATH = /^\/agent\/([^/]+)(?:\/|$)/;export const parseAgentTabContext = (url: string): AgentTabContext | null => {- const [rawPath = '', rawQuery = ''] = url.split('?');+ const [withoutHash = ''] = url.split('#');+ const [rawPath = '', rawQuery = ''] = withoutHash.split('?');const workspaceTopicMatch = rawPath.match(WORKSPACE_AGENT_TOPIC_PATH);if (workspaceTopicMatch) {@@ -48,7 +53,7 @@ export const parseAgentTabContext = (url: string): AgentTabContext | null => {const workspaceAgentMatch = rawPath.match(WORKSPACE_AGENT_PATH);if (workspaceAgentMatch) {- const queryTopic = new URLSearchParams(rawQuery.split('#')[0] ?? '').get('topic');+ const queryTopic = new URLSearchParams(rawQuery).get('topic');return {agentId: workspaceAgentMatch[2],topicId: queryTopic || null,@@ -59,6 +64,6 @@ export const parseAgentTabContext = (url: string): AgentTabContext | null => {const agentMatch = rawPath.match(AGENT_PATH);if (!agentMatch) return null;- const queryTopic = new URLSearchParams(rawQuery.split('#')[0] ?? '').get('topic');+ const queryTopic = new URLSearchParams(rawQuery).get('topic');return { agentId: agentMatch[1], topicId: queryTopic || null };};diff --git a/src/features/Electron/titlebar/TitleBar.tsx b/src/features/Electron/titlebar/TitleBar.tsxindex 182b0230f4b..f1b4fb9f271 100644--- a/src/features/Electron/titlebar/TitleBar.tsx+++ b/src/features/Electron/titlebar/TitleBar.tsx@@ -8,7 +8,6 @@ import { getPlatform } from '@/utils/platform';import Connection from '../connection/Connection';import DeviceGateway from '../connection/DeviceGateway';-import { useTabNavigation } from '../navigation/useTabNavigation';import { useWatchThemeUpdate } from '../system/useWatchThemeUpdate';import { UpdateNotification } from '../updater/UpdateNotification';import { getTitleBarLayoutConfig } from './layout';@@ -20,7 +19,6 @@ const platform = getPlatform();const TitleBar = memo(() => {useWatchThemeUpdate();- useTabNavigation();const { padding, showCustomWinControl } = getTitleBarLayoutConfig(platform);diff --git a/src/features/NavPanel/components/BackButton.tsx b/src/features/NavPanel/components/BackButton.tsxindex e870625db42..bb538fc1355 100644--- a/src/features/NavPanel/components/BackButton.tsx+++ b/src/features/NavPanel/components/BackButton.tsx@@ -1,11 +1,11 @@import { type ActionIconProps } from '@lobehub/ui';import { ActionIcon } from '@lobehub/ui';import { ChevronLeftIcon } from 'lucide-react';-import { memo } from 'react';-import { Link } from 'react-router';+import { memo, type MouseEvent } from 'react';import { useActiveWorkspaceSlug } from '@/business/client/hooks/useActiveWorkspaceSlug';import { DESKTOP_HEADER_ICON_SMALL_SIZE } from '@/const/layoutTokens';+import { appNavigate } from '@/features/Electron/navigation/appNavigate';import { buildWorkspaceAwarePath } from '@/features/Workspace/workspaceAwarePath';export const BACK_BUTTON_ID = 'lobe-back-button';@@ -14,16 +14,27 @@ const BackButton = memo<ActionIconProps & { to?: string }>(({ to = '/', onClick,const activeSlug = useActiveWorkspaceSlug();const resolvedTo = buildWorkspaceAwarePath(to, activeSlug);+ const handleClick = (event: MouseEvent<HTMLAnchorElement>) => {+ onClick?.(event as never);+ if (event.defaultPrevented) return;+ // Let the browser handle modifier/middle clicks (open-in-new) β matches the+ // previous <Link> behavior; a plain click stays in-app via the facade.+ if (event.metaKey || event.ctrlKey || event.shiftKey || event.altKey || event.button !== 0) {+ return;+ }+ event.preventDefault();+ appNavigate(resolvedTo, { escape: true });+ };+return (- // @ts-expect-error- <Link to={resolvedTo} onClick={onClick}>+ <a href={resolvedTo} onClick={handleClick}><ActionIconicon={ChevronLeftIcon}id={BACK_BUTTON_ID}size={DESKTOP_HEADER_ICON_SMALL_SIZE}{...rest}/>- </Link>+ </a>);});diff --git a/src/features/NavPanel/index.tsx b/src/features/NavPanel/index.tsxindex 1b4fa6d696a..c7d42303512 100644--- a/src/features/NavPanel/index.tsx+++ b/src/features/NavPanel/index.tsx@@ -2,12 +2,12 @@import { type PropsWithChildren, type ReactNode } from 'react';import { memo, useLayoutEffect, useRef, useSyncExternalStore } from 'react';-import { useLocation } from 'react-router';import { useActiveWorkspaceSlug } from '@/business/client/hooks/useActiveWorkspaceSlug';import AgentSidebarContent from '@/features/AgentSidebar/Content';import PageSidebarContent from '@/features/Pages/PageLayout/SidebarContent';import WorkspaceSettingsSideBarContent from '@/features/WorkspaceSetting/SideBar/Content';+import { useActiveLocation } from '@/hooks/useActiveLocation';import ImageSidebarContent from '@/routes/(main)/(create)/image/_layout/Sidebar/Content';import VideoSidebarContent from '@/routes/(main)/(create)/video/_layout/Sidebar/Content';import CommunitySidebarContent from '@/routes/(main)/community/_layout/Sidebar/Content';@@ -84,7 +84,7 @@ const getMainRouteSegment = (pathname: string, activeSlug: string | null) => {};const NavPanel = memo(() => {- const { pathname } = useLocation();+ const { pathname } = useActiveLocation();const activeSlug = useActiveWorkspaceSlug();const panelContent = useSyncExternalStore(subscribeNavPanel,diff --git a/src/features/User/UserPanel/useMenu.tsx b/src/features/User/UserPanel/useMenu.tsxindex d00b452d07b..897ba8180fb 100644--- a/src/features/User/UserPanel/useMenu.tsx+++ b/src/features/User/UserPanel/useMenu.tsx@@ -6,7 +6,6 @@ import { BrainCircuit, Cloudy, Download, HardDriveDownload, LogOut, Settings2 }import type { PropsWithChildren } from 'react';import { memo } from 'react';import { useTranslation } from 'react-i18next';-import { Link } from 'react-router';import useBusinessMenuItems from '@/business/client/features/User/useBusinessMenuItems';import { useHasActiveWorkspace } from '@/business/client/hooks/useHasActiveWorkspace';@@ -80,7 +79,11 @@ export const useMenu = () => {{icon: <Icon icon={BrainCircuit} />,key: 'memory',- label: <Link to="/memory">{t('tab.memory')}</Link>,+ label: (+ <WorkspaceLink escape to="/memory">+ {t('tab.memory')}+ </WorkspaceLink>+ ),},]: []),diff --git a/src/features/Workspace/WorkspaceLink.desktop.test.ts b/src/features/Workspace/WorkspaceLink.desktop.test.tsnew file mode 100644index 00000000000..7809b921d2d--- /dev/null+++ b/src/features/Workspace/WorkspaceLink.desktop.test.ts@@ -0,0 +1,91 @@+import { cleanup, fireEvent, render, screen } from '@testing-library/react';+import React from 'react';+import { createMemoryRouter } from 'react-router';+import { afterEach, describe, expect, it, vi } from 'vitest';++import { TabIdContext } from '@/features/Electron/TabHost/TabIdContext';+import {+ getOrCreateTabRouter,+ resetTabRouterManager,+} from '@/features/Electron/TabHost/tabRouterManager';++const mocks = vi.hoisted(() => ({+ storeState: { activeTabId: 'active' as string | null, addNewTab: vi.fn() },+}));++vi.mock('@/store/electron', () => ({+ useElectronStore: Object.assign(+ (selector: (s: unknown) => unknown) => selector(mocks.storeState),+ { getState: () => mocks.storeState },+ ),+}));++vi.mock('./useWorkspaceAwareNavigate', () => import('./useWorkspaceAwareNavigate.desktop'));+vi.mock(+ '@/features/Electron/navigation/appNavigate',+ () => import('@/features/Electron/navigation/appNavigate.desktop'),+);++const { default: WorkspaceLink } = await import('./WorkspaceLink.desktop');++const makeRouter = (url: string) =>+ createMemoryRouter([{ element: null, path: '*' }], { initialEntries: [url] });++const seedRouter = (tabId: string) => {+ const router = getOrCreateTabRouter(tabId, '/', makeRouter);+ return vi.spyOn(router, 'navigate').mockResolvedValue(undefined);+};++afterEach(() => {+ cleanup();+ resetTabRouterManager();+ vi.restoreAllMocks();+ mocks.storeState.activeTabId = 'active';+});++describe('WorkspaceLink (desktop)', () => {+ it('navigates the active tab router on plain click in shell context', () => {+ const activeNavigate = seedRouter('active');++ render(React.createElement(WorkspaceLink, { to: '/settings' }, 'settings'));++ const link = screen.getByText('settings');+ expect(link).toHaveAttribute('href', '/settings');++ fireEvent.click(link);++ expect(activeNavigate).toHaveBeenCalledWith('/settings', {});+ });++ it('navigates the originating tab router when TabIdContext is present, not the active tab', () => {+ const activeNavigate = seedRouter('active');+ const originNavigate = seedRouter('origin');++ render(+ React.createElement(+ TabIdContext,+ { value: 'origin' },+ React.createElement(WorkspaceLink, { to: '/agent/x/tasks' }, 'tasks'),+ ),+ );++ fireEvent.click(screen.getByText('tasks'));++ expect(originNavigate).toHaveBeenCalledWith('/agent/x/tasks', {});+ expect(activeNavigate).not.toHaveBeenCalled();+ });++ it('does not touch any router on modifier click', () => {+ const activeNavigate = seedRouter('active');++ render(React.createElement(WorkspaceLink, { to: '/settings' }, 'settings'));++ const link = screen.getByText('settings');+ fireEvent.click(link, { metaKey: true });+ fireEvent.click(link, { ctrlKey: true });+ fireEvent.click(link, { shiftKey: true });+ fireEvent.click(link, { button: 1 });++ expect(activeNavigate).not.toHaveBeenCalled();+ });+});diff --git a/src/features/Workspace/WorkspaceLink.desktop.tsx b/src/features/Workspace/WorkspaceLink.desktop.tsxnew file mode 100644index 00000000000..eaa78dca938--- /dev/null+++ b/src/features/Workspace/WorkspaceLink.desktop.tsx@@ -0,0 +1,39 @@+'use client';++import { type AnchorHTMLAttributes, type MouseEvent, type Ref } from 'react';++import { useActiveWorkspaceSlug } from '@/business/client/hooks/useActiveWorkspaceSlug';++import { useWorkspaceAwareNavigate } from './useWorkspaceAwareNavigate';+import { buildWorkspaceAwarePath } from './workspaceAwarePath';+import type { WorkspaceLinkProps } from './WorkspaceLink';++const WorkspaceLink = ({ ref, to, escape, onClick, target, ...rest }: WorkspaceLinkProps) => {+ const activeSlug = useActiveWorkspaceSlug();+ const navigate = useWorkspaceAwareNavigate();+ const resolved = buildWorkspaceAwarePath(to, activeSlug, { escape });++ const handleClick = (event: MouseEvent<HTMLAnchorElement>) => {+ onClick?.(event);+ if (event.defaultPrevented) return;+ if (target && target !== '_self') return;+ if (event.metaKey || event.ctrlKey || event.shiftKey || event.altKey || event.button !== 0)+ return;+ event.preventDefault();+ navigate(resolved, { escape: true });+ };++ return (+ <a+ href={resolved}+ ref={ref as Ref<HTMLAnchorElement>}+ target={target}+ onClick={handleClick}+ {...(rest as AnchorHTMLAttributes<HTMLAnchorElement>)}+ />+ );+};++WorkspaceLink.displayName = 'WorkspaceLink';++export default WorkspaceLink;diff --git a/src/features/Workspace/useWorkspaceAwareNavigate.desktop.test.ts b/src/features/Workspace/useWorkspaceAwareNavigate.desktop.test.tsnew file mode 100644index 00000000000..509bcbabee6--- /dev/null+++ b/src/features/Workspace/useWorkspaceAwareNavigate.desktop.test.ts@@ -0,0 +1,126 @@+import { renderHook } from '@testing-library/react';+import { createElement, type ReactNode } from 'react';+import { createMemoryRouter } from 'react-router';+import { afterEach, describe, expect, it, vi } from 'vitest';++import * as slugModule from '@/business/client/hooks/useActiveWorkspaceSlug';+import {+ getOrCreateTabRouter,+ resetTabRouterManager,+ TabIdContext,+} from '@/features/Electron/TabHost';++const mocks = vi.hoisted(() => ({+ storeState: { activeTabId: 'tA' as string | null, addNewTab: vi.fn() },+}));++vi.mock('@/store/electron', () => ({+ useElectronStore: Object.assign(+ (selector: (s: unknown) => unknown) => selector(mocks.storeState),+ { getState: () => mocks.storeState },+ ),+}));++// Mirror platformResolve: the electron build rewrites the base appNavigate+// import inside the desktop twin to the .desktop implementation.+vi.mock('@/features/Electron/navigation/appNavigate', () =>+ vi.importActual('@/features/Electron/navigation/appNavigate.desktop'),+);++const { useWorkspaceAwareNavigate } = await import('./useWorkspaceAwareNavigate.desktop');++const makeRouter = (url: string) =>+ createMemoryRouter([{ element: null, path: '*' }], { initialEntries: [url] });++const seedRouter = (tabId: string) => {+ const router = getOrCreateTabRouter(tabId, '/', makeRouter);+ return vi.spyOn(router, 'navigate').mockResolvedValue(undefined);+};++const renderNavigate = (tabId?: string) =>+ renderHook(() => useWorkspaceAwareNavigate(), {+ wrapper: tabId+ ? ({ children }: { children: ReactNode }) =>+ createElement(TabIdContext, { value: tabId }, children)+ : undefined,+ }).result.current;++afterEach(() => {+ resetTabRouterManager();+ vi.restoreAllMocks();+ mocks.storeState.activeTabId = 'tA';+ mocks.storeState.addNewTab = vi.fn();+});++describe('useWorkspaceAwareNavigate (desktop)', () => {+ it('shell (no tab context): navigates the active tab with the workspace-resolved url', () => {+ vi.spyOn(slugModule, 'getActiveWorkspaceSlug').mockReturnValue('acme');+ const navigateA = seedRouter('tA');++ renderNavigate()('/agent/x');++ expect(navigateA).toHaveBeenCalledWith('/acme/agent/x', {});+ });++ it('content: navigates the originating tab with the workspace-resolved url', () => {+ vi.spyOn(slugModule, 'getActiveWorkspaceSlug').mockReturnValue('acme');+ const navigateA = seedRouter('tA');++ renderNavigate('tA')('/agent/x');++ expect(navigateA).toHaveBeenCalledWith('/acme/agent/x', {});+ });++ it('content: escape skips workspace resolution', () => {+ vi.spyOn(slugModule, 'getActiveWorkspaceSlug').mockReturnValue('acme');+ const navigateA = seedRouter('tA');++ renderNavigate('tA')('/agent/x', { escape: true });++ expect(navigateA).toHaveBeenCalledWith('/agent/x', {});+ });++ it('content: a captured navigate still targets the originating tab after the active tab switches', () => {+ const navigateA = seedRouter('tA');+ const navigateB = seedRouter('tB');+ const navigate = renderNavigate('tA');++ mocks.storeState.activeTabId = 'tB';+ navigate('/agent/x');++ expect(navigateA).toHaveBeenCalledWith('/agent/x', {});+ expect(navigateB).not.toHaveBeenCalled();+ });++ it('content: object form targets the originating tab, not the active one', () => {+ const navigateA = seedRouter('tA');+ const navigateB = seedRouter('tB');+ mocks.storeState.activeTabId = 'tB';++ renderNavigate('tA')({ pathname: '/settings' }, { replace: true });++ expect(navigateA).toHaveBeenCalledWith({ pathname: '/settings' }, { replace: true });+ expect(navigateB).not.toHaveBeenCalled();+ });++ it('content: delta form targets the originating tab, not the active one', () => {+ const navigateA = seedRouter('tA');+ const navigateB = seedRouter('tB');+ mocks.storeState.activeTabId = 'tB';++ renderNavigate('tA')(-1);++ expect(navigateA).toHaveBeenCalledWith(-1);+ expect(navigateB).not.toHaveBeenCalled();+ });++ it('content: drops the navigation when the originating tab router was disposed', () => {+ const navigateA = seedRouter('tA');+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => {});++ expect(() => renderNavigate('tGone')('/agent/x')).not.toThrow();++ expect(warn).toHaveBeenCalled();+ expect(navigateA).not.toHaveBeenCalled();+ });+});diff --git a/src/features/Workspace/useWorkspaceAwareNavigate.desktop.ts b/src/features/Workspace/useWorkspaceAwareNavigate.desktop.tsnew file mode 100644index 00000000000..b369d7547f9--- /dev/null+++ b/src/features/Workspace/useWorkspaceAwareNavigate.desktop.ts@@ -0,0 +1,47 @@+'use client';++import { use, useCallback } from 'react';+import { type NavigateOptions, type To } from 'react-router';++import { getActiveWorkspaceSlug } from '@/business/client/hooks/useActiveWorkspaceSlug';+import {+ navigateActiveTab,+ navigateActiveTabByDelta,+ navigateTab,+ navigateTabByDelta,+} from '@/features/Electron/navigation/activeTabNavigate';+import { appNavigate } from '@/features/Electron/navigation/appNavigate';+import { TabIdContext } from '@/features/Electron/TabHost/TabIdContext';++import type { WorkspaceAwareNavigateFunction } from './useWorkspaceAwareNavigate';+import { buildWorkspaceAwarePath, type WorkspaceAwareNavigateOptions } from './workspaceAwarePath';++export type { WorkspaceAwareNavigateOptions } from './workspaceAwarePath';++// The desktop shell (sidebars, titlebar, cmdk) renders outside the per-tab+// routers, so its `useNavigate` targets the frozen root router β route it into+// the ACTIVE tab's memory router. Content inside a tab tree captures its+// ORIGINATING tab id instead: an async callback (create β redirect) must+// navigate the tab it started in, not whichever tab is active when it fires.+export const useWorkspaceAwareNavigate = (): WorkspaceAwareNavigateFunction => {+ const tabId = use(TabIdContext);++ return useCallback(+ ((to: To | number, options?: WorkspaceAwareNavigateOptions) => {+ if (typeof to === 'number') {+ return tabId ? navigateTabByDelta(tabId, to) : navigateActiveTabByDelta(to);+ }+ if (typeof to !== 'string') {+ return tabId+ ? navigateTab(tabId, to, options as NavigateOptions)+ : navigateActiveTab(to, options as NavigateOptions);+ }+ if (!tabId) return appNavigate(to, options);++ const { escape, ...navOptions } = options ?? {};+ const resolved = buildWorkspaceAwarePath(to, getActiveWorkspaceSlug(), { escape });+ return navigateTab(tabId, resolved, navOptions);+ }) as WorkspaceAwareNavigateFunction,+ [tabId],+ );+};diff --git a/src/features/Workspace/useWorkspaceSyncPathname.desktop.ts b/src/features/Workspace/useWorkspaceSyncPathname.desktop.tsnew file mode 100644index 00000000000..425490b714f--- /dev/null+++ b/src/features/Workspace/useWorkspaceSyncPathname.desktop.ts@@ -0,0 +1,23 @@+'use client';++import { selectActiveTabUrl } from '@/features/Electron/shell/activeTabUrl';+import { type ElectronStore, useElectronStore } from '@/store/electron';++const selectActiveTabPathname = (s: ElectronStore): string | null => {+ const url = selectActiveTabUrl(s);+ if (!url) return null;++ const queryIndex = url.search(/[#?]/);+ return queryIndex === -1 ? url : url.slice(0, queryIndex);+};++// The desktop shell (where workspace context mounts) lives outside the per-tab+// memory routers, so its `useLocation` stays frozen at the boot url β+// `useWindowUrlMirror` only calls `replaceState` and deliberately never+// navigates the root router. Follow the active tab instead, falling back to the+// window url for the frame before `useSeedTabsOnBoot` fills the tab list.+export const useWorkspaceSyncPathname = (): string => {+ const activeTabPathname = useElectronStore(selectActiveTabPathname);++ return activeTabPathname ?? window.location.pathname;+};diff --git a/src/features/Workspace/useWorkspaceSyncPathname.ts b/src/features/Workspace/useWorkspaceSyncPathname.tsnew file mode 100644index 00000000000..989b0b83a02--- /dev/null+++ b/src/features/Workspace/useWorkspaceSyncPathname.ts@@ -0,0 +1,8 @@+'use client';++import { useLocation } from 'react-router';++// The pathname workspace context follows. Split out purely so the desktop shell+// can override it (`.desktop.ts`): there, workspace context mounts outside the+// per-tab routers, where this router location never moves.+export const useWorkspaceSyncPathname = (): string => useLocation().pathname;diff --git a/src/features/Workspace/useWorkspaceUrlSync.desktop.test.ts b/src/features/Workspace/useWorkspaceUrlSync.desktop.test.tsnew file mode 100644index 00000000000..ea180f10371--- /dev/null+++ b/src/features/Workspace/useWorkspaceUrlSync.desktop.test.ts@@ -0,0 +1,122 @@+import { act, renderHook } from '@testing-library/react';+import React, { type ReactNode } from 'react';+import { MemoryRouter } from 'react-router';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';++import * as useActiveWorkspaceIdModule from '@/business/client/hooks/useActiveWorkspaceId';+import * as useIsWorkspaceLoadingModule from '@/business/client/hooks/useIsWorkspaceLoading';+import * as useSwitchWorkspaceModule from '@/business/client/hooks/useSwitchWorkspace';+import * as useWorkspacesModule from '@/business/client/hooks/useWorkspaces';+import { useElectronStore } from '@/store/electron';+import { initialState } from '@/store/electron/initialState';++import { useWorkspaceSyncPathname } from './useWorkspaceSyncPathname.desktop';+import { useWorkspaceUrlSync } from './useWorkspaceUrlSync';++vi.mock(+ './useWorkspaceSyncPathname',+ async () => await import('./useWorkspaceSyncPathname.desktop'),+);++const switchWorkspace = vi.fn();+const switchToPersonal = vi.fn();++// The shell router is frozen at the boot url; every assertion below relies on+// the hook ignoring it in favour of the active tab.+const wrapper = ({ children }: { children: ReactNode }) =>+ React.createElement(MemoryRouter, { initialEntries: ['/'] }, children);++const setTabs = (tabs: { id: string; url: string }[], activeTabId: null | string) => {+ useElectronStore.setState({+ ...initialState,+ activeTabId,+ tabs: tabs.map((tab, index) => ({ ...tab, lastVisited: index })),+ });+};++beforeEach(() => {+ vi.spyOn(useWorkspacesModule, 'useWorkspaces').mockReturnValue([+ { id: 'ws-1', slug: 'acme' },+ ] as any);+ vi.spyOn(useIsWorkspaceLoadingModule, 'useIsWorkspaceLoading').mockReturnValue(false);+ vi.spyOn(useActiveWorkspaceIdModule, 'useActiveWorkspaceId').mockReturnValue(null);+ vi.spyOn(useSwitchWorkspaceModule, 'useSilentSwitchWorkspace').mockReturnValue({+ switchToPersonal,+ switchWorkspace,+ } as any);+});++afterEach(() => {+ vi.restoreAllMocks();+ switchWorkspace.mockClear();+ switchToPersonal.mockClear();+ window.history.replaceState(null, '', '/');+});++describe('useWorkspaceSyncPathname (desktop)', () => {+ it('reads the active tab pathname without its query or anchor', () => {+ setTabs([{ id: 'a', url: '/acme/agent/x?q=1#msg_1' }], 'a');++ const { result } = renderHook(() => useWorkspaceSyncPathname(), { wrapper });++ expect(result.current).toBe('/acme/agent/x');+ });++ it('follows tab switches instead of the frozen shell router', () => {+ setTabs(+ [+ { id: 'a', url: '/acme/agent/x' },+ { id: 'b', url: '/agent/y' },+ ],+ 'a',+ );++ const { result } = renderHook(() => useWorkspaceSyncPathname(), { wrapper });+ expect(result.current).toBe('/acme/agent/x');++ act(() => {+ useElectronStore.setState({ activeTabId: 'b' });+ });++ expect(result.current).toBe('/agent/y');+ });++ it('falls back to the window url before the tab list is seeded', () => {+ window.history.replaceState(null, '', '/acme/agent/boot');+ setTabs([], null);++ const { result } = renderHook(() => useWorkspaceSyncPathname(), { wrapper });++ expect(result.current).toBe('/acme/agent/boot');+ });+});++describe('useWorkspaceUrlSync (desktop)', () => {+ it('activates the workspace of the active tab, not the boot location', () => {+ setTabs([{ id: 'a', url: '/acme/agent/x' }], 'a');++ renderHook(() => useWorkspaceUrlSync(), { wrapper });++ expect(switchWorkspace).toHaveBeenCalledWith('ws-1');+ });++ it('returns to personal context when the user switches to a personal tab', () => {+ vi.spyOn(useActiveWorkspaceIdModule, 'useActiveWorkspaceId').mockReturnValue('ws-1');+ setTabs(+ [+ { id: 'a', url: '/acme/agent/x' },+ { id: 'b', url: '/agent/y' },+ ],+ 'a',+ );++ renderHook(() => useWorkspaceUrlSync(), { wrapper });+ expect(switchToPersonal).not.toHaveBeenCalled();++ act(() => {+ useElectronStore.setState({ activeTabId: 'b' });+ });++ expect(switchToPersonal).toHaveBeenCalled();+ });+});diff --git a/src/features/Workspace/useWorkspaceUrlSync.ts b/src/features/Workspace/useWorkspaceUrlSync.tsindex 7849cdf708d..56a3a698b31 100644--- a/src/features/Workspace/useWorkspaceUrlSync.ts+++ b/src/features/Workspace/useWorkspaceUrlSync.ts@@ -1,13 +1,14 @@'use client';import { useLayoutEffect } from 'react';-import { useLocation } from 'react-router';import { useActiveWorkspaceId } from '@/business/client/hooks/useActiveWorkspaceId';import { useIsWorkspaceLoading } from '@/business/client/hooks/useIsWorkspaceLoading';import { useSilentSwitchWorkspace } from '@/business/client/hooks/useSwitchWorkspace';import { useWorkspaces } from '@/business/client/hooks/useWorkspaces';+import { useWorkspaceSyncPathname } from './useWorkspaceSyncPathname';+/*** Top-level route segments that share the namespace with `:workspaceSlug`.* Anything starting with one of these is NOT a workspace slug β even if the@@ -69,7 +70,7 @@ export const isWorkspaceSlugCandidatePath = (pathname: string): boolean => {* `WorkspaceSlugBoundary` can render its 404*/export const useWorkspaceUrlSync = (): void => {- const { pathname } = useLocation();+ const pathname = useWorkspaceSyncPathname();const workspaces = useWorkspaces();const activeId = useActiveWorkspaceId();const isLoading = useIsWorkspaceLoading();diff --git a/src/features/WorkspaceSetting/SideBar/Body.tsx b/src/features/WorkspaceSetting/SideBar/Body.tsxindex d061e11d67b..82aa09b0660 100644--- a/src/features/WorkspaceSetting/SideBar/Body.tsx+++ b/src/features/WorkspaceSetting/SideBar/Body.tsx@@ -2,11 +2,12 @@import { Accordion, AccordionItem, Flexbox, Text } from '@lobehub/ui';import { memo, useMemo } from 'react';-import { Link, useLocation } from 'react-router';+import { Link } from 'react-router';import { useActiveWorkspaceSlug } from '@/business/client/hooks/useActiveWorkspaceSlug';import NavItem from '@/features/NavPanel/components/NavItem';import { useWorkspaceAwareNavigate } from '@/features/Workspace/useWorkspaceAwareNavigate';+import { useActiveLocation } from '@/hooks/useActiveLocation';import { DEFAULT_WORKSPACE_SETTINGS_TAB, WorkspaceSettingsTabs } from '@/types/workspaceSettings';import { isModifierClick } from '@/utils/navigation';@@ -14,7 +15,7 @@ import { useWorkspaceSettingCategory, WorkspaceSettingsGroupKey } from '../hooksconst Body = memo(() => {const navigate = useWorkspaceAwareNavigate();- const location = useLocation();+ const location = useActiveLocation();const slug = useActiveWorkspaceSlug();const groups = useWorkspaceSettingCategory();diff --git a/src/hooks/useActiveLocation.desktop.test.ts b/src/hooks/useActiveLocation.desktop.test.tsnew file mode 100644index 00000000000..657fa41f750--- /dev/null+++ b/src/hooks/useActiveLocation.desktop.test.ts@@ -0,0 +1,50 @@+import { act, renderHook } from '@testing-library/react';+import { afterEach, describe, expect, it } from 'vitest';++import { useElectronStore } from '@/store/electron';++import { useActiveLocation } from './useActiveLocation.desktop';++const tab = (id: string, url: string) => ({ id, lastVisited: 0, url });++afterEach(() => {+ useElectronStore.setState({ activeTabId: null, tabs: [] });+});++describe('useActiveLocation (desktop)', () => {+ it('derives pathname/search from the active tab url and drops any hash', () => {+ useElectronStore.setState({+ activeTabId: 't1',+ tabs: [tab('t1', '/agent/a?topic=x#frag'), tab('t2', '/settings')],+ });++ const { result } = renderHook(() => useActiveLocation());++ expect(result.current.pathname).toBe('/agent/a');+ expect(result.current.search).toBe('?topic=x');+ expect(result.current.hash).toBe('');+ });++ it('updates when the active tab switches', () => {+ useElectronStore.setState({+ activeTabId: 't1',+ tabs: [tab('t1', '/agent/a'), tab('t2', '/settings/general')],+ });++ const { result } = renderHook(() => useActiveLocation());+ expect(result.current.pathname).toBe('/agent/a');++ act(() => useElectronStore.setState({ activeTabId: 't2' }));++ expect(result.current.pathname).toBe('/settings/general');+ });++ it('falls back to "/" when there is no active tab', () => {+ useElectronStore.setState({ activeTabId: null, tabs: [] });++ const { result } = renderHook(() => useActiveLocation());++ expect(result.current.pathname).toBe('/');+ expect(result.current.search).toBe('');+ });+});diff --git a/src/hooks/useActiveLocation.desktop.ts b/src/hooks/useActiveLocation.desktop.tsnew file mode 100644index 00000000000..0247c795648--- /dev/null+++ b/src/hooks/useActiveLocation.desktop.ts@@ -0,0 +1,23 @@+import { useMemo } from 'react';+import { type Location } from 'react-router';++import { selectActiveTabUrl } from '@/features/Electron/shell/activeTabUrl';+import { useElectronStore } from '@/store/electron';++// Tab urls only ever carry pathname+search: `TabLocationReporter` and the+// eviction snapshot both persist `pathname + search`, never a hash. Drop any+// stray hash so this mirror stays aligned with what the store holds.+const parseLocation = (url: string): Location => {+ const withoutHash = url.split('#')[0];++ const searchIndex = withoutHash.indexOf('?');+ const search = searchIndex === -1 ? '' : withoutHash.slice(searchIndex);+ const pathname = searchIndex === -1 ? withoutHash : withoutHash.slice(0, searchIndex);++ return { hash: '', key: 'default', pathname: pathname || '/', search, state: null };+};++export const useActiveLocation = (): Location => {+ const url = useElectronStore(selectActiveTabUrl) ?? '/';+ return useMemo(() => parseLocation(url), [url]);+};diff --git a/src/hooks/useActiveLocation.ts b/src/hooks/useActiveLocation.tsnew file mode 100644index 00000000000..b4f9622f9c6--- /dev/null+++ b/src/hooks/useActiveLocation.ts@@ -0,0 +1,3 @@+import { type Location, useLocation } from 'react-router';++export const useActiveLocation = (): Location => useLocation();diff --git a/src/hooks/useActiveRouteParams.desktop.test.ts b/src/hooks/useActiveRouteParams.desktop.test.tsnew file mode 100644index 00000000000..c7163657c9d--- /dev/null+++ b/src/hooks/useActiveRouteParams.desktop.test.ts@@ -0,0 +1,82 @@+import { act, renderHook } from '@testing-library/react';+import type * as ReactRouter from 'react-router';+import { matchRoutes } from 'react-router';+import { afterEach, describe, expect, it, vi } from 'vitest';++import { useElectronStore } from '@/store/electron';++import { useActiveRouteParams } from './useActiveRouteParams.desktop';++vi.mock('react-router', async (importOriginal) => {+ const actual = await importOriginal<typeof ReactRouter>();+ return { ...actual, matchRoutes: vi.fn(actual.matchRoutes) };+});++const matchRoutesSpy = vi.mocked(matchRoutes);+const tab = (id: string, url: string) => ({ id, lastVisited: 0, url });++afterEach(() => {+ useElectronStore.setState({ activeTabId: null, tabs: [] });+ matchRoutesSpy.mockClear();+});++describe('useActiveRouteParams (desktop)', () => {+ it('matches the active tab url once no matter how many consumers read it', () => {+ useElectronStore.setState({+ activeTabId: 't1',+ tabs: [tab('t1', '/agent/agt_many_consumers')],+ });+ matchRoutesSpy.mockClear();++ const consumers = Array.from({ length: 5 }, () => renderHook(() => useActiveRouteParams()));++ expect(matchRoutesSpy).toHaveBeenCalledTimes(1);+ expect(consumers.every((c) => c.result.current === consumers[0].result.current)).toBe(true);+ });++ it('matches once more when the active tab url changes, not once per consumer', () => {+ useElectronStore.setState({+ activeTabId: 't1',+ tabs: [tab('t1', '/agent/agt_before_switch')],+ });+ const consumers = Array.from({ length: 4 }, () => renderHook(() => useActiveRouteParams()));+ matchRoutesSpy.mockClear();++ act(() => {+ useElectronStore.setState({ tabs: [tab('t1', '/agent/agt_after_switch')] });+ });++ expect(matchRoutesSpy).toHaveBeenCalledTimes(1);+ expect(consumers.every((c) => c.result.current === consumers[0].result.current)).toBe(true);+ });++ it('resolves the params of the active tab url', () => {+ useElectronStore.setState({+ activeTabId: 't1',+ tabs: [tab('t1', '/agent/agt_params_case')],+ });++ const { result } = renderHook(() => useActiveRouteParams<{ aid?: string }>());++ expect(result.current.aid).toBe('agt_params_case');+ });++ it('re-resolves after switching back to a previously visited url', () => {+ useElectronStore.setState({+ activeTabId: 't1',+ tabs: [tab('t1', '/agent/agt_round_trip_a')],+ });+ const { result } = renderHook(() => useActiveRouteParams<{ aid?: string }>());+ expect(result.current.aid).toBe('agt_round_trip_a');++ act(() => {+ useElectronStore.setState({ tabs: [tab('t1', '/agent/agt_round_trip_b')] });+ });+ expect(result.current.aid).toBe('agt_round_trip_b');++ act(() => {+ useElectronStore.setState({ tabs: [tab('t1', '/agent/agt_round_trip_a')] });+ });+ expect(result.current.aid).toBe('agt_round_trip_a');+ });+});diff --git a/src/hooks/useActiveRouteParams.desktop.ts b/src/hooks/useActiveRouteParams.desktop.tsnew file mode 100644index 00000000000..26beb730218--- /dev/null+++ b/src/hooks/useActiveRouteParams.desktop.ts@@ -0,0 +1,34 @@+import { useMemo } from 'react';+import { matchRoutes } from 'react-router';++import { selectActiveTabUrl } from '@/features/Electron/shell/activeTabUrl';+import { mainAreaMetaRoutes } from '@/spa/router/desktopRouter.config';+import { useElectronStore } from '@/store/electron';++// Every consumer resolves the same active-tab url against the same module-level+// route tree, and the public `matchRoutes` takes no precomputed branches β it+// re-flattens and re-compiles the whole tree on each call. Caching the last url+// keeps that at one match per navigation instead of one per consumer, which+// otherwise grows with the sidebar's item count.+let cachedUrl: string | null = null;+let cachedParams: Record<string, string | undefined> = {};++const resolveActiveRouteParams = (url: string) => {+ if (url !== cachedUrl) {+ const matches = matchRoutes(mainAreaMetaRoutes, url) ?? [];+ cachedUrl = url;+ cachedParams = matches.at(-1)?.params ?? {};+ }++ return cachedParams;+};++// Sidebar subtrees are portal'd into the shell (frozen root router), so raw+// `useParams` there resolves the boot url. Derive params from the active tab's+// url against the same meta route tree the tab routers are built from.+export const useActiveRouteParams = <+ T extends Record<string, string | undefined> = Record<string, string | undefined>,+>(): Readonly<T> => {+ const url = useElectronStore(selectActiveTabUrl) ?? '/';+ return useMemo(() => resolveActiveRouteParams(url) as T, [url]);+};diff --git a/src/hooks/useActiveRouteParams.ts b/src/hooks/useActiveRouteParams.tsnew file mode 100644index 00000000000..d5fe763f2ec--- /dev/null+++ b/src/hooks/useActiveRouteParams.ts@@ -0,0 +1,5 @@+import { useParams } from 'react-router';++export const useActiveRouteParams = <+ T extends Record<string, string | undefined> = Record<string, string | undefined>,+>() => useParams<T>();diff --git a/src/hooks/useActiveTabKey.ts b/src/hooks/useActiveTabKey.tsindex 807e05cbd3f..0d804c2b515 100644--- a/src/hooks/useActiveTabKey.ts+++ b/src/hooks/useActiveTabKey.ts@@ -1,3 +1,4 @@+import { useActiveLocation } from '@/hooks/useActiveLocation';import { usePathname, useSearchParams } from '@/libs/router/navigation';import { ProfileTabs, SettingsTabs, SidebarTabKey } from '@/store/global/initialState';@@ -6,7 +7,7 @@ import { ProfileTabs, SettingsTabs, SidebarTabKey } from '@/store/global/initial* React Router version for SPA*/export const useActiveTabKey = () => {- const pathname = usePathname();+ const { pathname } = useActiveLocation();return (pathname.split('/').find(Boolean)! as SidebarTabKey) || SidebarTabKey.Home;};diff --git a/src/hooks/useHotkeys/desktopTabScope.ts b/src/hooks/useHotkeys/desktopTabScope.tsindex 9b458974910..922f89b7aa0 100644--- a/src/hooks/useHotkeys/desktopTabScope.ts+++ b/src/hooks/useHotkeys/desktopTabScope.ts@@ -3,7 +3,6 @@import { useCallback } from 'react';import { useHotkeys } from 'react-hotkeys-hook';-import { useWorkspaceAwareNavigate } from '@/features/Workspace/useWorkspaceAwareNavigate';import { useElectronStore } from '@/store/electron';/**@@ -15,19 +14,13 @@ import { useElectronStore } from '@/store/electron';* (e.g. TabBar) β no `isDesktop` guard needed.*/export const useRegisterDesktopTabHotkeys = () => {- const navigate = useWorkspaceAwareNavigate();+ const switchToTabByIndex = useCallback((index: number) => {+ const { tabs, activateTab } = useElectronStore.getState();+ if (index < 0 || index >= tabs.length) return;- const switchToTabByIndex = useCallback(- (index: number) => {- const { tabs, activateTab } = useElectronStore.getState();- if (index < 0 || index >= tabs.length) return;-- const target = tabs[index];- activateTab(target.id);- navigate(target.url);- },- [navigate],- );+ const target = tabs[index];+ activateTab(target.id);+ }, []);// Mod+1 through Mod+9useHotkeys(@@ -58,7 +51,6 @@ export const useRegisterDesktopTabHotkeys = () => {const target = tabs[nextIndex];activateTab(target.id);- navigate(target.url);},{enableOnFormTags: true,@@ -79,7 +71,6 @@ export const useRegisterDesktopTabHotkeys = () => {const target = tabs[prevIndex];activateTab(target.id);- navigate(target.url);},{enableOnFormTags: true,diff --git a/src/routes/(main)/_layout/index.desktop.tsx b/src/routes/(main)/_layout/index.desktop.tsxnew file mode 100644index 00000000000..c37a6f96e6c--- /dev/null+++ b/src/routes/(main)/_layout/index.desktop.tsx@@ -0,0 +1,98 @@+'use client';++import { HotkeyScopeEnum } from '@lobechat/const/hotkeys';+import { TITLE_BAR_HEIGHT } from '@lobechat/desktop-bridge';+import { Flexbox } from '@lobehub/ui';+import { cx } from 'antd-style';+import { type CSSProperties, type FC } from 'react';+import { Suspense } from 'react';+import { HotkeysProvider } from 'react-hotkeys-hook';++import WorkspaceContextSlot from '@/business/client/WorkspaceContextSlot';+import DesktopBrowserGatewayBridge from '@/features/DesktopBrowserGatewayBridge';+import DesktopFileMenuBridge from '@/features/DesktopFileMenuBridge';+import DesktopNavigationBridge from '@/features/DesktopNavigationBridge';+import ActiveConversationBridge from '@/features/Electron/ActiveConversationBridge';+import AuthRequiredModal from '@/features/Electron/AuthRequiredModal';+import OverlayCaptureUploader from '@/features/Electron/ScreenCapture/OverlayCaptureUploader';+import OverlayMessageDispatcher from '@/features/Electron/ScreenCapture/OverlayMessageDispatcher';+import OverlaySnapshotPublisher from '@/features/Electron/ScreenCapture/OverlaySnapshotPublisher';+import { useDesktopDocumentTitle, useWindowUrlMirror } from '@/features/Electron/shell';+import ZoomHUD from '@/features/Electron/system/ZoomHUD';+import { TabHost, useSeedTabsOnBoot } from '@/features/Electron/TabHost';+import TabCacheBridges from '@/features/Electron/titlebar/TabBar/TabCacheBridges';+import TitleBar from '@/features/Electron/titlebar/TitleBar';+import HotkeyHelperPanel from '@/features/HotkeyHelperPanel';+import NavPanel from '@/features/NavPanel';+import { usePlatform } from '@/hooks/usePlatform';+import CmdkLazy from '@/layout/GlobalProvider/CmdkLazy';+import dynamic from '@/libs/next/dynamic';+import { DndContextWrapper } from '@/routes/(main)/resource/features/DndContextWrapper';+import { featureFlagsSelectors, useServerConfigStore } from '@/store/serverConfig';++import DesktopAutoOidcOnFirstOpen from './DesktopAutoOidcOnFirstOpen';+import DesktopLayoutContainer from './DesktopLayoutContainer';+import RegisterHotkeys from './RegisterHotkeys';+import { styles } from './style';++const CloudBanner = dynamic(() => import('@/features/AlertBanner/CloudBanner'));+const GlobalApprovalNotification = dynamic(() => import('@/features/GlobalApprovalNotification'));++const tabHostContainer: CSSProperties = { position: 'relative' };++const Layout: FC = () => {+ const { isPWA } = usePlatform();+ const { showCloudPromotion } = useServerConfigStore(featureFlagsSelectors);++ useSeedTabsOnBoot();+ useWindowUrlMirror();+ useDesktopDocumentTitle();++ return (+ <HotkeysProvider initiallyActiveScopes={[HotkeyScopeEnum.Global]}>+ <WorkspaceContextSlot>+ <ActiveConversationBridge />+ <TabCacheBridges />+ <Suspense fallback={null}>+ <DesktopAutoOidcOnFirstOpen />+ <DesktopNavigationBridge />+ <DesktopFileMenuBridge />+ <DesktopBrowserGatewayBridge />+ <OverlaySnapshotPublisher />+ <OverlayCaptureUploader />+ <OverlayMessageDispatcher />+ {showCloudPromotion && <CloudBanner />}+ </Suspense>+ <AuthRequiredModal />+ <ZoomHUD />++ <Suspense fallback={null}>+ <TitleBar />+ </Suspense>+ <DndContextWrapper>+ <Flexbox+ horizontal+ className={cx(isPWA ? styles.mainContainerPWA : styles.mainContainer)}+ height={`calc(100% - ${TITLE_BAR_HEIGHT}px)`}+ width={'100%'}+ >+ <NavPanel />+ <DesktopLayoutContainer>+ <Flexbox height={'100%'} style={tabHostContainer} width={'100%'}>+ <TabHost />+ </Flexbox>+ </DesktopLayoutContainer>+ </Flexbox>+ </DndContextWrapper>+ <Suspense fallback={null}>+ <HotkeyHelperPanel />+ <RegisterHotkeys />+ <CmdkLazy />+ <GlobalApprovalNotification />+ </Suspense>+ </WorkspaceContextSlot>+ </HotkeysProvider>+ );+};++export default Layout;diff --git a/src/routes/(main)/agent/_layout/AgentIdSync.tsx b/src/routes/(main)/agent/_layout/AgentIdSync.tsxindex b85f4ca3560..c0e932d8339 100644--- a/src/routes/(main)/agent/_layout/AgentIdSync.tsx+++ b/src/routes/(main)/agent/_layout/AgentIdSync.tsx@@ -1,94 +1,32 @@-import { BUILTIN_AGENT_SLUGS } from '@lobechat/builtin-agents';-import { usePrevious } from 'ahooks';-import { useEffect, useLayoutEffect, useMemo, useRef } from 'react';+import { useEffect } from 'react';import { useLocation, useParams, useSearchParams } from 'react-router';+import { useResolvedAgentRouteId } from '@/features/AgentRoute/useResolvedAgentRouteId';import { useWorkspaceAwareNavigate } from '@/features/Workspace/useWorkspaceAwareNavigate';-import { useAgentStore } from '@/store/agent';-import { builtinAgentSelectors } from '@/store/agent/selectors';-import { useChatStore } from '@/store/chat';-const BUILTIN_SLUG_SET = new Set<string>(Object.values(BUILTIN_AGENT_SLUGS));+import { useAgentIdStoreSync } from './useAgentIdStoreSync';const AgentIdSync = () => {const params = useParams<{ aid?: string; topicId?: string }>();const [searchParams] = useSearchParams();- const searchParamsRef = useRef(searchParams);- searchParamsRef.current = searchParams;const navigate = useWorkspaceAwareNavigate();const location = useLocation();-- // Resolve builtin agent slug to real agent ID- const isBuiltinSlug = !!params.aid && BUILTIN_SLUG_SET.has(params.aid);- const resolvedId = useAgentStore(- builtinAgentSelectors.getBuiltinAgentId(isBuiltinSlug ? params.aid! : ''),- );+ const { agentId: activeId, isBuiltinSlug, resolvedAgentId } = useResolvedAgentRouteId(params.aid);// Redirect slug URL to real agent ID URL, preserving child path and query stringuseEffect(() => {- if (isBuiltinSlug && resolvedId) {+ if (isBuiltinSlug && resolvedAgentId) {const suffix = location.pathname.replace(`/agent/${params.aid}`, '');const qs = searchParams.toString();- navigate(`/agent/${resolvedId}${suffix}${qs ? `?${qs}` : ''}`, { replace: true });- }- }, [isBuiltinSlug, resolvedId, navigate, searchParams, location.pathname, params.aid]);-- // Use resolved ID when available, fall back to URL param (e.g. anonymous mode)- const activeId = useMemo(- () => (isBuiltinSlug ? resolvedId || params.aid : params.aid),- [isBuiltinSlug, resolvedId, params.aid],- );-- const prevAgentId = usePrevious(activeId);-- // Sync activeAgentId before paint (layout effect, not passive effect) so a- // tab/route switch back to an agent with cached `agentMap` data renders the- // real UI on the first frame instead of flashing a skeleton.- useLayoutEffect(() => {- if (!activeId) return;-- if (useAgentStore.getState().activeAgentId !== activeId)- useAgentStore.setState({ activeAgentId: activeId }, false, 'AgentIdSync/syncAgentId');-- if (useChatStore.getState().activeAgentId !== activeId)- useChatStore.setState({ activeAgentId: activeId }, false, 'AgentIdSync/syncAgentId');- }, [activeId]);-- // Reset activeTopicId when switching to a different agent- // This prevents messages from being saved to the wrong topic bucket- useEffect(() => {- // Only reset topic when switching between agents (not on initial mount)- if (prevAgentId !== undefined && prevAgentId !== activeId) {- useChatStore.getState().clearPortalStack();-- // Preserve topic if the URL already carries one (e.g. tab navigation)- const topicFromUrl = params.topicId ?? searchParamsRef.current.get('topic');-- if (!topicFromUrl) {- useChatStore.getState().switchTopic(null, { skipRefreshMessage: true });- }+ navigate(`/agent/${resolvedAgentId}${suffix}${qs ? `?${qs}` : ''}`, { replace: true });}- // Note: we no longer clear all unread topics on agent visit β the badge counts- // unread topics and is cleared per-topic when the user actually opens each one.- }, [activeId, prevAgentId]);+ }, [isBuiltinSlug, resolvedAgentId, navigate, searchParams, location.pathname, params.aid]);- // Clear activeAgentId when unmounting (leaving chat page).- // Must be a layout-effect cleanup (not a passive `useUnmount`): in a route- // switch both run in one commit, and React runs all layout cleanups of the- // removed tree BEFORE the new tree's layout effects β so the next route's- // backfill above always wins over this clear. A passive cleanup would run- // after it and wipe the freshly synced id.- useLayoutEffect(- () => () => {- useAgentStore.setState({ activeAgentId: undefined }, false, 'AgentIdSync/unmountAgentId');- useChatStore.setState(- { activeAgentId: undefined, activeTopicId: undefined },- false,- 'AgentIdSync/unmountAgentId',- );- },- [],- );+ useAgentIdStoreSync({+ activeId,+ topicFromPath: params.topicId,+ topicFromQuery: searchParams.get('topic'),+ });return null;};diff --git a/src/routes/(main)/agent/_layout/useAgentIdStoreSync.desktop.ts b/src/routes/(main)/agent/_layout/useAgentIdStoreSync.desktop.tsnew file mode 100644index 00000000000..ad2b1e901e5--- /dev/null+++ b/src/routes/(main)/agent/_layout/useAgentIdStoreSync.desktop.ts@@ -0,0 +1,9 @@+interface AgentIdStoreSyncOptions {+ activeId?: string;+ topicFromPath?: string;+ topicFromQuery?: string | null;+}++export const useAgentIdStoreSync = (_options: AgentIdStoreSyncOptions) => {+ void _options;+};diff --git a/src/routes/(main)/agent/_layout/useAgentIdStoreSync.ts b/src/routes/(main)/agent/_layout/useAgentIdStoreSync.tsnew file mode 100644index 00000000000..3130dd473ae--- /dev/null+++ b/src/routes/(main)/agent/_layout/useAgentIdStoreSync.ts@@ -0,0 +1,51 @@+import { usePrevious } from 'ahooks';+import { useEffect, useLayoutEffect } from 'react';++import { useAgentStore } from '@/store/agent';+import { useChatStore } from '@/store/chat';++interface AgentIdStoreSyncOptions {+ activeId?: string;+ topicFromPath?: string;+ topicFromQuery?: string | null;+}++export const useAgentIdStoreSync = ({+ activeId,+ topicFromPath,+ topicFromQuery,+}: AgentIdStoreSyncOptions) => {+ const previousAgentId = usePrevious(activeId);++ useLayoutEffect(() => {+ if (!activeId) return;++ if (useAgentStore.getState().activeAgentId !== activeId) {+ useAgentStore.setState({ activeAgentId: activeId }, false, 'AgentIdSync/syncAgentId');+ }+ if (useChatStore.getState().activeAgentId !== activeId) {+ useChatStore.setState({ activeAgentId: activeId }, false, 'AgentIdSync/syncAgentId');+ }+ }, [activeId]);++ useEffect(() => {+ if (previousAgentId === undefined || previousAgentId === activeId) return;++ useChatStore.getState().clearPortalStack();+ if (!topicFromPath && !topicFromQuery) {+ useChatStore.getState().switchTopic(null, { skipRefreshMessage: true });+ }+ }, [activeId, previousAgentId, topicFromPath, topicFromQuery]);++ useLayoutEffect(+ () => () => {+ useAgentStore.setState({ activeAgentId: undefined }, false, 'AgentIdSync/unmountAgentId');+ useChatStore.setState(+ { activeAgentId: undefined, activeTopicId: undefined },+ false,+ 'AgentIdSync/unmountAgentId',+ );+ },+ [],+ );+};diff --git a/src/routes/(main)/agent/features/Conversation/ChatHydration/index.tsx b/src/routes/(main)/agent/features/Conversation/ChatHydration/index.tsxindex 2e736b530c3..dd49900b7cd 100644--- a/src/routes/(main)/agent/features/Conversation/ChatHydration/index.tsx+++ b/src/routes/(main)/agent/features/Conversation/ChatHydration/index.tsx@@ -1,30 +1,18 @@'use client';-import { AGENT_CHAT_TOPIC_URL, AGENT_CHAT_URL } from '@lobechat/const';-import { memo, useLayoutEffect, useRef } from 'react';-import { useLocation, useParams, useSearchParams } from 'react-router';+import { memo } from 'react';+import { useParams } from 'react-router';import { useClearActiveTopicUnread } from '@/features/Conversation/hooks';import { useTopicCommentDeepLink } from '@/features/TopicComment/useTopicCommentDeepLink';-import { useWorkspaceAwareNavigate } from '@/features/Workspace/useWorkspaceAwareNavigate';-import { useQueryState } from '@/hooks/useQueryParam';import { useChatStore } from '@/store/chat';import { topicSelectors } from '@/store/chat/selectors';-const getSearchSuffix = (searchParams: URLSearchParams) => {- const search = searchParams.toString();-- return search ? `?${search}` : '';-};+import { useChatRouteSync } from './useChatRouteSync';// sync outside state to useChatStoreconst ChatHydration = memo(() => {- const location = useLocation();- const navigate = useWorkspaceAwareNavigate();const params = useParams<{ aid?: string; topicId?: string }>();- const [searchParams] = useSearchParams();-- const [thread, setThread] = useQueryState('thread', { history: 'replace', throttleMs: 500 });const routeTopicId = params.topicId;const activeAgentId = useChatStore((s) => s.activeAgentId);const topicMetadata = useChatStore((s) =>@@ -32,82 +20,10 @@ const ChatHydration = memo(() => {);const useFetchTopicLinkedPullRequest = useChatStore((s) => s.useFetchTopicLinkedPullRequest);- // Route hydration sets activeTopicId directly (below) instead of going through- // switchTopic, so clear any lingering persisted unread once the topic loads.useClearActiveTopicUnread();useFetchTopicLinkedPullRequest(activeAgentId ? routeTopicId : undefined, topicMetadata);useTopicCommentDeepLink(routeTopicId);-- useLayoutEffect(() => {- const target = routeTopicId ?? null;- if (useChatStore.getState().activeTopicId !== target) {- useChatStore.setState({ activeTopicId: target! }, false, 'ChatHydration/syncTopicFromUrl');- }- }, [routeTopicId]);-- useLayoutEffect(() => {- const target = thread ?? null;- if (useChatStore.getState().activeThreadId !== target) {- useChatStore.setState({ activeThreadId: target! }, false, 'ChatHydration/syncThreadFromUrl');- }- }, [thread]);-- const locationRef = useRef(location);- const paramsRef = useRef(params);- const searchParamsRef = useRef(searchParams);-- locationRef.current = location;- paramsRef.current = params;- searchParamsRef.current = searchParams;-- useLayoutEffect(() => {- const unsubscribeTopic = useChatStore.subscribe(- (s) => s.activeTopicId,- (state) => {- const { aid, topicId } = paramsRef.current;-- if (!aid) return;- if (state === topicId) return;-- // Workspace bootstrap clears scoped chat data with `undefined` before- // loading the new scope. On a topic deep link the URL remains the- // source of truth, so restore that routed topic instead of treating the- // reset as an explicit request to open a blank conversation.- // `switchTopic(null)` normalizes to `null`, so intentional topic- // changes still take the normal store-to-URL path below.- if (state === undefined && topicId) {- useChatStore.setState(- { activeTopicId: topicId },- false,- 'ChatHydration/restoreTopicAfterScopedReset',- );- return;- }-- const nextSearchParams = new URLSearchParams(searchParamsRef.current);- nextSearchParams.delete('topic');-- const nextPath = state ? AGENT_CHAT_TOPIC_URL(aid, state) : AGENT_CHAT_URL(aid);- const nextUrl = `${nextPath}${getSearchSuffix(nextSearchParams)}${locationRef.current.hash}`;- const currentUrl = `${locationRef.current.pathname}${locationRef.current.search}${locationRef.current.hash}`;-- if (currentUrl !== nextUrl) {- navigate(nextUrl, { replace: true });- }- },- );- const unsubscribeThread = useChatStore.subscribe(- (s) => s.activeThreadId,- (state) => {- setThread(state || null);- },- );-- return () => {- unsubscribeTopic();- unsubscribeThread();- };- }, [navigate, setThread]);+ useChatRouteSync();return null;});diff --git a/src/routes/(main)/agent/features/Conversation/ChatHydration/useChatRouteSync.desktop.ts b/src/routes/(main)/agent/features/Conversation/ChatHydration/useChatRouteSync.desktop.tsnew file mode 100644index 00000000000..5eba3c9d629--- /dev/null+++ b/src/routes/(main)/agent/features/Conversation/ChatHydration/useChatRouteSync.desktop.ts@@ -0,0 +1 @@+export const useChatRouteSync = () => {};diff --git a/src/routes/(main)/agent/features/Conversation/ChatHydration/useChatRouteSync.ts b/src/routes/(main)/agent/features/Conversation/ChatHydration/useChatRouteSync.tsnew file mode 100644index 00000000000..ef67408e35d--- /dev/null+++ b/src/routes/(main)/agent/features/Conversation/ChatHydration/useChatRouteSync.ts@@ -0,0 +1,84 @@+import { AGENT_CHAT_TOPIC_URL, AGENT_CHAT_URL } from '@lobechat/const';+import { useLayoutEffect, useRef } from 'react';+import { useLocation, useParams, useSearchParams } from 'react-router';++import { useWorkspaceAwareNavigate } from '@/features/Workspace/useWorkspaceAwareNavigate';+import { useQueryState } from '@/hooks/useQueryParam';+import { useChatStore } from '@/store/chat';++const getSearchSuffix = (searchParams: URLSearchParams) => {+ const search = searchParams.toString();++ return search ? `?${search}` : '';+};++export const useChatRouteSync = () => {+ const location = useLocation();+ const navigate = useWorkspaceAwareNavigate();+ const params = useParams<{ aid?: string; topicId?: string }>();+ const [searchParams] = useSearchParams();+ const [thread, setThread] = useQueryState('thread', { history: 'replace', throttleMs: 500 });+ const routeTopicId = params.topicId;++ useLayoutEffect(() => {+ const target = routeTopicId ?? null;+ if (useChatStore.getState().activeTopicId !== target) {+ useChatStore.setState({ activeTopicId: target! }, false, 'ChatHydration/syncTopicFromUrl');+ }+ }, [routeTopicId]);++ useLayoutEffect(() => {+ const target = thread ?? null;+ if (useChatStore.getState().activeThreadId !== target) {+ useChatStore.setState({ activeThreadId: target! }, false, 'ChatHydration/syncThreadFromUrl');+ }+ }, [thread]);++ const locationRef = useRef(location);+ const paramsRef = useRef(params);+ const searchParamsRef = useRef(searchParams);++ locationRef.current = location;+ paramsRef.current = params;+ searchParamsRef.current = searchParams;++ useLayoutEffect(() => {+ const unsubscribeTopic = useChatStore.subscribe(+ (state) => state.activeTopicId,+ (state) => {+ const { aid, topicId } = paramsRef.current;++ if (!aid || state === topicId) return;++ if (state === undefined && topicId) {+ useChatStore.setState(+ { activeTopicId: topicId },+ false,+ 'ChatHydration/restoreTopicAfterScopedReset',+ );+ return;+ }++ const nextSearchParams = new URLSearchParams(searchParamsRef.current);+ nextSearchParams.delete('topic');++ const nextPath = state ? AGENT_CHAT_TOPIC_URL(aid, state) : AGENT_CHAT_URL(aid);+ const nextUrl = `${nextPath}${getSearchSuffix(nextSearchParams)}${locationRef.current.hash}`;+ const currentUrl = `${locationRef.current.pathname}${locationRef.current.search}${locationRef.current.hash}`;++ if (currentUrl !== nextUrl) navigate(nextUrl, { replace: true });+ },+ );+ const unsubscribeThread = useChatStore.subscribe(+ (state) => state.activeThreadId,+ (state) => {+ setThread(state || null);+ },+ );++ return () => {+ unsubscribeTopic();+ unsubscribeThread();+ };+ }, [navigate, setThread]);+};diff --git a/src/routes/(main)/community/_layout/Sidebar/Header/Nav.tsx b/src/routes/(main)/community/_layout/Sidebar/Header/Nav.tsxindex 64fed50eb36..892459a44a1 100644--- a/src/routes/(main)/community/_layout/Sidebar/Header/Nav.tsx+++ b/src/routes/(main)/community/_layout/Sidebar/Header/Nav.tsx@@ -10,7 +10,7 @@ import { type NavItemProps } from '@/features/NavPanel/components/NavItem';import NavItem from '@/features/NavPanel/components/NavItem';import { useWorkspaceAwareNavigate } from '@/features/Workspace/useWorkspaceAwareNavigate';import WorkspaceLink from '@/features/Workspace/WorkspaceLink';-import { usePathname } from '@/libs/router/navigation';+import { useActiveLocation } from '@/hooks/useActiveLocation';import { DiscoverTab } from '@/types/discover';import { isModifierClick } from '@/utils/navigation';@@ -23,7 +23,7 @@ interface Item {}const useActiveTabKey = () => {- const pathname = usePathname();+ const { pathname } = useActiveLocation();if (pathname.endsWith('/community')) return DiscoverTab.Home;return (pathname.split('/community/').at(1) as DiscoverTab) || DiscoverTab.Home;};diff --git a/src/routes/(main)/eval/_layout/Sidebar/Body/index.tsx b/src/routes/(main)/eval/_layout/Sidebar/Body/index.tsxindex 3c07d167687..fcaa06fc654 100644--- a/src/routes/(main)/eval/_layout/Sidebar/Body/index.tsx+++ b/src/routes/(main)/eval/_layout/Sidebar/Body/index.tsx@@ -8,14 +8,14 @@ import { useTranslation } from 'react-i18next';import NavItem from '@/features/NavPanel/components/NavItem';import { useWorkspaceAwareNavigate } from '@/features/Workspace/useWorkspaceAwareNavigate';import WorkspaceLink from '@/features/Workspace/WorkspaceLink';-import { usePathname } from '@/libs/router/navigation';+import { useActiveLocation } from '@/hooks/useActiveLocation';import { useEvalStore } from '@/store/eval';import BenchmarkList from './BenchmarkList';import ExperimentList from './ExperimentList';const useActiveKey = () => {- const pathname = usePathname();+ const { pathname } = useActiveLocation();if (pathname === '/eval') return 'dashboard';const benchMatch = pathname.match(/\/eval\/bench\/([^/]+)/);diff --git a/src/routes/(main)/eval/bench/[benchmarkId]/_layout/Sidebar/Body/index.tsx b/src/routes/(main)/eval/bench/[benchmarkId]/_layout/Sidebar/Body/index.tsxindex 144f3dae08c..47db1a7f55f 100644--- a/src/routes/(main)/eval/bench/[benchmarkId]/_layout/Sidebar/Body/index.tsx+++ b/src/routes/(main)/eval/bench/[benchmarkId]/_layout/Sidebar/Body/index.tsx@@ -4,44 +4,19 @@ import { Accordion, Flexbox } from '@lobehub/ui';import { LayoutDashboard } from 'lucide-react';import { memo } from 'react';import { useTranslation } from 'react-i18next';-import { useParams } from 'react-router';import NavItem from '@/features/NavPanel/components/NavItem';import { useWorkspaceAwareNavigate } from '@/features/Workspace/useWorkspaceAwareNavigate';import WorkspaceLink from '@/features/Workspace/WorkspaceLink';-import { usePathname } from '@/libs/router/navigation';-import { useEvalStore } from '@/store/eval';import DatasetList from './DatasetList';import RunList from './RunList';--const useActiveKey = () => {- const pathname = usePathname();-- const datasetMatch = pathname.match(/\/eval\/bench\/[^/]+\/datasets\/([^/]+)/);- if (datasetMatch) return `dataset-${datasetMatch[1]}`;-- const runMatch = pathname.match(/\/eval\/bench\/[^/]+\/runs\/([^/]+)/);- if (runMatch) return `run-${runMatch[1]}`;-- // Overview page: /eval/bench/{id} with no sub-route- const isOverview = /\/eval\/bench\/[^/]+\/?$/.test(pathname);- if (isOverview) return 'overview';-- return '';-};+import { useActiveBenchmarkSidebarRoute } from './useActiveBenchmarkSidebarRoute';const Body = memo(() => {const { t } = useTranslation('eval');- const { benchmarkId } = useParams<{ benchmarkId: string }>();+ const { activeKey, benchmarkId } = useActiveBenchmarkSidebarRoute();const navigate = useWorkspaceAwareNavigate();- const useFetchDatasets = useEvalStore((s) => s.useFetchDatasets);- const useFetchRuns = useEvalStore((s) => s.useFetchRuns);-- useFetchDatasets(benchmarkId);- useFetchRuns(benchmarkId);-- const activeKey = useActiveKey();return (<Flexbox gap={8} paddingInline={4}>diff --git a/src/routes/(main)/eval/bench/[benchmarkId]/_layout/Sidebar/Body/useActiveBenchmarkSidebarRoute.desktop.test.ts b/src/routes/(main)/eval/bench/[benchmarkId]/_layout/Sidebar/Body/useActiveBenchmarkSidebarRoute.desktop.test.tsnew file mode 100644index 00000000000..88e86aa44a4--- /dev/null+++ b/src/routes/(main)/eval/bench/[benchmarkId]/_layout/Sidebar/Body/useActiveBenchmarkSidebarRoute.desktop.test.ts@@ -0,0 +1,54 @@+import { act, renderHook } from '@testing-library/react';+import { afterEach, describe, expect, it, vi } from 'vitest';++import { useElectronStore } from '@/store/electron';++import { useActiveBenchmarkSidebarRoute } from './useActiveBenchmarkSidebarRoute';++const evalStore = vi.hoisted(() => ({+ useFetchDatasets: vi.fn(),+ useFetchRuns: vi.fn(),+}));++vi.mock('@/hooks/useActiveLocation', async () => await import('@/hooks/useActiveLocation.desktop'));+vi.mock(+ '@/hooks/useActiveRouteParams',+ async () => await import('@/hooks/useActiveRouteParams.desktop'),+);+vi.mock('@/store/eval', () => ({+ useEvalStore: (selector: (state: typeof evalStore) => unknown) => selector(evalStore),+}));++const tab = (url: string) => ({ id: 'benchmark-tab', lastVisited: 0, url });++afterEach(() => {+ useElectronStore.setState({ activeTabId: null, tabs: [] });+ vi.clearAllMocks();+});++describe('useActiveBenchmarkSidebarRoute (desktop)', () => {+ it('updates the benchmark target and active item when the active tab changes IDs', () => {+ useElectronStore.setState({+ activeTabId: 'benchmark-tab',+ tabs: [tab('/eval/bench/benchmark-a/datasets/dataset-a')],+ });++ const { result } = renderHook(() => useActiveBenchmarkSidebarRoute());+ expect(result.current).toEqual({+ activeKey: 'dataset-dataset-a',+ benchmarkId: 'benchmark-a',+ });+ expect(evalStore.useFetchDatasets).toHaveBeenLastCalledWith('benchmark-a');+ expect(evalStore.useFetchRuns).toHaveBeenLastCalledWith('benchmark-a');++ act(() => {+ useElectronStore.setState({+ tabs: [tab('/eval/bench/benchmark-b/runs/run-b')],+ });+ });++ expect(result.current).toEqual({ activeKey: 'run-run-b', benchmarkId: 'benchmark-b' });+ expect(evalStore.useFetchDatasets).toHaveBeenLastCalledWith('benchmark-b');+ expect(evalStore.useFetchRuns).toHaveBeenLastCalledWith('benchmark-b');+ });+});diff --git a/src/routes/(main)/eval/bench/[benchmarkId]/_layout/Sidebar/Body/useActiveBenchmarkSidebarRoute.ts b/src/routes/(main)/eval/bench/[benchmarkId]/_layout/Sidebar/Body/useActiveBenchmarkSidebarRoute.tsnew file mode 100644index 00000000000..c4a0504626c--- /dev/null+++ b/src/routes/(main)/eval/bench/[benchmarkId]/_layout/Sidebar/Body/useActiveBenchmarkSidebarRoute.ts@@ -0,0 +1,28 @@+import { useActiveLocation } from '@/hooks/useActiveLocation';+import { useEvalStore } from '@/store/eval';++import { useActiveBenchmarkId } from '../useActiveBenchmarkId';++const resolveActiveKey = (pathname: string) => {+ const datasetMatch = pathname.match(/\/eval\/bench\/[^/]+\/datasets\/([^/]+)/);+ if (datasetMatch) return `dataset-${datasetMatch[1]}`;++ const runMatch = pathname.match(/\/eval\/bench\/[^/]+\/runs\/([^/]+)/);+ if (runMatch) return `run-${runMatch[1]}`;++ if (/\/eval\/bench\/[^/]+\/?$/.test(pathname)) return 'overview';++ return '';+};++export const useActiveBenchmarkSidebarRoute = () => {+ const benchmarkId = useActiveBenchmarkId();+ const { pathname } = useActiveLocation();+ const useFetchDatasets = useEvalStore((state) => state.useFetchDatasets);+ const useFetchRuns = useEvalStore((state) => state.useFetchRuns);++ useFetchDatasets(benchmarkId || undefined);+ useFetchRuns(benchmarkId || undefined);++ return { activeKey: resolveActiveKey(pathname), benchmarkId };+};diff --git a/src/routes/(main)/eval/bench/[benchmarkId]/_layout/Sidebar/Header/index.tsx b/src/routes/(main)/eval/bench/[benchmarkId]/_layout/Sidebar/Header/index.tsxindex 4ccc3105e94..495715b0858 100644--- a/src/routes/(main)/eval/bench/[benchmarkId]/_layout/Sidebar/Header/index.tsx+++ b/src/routes/(main)/eval/bench/[benchmarkId]/_layout/Sidebar/Header/index.tsx@@ -2,19 +2,19 @@import { memo } from 'react';import { useTranslation } from 'react-i18next';-import { useParams } from 'react-router';import SideBarHeaderLayout from '@/features/NavPanel/SideBarHeaderLayout';+import { useActiveBenchmarkId } from '../useActiveBenchmarkId';import BenchmarkHead from './BenchmarkHead';const Header = memo(() => {- const { benchmarkId } = useParams<{ benchmarkId: string }>();+ const benchmarkId = useActiveBenchmarkId();const { t } = useTranslation('common');return (<SideBarHeaderLayoutbackTo="/eval"- left={<BenchmarkHead id={benchmarkId || ''} />}+ left={<BenchmarkHead id={benchmarkId} />}breadcrumb={[{href: `/eval/bench/${benchmarkId}`,diff --git a/src/routes/(main)/eval/bench/[benchmarkId]/_layout/Sidebar/useActiveBenchmarkId.ts b/src/routes/(main)/eval/bench/[benchmarkId]/_layout/Sidebar/useActiveBenchmarkId.tsnew file mode 100644index 00000000000..177983dd643--- /dev/null+++ b/src/routes/(main)/eval/bench/[benchmarkId]/_layout/Sidebar/useActiveBenchmarkId.ts@@ -0,0 +1,4 @@+import { useActiveRouteParams } from '@/hooks/useActiveRouteParams';++export const useActiveBenchmarkId = () =>+ useActiveRouteParams<{ benchmarkId?: string }>().benchmarkId ?? '';diff --git a/src/routes/(main)/group/_layout/Sidebar/GroupConfig/GroupMember.tsx b/src/routes/(main)/group/_layout/Sidebar/GroupConfig/GroupMember.tsxindex 2fbdca7a637..362d314ba93 100644--- a/src/routes/(main)/group/_layout/Sidebar/GroupConfig/GroupMember.tsx+++ b/src/routes/(main)/group/_layout/Sidebar/GroupConfig/GroupMember.tsx@@ -5,13 +5,13 @@ import { createStaticStyles } from 'antd-style';import { UserMinus } from 'lucide-react';import { memo, useMemo, useState } from 'react';import { useTranslation } from 'react-i18next';-import { useLocation } from 'react-router';import { DEFAULT_AVATAR } from '@/const/meta';import AgentProfilePopup from '@/features/AgentProfileCard/AgentProfilePopup';import NavItem from '@/features/NavPanel/components/NavItem';import { useResourceAccess } from '@/features/ResourcePermission/useResourceAccess';import UserAvatar from '@/features/User/UserAvatar';+import { useActiveLocation } from '@/hooks/useActiveLocation';import { usePermission } from '@/hooks/usePermission';import { useQueryRoute } from '@/hooks/useQueryRoute';import { useAgentGroupStore } from '@/store/agentGroup';@@ -49,7 +49,7 @@ const GroupMember = memo<GroupMemberProps>(({ addModalOpen, onAddModalOpenChangeconst { canEditResource } = useResourceAccess('agentGroup', groupId);const canEdit = hasEditPermission && canEditResource;const router = useQueryRoute();- const location = useLocation();+ const location = useActiveLocation();const [nickname, username] = useUserStore((s) => [userProfileSelectors.nickName(s),userProfileSelectors.username(s),diff --git a/src/routes/(main)/group/_layout/Sidebar/Header/Agent/index.tsx b/src/routes/(main)/group/_layout/Sidebar/Header/Agent/index.tsxindex 3271de98bc9..8469b8c19d9 100644--- a/src/routes/(main)/group/_layout/Sidebar/Header/Agent/index.tsx+++ b/src/routes/(main)/group/_layout/Sidebar/Header/Agent/index.tsx@@ -5,9 +5,9 @@ import { ChevronsUpDownIcon } from 'lucide-react';import { type PropsWithChildren } from 'react';import React, { memo } from 'react';import { useTranslation } from 'react-i18next';-import { useParams } from 'react-router';import { SkeletonItem } from '@/features/NavPanel/components/SkeletonList';+import { useActiveRouteParams } from '@/hooks/useActiveRouteParams';import SupervisorAvatar from '@/routes/(main)/group/features/GroupAvatar';import { useAgentGroupStore } from '@/store/agentGroup';import { agentGroupSelectors } from '@/store/agentGroup/selectors';@@ -17,7 +17,7 @@ import SwitchPanel from './SwitchPanel';const Agent = memo<PropsWithChildren>(() => {const { t } = useTranslation(['chat', 'common']);- const { gid } = useParams<{ gid: string }>();+ const { gid } = useActiveRouteParams<{ gid: string }>();const [isGroupsInit, groupMeta] = useAgentGroupStore((s) => [agentGroupSelectors.isGroupsInit(s),agentGroupSelectors.getGroupMeta(gid ?? '')(s),diff --git a/src/routes/(main)/group/_layout/Sidebar/Header/Nav.tsx b/src/routes/(main)/group/_layout/Sidebar/Header/Nav.tsxindex f4c7ccadfb9..bac315c393c 100644--- a/src/routes/(main)/group/_layout/Sidebar/Header/Nav.tsx+++ b/src/routes/(main)/group/_layout/Sidebar/Header/Nav.tsx@@ -5,14 +5,14 @@ import { BotPromptIcon } from '@lobehub/ui/icons';import { MessageSquarePlusIcon, SearchIcon } from 'lucide-react';import { memo } from 'react';import { useTranslation } from 'react-i18next';-import { useParams } from 'react-router';import urlJoin from 'url-join';import NavItem from '@/features/NavPanel/components/NavItem';import { useResourceAccess } from '@/features/ResourcePermission/useResourceAccess';+import { useActiveLocation } from '@/hooks/useActiveLocation';+import { useActiveRouteParams } from '@/hooks/useActiveRouteParams';import { usePermission } from '@/hooks/usePermission';import { useQueryRoute } from '@/hooks/useQueryRoute';-import { usePathname } from '@/libs/router/navigation';import { useAgentGroupStore } from '@/store/agentGroup';import { useChatStore } from '@/store/chat';import { useGlobalStore } from '@/store/global';@@ -21,9 +21,9 @@ import { featureFlagsSelectors, useServerConfigStore } from '@/store/serverConficonst Nav = memo(() => {const { t } = useTranslation('chat');const { t: tTopic } = useTranslation('topic');- const params = useParams();+ const params = useActiveRouteParams();const groupId = params.gid;- const pathname = usePathname();+ const { pathname } = useActiveLocation();const isProfileActive = pathname.includes('/profile');const router = useQueryRoute();const { isAgentEditable } = useServerConfigStore(featureFlagsSelectors);diff --git a/src/routes/(main)/group/_layout/Sidebar/Topic/hooks/useThreadNavigation.ts b/src/routes/(main)/group/_layout/Sidebar/Topic/hooks/useThreadNavigation.tsindex 1a38ccb8397..26acbdfe68f 100644--- a/src/routes/(main)/group/_layout/Sidebar/Topic/hooks/useThreadNavigation.ts+++ b/src/routes/(main)/group/_layout/Sidebar/Topic/hooks/useThreadNavigation.ts@@ -1,9 +1,9 @@import { useCallback } from 'react';-import { useParams } from 'react-router';import urlJoin from 'url-join';+import { useActiveLocation } from '@/hooks/useActiveLocation';+import { useActiveRouteParams } from '@/hooks/useActiveRouteParams';import { useQueryRoute } from '@/hooks/useQueryRoute';-import { usePathname } from '@/libs/router/navigation';import { useChatStore } from '@/store/chat';import { useGlobalStore } from '@/store/global';@@ -12,8 +12,8 @@ import { useGlobalStore } from '@/store/global';* If in agent sub-route (e.g., /agent/:aid/profile), navigate back to chat first*/export const useThreadNavigation = () => {- const pathname = usePathname();- const params = useParams();+ const { pathname } = useActiveLocation();+ const params = useActiveRouteParams();const router = useQueryRoute();const toggleConfig = useGlobalStore((s) => s.toggleMobileTopic);const switchThread = useChatStore((s) => s.switchThread);diff --git a/src/routes/(main)/home/_layout/Body/Agent/List/usePreservedAgentUrl.ts b/src/routes/(main)/home/_layout/Body/Agent/List/usePreservedAgentUrl.tsindex b75a16e7c6f..d661707176c 100644--- a/src/routes/(main)/home/_layout/Body/Agent/List/usePreservedAgentUrl.ts+++ b/src/routes/(main)/home/_layout/Body/Agent/List/usePreservedAgentUrl.ts@@ -1,6 +1,7 @@import { AGENT_CHAT_URL } from '@lobechat/const';import { useMemo } from 'react';-import { useLocation } from 'react-router';++import { useActiveLocation } from '@/hooks/useActiveLocation';// Sub-routes that are agent-scoped views (not tied to a specific topic/task id),// safe to carry over when switching between agents from the sidebar switcher.@@ -13,7 +14,7 @@ const PRESERVED_AGENT_SUB_PATHS = new Set(['topics', 'profile', 'channel']);* intentionally dropped.*/export const usePreservedAgentUrl = (agentId: string): string => {- const { pathname } = useLocation();+ const { pathname } = useActiveLocation();return useMemo(() => {const match = pathname.match(/^\/agent\/[^/]+\/([^/]+)\/?$/);const subPath = match?.[1];diff --git a/src/routes/(main)/memory/_layout/Sidebar/Header/Nav.tsx b/src/routes/(main)/memory/_layout/Sidebar/Header/Nav.tsxindex adcabcbf55d..790090c1d2a 100644--- a/src/routes/(main)/memory/_layout/Sidebar/Header/Nav.tsx+++ b/src/routes/(main)/memory/_layout/Sidebar/Header/Nav.tsx@@ -17,7 +17,7 @@ import { Link } from 'react-router';import { type NavItemProps } from '@/features/NavPanel/components/NavItem';import NavItem from '@/features/NavPanel/components/NavItem';import { useWorkspaceAwareNavigate } from '@/features/Workspace/useWorkspaceAwareNavigate';-import { usePathname } from '@/libs/router/navigation';+import { useActiveLocation } from '@/hooks/useActiveLocation';import { useGlobalStore } from '@/store/global';import { isModifierClick } from '@/utils/navigation';@@ -39,7 +39,7 @@ enum MemoryTabKey {}const useActiveTabKey = () => {- const pathname = usePathname();+ const { pathname } = useActiveLocation();if (pathname === '/memory') return MemoryTabKey.Home;return (pathname.split('/memory/').find(Boolean)! as MemoryTabKey) || MemoryTabKey.Home;};diff --git a/src/routes/(main)/resource/(home)/_layout/Header/CategoryMenu.tsx b/src/routes/(main)/resource/(home)/_layout/Header/CategoryMenu.tsxindex d600dd0aa42..33dd3c961ee 100644--- a/src/routes/(main)/resource/(home)/_layout/Header/CategoryMenu.tsx+++ b/src/routes/(main)/resource/(home)/_layout/Header/CategoryMenu.tsx@@ -11,11 +11,12 @@ import {} from 'lucide-react';import { memo, useMemo } from 'react';import { useTranslation } from 'react-i18next';-import { Link, useLocation } from 'react-router';+import { Link } from 'react-router';import { useBusinessResourceCategories } from '@/business/client/features/ResourceCategories';import NavItem from '@/features/NavPanel/components/NavItem';import { useWorkspaceAwareNavigate } from '@/features/Workspace/useWorkspaceAwareNavigate';+import { useActiveLocation } from '@/hooks/useActiveLocation';import { FilesTabs } from '@/types/files';import { useResourceManagerStore } from '../../../features/store';@@ -25,7 +26,7 @@ const CategoryMenu = memo(() => {const [activeKey, setMode] = useResourceManagerStore((s) => [s.category, s.setMode]);const navigate = useWorkspaceAwareNavigate();const businessCategories = useBusinessResourceCategories();- const location = useLocation();+ const location = useActiveLocation();// In Work-gallery mode (`?works=`) no file category is selected, so suppress// the category highlight β otherwise "All" reads as active alongside the// active Work entry.diff --git a/src/routes/(main)/resource/library/_layout/Header/index.tsx b/src/routes/(main)/resource/library/_layout/Header/index.tsxindex 228dc9d650a..5403054080c 100644--- a/src/routes/(main)/resource/library/_layout/Header/index.tsx+++ b/src/routes/(main)/resource/library/_layout/Header/index.tsx@@ -2,19 +2,19 @@import { memo } from 'react';import { useTranslation } from 'react-i18next';-import { useParams } from 'react-router';import SideBarHeaderLayout from '@/features/NavPanel/SideBarHeaderLayout';import LibraryHead from './LibraryHead';+import { useActiveLibraryId } from './useActiveLibraryId';const Header = memo(() => {- const { id } = useParams<{ id: string }>();+ const id = useActiveLibraryId();const { t } = useTranslation('common');return (<SideBarHeaderLayoutbackTo="/resource"- left={<LibraryHead id={id || ''} />}+ left={<LibraryHead id={id} />}breadcrumb={[{href: `/resource/library/${id}`,diff --git a/src/routes/(main)/resource/library/_layout/Header/useActiveLibraryId.desktop.test.ts b/src/routes/(main)/resource/library/_layout/Header/useActiveLibraryId.desktop.test.tsnew file mode 100644index 00000000000..c234e7f2d98--- /dev/null+++ b/src/routes/(main)/resource/library/_layout/Header/useActiveLibraryId.desktop.test.ts@@ -0,0 +1,35 @@+import { act, renderHook } from '@testing-library/react';+import { afterEach, describe, expect, it, vi } from 'vitest';++import { useElectronStore } from '@/store/electron';++import { useActiveLibraryId } from './useActiveLibraryId';++vi.mock(+ '@/hooks/useActiveRouteParams',+ async () => await import('@/hooks/useActiveRouteParams.desktop'),+);++const tab = (url: string) => ({ id: 'resource-tab', lastVisited: 0, url });++afterEach(() => {+ useElectronStore.setState({ activeTabId: null, tabs: [] });+});++describe('useActiveLibraryId (desktop)', () => {+ it('follows a library ID change in the active tab', () => {+ useElectronStore.setState({+ activeTabId: 'resource-tab',+ tabs: [tab('/resource/library/library-a')],+ });++ const { result } = renderHook(() => useActiveLibraryId());+ expect(result.current).toBe('library-a');++ act(() => {+ useElectronStore.setState({ tabs: [tab('/resource/library/library-b')] });+ });++ expect(result.current).toBe('library-b');+ });+});diff --git a/src/routes/(main)/resource/library/_layout/Header/useActiveLibraryId.ts b/src/routes/(main)/resource/library/_layout/Header/useActiveLibraryId.tsnew file mode 100644index 00000000000..15009c70e36--- /dev/null+++ b/src/routes/(main)/resource/library/_layout/Header/useActiveLibraryId.ts@@ -0,0 +1,3 @@+import { useActiveRouteParams } from '@/hooks/useActiveRouteParams';++export const useActiveLibraryId = () => useActiveRouteParams<{ id?: string }>().id ?? '';diff --git a/src/routes/(main)/settings/_layout/Body/activeTab.desktop.test.ts b/src/routes/(main)/settings/_layout/Body/activeTab.desktop.test.tsnew file mode 100644index 00000000000..14eb28e77a3--- /dev/null+++ b/src/routes/(main)/settings/_layout/Body/activeTab.desktop.test.ts@@ -0,0 +1,84 @@+/**+ * @vitest-environment happy-dom+ */+import { act, render, screen } from '@testing-library/react';+import { createElement as h, type ReactNode } from 'react';+import { afterEach, describe, expect, it, vi } from 'vitest';++import { useElectronStore } from '@/store/electron';++// The settings sidebar is portal'd into the shell (frozen root router on+// desktop). This binds `@/hooks/useActiveLocation` to the real desktop variant,+// which mirrors the active tab's url from the electron store, and asserts the+// sidebar's active-tab highlight follows a store-driven tab switch β the+// Critical-2 regression (raw useLocation would freeze at the boot url).+vi.mock('@/hooks/useActiveLocation', async () => await import('@/hooks/useActiveLocation.desktop'));++vi.mock('../../hooks/useCategory', () => ({+ SettingsGroupKey: { General: 'general' },+ useCategory: () => [+ {+ items: [+ { icon: () => null, key: 'profile', label: 'Profile' },+ { icon: () => null, key: 'appearance', label: 'Appearance' },+ ],+ key: 'general',+ title: 'General',+ },+ ],+}));++vi.mock('@/features/SettingsSearch', () => ({+ getTabUrl: (tab: string) => `/settings/${tab}`,+ SearchSection: ({ children }: { children?: ReactNode }) => h('div', null, children),+}));++vi.mock('@/features/Workspace/useWorkspaceAwareNavigate', () => ({+ useWorkspaceAwareNavigate: () => vi.fn(),+}));++vi.mock('@/features/NavPanel/components/NavItem', () => ({+ default: ({ active, title }: { active?: boolean; title: ReactNode }) =>+ h('button', { 'data-active': String(!!active), 'type': 'button' }, title),+}));++vi.mock('react-router', () => ({+ Link: ({ children }: { children?: ReactNode }) => h('span', null, children),+}));++vi.mock('@lobehub/ui', () => ({+ Accordion: ({ children }: { children?: ReactNode }) => h('div', null, children),+ AccordionItem: ({ children, title }: { children?: ReactNode; title?: ReactNode }) =>+ h('div', null, title, children),+ Flexbox: ({ children }: { children?: ReactNode }) => h('div', null, children),+ Text: ({ children }: { children?: ReactNode }) => h('span', null, children),+}));++const tab = (id: string, url: string) => ({ id, lastVisited: 0, url });++const activeStateOf = (label: string) =>+ screen.getByText(label).closest('button')?.getAttribute('data-active');++afterEach(() => {+ useElectronStore.setState({ activeTabId: null, tabs: [] });+});++describe('settings sidebar active tab (desktop)', () => {+ it('follows the active tab url via the electron store mirror', async () => {+ useElectronStore.setState({+ activeTabId: 't1',+ tabs: [tab('t1', '/settings/profile'), tab('t2', '/settings/appearance')],+ });++ const { default: Body } = await import('./index');+ render(h(Body));++ expect(activeStateOf('Profile')).toBe('true');+ expect(activeStateOf('Appearance')).toBe('false');++ act(() => useElectronStore.setState({ activeTabId: 't2' }));++ expect(activeStateOf('Profile')).toBe('false');+ expect(activeStateOf('Appearance')).toBe('true');+ });+});diff --git a/src/routes/(main)/settings/_layout/Body/index.tsx b/src/routes/(main)/settings/_layout/Body/index.tsxindex ca667fc5ea9..5657e447f56 100644--- a/src/routes/(main)/settings/_layout/Body/index.tsx+++ b/src/routes/(main)/settings/_layout/Body/index.tsx@@ -2,11 +2,12 @@import { Accordion, AccordionItem, Flexbox, Text } from '@lobehub/ui';import { memo, useMemo } from 'react';-import { Link, useLocation } from 'react-router';+import { Link } from 'react-router';import NavItem from '@/features/NavPanel/components/NavItem';import { getTabUrl, SearchSection } from '@/features/SettingsSearch';import { useWorkspaceAwareNavigate } from '@/features/Workspace/useWorkspaceAwareNavigate';+import { useActiveLocation } from '@/hooks/useActiveLocation';import { SettingsTabs } from '@/store/global/initialState';import { isModifierClick } from '@/utils/navigation';@@ -15,7 +16,7 @@ import { SettingsGroupKey, useCategory } from '../../hooks/useCategory';const Body = memo(() => {const categoryGroups = useCategory();const navigate = useWorkspaceAwareNavigate();- const location = useLocation();+ const location = useActiveLocation();// Extract current tab from pathname: /settings/profile -> profileconst activeTab = useMemo(() => {diff --git a/src/spa/router/desktopRouter.bootInitOrder.test.ts b/src/spa/router/desktopRouter.bootInitOrder.test.tsnew file mode 100644index 00000000000..cd389eecf5e--- /dev/null+++ b/src/spa/router/desktopRouter.bootInitOrder.test.ts@@ -0,0 +1,29 @@+// Import ORDER is load-bearing and must not be reshuffled: the desktop boot+// evaluates the navigation facade (`NavigatorRegistrar.desktop` β `appNavigate`+// β `activeTabNavigate`) before the router config. If any of those statically+// pull `desktopRouter.config` back in, the config twin runs its top-level+// `redirectElement(...)` while `@/utils/router` is still initializing and hits+// a jsx-runtime TDZ ("Cannot access '_jsxDEV' before initialization"), leaving+// the renderer white-screened. This test wires that order up so a regression in+// the navigation import graph fails here instead of only on the packaged app.+import '@/utils/NavigatorRegistrar.desktop';++import { describe, expect, it } from 'vitest';++import {+ createMainAreaChildren,+ desktopRoutes,+ mainAreaMetaRoutes,+} from './desktopRouter.config.desktop';++describe('desktop boot init order', () => {+ it('evaluates desktopRouter.config after the navigation facade without a TDZ crash', () => {+ expect(Array.isArray(desktopRoutes)).toBe(true);+ expect(desktopRoutes.length).toBeGreaterThan(0);++ expect(Array.isArray(mainAreaMetaRoutes)).toBe(true);+ expect(mainAreaMetaRoutes.length).toBeGreaterThan(0);++ expect(createMainAreaChildren().length).toBeGreaterThan(0);+ });+});diff --git a/src/spa/router/desktopRouter.config.desktop.tsx b/src/spa/router/desktopRouter.config.desktop.tsxindex 75a2fd390b7..d43275125c9 100644--- a/src/spa/router/desktopRouter.config.desktop.tsx+++ b/src/spa/router/desktopRouter.config.desktop.tsx@@ -112,6 +112,8 @@ import GroupPage from '@/routes/(main)/group';import DesktopGroupLayout from '@/routes/(main)/group/_layout';import { groupRouteMeta } from '@/routes/(main)/group/features/routeMeta';import GroupProfilePage from '@/routes/(main)/group/profile';+import DesktopHome from '@/routes/(main)/home';+import DesktopHomeLayout from '@/routes/(main)/home/_layout';import DesktopMemoryLayout from '@/routes/(main)/memory/_layout';import MemoryHomePage from '@/routes/(main)/memory/(home)';import MemoryActivitiesPage from '@/routes/(main)/memory/activities';@@ -635,153 +637,182 @@ export const sharedMainAreaChildren: RouteObject[] = [},];-// Desktop router configuration β all sync imports for Electron local build-export const desktopRoutes: RouteObject[] = [+export const createMainAreaChildren = (): RouteObject[] => [+ ...sharedMainAreaChildren,++ // Downloads page (personal-only β never mirrored under /:workspaceSlug){- children: [- ...sharedMainAreaChildren,+ element: <DownloadsPage />,+ errorElement: <ErrorBoundary />,+ handle: { meta: routeMeta({ icon: Download, titleKey: 'navigation.downloads' }) },+ path: 'downloads',+ },- // Downloads page (personal-only β never mirrored under /:workspaceSlug)+ // Settings routes (personal-only β never mirrored under /:workspaceSlug)+ {+ children: [{- element: <DownloadsPage />,- errorElement: <ErrorBoundary />,- handle: { meta: routeMeta({ icon: Download, titleKey: 'navigation.downloads' }) },- path: 'downloads',+ element: redirectElement('/settings/profile'),+ index: true,},-- // Settings routes (personal-only β never mirrored under /:workspaceSlug)+ // Provider routes with nested structure{children: [{- element: redirectElement('/settings/profile'),+ element: redirectElement('/settings/provider/all'),index: true,},- // Provider routes with nested structure{- children: [- {- element: redirectElement('/settings/provider/all'),- index: true,- },- {- element: <ProviderDetailPage />,- handle: {- meta: routeMeta({ icon: Settings, titleKey: 'navigation.provider' }),- },- path: ':providerId',- },- ],- element: <ProviderLayout />,+ element: <ProviderDetailPage />,handle: {meta: routeMeta({ icon: Settings, titleKey: 'navigation.provider' }),},- path: 'provider',- },- {- element: <SettingsTabPage />,- handle: { settingsTab: SettingsTabs.Memory },- path: 'memory',- },- {- element: redirectElement('/settings/credential'),- path: 'creds',- },- // Other settings tabs- {- element: <SettingsTabPage />,- handle: { meta: settingsRouteMeta },- path: ':tab',- },- // Tabs that need a sub-segment (e.g. /settings/messenger/discord) reuse- // the same tab page; nested feature components read `:sub` via useParams.- {- element: <SettingsTabPage />,- handle: { meta: settingsRouteMeta },- path: ':tab/:sub',+ path: ':providerId',},],- element: <SettingsLayout />,- errorElement: <ErrorBoundary />,- path: 'settings',+ element: <ProviderLayout />,+ handle: {+ meta: routeMeta({ icon: Settings, titleKey: 'navigation.provider' }),+ },+ path: 'provider',+ },+ {+ element: <SettingsTabPage />,+ handle: { settingsTab: SettingsTabs.Memory },+ path: 'memory',},+ {+ element: redirectElement('/settings/credential'),+ path: 'creds',+ },+ // Other settings tabs+ {+ element: <SettingsTabPage />,+ handle: { meta: settingsRouteMeta },+ path: ':tab',+ },+ // Tabs that need a sub-segment (e.g. /settings/messenger/discord) reuse+ // the same tab page; nested feature components read `:sub` via useParams.+ {+ element: <SettingsTabPage />,+ handle: { meta: settingsRouteMeta },+ path: ':tab/:sub',+ },+ ],+ element: <SettingsLayout />,+ errorElement: <ErrorBoundary />,+ path: 'settings',+ },- // Workspace slug routes β `/:workspaceSlug/*` mirrors the shared main area.- // Must come AFTER all reserved root paths so they don't shadow e.g. /agent.+ // Workspace slug routes β `/:workspaceSlug/*` mirrors the shared main area.+ // Must come AFTER all reserved root paths so they don't shadow e.g. /agent.+ {+ children: [+ // Workspace home β rendered as tab content (mirrors `/` index). Each tab+ // owns its location, so the home element only mounts inside a home tab.+ {+ element: (+ <DesktopHomeLayout>+ <DesktopHome />+ </DesktopHomeLayout>+ ),+ handle: { meta: workspaceHomeRouteMeta },+ index: true,+ },+ ...sharedMainAreaChildren,+ // Workspace settings β `/:slug/settings/*`. Dedicated layout with+ // its own sidebar (workspace avatar + 6 tabs + back-to-chat), fully+ // decoupled from personal `/settings/*`.{children: [- // Workspace home β handled by the persistent `DesktopHomeLayout`- // (mirrors `/` index). Adding an element renders Home twice.- { handle: { meta: workspaceHomeRouteMeta }, index: true },- ...sharedMainAreaChildren,- // Workspace settings β `/:slug/settings/*`. Dedicated layout with- // its own sidebar (workspace avatar + 6 tabs + back-to-chat), fully- // decoupled from personal `/settings/*`.- {- children: [- { element: <WorkspaceSlugSettingsIndexPage />, index: true },- // Full-bleed tabs render directly inside the workspace settings- // shell (sidebar + outlet) β they own their internal layout.- { element: <WorkspaceSlugSettingsProviderPage />, path: 'provider' },- { element: <WorkspaceSlugSettingsSkillPage />, path: 'skill' },- { element: <WorkspaceSlugSettingsConnectorPage />, path: 'connector' },- // Padded tabs share a centered, max-width container layout.- {- children: [- { element: <WorkspaceSlugSettingsGeneralPage />, path: 'general' },- { element: <WorkspaceSlugSettingsMembersPage />, path: 'members' },- { element: <WorkspaceSlugSettingsNotificationPage />, path: 'notification' },- { element: <WorkspaceSlugSettingsStatsPage />, path: 'stats' },- { element: <WorkspaceSlugSettingsPlansPage />, path: 'plans' },- { element: <WorkspaceSlugSettingsBillingPage />, path: 'billing' },- { element: <WorkspaceSlugSettingsCreditsPage />, path: 'credits' },- { element: <WorkspaceSlugSettingsUsagePage />, path: 'usage' },- { element: <WorkspaceSlugSettingsServiceModelPage />, path: 'service-model' },- { element: <WorkspaceSlugSettingsCredentialPage />, path: 'credential' },- // Legacy `/:slug/settings/creds` URLs β kept for deep-links.- { element: redirectElement('../credential'), path: 'creds' },- { element: <WorkspaceSlugSettingsApiKeyPage />, path: 'apikey' },- { element: <WorkspaceSlugSettingsOAuthAppsPage />, path: 'oauth-apps' },- { element: <WorkspaceSlugSettingsOAuthAppsPage />, path: 'oauth-apps/:sub' },- { element: <WorkspaceSlugSettingsAuditLogPage />, path: 'audit-log' },- { element: <WorkspaceSlugSettingsStoragePage />, path: 'storage' },- { element: <WorkspaceSlugSettingsDevicesPage />, path: 'devices' },- ],- element: <WorkspaceSlugSettingsContentLayout />,- },- ],- element: <WorkspaceSlugSettingsLayout />,- errorElement: <ErrorBoundary />,- path: 'settings',- },- // Legacy `/:slug/billing/*` URLs β redirect to `/:slug/settings/*`.+ { element: <WorkspaceSlugSettingsIndexPage />, index: true },+ // Full-bleed tabs render directly inside the workspace settings+ // shell (sidebar + outlet) β they own their internal layout.+ { element: <WorkspaceSlugSettingsProviderPage />, path: 'provider' },+ { element: <WorkspaceSlugSettingsSkillPage />, path: 'skill' },+ { element: <WorkspaceSlugSettingsConnectorPage />, path: 'connector' },+ // Padded tabs share a centered, max-width container layout.{children: [- { element: redirectElement('../settings/plans'), path: 'plans' },- { element: redirectElement('../settings/usage'), path: 'usage' },- { element: redirectElement('../settings/credits'), path: 'credits' },- { element: redirectElement('../settings/billing'), path: 'billing' },+ { element: <WorkspaceSlugSettingsGeneralPage />, path: 'general' },+ { element: <WorkspaceSlugSettingsMembersPage />, path: 'members' },+ { element: <WorkspaceSlugSettingsNotificationPage />, path: 'notification' },+ { element: <WorkspaceSlugSettingsStatsPage />, path: 'stats' },+ { element: <WorkspaceSlugSettingsPlansPage />, path: 'plans' },+ { element: <WorkspaceSlugSettingsBillingPage />, path: 'billing' },+ { element: <WorkspaceSlugSettingsCreditsPage />, path: 'credits' },+ { element: <WorkspaceSlugSettingsUsagePage />, path: 'usage' },+ { element: <WorkspaceSlugSettingsServiceModelPage />, path: 'service-model' },+ { element: <WorkspaceSlugSettingsCredentialPage />, path: 'credential' },+ // Legacy `/:slug/settings/creds` URLs β kept for deep-links.+ { element: redirectElement('../credential'), path: 'creds' },+ { element: <WorkspaceSlugSettingsApiKeyPage />, path: 'apikey' },+ { element: <WorkspaceSlugSettingsOAuthAppsPage />, path: 'oauth-apps' },+ { element: <WorkspaceSlugSettingsOAuthAppsPage />, path: 'oauth-apps/:sub' },+ { element: <WorkspaceSlugSettingsAuditLogPage />, path: 'audit-log' },+ { element: <WorkspaceSlugSettingsStoragePage />, path: 'storage' },+ { element: <WorkspaceSlugSettingsDevicesPage />, path: 'devices' },],- path: 'billing',+ element: <WorkspaceSlugSettingsContentLayout />,},],- element: <WorkspaceSlugLayout />,+ element: <WorkspaceSlugSettingsLayout />,errorElement: <ErrorBoundary />,- path: ':workspaceSlug',- },-- // Default route - home page (handled by persistent layout)- {- handle: {- meta: routeMeta({ icon: Home, titleKey: 'navigation.home' }),- },- index: true,+ path: 'settings',},- // Catch-all route+ // Legacy `/:slug/billing/*` URLs β redirect to `/:slug/settings/*`.{- element: redirectElement('/'),- path: '*',+ children: [+ { element: redirectElement('../settings/plans'), path: 'plans' },+ { element: redirectElement('../settings/usage'), path: 'usage' },+ { element: redirectElement('../settings/credits'), path: 'credits' },+ { element: redirectElement('../settings/billing'), path: 'billing' },+ ],+ path: 'billing',},],+ element: <WorkspaceSlugLayout />,+ errorElement: <ErrorBoundary />,+ path: ':workspaceSlug',+ },++ // Default route - home page (rendered as tab content)+ {+ element: (+ <DesktopHomeLayout>+ <DesktopHome />+ </DesktopHomeLayout>+ ),+ handle: {+ meta: routeMeta({ icon: Home, titleKey: 'navigation.home' }),+ },+ index: true,+ },+ // Catch-all route+ {+ element: redirectElement('/'),+ path: '*',+ },+];++// Meta-resolution route tree consumed by the desktop tab bar / recently-viewed+// panels. Twin-identical to the async config so `matchRouteMeta` resolves every+// tab url's static meta β the `/` root router below only hosts the TabHost shell+// (slim null-stub children with no meta), so the consumers must match against+// this populated tree, never `desktopRoutes`.+export const mainAreaMetaRoutes: RouteObject[] = [+ { children: createMainAreaChildren(), path: '/' },+];++// Desktop router configuration β all sync imports for Electron local build.+// The `/` route only hosts the TabHost shell; page content lives in per-tab+// routers built from `createMainAreaChildren()` (see `tabRouter.tsx`).+export const desktopRoutes: RouteObject[] = [+ {+ children: [+ { element: null, index: true },+ { element: null, path: '*' },+ ],element: <DesktopMainLayout />,errorElement: <ErrorBoundary />,path: '/',diff --git a/src/spa/router/desktopRouter.config.tsx b/src/spa/router/desktopRouter.config.tsxindex a4d84aab6d1..e75ca15dd35 100644--- a/src/spa/router/desktopRouter.config.tsx+++ b/src/spa/router/desktopRouter.config.tsx@@ -727,306 +727,316 @@ export const sharedMainAreaChildren: RouteObject[] = [},];-// Desktop router configuration (declarative mode)-export const desktopRoutes: RouteObject[] = [+export const createMainAreaChildren = (): RouteObject[] => [+ ...sharedMainAreaChildren,++ // Downloads page (personal-only β never mirrored under /:workspaceSlug){- children: [- ...sharedMainAreaChildren,+ element: dynamicElement(() => import('@/routes/(main)/downloads'), 'Desktop > Downloads'),+ errorElement: <ErrorBoundary />,+ handle: { meta: routeMeta({ icon: Download, titleKey: 'navigation.downloads' }) },+ path: 'downloads',+ },- // Downloads page (personal-only β never mirrored under /:workspaceSlug)+ // Settings routes (personal-only β never mirrored under /:workspaceSlug)+ {+ children: [{- element: dynamicElement(() => import('@/routes/(main)/downloads'), 'Desktop > Downloads'),- errorElement: <ErrorBoundary />,- handle: { meta: routeMeta({ icon: Download, titleKey: 'navigation.downloads' }) },- path: 'downloads',+ element: redirectElement('/settings/profile'),+ index: true,},-- // Settings routes (personal-only β never mirrored under /:workspaceSlug)+ // Provider routes with nested structure{children: [{- element: redirectElement('/settings/profile'),+ element: redirectElement('/settings/provider/all'),index: true,},- // Provider routes with nested structure{- children: [- {- element: redirectElement('/settings/provider/all'),- index: true,- },- {- element: dynamicElement(- () =>- import('@/routes/(main)/settings/provider').then((m) => m.ProviderDetailPage),- 'Desktop > Settings > Provider > Detail',- ),- handle: {- meta: routeMeta({ icon: Settings, titleKey: 'navigation.provider' }),- },- path: ':providerId',- },- ],element: dynamicElement(- () => import('@/routes/(main)/settings/provider').then((m) => m.ProviderLayout),- 'Desktop > Settings > Provider > Layout',+ () => import('@/routes/(main)/settings/provider').then((m) => m.ProviderDetailPage),+ 'Desktop > Settings > Provider > Detail',),handle: {meta: routeMeta({ icon: Settings, titleKey: 'navigation.provider' }),},- path: 'provider',- },- {- element: dynamicElement(- () => import('@/routes/(main)/settings'),- 'Desktop > Settings > Memory',- ),- handle: { settingsTab: SettingsTabs.Memory },- path: 'memory',+ path: ':providerId',},+ ],+ element: dynamicElement(+ () => import('@/routes/(main)/settings/provider').then((m) => m.ProviderLayout),+ 'Desktop > Settings > Provider > Layout',+ ),+ handle: {+ meta: routeMeta({ icon: Settings, titleKey: 'navigation.provider' }),+ },+ path: 'provider',+ },+ {+ element: dynamicElement(+ () => import('@/routes/(main)/settings'),+ 'Desktop > Settings > Memory',+ ),+ handle: { settingsTab: SettingsTabs.Memory },+ path: 'memory',+ },+ {+ element: redirectElement('/settings/credential'),+ path: 'creds',+ },+ // Other settings tabs+ {+ element: dynamicElement(+ () => import('@/routes/(main)/settings'),+ 'Desktop > Settings > Tab',+ ),+ handle: { meta: settingsRouteMeta },+ path: ':tab',+ },+ // Tabs that need a sub-segment (e.g. /settings/messenger/discord) reuse+ // the same tab page; nested feature components read `:sub` via useParams.+ {+ element: dynamicElement(+ () => import('@/routes/(main)/settings'),+ 'Desktop > Settings > Tab > Sub',+ ),+ handle: { meta: settingsRouteMeta },+ path: ':tab/:sub',+ },+ ],+ element: dynamicElement(+ () => import('@/routes/(main)/settings/_layout'),+ 'Desktop > Settings > Layout',+ ),+ errorElement: <ErrorBoundary />,+ path: 'settings',+ },++ // Workspace slug routes β `/:workspaceSlug/*` mirrors the shared main area.+ // Must come AFTER all reserved root paths so they don't shadow e.g. /agent.+ {+ children: [+ // Workspace home β handled by the persistent `DesktopHomeLayout` at+ // the outer main layout (mirrors how `/` index is empty here). Adding+ // an element would render Home twice on top of `DesktopHomeLayout`.+ {+ handle: { meta: workspaceHomeRouteMeta },+ index: true,+ },+ ...sharedMainAreaChildren,+ // Workspace settings β `/:slug/settings/*`. Dedicated layout with its+ // own sidebar (workspace avatar + 6 tabs + back-to-chat), fully+ // decoupled from personal `/settings/*`.+ {+ children: [{- element: redirectElement('/settings/credential'),- path: 'creds',+ element: redirectElement('general'),+ index: true,},- // Other settings tabs+ // Full-bleed tabs render directly inside the workspace settings+ // shell (sidebar + outlet) β they own their internal layout.{element: dynamicElement(- () => import('@/routes/(main)/settings'),- 'Desktop > Settings > Tab',+ () => import('@/routes/(main)/[workspaceSlug]/settings/provider'),+ 'Desktop > Workspace > Settings > Provider',),- handle: { meta: settingsRouteMeta },- path: ':tab',+ path: 'provider',},- // Tabs that need a sub-segment (e.g. /settings/messenger/discord) reuse- // the same tab page; nested feature components read `:sub` via useParams.{element: dynamicElement(- () => import('@/routes/(main)/settings'),- 'Desktop > Settings > Tab > Sub',+ () => import('@/routes/(main)/[workspaceSlug]/settings/skill'),+ 'Desktop > Workspace > Settings > Skill',),- handle: { meta: settingsRouteMeta },- path: ':tab/:sub',+ path: 'skill',},- ],- element: dynamicElement(- () => import('@/routes/(main)/settings/_layout'),- 'Desktop > Settings > Layout',- ),- errorElement: <ErrorBoundary />,- path: 'settings',- },-- // Workspace slug routes β `/:workspaceSlug/*` mirrors the shared main area.- // Must come AFTER all reserved root paths so they don't shadow e.g. /agent.- {- children: [- // Workspace home β handled by the persistent `DesktopHomeLayout` at- // the outer main layout (mirrors how `/` index is empty here). Adding- // an element would render Home twice on top of `DesktopHomeLayout`.{- handle: { meta: workspaceHomeRouteMeta },- index: true,+ element: dynamicElement(+ () => import('@/routes/(main)/[workspaceSlug]/settings/connector'),+ 'Desktop > Workspace > Settings > Connector',+ ),+ path: 'connector',},- ...sharedMainAreaChildren,- // Workspace settings β `/:slug/settings/*`. Dedicated layout with its- // own sidebar (workspace avatar + 6 tabs + back-to-chat), fully- // decoupled from personal `/settings/*`.+ // Padded tabs share a centered, max-width container layout.{children: [{- element: redirectElement('general'),- index: true,+ element: dynamicElement(+ () => import('@/routes/(main)/[workspaceSlug]/settings/general'),+ 'Desktop > Workspace > Settings > General',+ ),+ path: 'general',+ },+ {+ element: dynamicElement(+ () => import('@/routes/(main)/[workspaceSlug]/settings/members'),+ 'Desktop > Workspace > Settings > Members',+ ),+ path: 'members',+ },+ {+ element: dynamicElement(+ () => import('@/routes/(main)/[workspaceSlug]/settings/notification'),+ 'Desktop > Workspace > Settings > Notification',+ ),+ path: 'notification',+ },+ {+ element: dynamicElement(+ () => import('@/routes/(main)/[workspaceSlug]/settings/stats'),+ 'Desktop > Workspace > Settings > Stats',+ ),+ path: 'stats',+ },+ {+ element: dynamicElement(+ () => import('@/routes/(main)/[workspaceSlug]/settings/plans'),+ 'Desktop > Workspace > Settings > Plans',+ ),+ path: 'plans',+ },+ {+ element: dynamicElement(+ () => import('@/routes/(main)/[workspaceSlug]/settings/billing'),+ 'Desktop > Workspace > Settings > Billing',+ ),+ path: 'billing',+ },+ {+ element: dynamicElement(+ () => import('@/routes/(main)/[workspaceSlug]/settings/credits'),+ 'Desktop > Workspace > Settings > Credits',+ ),+ path: 'credits',+ },+ {+ element: dynamicElement(+ () => import('@/routes/(main)/[workspaceSlug]/settings/usage'),+ 'Desktop > Workspace > Settings > Usage',+ ),+ path: 'usage',+ },+ {+ element: dynamicElement(+ () => import('@/routes/(main)/[workspaceSlug]/settings/service-model'),+ 'Desktop > Workspace > Settings > Service Model',+ ),+ path: 'service-model',+ },+ {+ element: dynamicElement(+ () => import('@/routes/(main)/[workspaceSlug]/settings/credential'),+ 'Desktop > Workspace > Settings > Credential',+ ),+ path: 'credential',+ },+ // Legacy `/:slug/settings/creds` URLs β kept for deep-links.+ {+ element: redirectElement('../credential'),+ path: 'creds',+ },+ {+ element: dynamicElement(+ () => import('@/routes/(main)/[workspaceSlug]/settings/apikey'),+ 'Desktop > Workspace > Settings > API Key',+ ),+ path: 'apikey',},- // Full-bleed tabs render directly inside the workspace settings- // shell (sidebar + outlet) β they own their internal layout.{element: dynamicElement(- () => import('@/routes/(main)/[workspaceSlug]/settings/provider'),- 'Desktop > Workspace > Settings > Provider',+ () => import('@/routes/(main)/[workspaceSlug]/settings/oauth-apps'),+ 'Desktop > Workspace > Settings > OAuth Apps',),- path: 'provider',+ path: 'oauth-apps',},{element: dynamicElement(- () => import('@/routes/(main)/[workspaceSlug]/settings/skill'),- 'Desktop > Workspace > Settings > Skill',+ () => import('@/routes/(main)/[workspaceSlug]/settings/oauth-apps'),+ 'Desktop > Workspace > Settings > OAuth App Detail',),- path: 'skill',+ path: 'oauth-apps/:sub',},{element: dynamicElement(- () => import('@/routes/(main)/[workspaceSlug]/settings/connector'),- 'Desktop > Workspace > Settings > Connector',+ () => import('@/routes/(main)/[workspaceSlug]/settings/audit-log'),+ 'Desktop > Workspace > Settings > Audit Log',),- path: 'connector',+ path: 'audit-log',},- // Padded tabs share a centered, max-width container layout.{- children: [- {- element: dynamicElement(- () => import('@/routes/(main)/[workspaceSlug]/settings/general'),- 'Desktop > Workspace > Settings > General',- ),- path: 'general',- },- {- element: dynamicElement(- () => import('@/routes/(main)/[workspaceSlug]/settings/members'),- 'Desktop > Workspace > Settings > Members',- ),- path: 'members',- },- {- element: dynamicElement(- () => import('@/routes/(main)/[workspaceSlug]/settings/notification'),- 'Desktop > Workspace > Settings > Notification',- ),- path: 'notification',- },- {- element: dynamicElement(- () => import('@/routes/(main)/[workspaceSlug]/settings/stats'),- 'Desktop > Workspace > Settings > Stats',- ),- path: 'stats',- },- {- element: dynamicElement(- () => import('@/routes/(main)/[workspaceSlug]/settings/plans'),- 'Desktop > Workspace > Settings > Plans',- ),- path: 'plans',- },- {- element: dynamicElement(- () => import('@/routes/(main)/[workspaceSlug]/settings/billing'),- 'Desktop > Workspace > Settings > Billing',- ),- path: 'billing',- },- {- element: dynamicElement(- () => import('@/routes/(main)/[workspaceSlug]/settings/credits'),- 'Desktop > Workspace > Settings > Credits',- ),- path: 'credits',- },- {- element: dynamicElement(- () => import('@/routes/(main)/[workspaceSlug]/settings/usage'),- 'Desktop > Workspace > Settings > Usage',- ),- path: 'usage',- },- {- element: dynamicElement(- () => import('@/routes/(main)/[workspaceSlug]/settings/service-model'),- 'Desktop > Workspace > Settings > Service Model',- ),- path: 'service-model',- },- {- element: dynamicElement(- () => import('@/routes/(main)/[workspaceSlug]/settings/credential'),- 'Desktop > Workspace > Settings > Credential',- ),- path: 'credential',- },- // Legacy `/:slug/settings/creds` URLs β kept for deep-links.- {- element: redirectElement('../credential'),- path: 'creds',- },- {- element: dynamicElement(- () => import('@/routes/(main)/[workspaceSlug]/settings/apikey'),- 'Desktop > Workspace > Settings > API Key',- ),- path: 'apikey',- },- {- element: dynamicElement(- () => import('@/routes/(main)/[workspaceSlug]/settings/oauth-apps'),- 'Desktop > Workspace > Settings > OAuth Apps',- ),- path: 'oauth-apps',- },- {- element: dynamicElement(- () => import('@/routes/(main)/[workspaceSlug]/settings/oauth-apps'),- 'Desktop > Workspace > Settings > OAuth App Detail',- ),- path: 'oauth-apps/:sub',- },- {- element: dynamicElement(- () => import('@/routes/(main)/[workspaceSlug]/settings/audit-log'),- 'Desktop > Workspace > Settings > Audit Log',- ),- path: 'audit-log',- },- {- element: dynamicElement(- () => import('@/routes/(main)/[workspaceSlug]/settings/storage'),- 'Desktop > Workspace > Settings > Storage',- ),- path: 'storage',- },- {- element: dynamicElement(- () => import('@/routes/(main)/[workspaceSlug]/settings/devices'),- 'Desktop > Workspace > Settings > Devices',- ),- path: 'devices',- },- ],- element: dynamicLayout(- () => import('@/routes/(main)/[workspaceSlug]/settings/_content-layout'),- 'Desktop > Workspace > Settings > Content Layout',+ element: dynamicElement(+ () => import('@/routes/(main)/[workspaceSlug]/settings/storage'),+ 'Desktop > Workspace > Settings > Storage',+ ),+ path: 'storage',+ },+ {+ element: dynamicElement(+ () => import('@/routes/(main)/[workspaceSlug]/settings/devices'),+ 'Desktop > Workspace > Settings > Devices',),+ path: 'devices',},],element: dynamicLayout(- () => import('@/routes/(main)/[workspaceSlug]/settings/_layout'),- 'Desktop > Workspace > Settings > Layout',+ () => import('@/routes/(main)/[workspaceSlug]/settings/_content-layout'),+ 'Desktop > Workspace > Settings > Content Layout',),- errorElement: <ErrorBoundary />,- path: 'settings',- },- // Legacy `/:slug/billing/*` URLs β redirect to the corresponding- // `/:slug/settings/*` page. Kept for deep-links and bookmarks.- {- children: [- { element: redirectElement('../settings/plans'), path: 'plans' },- { element: redirectElement('../settings/usage'), path: 'usage' },- { element: redirectElement('../settings/credits'), path: 'credits' },- { element: redirectElement('../settings/billing'), path: 'billing' },- ],- path: 'billing',},],element: dynamicLayout(- () => import('@/routes/(main)/[workspaceSlug]/_layout'),- 'Desktop > Workspace > Layout',+ () => import('@/routes/(main)/[workspaceSlug]/settings/_layout'),+ 'Desktop > Workspace > Settings > Layout',),errorElement: <ErrorBoundary />,- path: ':workspaceSlug',- },-- // Default route - home page (handled by persistent layout)- {- handle: {- meta: routeMeta({ icon: Home, titleKey: 'navigation.home' }),- },- index: true,+ path: 'settings',},- // Catch-all route+ // Legacy `/:slug/billing/*` URLs β redirect to the corresponding+ // `/:slug/settings/*` page. Kept for deep-links and bookmarks.{- element: redirectElement('/'),- path: '*',+ children: [+ { element: redirectElement('../settings/plans'), path: 'plans' },+ { element: redirectElement('../settings/usage'), path: 'usage' },+ { element: redirectElement('../settings/credits'), path: 'credits' },+ { element: redirectElement('../settings/billing'), path: 'billing' },+ ],+ path: 'billing',},],+ element: dynamicLayout(+ () => import('@/routes/(main)/[workspaceSlug]/_layout'),+ 'Desktop > Workspace > Layout',+ ),+ errorElement: <ErrorBoundary />,+ path: ':workspaceSlug',+ },++ // Default route - home page (handled by persistent layout)+ {+ handle: {+ meta: routeMeta({ icon: Home, titleKey: 'navigation.home' }),+ },+ index: true,+ },+ // Catch-all route+ {+ element: redirectElement('/'),+ path: '*',+ },+];++// Meta-resolution route tree consumed by the desktop tab bar / recently-viewed+// panels. Twin-identical to the `.desktop` config so `matchRouteMeta` resolves+// every tab url's static meta on both the web and electron builds β the+// electron root router's `/` children are slim stubs with no meta, so the+// consumers must match against this populated tree, never `desktopRoutes`.+export const mainAreaMetaRoutes: RouteObject[] = [+ { children: createMainAreaChildren(), path: '/' },+];++// Desktop router configuration (declarative mode)+export const desktopRoutes: RouteObject[] = [+ {+ children: createMainAreaChildren(),element: dynamicLayout(() => import('@/routes/(main)/_layout'), 'Desktop > Main > Layout'),errorElement: <ErrorBoundary />,path: '/',diff --git a/src/spa/router/desktopRouter.meta.desktop.test.ts b/src/spa/router/desktopRouter.meta.desktop.test.tsnew file mode 100644index 00000000000..cd5cba76204--- /dev/null+++ b/src/spa/router/desktopRouter.meta.desktop.test.ts@@ -0,0 +1,35 @@+import { describe, expect, it } from 'vitest';++import { matchRouteMeta } from '@/features/Electron/titlebar/TabBar/resolveRouteMeta';++import { mainAreaMetaRoutes } from './desktopRouter.config.desktop';++// vitest does not apply the platformResolve vite plugin, so the electron twin+// must be imported by its explicit `.desktop` path. This guards Critical 1: the+// electron root router's `/` children are slim null stubs with zero meta, so a+// meta tree that aliased those stubs would silently degrade every tab title to+// brand and every icon to the Circle fallback on the packaged app.+describe('mainAreaMetaRoutes (electron twin)', () => {+ it('resolves a static settings meta from the electron build meta tree', () => {+ const { static: staticMeta } = matchRouteMeta(mainAreaMetaRoutes, '/settings/profile');++ expect(staticMeta.titleKey).toBeDefined();+ expect(staticMeta.icon).toBeDefined();+ });++ it('resolves a static agent meta and its DynamicMeta runner', () => {+ const matched = matchRouteMeta(mainAreaMetaRoutes, '/agent/agt_1');++ expect(matched.static.titleKey).toBe('navigation.chat');+ expect(matched.static.icon).toBeDefined();+ expect(matched.meta?.DynamicMeta).toBeDefined();+ expect(matched.params.aid).toBe('agt_1');+ });++ it('resolves meta for workspace-scoped tab urls', () => {+ const { static: staticMeta } = matchRouteMeta(mainAreaMetaRoutes, '/team-x/agent/agt_2');++ expect(staticMeta.titleKey).toBe('navigation.chat');+ expect(staticMeta.icon).toBeDefined();+ });+});diff --git a/src/spa/router/desktopRouter.sync.test.tsx b/src/spa/router/desktopRouter.sync.test.tsxindex d21b19c7a2c..71c0ad76668 100644--- a/src/spa/router/desktopRouter.sync.test.tsx+++ b/src/spa/router/desktopRouter.sync.test.tsx@@ -7,7 +7,7 @@ import { describe, expect, it } from 'vitest';import { WORKSPACE_SETTINGS_TABS } from '@/features/Workspace/workspaceAwarePath';-import { desktopRoutes } from './desktopRouter.config';+import { createMainAreaChildren, desktopRoutes } from './desktopRouter.config';/*** Known path pairs that intentionally differ between web and desktop (Electron).@@ -31,6 +31,14 @@ const WEB_ONLY_PATHS = new Set([/** Extra `index: true` routes present only on web. */const WEB_ONLY_INDEX_DELTA = 0;+/**+ * The Electron `/` route hosts only the TabHost shell; its children are two+ * slim stubs (`{ index }` + `{ path: '*' }`). The stub index route has no web+ * counterpart (web's `/` renders `createMainAreaChildren()` directly), so the+ * desktop config carries exactly one extra `index: true`.+ */+const DESKTOP_ROOT_STUB_INDEX_ROUTES = 1;+/** handle.meta blobs present only on web. */const WEB_ONLY_HANDLE_METAS = new Set<string>([]);@@ -115,7 +123,7 @@ describe('desktopRouter config sync', () => {expect(missingInSync, `Missing in desktop config: ${missingInSync.join(', ')}`).toEqual([]);expect(extraInSync, `Extra in desktop config: ${extraInSync.join(', ')}`).toEqual([]);expect(syncIndexCount, 'Desktop config index route count must match async config').toBe(- asyncIndexCount - WEB_ONLY_INDEX_DELTA,+ asyncIndexCount - WEB_ONLY_INDEX_DELTA + DESKTOP_ROOT_STUB_INDEX_ROUTES,);});@@ -135,6 +143,39 @@ describe('desktopRouter config sync', () => {);});+ it('electron `/` route children are the slim TabHost stubs', async () => {+ const [, syncSource] = await readDesktopRouterSources();+ const collapsed = syncSource.replaceAll(/\s+/g, ' ');++ expect(collapsed).toMatch(+ /children:\s*\[\s*\{\s*element:\s*null,\s*index:\s*true\s*\},\s*\{\s*element:\s*null,\s*path:\s*'\*'\s*\},?\s*\]/,+ );+ });++ it('index-element divergence: electron index routes render home, web index routes are element-less', async () => {+ const [asyncSource, syncSource] = await readDesktopRouterSources();+ const collapsedSync = syncSource.replaceAll(/\s+/g, ' ');++ // Electron builder mounts the home element on the root + workspace index routes.+ const homeElementMatches = [+ ...collapsedSync.matchAll(/<DesktopHomeLayout>\s*<DesktopHome \/>\s*<\/DesktopHomeLayout>/g),+ ];+ expect(homeElementMatches).toHaveLength(2);++ // Web builder never renders home via the router (it uses the always-mounted+ // sibling). Comments may mention the component name, so match the JSX element.+ expect(asyncSource).not.toContain('<DesktopHome');++ // Structural check: the web `createMainAreaChildren()` index routes carry no element.+ const webChildren = createMainAreaChildren();+ const webRootIndex = webChildren.find((route) => route.index);+ expect(webRootIndex?.element).toBeUndefined();++ const webWorkspace = webChildren.find((route) => route.path === ':workspaceSlug');+ const webWorkspaceIndex = webWorkspace?.children?.find((route) => route.index);+ expect(webWorkspaceIndex?.element).toBeUndefined();+ });+it('workspace settings tree is registered with all tabs in both configs', async () => {const [asyncSource, syncSource] = await readDesktopRouterSources();diff --git a/src/spa/router/tabRouter.test.ts b/src/spa/router/tabRouter.test.tsnew file mode 100644index 00000000000..bd5d160a08f--- /dev/null+++ b/src/spa/router/tabRouter.test.ts@@ -0,0 +1,72 @@+import { Children, type ReactElement, type ReactNode } from 'react';+import { describe, expect, it } from 'vitest';++import TabLocationReporter from '@/features/Electron/TabHost/TabLocationReporter';++import { createMainAreaChildren } from './desktopRouter.config';+import { createTabRouter } from './tabRouter';++const matchedPaths = (router: ReturnType<typeof createTabRouter>) =>+ router.state.matches.map((match) => match.route.path);++describe('createTabRouter', () => {+ it('matches the agent chat route for /agent/abc', () => {+ const router = createTabRouter('/agent/abc');+ const paths = matchedPaths(router);++ expect(router.state.location.pathname).toBe('/agent/abc');+ expect(paths).toContain('agent');+ expect(paths).toContain(':aid');+ });++ it('matches a nested agent route for /agent/abc/topics', () => {+ const paths = matchedPaths(createTabRouter('/agent/abc/topics'));++ expect(paths).toContain(':aid');+ expect(paths).toContain('topics');+ });++ it('matches the workspace-mirrored agent route for /my-team/agent/abc', () => {+ const paths = matchedPaths(createTabRouter('/my-team/agent/abc'));++ expect(paths).toContain(':workspaceSlug');+ expect(paths).toContain('agent');+ expect(paths).toContain(':aid');+ });++ it('matches the catch-all route for an unknown URL', () => {+ const paths = matchedPaths(createTabRouter('/definitely/not/a/route'));++ expect(paths.at(-1)).toBe('*');+ });++ it('still reports the location from the root error element, which replaces the layout', () => {+ const errorElement = createTabRouter('/').routes[0].errorElement as ReactElement;+ const children = Children.toArray(+ (errorElement.props as { children?: ReactNode }).children,+ ) as ReactElement[];++ expect(children.map((child) => child.type)).toContain(TabLocationReporter);+ });++ it('creates independent instances for different URLs', () => {+ const first = createTabRouter('/agent/abc');+ const second = createTabRouter('/image');++ expect(first.state.location.pathname).toBe('/agent/abc');+ expect(second.state.location.pathname).toBe('/image');+ expect(first.state.location.pathname).not.toBe(second.state.location.pathname);+ expect(matchedPaths(first)).toContain('agent');+ expect(matchedPaths(second)).toContain('image');+ });+});++describe('createMainAreaChildren', () => {+ it('returns a fresh array instance of the same length on each call', () => {+ const first = createMainAreaChildren();+ const second = createMainAreaChildren();++ expect(first).not.toBe(second);+ expect(first).toHaveLength(second.length);+ });+});diff --git a/src/spa/router/tabRouter.tsx b/src/spa/router/tabRouter.tsxnew file mode 100644index 00000000000..adc9e8be191--- /dev/null+++ b/src/spa/router/tabRouter.tsx@@ -0,0 +1,39 @@+'use client';++import { Suspense } from 'react';+import { createMemoryRouter, Outlet } from 'react-router';++import Loading from '@/components/Loading/BrandTextLoading';+import TabLocationReporter from '@/features/Electron/TabHost/TabLocationReporter';+import { ErrorBoundary } from '@/utils/router';++import { createMainAreaChildren } from './desktopRouter.config';++const TabRootLayout = () => (+ <Suspense fallback={<Loading debugId="TabRootLayout > Outlet" />}>+ <Outlet />+ <TabLocationReporter />+ </Suspense>+);++export const createTabRouter = (initialUrl: string) =>+ createMemoryRouter(+ [+ {+ children: createMainAreaChildren(),+ element: <TabRootLayout />,+ // The error element replaces `TabRootLayout`, so the reporter is repeated+ // here: the memory router has already advanced to the failing url, and+ // without a report the tab store and window url keep describing the+ // previous page (stale title, and Retry reloading the wrong route).+ errorElement: (+ <>+ <ErrorBoundary />+ <TabLocationReporter />+ </>+ ),+ path: '/',+ },+ ],+ { initialEntries: [initialUrl] },+ );diff --git a/src/store/electron/actions/__tests__/tabPages.test.ts b/src/store/electron/actions/__tests__/tabPages.test.tsindex 31751bea82d..bbe37249e61 100644--- a/src/store/electron/actions/__tests__/tabPages.test.ts+++ b/src/store/electron/actions/__tests__/tabPages.test.ts@@ -1,6 +1,9 @@import { act, renderHook } from '@testing-library/react';import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';+import { resolveLiveTabIds } from '@/features/Electron/TabHost/resolveLiveTabIds';+import { PERSONAL_TAB_SCOPE } from '@/features/Electron/titlebar/TabBar/scope';+import { getTabPages, saveTabPages } 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';@@ -30,6 +33,7 @@ const buildTab = (url: string, cached?: TabItem['cached']): TabItem => ({describe('tabPages actions', () => {beforeEach(() => {vi.clearAllMocks();+ window.localStorage.clear();useElectronStore.setState({ ...initialState, activeTabId: null, tabs: [] });});@@ -37,6 +41,65 @@ describe('tabPages actions', () => {vi.restoreAllMocks();});+ describe('activation refreshes LRU recency', () => {+ const visitedTab = (url: string, lastVisited: number): TabItem => ({+ ...buildTab(url),+ lastVisited,+ });++ it('keeps a tab activated without navigating alive after the user switches away', () => {+ const { result } = renderHook(() => useElectronStore());+ const oldest = visitedTab('/agent/a', 1);+ const middle = visitedTab('/agent/b', 2);+ const newest = visitedTab('/agent/c', 3);++ act(() => {+ useElectronStore.setState({ activeTabId: newest.id, tabs: [oldest, middle, newest] });+ });++ act(() => {+ result.current.activateTab(oldest.id);+ });+ act(() => {+ result.current.activateTab(newest.id);+ });++ expect(resolveLiveTabIds(result.current.tabs, newest.id, 2)).toEqual([oldest.id, newest.id]);+ });++ it('refreshes recency when addTab reuses an existing tab', () => {+ const { result } = renderHook(() => useElectronStore());+ const existing = visitedTab('/agent/a', 1);++ act(() => {+ useElectronStore.setState({ activeTabId: null, tabs: [existing] });+ });++ act(() => {+ result.current.addTab('/agent/a');+ });++ expect(result.current.tabs[0].lastVisited).toBeGreaterThan(existing.lastVisited);+ });++ it('refreshes recency on the tab promoted to active by a close', () => {+ const { result } = renderHook(() => useElectronStore());+ const closing = visitedTab('/agent/a', 1);+ const promoted = visitedTab('/agent/b', 2);++ act(() => {+ useElectronStore.setState({ activeTabId: closing.id, tabs: [closing, promoted] });+ });++ act(() => {+ result.current.removeTab(closing.id);+ });++ expect(result.current.activeTabId).toBe(promoted.id);+ expect(result.current.tabs[0].lastVisited).toBeGreaterThan(promoted.lastVisited);+ });+ });+describe('addTab', () => {it('creates a tab with a stable generated id and activates it', () => {const { result } = renderHook(() => useElectronStore());@@ -182,6 +245,153 @@ describe('tabPages actions', () => {});});+ describe('reportTabLocation', () => {+ it('rewrites the active tab url when the reported url stays in scope', () => {+ const { result } = renderHook(() => useElectronStore());+ const tab = buildTab('/agent/abc');++ act(() => {+ useElectronStore.setState({+ activeTabId: tab.id,+ activeTabScope: PERSONAL_TAB_SCOPE,+ tabs: [tab],+ });+ });++ act(() => {+ result.current.reportTabLocation(tab.id, '/agent/def');+ });++ expect(result.current.activeTabScope).toEqual({ type: 'personal' });+ expect(result.current.tabs).toHaveLength(1);+ expect(result.current.tabs[0].id).toBe(tab.id);+ expect(result.current.tabs[0].url).toBe('/agent/def');+ });++ it('swaps scope, keeps the navigating tab at its pre-nav url in the old scope, and activates a tab in the new scope', () => {+ const { result } = renderHook(() => useElectronStore());+ const personalTab = buildTab('/agent/abc');++ act(() => {+ useElectronStore.setState({+ activeTabId: personalTab.id,+ activeTabScope: PERSONAL_TAB_SCOPE,+ tabs: [personalTab],+ });+ });++ act(() => {+ result.current.reportTabLocation(personalTab.id, '/acme/agent/xyz');+ });++ expect(result.current.activeTabScope).toEqual({ slug: 'acme', type: 'workspace' });+ expect(result.current.tabs).toHaveLength(1);+ expect(result.current.tabs[0].url).toBe('/acme/agent/xyz');+ expect(result.current.activeTabId).toBe(result.current.tabs[0].id);++ const persistedPersonal = getTabPages(PERSONAL_TAB_SCOPE);+ expect(persistedPersonal.tabs.map((t) => t.url)).toEqual(['/agent/abc']);+ expect(persistedPersonal.activeTabId).toBe(personalTab.id);+ });++ it('reuses an existing tab in the target scope instead of duplicating it', () => {+ const { result } = renderHook(() => useElectronStore());+ const acmeScope = { slug: 'acme', type: 'workspace' } as const;+ const existing = buildTab('/acme/agent/xyz');+ saveTabPages(acmeScope, [existing], existing.id);++ const personalTab = buildTab('/agent/abc');+ act(() => {+ useElectronStore.setState({+ activeTabId: personalTab.id,+ activeTabScope: PERSONAL_TAB_SCOPE,+ tabs: [personalTab],+ });+ });++ act(() => {+ result.current.reportTabLocation(personalTab.id, '/acme/agent/xyz');+ });++ expect(result.current.activeTabScope).toEqual(acmeScope);+ expect(result.current.tabs).toHaveLength(1);+ expect(result.current.tabs[0].id).toBe(existing.id);+ expect(result.current.activeTabId).toBe(existing.id);+ });++ it('does nothing when the reported tab id is not found', () => {+ const { result } = renderHook(() => useElectronStore());+ const tab = buildTab('/agent/abc');++ act(() => {+ useElectronStore.setState({+ activeTabId: tab.id,+ activeTabScope: PERSONAL_TAB_SCOPE,+ tabs: [tab],+ });+ });++ act(() => {+ result.current.reportTabLocation('non-existent', '/acme/agent/xyz');+ });++ expect(result.current.activeTabScope).toEqual({ type: 'personal' });+ expect(result.current.tabs).toEqual([tab]);+ });+ });++ describe('snapshotTabLocation', () => {+ it('persists a fragment-only move so an evicted tab cold-restores at its anchor', () => {+ const { result } = renderHook(() => useElectronStore());+ const settingsTab = buildTab('/settings/agent', { title: 'Settings' });++ act(() => {+ useElectronStore.setState({ activeTabId: settingsTab.id, tabs: [settingsTab] });+ });++ act(() => {+ result.current.snapshotTabLocation(settingsTab.id, '/settings/agent#llm');+ });++ expect(result.current.tabs[0].url).toBe('/settings/agent#llm');+ expect(result.current.tabs[0].cached).toEqual({ title: 'Settings' });+ expect(result.current.tabs[0].lastVisited).toBe(settingsTab.lastVisited);+ });++ it('drops cached data when the snapshot lands on a different page', () => {+ const { result } = renderHook(() => useElectronStore());+ const agentTab = buildTab('/agent/abc', { title: 'Claude Code' });++ act(() => {+ useElectronStore.setState({ activeTabId: agentTab.id, tabs: [agentTab] });+ });++ act(() => {+ result.current.snapshotTabLocation(agentTab.id, '/memory');+ });++ expect(result.current.tabs[0].url).toBe('/memory');+ expect(result.current.tabs[0].cached).toBeUndefined();+ });++ it('does nothing when the snapshot repeats the stored url', () => {+ const { result } = renderHook(() => useElectronStore());+ const agentTab = buildTab('/agent/abc', { title: 'Claude Code' });++ act(() => {+ useElectronStore.setState({ activeTabId: agentTab.id, tabs: [agentTab] });+ });++ const before = result.current.tabs;++ act(() => {+ result.current.snapshotTabLocation(agentTab.id, '/agent/abc');+ });++ expect(result.current.tabs).toBe(before);+ });+ });+describe('updateTabCache (guarded merge)', () => {it('skips undefined and empty-string fields, never clobbering a good value', () => {const { result } = renderHook(() => useElectronStore());diff --git a/src/store/electron/actions/currentRouteMeta.ts b/src/store/electron/actions/currentRouteMeta.tsnew file mode 100644index 00000000000..5c39dfb5a29--- /dev/null+++ b/src/store/electron/actions/currentRouteMeta.ts@@ -0,0 +1,59 @@+import { type DynamicRouteMeta } from '@/spa/router/routeMeta';+import { type StoreSetter } from '@/store/types';++import { type ElectronStore } from '../store';++// ======== Types ======== //++// Live resolved meta of the active route, published by RouteMetaBridge; the url+// is the one that produced it (used to match the meta against the active tab).+export interface CurrentRouteMetaState {+ currentRouteMeta: DynamicRouteMeta | null;+ currentRouteMetaUrl: string | null;+}++// ======== Initial State ======== //++export const currentRouteMetaInitialState: CurrentRouteMetaState = {+ currentRouteMeta: null,+ currentRouteMetaUrl: null,+};++// ======== Action Implementation ======== //++type Setter = StoreSetter<ElectronStore>;+export const createCurrentRouteMetaSlice = (+ set: Setter,+ get: () => ElectronStore,+ _api?: unknown,+) => new CurrentRouteMetaActionImpl(set, get, _api);++export class CurrentRouteMetaActionImpl {+ readonly #get: () => ElectronStore;+ readonly #set: Setter;++ constructor(set: Setter, get: () => ElectronStore, _api?: unknown) {+ void _api;+ this.#set = set;+ this.#get = get;+ }++ setCurrentRouteMeta = (meta: DynamicRouteMeta | null, url: string | null = null): void => {+ const { currentRouteMeta, currentRouteMetaUrl } = this.#get();+ if (+ currentRouteMetaUrl === url &&+ (currentRouteMeta === null) === (meta === null) &&+ currentRouteMeta?.avatar === meta?.avatar &&+ currentRouteMeta?.backgroundColor === meta?.backgroundColor &&+ currentRouteMeta?.title === meta?.title+ ) {+ return;+ }+ this.#set({ currentRouteMeta: meta, currentRouteMetaUrl: url }, false, 'setCurrentRouteMeta');+ };+}++export type CurrentRouteMetaAction = Pick<+ CurrentRouteMetaActionImpl,+ keyof CurrentRouteMetaActionImpl+>;diff --git a/src/store/electron/actions/navigationHistory.ts b/src/store/electron/actions/navigationHistory.tsdeleted file mode 100644index 7b7418a76f0..00000000000--- a/src/store/electron/actions/navigationHistory.ts+++ /dev/null@@ -1,228 +0,0 @@-import { type DynamicRouteMeta } from '@/spa/router/routeMeta';-import { type StoreSetter } from '@/store/types';--import { type ElectronStore } from '../store';--// ======== Types ======== //--export interface HistoryEntry {- icon?: string;- metadata?: {- [key: string]: any;- sessionId?: string;- timestamp: number;- };- title: string;- url: string;-}--export interface NavigationHistoryState {- /**- * Live resolved meta of the active route, published by RouteMetaBridge- */- currentRouteMeta: DynamicRouteMeta | null;- /**- * URL that produced currentRouteMeta.- */- currentRouteMetaUrl: string | null;- /**- * Current position in history (-1 means empty)- */- historyCurrentIndex: number;- /**- * History entries list- */- historyEntries: HistoryEntry[];- /**- * Flag to indicate if currently navigating via back/forward- * Used to prevent adding duplicate history entries- */- isNavigatingHistory: boolean;-}--// ======== Action Interface ======== //--// ======== Initial State ======== //--export const navigationHistoryInitialState: NavigationHistoryState = {- currentRouteMeta: null,- currentRouteMetaUrl: null,- historyCurrentIndex: -1,- historyEntries: [],- isNavigatingHistory: false,-};--// ======== Action Implementation ======== //--type Setter = StoreSetter<ElectronStore>;-export const createNavigationHistorySlice = (- set: Setter,- get: () => ElectronStore,- _api?: unknown,-) => new NavigationHistoryActionImpl(set, get, _api);--export class NavigationHistoryActionImpl {- readonly #get: () => ElectronStore;- readonly #set: Setter;-- constructor(set: Setter, get: () => ElectronStore, _api?: unknown) {- void _api;- this.#set = set;- this.#get = get;- }-- canGoBack = (): boolean => {- const { historyCurrentIndex } = this.#get();- return historyCurrentIndex > 0;- };-- canGoForward = (): boolean => {- const { historyCurrentIndex, historyEntries } = this.#get();- return historyCurrentIndex < historyEntries.length - 1;- };-- getCurrentEntry = (): HistoryEntry | null => {- const { historyCurrentIndex, historyEntries } = this.#get();- if (historyCurrentIndex < 0 || historyCurrentIndex >= historyEntries.length) {- return null;- }- return historyEntries[historyCurrentIndex];- };-- goBack = (): HistoryEntry | null => {- const { historyCurrentIndex, historyEntries } = this.#get();-- if (historyCurrentIndex <= 0) {- return null;- }-- const newIndex = historyCurrentIndex - 1;- const targetEntry = historyEntries[newIndex];-- this.#set(- {- historyCurrentIndex: newIndex,- isNavigatingHistory: true,- },- false,- 'goBack',- );-- return targetEntry;- };-- goForward = (): HistoryEntry | null => {- const { historyCurrentIndex, historyEntries } = this.#get();-- if (historyCurrentIndex >= historyEntries.length - 1) {- return null;- }-- const newIndex = historyCurrentIndex + 1;- const targetEntry = historyEntries[newIndex];-- this.#set(- {- historyCurrentIndex: newIndex,- isNavigatingHistory: true,- },- false,- 'goForward',- );-- return targetEntry;- };-- pushHistory = (- entry: Omit<HistoryEntry, 'metadata'> & { metadata?: Partial<HistoryEntry['metadata']> },- ): void => {- const { historyCurrentIndex, historyEntries } = this.#get();-- // Create full entry with metadata- const fullEntry: HistoryEntry = {- icon: entry.icon,- metadata: {- timestamp: Date.now(),- ...entry.metadata,- },- title: entry.title,- url: entry.url,- };-- // If not at the end, truncate forward history- const newEntries =- historyCurrentIndex < historyEntries.length - 1- ? historyEntries.slice(0, historyCurrentIndex + 1)- : [...historyEntries];-- // Add new entry- newEntries.push(fullEntry);-- this.#set(- {- historyCurrentIndex: newEntries.length - 1,- historyEntries: newEntries,- },- false,- 'pushHistory',- );- };-- replaceHistory = (- entry: Omit<HistoryEntry, 'metadata'> & { metadata?: Partial<HistoryEntry['metadata']> },- ): void => {- const { historyCurrentIndex, historyEntries } = this.#get();-- // If history is empty, just push- if (historyCurrentIndex < 0 || historyEntries.length === 0) {- this.#get().pushHistory(entry);- return;- }-- // Create full entry with metadata- const fullEntry: HistoryEntry = {- icon: entry.icon,- metadata: {- timestamp: Date.now(),- ...entry.metadata,- },- title: entry.title,- url: entry.url,- };-- // Replace current entry- const newEntries = [...historyEntries];- newEntries[historyCurrentIndex] = fullEntry;-- this.#set(- {- historyEntries: newEntries,- },- false,- 'replaceHistory',- );- };-- setCurrentRouteMeta = (meta: DynamicRouteMeta | null, url: string | null = null): void => {- const { currentRouteMeta, currentRouteMetaUrl } = this.#get();- if (- currentRouteMetaUrl === url &&- (currentRouteMeta === null) === (meta === null) &&- currentRouteMeta?.avatar === meta?.avatar &&- currentRouteMeta?.backgroundColor === meta?.backgroundColor &&- currentRouteMeta?.title === meta?.title- ) {- return;- }- this.#set({ currentRouteMeta: meta, currentRouteMetaUrl: url }, false, 'setCurrentRouteMeta');- };-- setIsNavigatingHistory = (value: boolean): void => {- this.#set({ isNavigatingHistory: value }, false, 'setIsNavigatingHistory');- };-}--export type NavigationHistoryAction = Pick<- NavigationHistoryActionImpl,- keyof NavigationHistoryActionImpl->;diff --git a/src/store/electron/actions/tabPages.ts b/src/store/electron/actions/tabPages.tsindex 98b95a7c5eb..d5d1f163dee 100644--- a/src/store/electron/actions/tabPages.ts+++ b/src/store/electron/actions/tabPages.ts@@ -1,6 +1,7 @@import { nanoid } from 'nanoid';import { guardedMergeCache } from '@/features/Electron/titlebar/TabBar/resolveRouteMeta';+import { resolveTabUpdate } from '@/features/Electron/titlebar/TabBar/resolveTabUpdate';import {isSameTabTarget,PERSONAL_TAB_SCOPE,@@ -54,7 +55,7 @@ export class TabPagesActionImpl {const { tabs } = this.#get();if (!tabs.some((t) => t.id === id)) return;- this.#set({ activeTabId: id }, false, 'activateTab');+ this.#set({ activeTabId: id, tabs: this.#touch(tabs, id) }, false, 'activateTab');this.#persist();};@@ -65,7 +66,11 @@ export class TabPagesActionImpl {if (existing) {if (activate) {- this.#set({ activeTabId: existing.id }, false, 'activateExistingTab');+ this.#set(+ { activeTabId: existing.id, tabs: this.#touch(tabs, existing.id) },+ false,+ 'activateExistingTab',+ );this.#persist();}return existing.id;@@ -107,7 +112,11 @@ export class TabPagesActionImpl {}}- this.#set({ activeTabId: newActiveId, tabs: newTabs }, false, 'removeTab');+ this.#set(+ { activeTabId: newActiveId, tabs: this.#touch(newTabs, newActiveId) },+ false,+ 'removeTab',+ );this.#persist();return newActiveId;@@ -121,7 +130,11 @@ export class TabPagesActionImpl {const newTabs = tabs.slice(index);const newActiveId = newTabs.some((t) => t.id === activeTabId) ? activeTabId : id;- this.#set({ activeTabId: newActiveId, tabs: newTabs }, false, 'closeLeftTabs');+ this.#set(+ { activeTabId: newActiveId, tabs: this.#touch(newTabs, newActiveId) },+ false,+ 'closeLeftTabs',+ );this.#persist();};@@ -130,7 +143,7 @@ export class TabPagesActionImpl {const target = tabs.find((t) => t.id === id);if (!target) return;- this.#set({ activeTabId: id, tabs: [target] }, false, 'closeOtherTabs');+ this.#set({ activeTabId: id, tabs: this.#touch([target], id) }, false, 'closeOtherTabs');this.#persist();};@@ -142,7 +155,11 @@ export class TabPagesActionImpl {const newTabs = tabs.slice(0, index + 1);const newActiveId = newTabs.some((t) => t.id === activeTabId) ? activeTabId : id;- this.#set({ activeTabId: newActiveId, tabs: newTabs }, false, 'closeRightTabs');+ this.#set(+ { activeTabId: newActiveId, tabs: this.#touch(newTabs, newActiveId) },+ false,+ 'closeRightTabs',+ );this.#persist();};@@ -180,6 +197,41 @@ export class TabPagesActionImpl {return id;};+ // Routerβstore snapshot taken by TabHost right before a hidden tab's router is+ // LRU-evicted: a pinned navigation into a hidden tab moves its router but the+ // hidden reporter can't fire, so persist the latest location for cold restore.+ // `lastVisited` is intentionally preserved so the snapshot doesn't reshuffle+ // the LRU ranking (which would re-promote the just-evicted tab).+ snapshotTabLocation = (id: string, url: string): void => {+ const { tabs } = this.#get();+ const index = tabs.findIndex((t) => t.id === id);+ if (index < 0) return;++ const prev = tabs[index];+ if (url === prev.url) return;++ const sameTarget = normalizeTabUrl(url) === normalizeTabUrl(prev.url);++ const newTabs = [...tabs];+ newTabs[index] = { ...prev, cached: sameTarget ? prev.cached : undefined, url };++ this.#set({ tabs: newTabs }, false, 'snapshotTabLocation');+ this.#persist();+ };++ reportTabLocation = (id: string, url: string): void => {+ const { activeTabScope, tabs } = this.#get();+ if (!tabs.some((t) => t.id === id)) return;++ const action = resolveTabUpdate(activeTabScope, url);+ if (action.type === 'scope-swap') {+ this.#swapScope(action.scope, action.url);+ return;+ }++ this.updateTab(id, url);+ };+updateTabCache = (id: string, cached: DynamicRouteMeta): void => {const { tabs } = this.#get();const index = tabs.findIndex((t) => t.id === id);@@ -195,6 +247,20 @@ export class TabPagesActionImpl {this.#persist();};+ // Every path that makes a tab active must refresh its `lastVisited`: TabHost+ // ranks keep-alive routers by that timestamp, so a tab activated without a+ // navigation would stay at its stale recency and get its router disposed (and+ // its in-page state lost) the moment the user switches away again.+ #touch = (tabs: TabItem[], id: string | null): TabItem[] => {+ if (!id) return tabs;+ const index = tabs.findIndex((t) => t.id === id);+ if (index < 0) return tabs;++ const newTabs = [...tabs];+ newTabs[index] = { ...newTabs[index], lastVisited: Date.now() };+ return newTabs;+ };+#createTab = (url: string, cached: DynamicRouteMeta | undefined, activate: boolean): string => {const { tabs, activeTabId } = this.#get();const id = generateTabId();@@ -214,6 +280,17 @@ export class TabPagesActionImpl {return id;};+ // Cross-scope in-tab navigation reported by TabLocationReporter: persist the+ // old scope with the navigating tab still at its pre-nav url (it stays in the+ // old window), load the target scope, then find-or-add + activate a tab there.+ // TabHost disposes the old-scope routers once `tabs` swaps (one-way; no router+ // is ever navigated from here).+ #swapScope = (scope: TabScope, url: string): void => {+ this.#persist();+ this.#loadScope(scope, true);+ this.addTab(url);+ };+#persist = (): void => {const { activeTabScope, tabs, activeTabId } = this.#get();saveTabPages(activeTabScope, tabs, activeTabId);diff --git a/src/store/electron/initialState.ts b/src/store/electron/initialState.tsindex 3e049b75546..00e8f2a88e1 100644--- a/src/store/electron/initialState.ts+++ b/src/store/electron/initialState.ts@@ -5,9 +5,9 @@ import {type NetworkProxySettings,} from '@lobechat/electron-client-ipc';+import { type CurrentRouteMetaState } from './actions/currentRouteMeta';+import { currentRouteMetaInitialState } from './actions/currentRouteMeta';import { type GatewayDeviceInfo } from './actions/gateway';-import { type NavigationHistoryState } from './actions/navigationHistory';-import { navigationHistoryInitialState } from './actions/navigationHistory';import { type RecentPagesState } from './actions/recentPages';import { recentPagesInitialState } from './actions/recentPages';import { type TabPagesState } from './actions/tabPages';@@ -24,7 +24,7 @@ export const defaultProxySettings: NetworkProxySettings = {proxyType: 'http',};-export interface ElectronState extends NavigationHistoryState, RecentPagesState, TabPagesState {+export interface ElectronState extends CurrentRouteMetaState, RecentPagesState, TabPagesState {appState: ElectronAppState;appTrayVisible: boolean;dataSyncConfig: DataSyncConfig;@@ -42,7 +42,7 @@ export interface ElectronState extends NavigationHistoryState, RecentPagesState,}export const initialState: ElectronState = {- ...navigationHistoryInitialState,+ ...currentRouteMetaInitialState,...recentPagesInitialState,...tabPagesInitialState,appState: {},diff --git a/src/store/electron/store.ts b/src/store/electron/store.tsindex 1b9d0aa5139..c53d59efd6c 100644--- a/src/store/electron/store.ts+++ b/src/store/electron/store.ts@@ -7,10 +7,10 @@ import { expose } from '../middleware/expose';import { flattenActions } from '../utils/flattenActions';import { type ElectronAppAction } from './actions/app';import { createElectronAppSlice } from './actions/app';+import { type CurrentRouteMetaAction } from './actions/currentRouteMeta';+import { createCurrentRouteMetaSlice } from './actions/currentRouteMeta';import { type ElectronGatewayAction } from './actions/gateway';import { gatewaySlice } from './actions/gateway';-import { type NavigationHistoryAction } from './actions/navigationHistory';-import { createNavigationHistorySlice } from './actions/navigationHistory';import { type RecentPagesAction } from './actions/recentPages';import { createRecentPagesSlice } from './actions/recentPages';import { type ElectronSettingsAction } from './actions/settings';@@ -31,7 +31,7 @@ export interface ElectronStoreElectronAppAction,ElectronGatewayAction,ElectronSettingsAction,- NavigationHistoryAction,+ CurrentRouteMetaAction,RecentPagesAction,TabPagesAction {/* empty */@@ -41,7 +41,7 @@ type ElectronStoreAction = ElectronRemoteServerAction &ElectronAppAction &ElectronGatewayAction &ElectronSettingsAction &- NavigationHistoryAction &+ CurrentRouteMetaAction &RecentPagesAction &TabPagesAction;@@ -54,7 +54,7 @@ const createStore: StateCreator<ElectronStore, [['zustand/devtools', never]]> =createElectronAppSlice(...parameters),gatewaySlice(...parameters),settingsSlice(...parameters),- createNavigationHistorySlice(...parameters),+ createCurrentRouteMetaSlice(...parameters),createRecentPagesSlice(...parameters),createTabPagesSlice(...parameters),]),diff --git a/src/utils/NavigatorRegistrar.desktop.tsx b/src/utils/NavigatorRegistrar.desktop.tsxnew file mode 100644index 00000000000..7f7a6bc70d4--- /dev/null+++ b/src/utils/NavigatorRegistrar.desktop.tsx@@ -0,0 +1,35 @@+'use client';++import { memo, useLayoutEffect } from 'react';+import { type NavigateFunction, type NavigateOptions, type To } from 'react-router';++import {+ navigateActiveTab,+ navigateActiveTabByDelta,+} from '@/features/Electron/navigation/activeTabNavigate';+import { appNavigate } from '@/features/Electron/navigation/appNavigate';+import { useGlobalStore } from '@/store/global';+import { createNavigationRef } from '@/store/global/initialState';++// The root router is frozen on desktop, so point the global navigate ref at the+// active tab. Global-ref callers (`stableWorkspaceAwareNavigate`,+// `useStableNavigate`) resolve their own paths, so pass `escape` to route+// through `appNavigate` without re-applying the workspace prefix.+const activeTabNavigate: NavigateFunction = ((to: To | number, options?: NavigateOptions) => {+ if (typeof to === 'number') return navigateActiveTabByDelta(to);+ if (typeof to !== 'string') return navigateActiveTab(to, options);+ return appNavigate(to, { ...options, escape: true });+}) as NavigateFunction;++export const NavigatorRegistrar = memo(() => {+ useLayoutEffect(() => {+ useGlobalStore.setState({ navigationRef: { current: activeTabNavigate } });+ return () => {+ useGlobalStore.setState({ navigationRef: createNavigationRef() });+ };+ }, []);++ return null;+});++NavigatorRegistrar.displayName = 'NavigatorRegistrar';diff --git a/src/utils/NavigatorRegistrar.tsx b/src/utils/NavigatorRegistrar.tsxnew file mode 100644index 00000000000..7e7779f86e8--- /dev/null+++ b/src/utils/NavigatorRegistrar.tsx@@ -0,0 +1,24 @@+'use client';++import { memo, useLayoutEffect } from 'react';+import { useNavigate } from 'react-router';++import { useGlobalStore } from '@/store/global';+import { createNavigationRef } from '@/store/global/initialState';++// Syncs React Router's `navigate` into `navigationRef` so imperative navigation+// (see `getStableNavigate` / `useStableNavigate`) works outside the React tree.+export const NavigatorRegistrar = memo(() => {+ const navigate = useNavigate();++ useLayoutEffect(() => {+ useGlobalStore.setState({ navigationRef: { current: navigate } });+ return () => {+ useGlobalStore.setState({ navigationRef: createNavigationRef() });+ };+ }, [navigate]);++ return null;+});++NavigatorRegistrar.displayName = 'NavigatorRegistrar';diff --git a/src/utils/router.tsx b/src/utils/router.tsxindex 5c426270eda..656a6e16f2f 100644--- a/src/utils/router.tsx+++ b/src/utils/router.tsx@@ -3,9 +3,9 @@import { ConfigProvider, ThemeProvider } from '@lobehub/ui';import * as m from 'motion/react-m';import { type ComponentType, type ReactElement } from 'react';-import { lazy, memo, Suspense, useLayoutEffect } from 'react';+import { lazy, memo, Suspense } from 'react';import type { RouteObject } from 'react-router';-import { Navigate, Outlet, useNavigate, useRouteError } from 'react-router';+import { Navigate, Outlet, useRouteError } from 'react-router';import BusinessGlobalProvider from '@/business/client/BusinessGlobalProvider';import ErrorCapture from '@/components/Error';@@ -14,10 +14,10 @@ import { useIsDark } from '@/hooks/useIsDark';import SPAGlobalProvider from '@/layout/SPAGlobalProvider';import AppLayer from '@/spa/AppLayer';import { createSPABrowserRouter } from '@/spa/runtime';-import { useGlobalStore } from '@/store/global';-import { createNavigationRef } from '@/store/global/initialState';import { isChunkLoadError, notifyChunkError } from '@/utils/chunkError';+import { NavigatorRegistrar } from './NavigatorRegistrar';+async function importModule<T>(importFn: () => Promise<T>): Promise<T> {return importFn();}@@ -117,23 +117,6 @@ export const ErrorBoundary = ({ resetPath }: ErrorBoundaryProps) => {);};-/**- * Syncs React Router's `navigate` into `navigationRef` (see `getStableNavigate` / `useStableNavigate`).- * Mounted once on {@link RouterRoot} so imperative navigation works app-wide (desktop + mobile).- */-export const NavigatorRegistrar = memo(() => {- const navigate = useNavigate();-- useLayoutEffect(() => {- useGlobalStore.setState({ navigationRef: { current: navigate } });- return () => {- useGlobalStore.setState({ navigationRef: createNavigationRef() });- };- }, [navigate]);-- return null;-});-export interface CreateAppRouterOptions {basename?: string;}