🤯 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
🐛 fix(nav-panel): keep the Home sidebar scroll offset across route round trips (#19441)
Inneiffaa7d2a1c81
diff --git a/.github/scripts/bundle-size-gate.cjs b/.github/scripts/bundle-size-gate.cjsindex 10075cd9f55..7ad79a95e1d 100644--- a/.github/scripts/bundle-size-gate.cjs+++ b/.github/scripts/bundle-size-gate.cjs@@ -40,6 +40,7 @@ const VITE_JS_TARGETS = [const STATIC_IMPORT_RE =/(?:^|[;{}\s)])(?:import(?:[\w$*{},\s]+from\s*)?|export\s*(?:\*|\{[^}]*\})\s*from\s*)["']([^"']+\.js)["']/g;const ASAR_SEARCH_ROOT = 'apps/desktop/release';+const PNPM_STORE_DIR = 'node_modules/.pnpm';const die = (message) => {console.error(`❌ ${message}`);@@ -156,6 +157,43 @@ const measureEntryGraph = (root, htmlFile = 'index.html') => {return { chunks, count: visited.size, entry, gz };};+// pnpm-workspace.yaml sets `lockfile: false`, so the only record of what a build+// actually resolved is the virtual store directory: `<name>@<version>[_<peer-hash>]`.+const readResolvedDeps = (storeDir = PNPM_STORE_DIR) => {+ if (!fs.existsSync(storeDir)) return [];+ const deps = new Set();+ for (const entry of fs.readdirSync(storeDir)) {+ if (entry.startsWith('.') || entry === 'lock.yaml' || entry === 'node_modules') continue;+ const at = entry.indexOf('@', 1);+ if (at < 1) continue;+ const version = entry.slice(at + 1).split('_')[0];+ deps.add(`${entry.slice(0, at).replace('+', '/')}@${version}`);+ }+ return [...deps].sort();+};++const diffResolvedDeps = (baseline = [], current = []) => {+ const versionsOf = (list) => {+ const map = new Map();+ for (const dep of list) {+ const at = dep.lastIndexOf('@');+ const name = dep.slice(0, at);+ if (!map.has(name)) map.set(name, []);+ map.get(name).push(dep.slice(at + 1));+ }+ return map;+ };+ const base = versionsOf(baseline);+ const cur = versionsOf(current);+ const drift = [];+ for (const name of new Set([...base.keys(), ...cur.keys()])) {+ const before = (base.get(name) || []).join(', ');+ const after = (cur.get(name) || []).join(', ');+ if (before !== after) drift.push({ after, before, name });+ }+ return drift.sort((a, b) => a.name.localeCompare(b.name));+};+const measure = (args) => {const { type, out } = args;if (!type || !out) die('measure requires --type <web|asar> and --out <file.json>');@@ -172,7 +210,7 @@ const measure = (args) => {}if (Object.keys(sizes).length === 0) die('no dist targets found — did the build run?');sizes.total = Object.values(sizes).reduce((sum, size) => sum + size, 0);- result = { sizes, type };+ result = { resolvedDeps: readResolvedDeps(), sizes, type };} else if (type === 'entry-graph') {const sizes = {};const graphs = {};@@ -337,6 +375,14 @@ const check = (args) => {}}+ const drift =+ baselineReport.resolvedDeps && currentReport.resolvedDeps+ ? diffResolvedDeps(baselineReport.resolvedDeps, currentReport.resolvedDeps)+ : null;+ const driftRows = (drift || []).map(+ ({ name, before, after }) => `| ${name} | ${before || '—'} | ${after || '—'} |`,+ );+const section = [`### ${failed ? '❌' : '✅'} ${label}`,'',@@ -365,6 +411,20 @@ const check = (args) => {`> Static graph chunk names are informational; the gate above uses the total Vite JS output file count.`,]: []),+ ...(drift+ ? [+ '',+ `<details><summary>Resolved dependency drift vs baseline: ${drift.length} package(s)</summary>`,+ '',+ ...(drift.length > 0+ ? [`| Package | Baseline | Current |`, `| --- | --- | --- |`, ...driftRows]+ : ['No dependency version changed between the baseline install and this install.']),+ '',+ `> No lockfile is committed, so every install re-resolves. Size deltas with drift but no package.json change come from upstream releases, not this PR.`,+ '',+ '</details>',+ ]+ : []),].join('\n');console.log(`\n${section}\n`);@@ -377,11 +437,23 @@ const check = (args) => {`❌ ${label} exceeds the gate: size increase > max(${percent}%, ${humanSize(floor)}) or Vite JS output file count increases by more than ${jsChunkPercent}% from baseline. ` +'Inspect the added dependencies or imports, or adjust SIZE_GATE_PERCENT / SIZE_GATE_FLOOR_BYTES / SIZE_GATE_JS_CHUNK_PERCENT if this is expected.',);+ if (drift?.length) {+ console.error(+ `⚠️ ${drift.length} resolved dependency version(s) differ from the baseline install; see the drift table before attributing the increase to this PR.`,+ );+ }process.exit(1);}};-module.exports = { countJsFiles, measureEntryGraph, measureViteJsChunks, stripHash };+module.exports = {+ countJsFiles,+ diffResolvedDeps,+ measureEntryGraph,+ measureViteJsChunks,+ readResolvedDeps,+ stripHash,+};if (require.main === module) {const [command, ...rest] = process.argv.slice(2);diff --git a/.github/scripts/bundle-size-gate.test.cjs b/.github/scripts/bundle-size-gate.test.cjsindex 2214fea1fc1..7db1c847901 100644--- a/.github/scripts/bundle-size-gate.test.cjs+++ b/.github/scripts/bundle-size-gate.test.cjs@@ -4,7 +4,13 @@ const os = require('node:os');const path = require('node:path');const { test } = require('node:test');-const { countJsFiles, measureEntryGraph, stripHash } = require('./bundle-size-gate.cjs');+const {+ countJsFiles,+ diffResolvedDeps,+ measureEntryGraph,+ readResolvedDeps,+ stripHash,+} = require('./bundle-size-gate.cjs');const writeDist = (files) => {const root = fs.mkdtempSync(path.join(os.tmpdir(), 'entry-graph-'));@@ -95,8 +101,9 @@ const runCheck = ({ baselineGraphCount, baselineJsTotal, currentGraphCount, currpath.join(root, 'current.json'),'--baseline',path.join(root, 'baseline.json'),+ '--js-chunk-percent',+ '5',];- args.push('--js-chunk-percent', '5');return spawnSync(process.execPath, args, { encoding: 'utf8' });};@@ -131,3 +138,33 @@ test('reachable graph count increase alone does not fail the gate', () => {});assert.equal(result.status, 0);});++test('readResolvedDeps turns pnpm virtual store entries into name@version and drops peer suffixes', () => {+ const store = writeDist({+ '@[email protected][email protected]/x': '',+ '[email protected]/x': '',+ '[email protected]_abc/x': '',+ 'lock.yaml': '',+ 'node_modules/x': '',+ });++ assert.deepEqual(readResolvedDeps(store), [+ '@scope/[email protected]',+ '[email protected]',+ '[email protected]',+ ]);+});++test('diffResolvedDeps reports changed, added and removed package versions only', () => {+ const drift = diffResolvedDeps(+ ['[email protected]', '[email protected]', '[email protected]', '[email protected]', '[email protected]'],+ );++ assert.deepEqual(drift, [+ { after: '1.1.0', before: '1.0.0', name: 'a' },+ { after: '1.0.0', before: '1.0.0, 2.0.0', name: 'b' },+ { after: '', before: '1.0.0', name: 'gone' },+ { after: '0.1.0', before: '', name: 'new' },+ ]);+});diff --git a/.github/workflows/e2e.yml b/.github/workflows/e2e.ymlindex ab5337c6efa..87db806dba2 100644--- a/.github/workflows/e2e.yml+++ b/.github/workflows/e2e.yml@@ -182,6 +182,15 @@ jobs:continue-on-error: truerun: node .github/scripts/bundle-size-gate.cjs check --current size-report/entry-graph.json --baseline .size-baseline/entry-graph.json --label "First-screen static import graph (gzip)" --report size-report/report.md --floor 65536+ - name: Upload size report with resolved dependency versions+ if: always() && env.SIZE_GATE_ENABLED == 'true'+ uses: actions/upload-artifact@v6+ with:+ name: size-report+ path: size-report/+ retention-days: 30+ if-no-files-found: ignore+- name: Comment bundle size report on PRif: always() && env.SIZE_GATE_ENABLED == 'true' && (github.event_name == 'push' || github.event.pull_request.head.repo.full_name == github.repository)uses: actions/github-script@v8diff --git a/e2e/src/steps/agent/conversation-mgmt.steps.ts b/e2e/src/steps/agent/conversation-mgmt.steps.tsindex 51f92f1c95e..cab6775eeb1 100644--- a/e2e/src/steps/agent/conversation-mgmt.steps.ts+++ b/e2e/src/steps/agent/conversation-mgmt.steps.ts@@ -451,16 +451,20 @@ When('用户在搜索框中输入 {string}', async function (this: CustomWorld,// Find the search input in the sidebar// Support both English and Chinese placeholders- const searchInput = this.page.locator(- 'input[placeholder*="Search"], input[placeholder*="搜索"], [data-testid="search-input"]',- );+ const searchInput = this.page+ .locator(+ 'input[placeholder*="Search"], input[placeholder*="搜索"], [data-testid="search-input"]',+ )+ .locator('visible=true');+ const searchIcon = this.page.locator('svg.lucide-search').locator('..').locator('visible=true');++ await searchInput.or(searchIcon).first().waitFor({ state: 'visible', timeout: 10_000 });if ((await searchInput.count()) > 0) {await searchInput.first().click();await searchInput.first().fill(searchText);} else {// Fallback: click on search icon to reveal search input- const searchIcon = this.page.locator('svg.lucide-search').locator('..');if ((await searchIcon.count()) > 0) {await searchIcon.first().click();await this.page.waitForTimeout(300);diff --git a/e2e/src/steps/agent/message-ops.steps.ts b/e2e/src/steps/agent/message-ops.steps.tsindex ff83bb5e57d..a882558201a 100644--- a/e2e/src/steps/agent/message-ops.steps.ts+++ b/e2e/src/steps/agent/message-ops.steps.ts@@ -101,7 +101,10 @@ When('用户点击消息的复制按钮', async function (this: CustomWorld) {}// Last fallback: find more button by icon and open menu- const moreButtonByIcon = this.page.locator('svg.lucide-more-horizontal').locator('..');+ const moreButtonByIcon = this.page+ .locator('svg.lucide-more-horizontal')+ .locator('..')+ .locator('visible=true');if ((await moreButtonByIcon.count()) > 0) {await moreButtonByIcon.first().click();await this.page.waitForTimeout(300);@@ -144,7 +147,10 @@ When('用户点击助手消息的编辑按钮', async function (this: CustomWorl// Fallback: Look for edit in more menuconsole.log(' 📍 Fallback: Looking for edit in more menu...');- const moreButtonByIcon = this.page.locator('svg.lucide-more-horizontal').locator('..');+ const moreButtonByIcon = this.page+ .locator('svg.lucide-more-horizontal')+ .locator('..')+ .locator('visible=true');if ((await moreButtonByIcon.count()) > 0) {await moreButtonByIcon.first().click();await this.page.waitForTimeout(300);diff --git a/packages/conversation-flow/src/__tests__/parse.test.ts b/packages/conversation-flow/src/__tests__/parse.test.tsindex cfd3dcb936f..185ec3d30e4 100644--- a/packages/conversation-flow/src/__tests__/parse.test.ts+++ b/packages/conversation-flow/src/__tests__/parse.test.ts@@ -1656,27 +1656,4 @@ describe('parse', () => {});});});-- describe('Performance', () => {- it('should parse 10000 items within 100ms', () => {- // Generate 10000 messages as flat siblings (no deep nesting to avoid stack overflow)- // This simulates a more realistic scenario where messages are not deeply nested- const largeInput = Array.from({ length: 10000 }, (_, i) => ({- id: `msg-${i}`,- role: i % 2 === 0 ? ('user' as const) : ('assistant' as const),- content: `Message ${i}`,- parentId: undefined, // All messages at the same level- createdAt: Date.now() + i,- }));-- const startTime = performance.now();- const result = parse(largeInput as any[]);- const endTime = performance.now();-- const executionTime = endTime - startTime;-- expect(result.flatList.length).toBeGreaterThan(0);- expect(executionTime).toBeLessThan(100);- });- });});diff --git a/src/features/NavPanel/SideBarLayout.tsx b/src/features/NavPanel/SideBarLayout.tsxindex 9663898a85a..130a514cc54 100644--- a/src/features/NavPanel/SideBarLayout.tsx+++ b/src/features/NavPanel/SideBarLayout.tsx@@ -1,24 +1,50 @@-import { Flexbox, ScrollShadow, TooltipGroup } from '@lobehub/ui';-import { type ReactNode } from 'react';-import { memo, Suspense } from 'react';+import { Flexbox, TooltipGroup } from '@lobehub/ui';+import { ScrollArea } from '@lobehub/ui/base-ui';+import { type ReactNode, type UIEvent } from 'react';+import { memo, Suspense, useCallback, useLayoutEffect, useRef } from 'react';import { SideBarHeaderSkeleton } from '@/features/NavPanel/components/SideBarSkeleton';import SkeletonList from '@/features/NavPanel/components/SkeletonList';+import { useActiveNavKey } from './useActiveNavKey';++const scrollOffsets = new Map<string, number>();+interface SidebarLayoutProps {body?: ReactNode;header?: ReactNode;}const SideBarLayout = memo<SidebarLayoutProps>(({ header, body }) => {+ const navKey = useActiveNavKey();+ const scrollerRef = useRef<HTMLDivElement>(null);++ const handleScroll = useCallback(+ (e: UIEvent<HTMLDivElement>) => {+ scrollOffsets.set(navKey, e.currentTarget.scrollTop);+ },+ [navKey],+ );++ // Runs on mount and on Activity reveal; display:none drops the browser's own offset.+ useLayoutEffect(() => {+ const offset = scrollOffsets.get(navKey);+ if (offset && scrollerRef.current) scrollerRef.current.scrollTop = offset;+ }, [navKey]);+return (<Flexbox gap={1} style={{ height: '100%', overflow: 'hidden' }}><Suspense fallback={<SideBarHeaderSkeleton />}>{header}</Suspense>- <ScrollShadow size={2} style={{ height: '100%' }}>+ <ScrollArea+ disableContentFit+ scrollFade+ style={{ flex: 1, minHeight: 0 }}+ viewportProps={{ onScroll: handleScroll, ref: scrollerRef }}+ ><TooltipGroup><Suspense fallback={<SkeletonList paddingBlock={8} />}>{body}</Suspense></TooltipGroup>- </ScrollShadow>+ </ScrollArea></Flexbox>);});diff --git a/src/features/NavPanel/components/NavPanelDraggable.tsx b/src/features/NavPanel/components/NavPanelDraggable.tsxindex a5498a8e0e4..c583fd6a6dd 100644--- a/src/features/NavPanel/components/NavPanelDraggable.tsx+++ b/src/features/NavPanel/components/NavPanelDraggable.tsx@@ -3,7 +3,7 @@import { DraggablePanel } from '@lobehub/ui/base-ui';import { createStaticStyles, cssVar } from 'antd-style';import { type ReactNode } from 'react';-import { memo, Suspense, useMemo, useRef } from 'react';+import { Activity, memo, Suspense, useMemo, useRef } from 'react';import NavPanelUpgradeEntry from '@/business/client/features/NavPanelUpgradeEntry';import { isDesktop } from '@/const/version';@@ -104,13 +104,16 @@ interface NavPanelDraggableProps {key: string;node: ReactNode;};+ homeContent?: ReactNode;}const classNames = {content: draggableStyles.content,};-export const NavPanelDraggable = memo<NavPanelDraggableProps>(({ activeContent }) => {+const hiddenLayerStyle = { display: 'none' };++export const NavPanelDraggable = memo<NavPanelDraggableProps>(({ activeContent, homeContent }) => {const [expand, togglePanel, isStatusInit] = useGlobalStore((s) => [systemStatusSelectors.showLeftPanel(s),s.toggleLeftPanel,@@ -139,6 +142,7 @@ export const NavPanelDraggable = memo<NavPanelDraggableProps>(({ activeContent }}const defaultSize = { height: '100%', width: defaultWidthRef.current };+ const isHomeActive = activeContent.key === 'home';return (<DraggablePanel@@ -156,9 +160,24 @@ export const NavPanelDraggable = memo<NavPanelDraggableProps>(({ activeContent }onSizeDragging={handleSizeChange}><div className={draggableStyles.inner}>- <div className={draggableStyles.layer} key={activeContent.key}>- {activeContent.node}- </div>+ {/* Home stays mounted while a route-owned panel is active so its list+ state survives the round trip. Activity keeps the fibers but not the+ visibility, so the layer is force-hidden like HomeLayout does. */}+ {homeContent && (+ <Activity mode={isHomeActive ? 'visible' : 'hidden'} name="NavPanelHome">+ <div+ className={draggableStyles.layer}+ style={isHomeActive ? undefined : hiddenLayerStyle}+ >+ {homeContent}+ </div>+ </Activity>+ )}+ {!isHomeActive && (+ <div className={draggableStyles.layer} key={activeContent.key}>+ {activeContent.node}+ </div>+ )}</div><Suspense fallback={null}><NavPanelUpgradeEntry />diff --git a/src/features/NavPanel/index.test.tsx b/src/features/NavPanel/index.test.tsxindex 91ca2e1e354..66df232e0ab 100644--- a/src/features/NavPanel/index.test.tsx+++ b/src/features/NavPanel/index.test.tsx@@ -1,4 +1,4 @@-import { act, render, screen, waitFor } from '@testing-library/react';+import { act, fireEvent, render, screen, waitFor } from '@testing-library/react';import type { ReactNode } from 'react';import { beforeEach, describe, expect, it, vi } from 'vitest';@@ -10,6 +10,7 @@ import {unregisterNavPanelContent,} from './registry';import NavPanelShell from './Shell';+import SideBarLayout from './SideBarLayout';const panelRender = vi.fn();@@ -25,6 +26,7 @@ interface NavPanelDraggableMockProps {key: string;node: ReactNode;};+ homeContent?: ReactNode;}const workspaceState: WorkspaceMock = {@@ -43,10 +45,10 @@ vi.mock('@/business/client/hooks/useActiveWorkspaceSlug', () => ({}));vi.mock('./components/NavPanelDraggable', () => ({- NavPanelDraggable: ({ activeContent }: NavPanelDraggableMockProps) => {+ NavPanelDraggable: ({ activeContent, homeContent }: NavPanelDraggableMockProps) => {panelRender();return (- <div data-nav-key={activeContent.key} data-testid="nav-panel">+ <div data-has-home={!!homeContent} data-nav-key={activeContent.key} data-testid="nav-panel">{activeContent.node}</div>);@@ -104,6 +106,21 @@ describe('NavPanel', () => {expect(screen.queryByText('Home sidebar')).not.toBeInTheDocument();});+ it('keeps handing the Home entry down while a route-owned panel is active', async () => {+ const owner = Symbol('workspace-settings');+ registerNavPanelContent('workspace-settings', owner, <div>Workspace settings sidebar</div>);+ render(<NavPanel />);++ expect(screen.getByTestId('nav-panel')).toHaveAttribute('data-has-home', 'false');++ act(() => registerNavPanelContent('home', Symbol('home'), <div>Home sidebar</div>));++ await waitFor(() => {+ expect(screen.getByTestId('nav-panel')).toHaveAttribute('data-has-home', 'true');+ });+ expect(screen.getByTestId('nav-panel')).toHaveAttribute('data-nav-key', 'workspace-settings');+ });+it('uses the Home entry for routes without a dedicated navigation panel', async () => {pathname = '/lobe-team/tasks';@@ -235,3 +252,33 @@ describe('NavPanelShell', () => {expect(screen.queryByText('Home sidebar')).not.toBeInTheDocument();});});++describe('SideBarLayout scroll restoration', () => {+ const getViewport = (container: HTMLElement) =>+ container.querySelector('[data-id$="-viewport"]') as HTMLDivElement;++ it('restores the scroll offset for the same nav key after a remount', () => {+ pathname = '/';+ const first = render(<SideBarLayout body={<div>body</div>} />);+ const viewport = getViewport(first.container);+ viewport.scrollTop = 120;+ fireEvent.scroll(viewport);+ first.unmount();++ const second = render(<SideBarLayout body={<div>body</div>} />);+ expect(getViewport(second.container).scrollTop).toBe(120);+ });++ it('keeps offsets isolated per nav key', () => {+ pathname = '/community';+ const first = render(<SideBarLayout body={<div>body</div>} />);+ const viewport = getViewport(first.container);+ viewport.scrollTop = 80;+ fireEvent.scroll(viewport);+ first.unmount();++ pathname = '/memory';+ const second = render(<SideBarLayout body={<div>body</div>} />);+ expect(getViewport(second.container).scrollTop).toBe(0);+ });+});diff --git a/src/features/NavPanel/index.tsx b/src/features/NavPanel/index.tsxindex a16d9dc1fda..ff971eacbae 100644--- a/src/features/NavPanel/index.tsx+++ b/src/features/NavPanel/index.tsx@@ -27,10 +27,16 @@ const NavPanel = memo(() => {const activeContent = registeredContent? { key: activeNavKey, node: registeredContent.node }: { key: `pending:${activeNavKey}`, node: <NavPanelFallback navKey={activeNavKey} /> };+ const getHomeContent = () => getNavPanelRegistrySnapshot().get('home')?.node;+ const homeContent = useSyncExternalStore(+ subscribeNavPanelRegistry,+ getHomeContent,+ getHomeContent,+ );return (<>- <NavPanelDraggable activeContent={activeContent} />+ <NavPanelDraggable activeContent={activeContent} homeContent={homeContent} /><divid={NAV_PANEL_RIGHT_DRAWER_ID}style={{