🤯 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
⚡ perf(ui): cut agent page render cost across sidebars, composer and topic list (#17991)
Innei7f558f21d9bd
diff --git a/apps/desktop/README.md b/apps/desktop/README.mdindex 558b93ed4de..9edb7a9d034 100644--- a/apps/desktop/README.md+++ b/apps/desktop/README.md@@ -84,15 +84,15 @@ pnpm package:local # Local testing packageThe renderer is served from the custom `app://renderer` origin, and Chromiumrefuses to match extension content scripts against custom schemes — so theReact DevTools **browser extension can never attach** here, no matter how it is-installed. Use the standalone bridge instead, in two terminals:+installed. Use the standalone bridge instead:```bash-pnpm react-devtools # standalone UI, listens on ws://localhost:8097-pnpm dev:react-devtools # dev run that injects the bridge script into the renderer+pnpm react-devtools # standalone UI, listens on ws://localhost:8097+pnpm dev # dev mode injects the bridge script automatically```-The bridge script is only injected while `DESKTOP_REACT_DEVTOOLS=1` is set, and-never in production builds.+The bridge script is only injected during dev (`vite serve`), and never in+production builds.## 🎯 Release Channelsdiff --git a/apps/desktop/README.zh-CN.md b/apps/desktop/README.zh-CN.mdindex fac2584379a..170a363d5b4 100644--- a/apps/desktop/README.zh-CN.md+++ b/apps/desktop/README.zh-CN.md@@ -83,14 +83,14 @@ pnpm package:local # 本地测试打包渲染进程始终从自定义协议 `app://renderer` 加载,而 Chromium 不允许扩展的 contentscript 匹配自定义协议 —— 因此 React DevTools **浏览器扩展在此永远无法挂载**,无论用-何种方式安装。请改用 standalone 桥接,开两个终端:+何种方式安装。请改用 standalone 桥接:```bash-pnpm react-devtools # standalone 界面,监听 ws://localhost:8097-pnpm dev:react-devtools # 注入桥接脚本的开发启动命令+pnpm react-devtools # standalone 界面,监听 ws://localhost:8097+pnpm dev # 开发模式会自动注入桥接脚本```-桥接脚本仅在 `DESKTOP_REACT_DEVTOOLS=1` 时注入,生产构建绝不包含。+桥接脚本仅在 dev(`vite serve`)时注入,生产构建绝不包含。## 🎯 发布渠道diff --git a/apps/desktop/package.json b/apps/desktop/package.jsonindex 2e09ece9845..1d058ada7cb 100644--- a/apps/desktop/package.json+++ b/apps/desktop/package.json@@ -17,7 +17,6 @@"build:run-unpack": "electron .","db:generate:local": "drizzle-kit generate --config drizzle.local.config.ts","dev": "node scripts/dev.mjs",- "dev:react-devtools": "cross-env DESKTOP_REACT_DEVTOOLS=1 npm run dev","dev:static": "cross-env DESKTOP_RENDERER_STATIC=1 npm run dev","fix:electron": "node scripts/fix-electron-runtime.mjs","format": "prettier --write ",diff --git a/apps/desktop/vite.shared.test.ts b/apps/desktop/vite.shared.test.tsindex 051b32cf58e..509449bd3dc 100644--- a/apps/desktop/vite.shared.test.ts+++ b/apps/desktop/vite.shared.test.ts@@ -47,10 +47,6 @@ describe('applyDesktopViteConfigExtension', () => {});describe('reactDevtoolsPlugin', () => {- afterEach(() => {- vi.unstubAllEnvs();- });-const transformIndexHtml = () => {const plugin = reactDevtoolsPlugin() as Plugin & {transformIndexHtml: () => IndexHtmlTransformResult;@@ -59,23 +55,13 @@ describe('reactDevtoolsPlugin', () => {return plugin.transformIndexHtml();};- it('injects nothing when DESKTOP_REACT_DEVTOOLS is unset', () => {- vi.stubEnv('DESKTOP_REACT_DEVTOOLS', '');-- expect(transformIndexHtml()).toEqual([]);- });-- it('injects the standalone bridge script when enabled', () => {- vi.stubEnv('DESKTOP_REACT_DEVTOOLS', '1');-+ it('injects the standalone bridge script in dev', () => {expect(transformIndexHtml()).toEqual([{ attrs: { src: REACT_DEVTOOLS_BRIDGE_URL }, injectTo: 'head-prepend', tag: 'script' },]);});it('stays out of production builds', () => {- vi.stubEnv('DESKTOP_REACT_DEVTOOLS', '1');-expect((reactDevtoolsPlugin() as Plugin).apply).toBe('serve');});});diff --git a/apps/desktop/vite.shared.ts b/apps/desktop/vite.shared.tsindex 6f2c7bf030f..87956ab002b 100644--- a/apps/desktop/vite.shared.ts+++ b/apps/desktop/vite.shared.ts@@ -48,10 +48,9 @@ export const REACT_DEVTOOLS_BRIDGE_URL = 'http://localhost:8097';export const reactDevtoolsPlugin = (): PluginOption => ({apply: 'serve',name: 'lobe-desktop-react-devtools',- transformIndexHtml: () =>- process.env.DESKTOP_REACT_DEVTOOLS === '1'- ? [{ attrs: { src: REACT_DEVTOOLS_BRIDGE_URL }, injectTo: 'head-prepend', tag: 'script' }]- : [],+ transformIndexHtml: () => [+ { attrs: { src: REACT_DEVTOOLS_BRIDGE_URL }, injectTo: 'head-prepend', tag: 'script' },+ ],});export const nodeExternals = [diff --git a/eslint.config.mjs b/eslint.config.mjsindex f200b4fe4c8..0a72e938fa8 100644--- a/eslint.config.mjs+++ b/eslint.config.mjs@@ -59,6 +59,32 @@ const createRestrictedImportRule = ({ paths = [], patterns } = {}) => [},];+// useRef(initial) re-evaluates `initial` on every render. Ban call/new expressions+// so expensive work and empty Map/Set allocations don't happen as throwaway inits.+// Use useSingleton(() => ...) for a once-created value; do not wrap it in useRef.+const useRefLazyInitMessage =+ "Do not pass a call or `new` expression to useRef() — the argument is evaluated on every render. Use useSingleton(() => ...) from '@/hooks/useSingleton' instead (do not wrap useSingleton in useRef).";++const useRefLazyInitRestrictedSyntax = [+ {+ message: useRefLazyInitMessage,+ selector: "CallExpression[callee.name='useRef'] > CallExpression.arguments:first-child",+ },+ {+ message: useRefLazyInitMessage,+ selector:+ "CallExpression[callee.property.name='useRef'] > CallExpression.arguments:first-child",+ },+ {+ message: useRefLazyInitMessage,+ selector: "CallExpression[callee.name='useRef'] > NewExpression.arguments:first-child",+ },+ {+ message: useRefLazyInitMessage,+ selector: "CallExpression[callee.property.name='useRef'] > NewExpression.arguments:first-child",+ },+];+export default eslint({ignores: [@@ -329,6 +355,7 @@ export default eslint(fixStyle: 'separate-type-imports',},],+ 'no-restricted-syntax': ['error', ...useRefLazyInitRestrictedSyntax],},},// MDX files@@ -360,6 +387,7 @@ export default eslint(rules: {'no-restricted-syntax': ['error',+ ...useRefLazyInitRestrictedSyntax,{message: 'Chinese characters are not allowed in aiModels files. Use English instead.',selector: 'Literal[value=/[\\u4e00-\\u9fff]/]',diff --git a/eslint.config.test.mts b/eslint.config.test.mtsindex e4d261a99c9..8529a8c6fb6 100644--- a/eslint.config.test.mts+++ b/eslint.config.test.mts@@ -13,6 +13,14 @@ const lintRestrictedImports = async (filePath: string, code: string): Promise<st.map(({ message }) => message);};+const lintRestrictedSyntax = async (filePath: string, code: string): Promise<string[]> => {+ const [result] = await eslint.lintText(code, { filePath });++ return result.messages+ .filter(({ ruleId }) => ruleId === 'no-restricted-syntax')+ .map(({ message }) => message);+};+const forbiddenImports = [['Conversation internal root barrel',@@ -153,3 +161,75 @@ describe('performance import boundaries', () => {await expect(lintRestrictedImports(filePath, code)).resolves.toEqual([]);});});++const useRefLazyInitFixture = 'src/hooks/useRef-lazy-init-lint-fixture.tsx';++const forbiddenUseRefInits = [+ [+ 'useRef(function call)',+ `import { useRef } from 'react';\nexport const C = () => { const r = useRef(getPlatform()); return r; };`,+ ],+ [+ 'useRef(new Map)',+ `import { useRef } from 'react';\nexport const C = () => { const r = useRef(new Map()); return r; };`,+ ],+ [+ 'useRef(new Set) with type args',+ `import { useRef } from 'react';\nexport const C = () => { const r = useRef<Set<string>>(new Set()); return r; };`,+ ],+ [+ 'useRef(Date.now())',+ `import { useRef } from 'react';\nexport const C = () => { const r = useRef(Date.now()); return r; };`,+ ],+ [+ 'useRef(Symbol())',+ `import { useRef } from 'react';\nexport const C = () => { const r = useRef(Symbol('x')); return r; };`,+ ],+ [+ 'React.useRef(new Map)',+ `import React from 'react';\nexport const C = () => { const r = React.useRef(new Map()); return r; };`,+ ],+ [+ 'useRef(useSingleton(...))',+ `import { useRef } from 'react';\nimport { useSingleton } from '@/hooks/useSingleton';\nexport const C = () => { const r = useRef(useSingleton(() => new Map())); return r; };`,+ ],+] as const;++const allowedUseRefInits = [+ [+ 'useRef(null)',+ `import { useRef } from 'react';\nexport const C = () => { const r = useRef(null); return r; };`,+ ],+ [+ 'useRef(false)',+ `import { useRef } from 'react';\nexport const C = () => { const r = useRef(false); return r; };`,+ ],+ [+ 'useRef(identifier)',+ `import { useRef } from 'react';\nexport const C = (v: string) => { const r = useRef(v); return r; };`,+ ],+ [+ 'useRef(arrow function)',+ `import { useRef } from 'react';\nexport const C = () => { const r = useRef(() => {}); return r; };`,+ ],+ [+ 'useSingleton alone',+ `import { useSingleton } from '@/hooks/useSingleton';\nexport const C = () => useSingleton(() => new Map());`,+ ],+ [+ 'useSingleton mutable box',+ `import { useSingleton } from '@/hooks/useSingleton';\nexport const C = () => { const r = useSingleton(() => ({ current: new Map() })); r.current = new Map(); return r; };`,+ ],+] as const;++describe('useRef lazy-init boundary', () => {+ it.each(forbiddenUseRefInits)('rejects %s', async (_name, code) => {+ await expect(lintRestrictedSyntax(useRefLazyInitFixture, code)).resolves.toEqual([+ expect.stringContaining('useSingleton'),+ ]);+ });++ it.each(allowedUseRefInits)('allows %s', async (_name, code) => {+ await expect(lintRestrictedSyntax(useRefLazyInitFixture, code)).resolves.toEqual([]);+ });+});diff --git a/package.json b/package.jsonindex a2519adbcb9..c69ef2d6d6a 100644--- a/package.json+++ b/package.json@@ -103,6 +103,7 @@"prettier": "prettier -c --write \"**/**\"","pull": "git pull","qstash": "pnpx @upstash/qstash-cli@latest dev",+ "react-devtools": "cd apps/desktop && pnpm run react-devtools","reinstall": "rm -rf .next && rm -rf node_modules && rm -rf ./packages/*/node_modules && pnpm -r exec rm -rf node_modules && pnpm install","reinstall:desktop": "rm -rf pnpm-lock.yaml && rm -rf node_modules && pnpm -r exec rm -rf node_modules && pnpm install --node-linker=hoisted","release": "semantic-release",diff --git a/src/features/AgentBuilder/SuggestionChips/useResolveFeedbackOnSend.ts b/src/features/AgentBuilder/SuggestionChips/useResolveFeedbackOnSend.tsindex d6cc615bf35..3ceacbb3819 100644--- a/src/features/AgentBuilder/SuggestionChips/useResolveFeedbackOnSend.ts+++ b/src/features/AgentBuilder/SuggestionChips/useResolveFeedbackOnSend.ts@@ -1,6 +1,7 @@import { useEffect, useRef } from 'react';import { conversationSelectors, useConversationStore } from '@/features/Conversation';+import { useSingleton } from '@/hooks/useSingleton';import { useBuilderSuggestionFeedbackStore } from './feedbackStore';@@ -19,20 +20,20 @@ export const useResolveFeedbackOnSend = () => {const resolveOnSend = useBuilderSuggestionFeedbackStore((s) => s.resolveOnSend);const initializedRef = useRef(false);- const seenIdsRef = useRef<Set<string>>(new Set());+ const seenIds = useSingleton(() => new Set<string>());useEffect(() => {if (!initializedRef.current) {initializedRef.current = true;- for (const m of messages) seenIdsRef.current.add(m.id);+ for (const m of messages) seenIds.add(m.id);return;}- const newUserMessage = messages.find((m) => m.role === 'user' && !seenIdsRef.current.has(m.id));- for (const m of messages) seenIdsRef.current.add(m.id);+ const newUserMessage = messages.find((m) => m.role === 'user' && !seenIds.has(m.id));+ for (const m of messages) seenIds.add(m.id);if (newUserMessage && typeof newUserMessage.content === 'string') {resolveOnSend(newUserMessage.content);}- }, [messages, resolveOnSend]);+ }, [messages, resolveOnSend, seenIds]);};diff --git a/src/features/AgentDocumentsExplorer/hooks/useDocumentTreeOps.ts b/src/features/AgentDocumentsExplorer/hooks/useDocumentTreeOps.tsindex f5f2b21bc1d..bab91c0db1f 100644--- a/src/features/AgentDocumentsExplorer/hooks/useDocumentTreeOps.ts+++ b/src/features/AgentDocumentsExplorer/hooks/useDocumentTreeOps.ts@@ -3,6 +3,7 @@ import { useCallback, useMemo, useRef } from 'react';import { useTranslation } from 'react-i18next';import type { KeyedMutator } from 'swr';+import { useSingleton } from '@/hooks/useSingleton';import { agentDocumentService } from '@/services/agentDocument';import type { AgentDocumentItem } from '../types';@@ -66,7 +67,7 @@ export const useDocumentTreeOps = ({// Tracks in-flight creates so a rename committed before the server response// lands can be deferred to the real row id once the create resolves.- const pendingCreatesRef = useRef(new Map<string, Promise<string | null>>());+ const pendingCreates = useSingleton(() => new Map<string, Promise<string | null>>());const byRowId = useMemo(() => {const map = new Map<string, AgentDocumentItem>();@@ -167,14 +168,14 @@ export const useDocumentTreeOps = ({);return null;} finally {- pendingCreatesRef.current.delete(pending.id);+ pendingCreates.delete(pending.id);}})();- pendingCreatesRef.current.set(pending.id, createPromise);+ pendingCreates.set(pending.id, createPromise);await createPromise;},- [agentId, buildParentPathFromRowId, byRowId, mutate, pickUniqueFilename, t],+ [agentId, buildParentPathFromRowId, byRowId, mutate, pendingCreates, pickUniqueFilename, t],);const createDocument = useCallback(@@ -226,14 +227,14 @@ export const useDocumentTreeOps = ({);return null;} finally {- pendingCreatesRef.current.delete(pending.id);+ pendingCreates.delete(pending.id);}})();- pendingCreatesRef.current.set(pending.id, createPromise);+ pendingCreates.set(pending.id, createPromise);await createPromise;},- [agentId, buildParentPathFromRowId, byRowId, mutate, pickUniqueFilename, t],+ [agentId, buildParentPathFromRowId, byRowId, mutate, pendingCreates, pickUniqueFilename, t],);const renameDocument = useCallback(@@ -255,7 +256,7 @@ export const useDocumentTreeOps = ({// path-based rename state survives the hydration, so the user's input// stays intact.if (isPendingId(id)) {- const pendingPromise = pendingCreatesRef.current.get(id);+ const pendingPromise = pendingCreates.get(id);if (!pendingPromise) return;const realId = await pendingPromise;if (!realId) return;@@ -291,7 +292,7 @@ export const useDocumentTreeOps = ({);}},- [agentId, mutate, t],+ [agentId, mutate, pendingCreates, t],);const moveDocument: DocumentTreeOps['moveDocument'] = useCallback(diff --git a/src/features/AgentSidebar/Topic/AllTopicsDrawer/Content.tsx b/src/features/AgentSidebar/Topic/AllTopicsDrawer/Content.tsxindex 9048f0d2169..27a16c9013f 100644--- a/src/features/AgentSidebar/Topic/AllTopicsDrawer/Content.tsx+++ b/src/features/AgentSidebar/Topic/AllTopicsDrawer/Content.tsx@@ -27,8 +27,6 @@ const Content = memo<ContentProps>(({ open, searchKeyword }) => {const initializedRef = useRef(false);const [- activeTopicId,- activeThreadId,hasMore,isLoadingMore,loadMoreError,@@ -37,8 +35,6 @@ const Content = memo<ContentProps>(({ open, searchKeyword }) => {activeAgentId,useSearchTopics,] = useChatStore((s) => [- s.activeTopicId,- s.activeThreadId,topicSelectors.hasMoreTopics(s),topicSelectors.isLoadingMoreTopics(s),topicSelectors.loadMoreTopicsError(s),@@ -184,12 +180,10 @@ const Content = memo<ContentProps>(({ open, searchKeyword }) => {{activeTopicList?.map((topic) => (<Flexbox gap={1} key={topic.id} paddingInline={4}><TopicItem- active={activeTopicId === topic.id}fav={topic.favorite}id={topic.id}metadata={topic.metadata}status={topic.status}- threadId={activeThreadId}title={topic.title}userId={topic.userId}/>diff --git a/src/features/AgentSidebar/Topic/List/Item/index.test.tsx b/src/features/AgentSidebar/Topic/List/Item/index.test.tsxindex 438c033624a..48c3a3abf62 100644--- a/src/features/AgentSidebar/Topic/List/Item/index.test.tsx+++ b/src/features/AgentSidebar/Topic/List/Item/index.test.tsx@@ -9,6 +9,7 @@ import TopicItem from './index';const useTopicNavigationMock = vi.hoisted(() => vi.fn());const prefetchMessagesMock = vi.hoisted(() => vi.fn());+const activeTopicIdMock = vi.hoisted(() => ({ value: undefined as string | undefined }));const agentRuntimeRunningMock = vi.hoisted(() => ({ value: false }));const runningStartTimeMock = vi.hoisted(() => ({ value: undefined as number | undefined }));const topicUnreadCompletedMock = vi.hoisted(() => ({ value: false }));@@ -114,10 +115,17 @@ vi.mock('@/store/agent', () => ({selector: (state: { activeAgentId: string; agentMap: Record<string, unknown> }) => unknown,) => selector({ activeAgentId: 'agt_test', agentMap: {} }),}));-vi.mock('@/store/chat', () => ({- useChatStore: (selector: (state: { prefetchMessages: typeof prefetchMessagesMock }) => unknown) =>- selector({ prefetchMessages: prefetchMessagesMock }),-}));+vi.mock('@/store/chat', () => {+ const useChatStore = (+ selector: (state: {+ activeThreadId?: string;+ activeTopicId?: string;+ prefetchMessages: typeof prefetchMessagesMock;+ }) => unknown,+ ) => selector({ activeTopicId: activeTopicIdMock.value, prefetchMessages: prefetchMessagesMock });+ useChatStore.getState = () => ({ prefetchMessages: prefetchMessagesMock });+ return { useChatStore };+});vi.mock('@/store/chat/selectors', () => ({operationSelectors: {getAgentRuntimeStartTimeByContext: () => () => runningStartTimeMock.value,@@ -128,10 +136,12 @@ vi.mock('@/store/chat/selectors', () => ({isTopicVisiblyRunning: () => () => false,},}));-vi.mock('@/store/electron', () => ({- useElectronStore: (selector: (state: { addTab: () => void }) => unknown) =>- selector({ addTab: vi.fn() }),-}));+vi.mock('@/store/electron', () => {+ const useElectronStore = (selector: (state: { addTab: () => void }) => unknown) =>+ selector({ addTab: vi.fn() });+ useElectronStore.getState = () => ({ addTab: vi.fn() });+ return { useElectronStore };+});vi.mock('../../hooks/useTopicNavigation', () => ({useTopicNavigation: () => useTopicNavigationMock(),}));@@ -159,6 +169,7 @@ vi.mock('../../TopicListContent/ThreadList', () => ({describe('TopicItem active state', () => {afterEach(() => {prefetchMessagesMock.mockClear();+ activeTopicIdMock.value = undefined;agentRuntimeRunningMock.value = false;runningStartTimeMock.value = undefined;topicUnreadCompletedMock.value = false;@@ -175,13 +186,14 @@ describe('TopicItem active state', () => {urlTopicId: 'tpc_test',});- render(<TopicItem active={false} id="tpc_test" title="Topic" />);+ render(<TopicItem id="tpc_test" title="Topic" />);expect(screen.getByTestId('nav-item')).toHaveAttribute('data-active', 'true');expect(screen.getByTestId('topic-thread-list')).toHaveAttribute('data-topic-id', 'tpc_test');});it('does not highlight a stale topic while visiting non-topic agent sub-routes', () => {+ activeTopicIdMock.value = 'tpc_test';useTopicNavigationMock.mockReturnValue({isInAgentSubRoute: true,isInTopicContextRoute: false,@@ -189,7 +201,7 @@ describe('TopicItem active state', () => {routeTopicId: undefined,});- render(<TopicItem active id="tpc_test" title="Topic" />);+ render(<TopicItem id="tpc_test" title="Topic" />);expect(screen.getByTestId('nav-item')).toHaveAttribute('data-active', 'false');expect(screen.queryByTestId('topic-thread-list')).not.toBeInTheDocument();@@ -229,6 +241,7 @@ describe('TopicItem active state', () => {});it('preserves the masked running-tail icon state for the active topic', () => {+ activeTopicIdMock.value = 'tpc_test';agentRuntimeRunningMock.value = true;useTopicNavigationMock.mockReturnValue({isInAgentSubRoute: false,@@ -238,7 +251,7 @@ describe('TopicItem active state', () => {urlTopicId: 'tpc_test',});- render(<TopicItem active id="tpc_test" status="running" title="Topic" />);+ render(<TopicItem id="tpc_test" status="running" title="Topic" />);expect(screen.queryByTestId('ring-loading')).not.toBeInTheDocument();expect(screen.getByTestId('topic-item-icon')).toHaveAttribute('data-icon', 'Hash');diff --git a/src/features/AgentSidebar/Topic/List/Item/index.tsx b/src/features/AgentSidebar/Topic/List/Item/index.tsxindex 7c58bbfc23a..01a381eccbd 100644--- a/src/features/AgentSidebar/Topic/List/Item/index.tsx+++ b/src/features/AgentSidebar/Topic/List/Item/index.tsx@@ -8,6 +8,7 @@ import {import { Flexbox, Icon, Popover, Skeleton, Tag, Text, Tooltip } from '@lobehub/ui';import { createStaticStyles, cssVar, useTheme } from 'antd-style';import dayjs from 'dayjs';+import isEqual from 'fast-deep-equal';import { HashIcon, MessageSquareDashed } from 'lucide-react';import type { CSSProperties, DragEvent, RefObject } from 'react';import { memo, Suspense, useCallback, useEffect, useMemo, useRef, useState } from 'react';@@ -133,7 +134,6 @@ const RunningElapsedTime = memo<RunningElapsedTimeProps>(({ agentId, topicId })RunningElapsedTime.displayName = 'RunningElapsedTime';interface TopicItemProps {- active?: boolean;fav?: boolean;id?: string;metadata?: ChatTopicMetadata;@@ -144,7 +144,6 @@ interface TopicItemProps {*/showWorkingDirectory?: boolean;status?: ChatTopicStatus | null;- threadId?: string;title: string;/** Creator of the topic; drives the workspace creator avatar. */userId?: string;@@ -178,20 +177,17 @@ const TopicItemRow = memo<TopicItemRowProps>(}) => {const { t } = useTranslation('topic');const { isDarkMode } = useTheme();- const activeAgentId = useAgentStore((s) => s.activeAgentId);+ // Rows render by the dozen, so agent-level reads share ONE subscription:+ // - heterogeneous agents (Claude Code, Codex, …) don't have chat-style+ // topic semantics, so their rows skip the default `#` placeholder icon;+ // - only workspace-shared (`public`) agents get the creator avatar — a+ // workspace-private agent's topics all belong to the viewer.+ const [activeAgentId, isHeterogeneousAgent, isSharedAgent] = useAgentStore((s) => [+ s.activeAgentId,+ agentSelectors.isCurrentAgentHeterogeneous(s),+ agentSelectors.currentAgentVisibility(s) === 'public',+ ]);const activeWorkspaceSlug = useActiveWorkspaceSlug();- // Heterogeneous agents (Claude Code, Codex, …) don't have the chat-style- // topic semantics, so skip the default `#` placeholder icon for their rows.- const isHeterogeneousAgent = useAgentStore(agentSelectors.isCurrentAgentHeterogeneous);- const addTab = useElectronStore((s) => s.addTab);- const prefetchMessages = useChatStore((s) => s.prefetchMessages);- // A workspace-private agent is a purely personal conversation space even- // inside a workspace — its topics all belong to the viewer, so the creator- // avatar carries no information there. Only workspace-shared (`public`)- // agents get the avatar treatment.- const isSharedAgent = useAgentStore(- (s) => agentSelectors.currentAgentVisibility(s) === 'public',- );// Creator of the topic — resolves only inside an active workspace; drives// the identity-first icon layout below.const author = useTopicCreator(isSharedAgent ? userId : undefined);@@ -206,24 +202,23 @@ const TopicItemRow = memo<TopicItemRowProps>(return buildWorkspaceAwarePath(AGENT_CHAT_TOPIC_URL(activeAgentId, id), activeWorkspaceSlug);}, [activeAgentId, activeWorkspaceSlug, id]);- const isLoading = useChatStore(id ? operationSelectors.isTopicVisiblyRunning(id) : () => false);-- const isUnreadCompleted = useChatStore(- id ? operationSelectors.isTopicUnreadCompleted(id) : () => false,- );- const hasLocalRunningRuntime = useChatStore(- id && activeAgentId- ? operationSelectors.isAgentRuntimeRunningByContext({ agentId: activeAgentId, topicId: id })- : () => false,- );- const isRuntimeVisiblyRunning = useChatStore(- id && activeAgentId- ? operationSelectors.isAgentRuntimeVisiblyRunningByContext({+ const [isLoading, isUnreadCompleted, hasLocalRunningRuntime, isRuntimeVisiblyRunning] =+ useChatStore((s) => [+ !!id && operationSelectors.isTopicVisiblyRunning(id)(s),+ !!id && operationSelectors.isTopicUnreadCompleted(id)(s),+ !!id &&+ !!activeAgentId &&+ operationSelectors.isAgentRuntimeRunningByContext({agentId: activeAgentId,topicId: id,- })- : () => false,- );+ })(s),+ !!id &&+ !!activeAgentId &&+ operationSelectors.isAgentRuntimeVisiblyRunningByContext({+ agentId: activeAgentId,+ topicId: id,+ })(s),+ ]);const handleDragStart = useCallback((event: DragEvent) => {@@ -253,9 +248,13 @@ const TopicItemRow = memo<TopicItemRowProps>(void navRef.current.navigateToTopic(id, { skipPopupFocus: true });return;}- addTab(buildWorkspaceAwarePath(AGENT_CHAT_TOPIC_URL(activeAgentId, id), activeWorkspaceSlug));+ useElectronStore+ .getState()+ .addTab(+ buildWorkspaceAwarePath(AGENT_CHAT_TOPIC_URL(activeAgentId, id), activeWorkspaceSlug),+ );void navRef.current.navigateToTopic(id);- }, [id, activeAgentId, activeWorkspaceSlug, addTab, navRef]);+ }, [id, activeAgentId, activeWorkspaceSlug, navRef]);const isFailed = status === 'failed';const isRunning = status === 'running';@@ -271,16 +270,18 @@ const TopicItemRow = memo<TopicItemRowProps>(// topic's working directory as a muted second line. Data is already on the// topic (`metadata.workingDirectoryConfig` / `workingDirectory`) — no fetch.// On web it's a github repo URL; on desktop a local path.- const workingDirectoryDisplay = getWorkingDirectoryDisplay(metadata);- const workingDirectoryNode =- showWorkingDirectory && workingDirectoryDisplay ? (- <Flexbox horizontal align={'center'} gap={4} style={{ overflow: 'hidden' }}>- <DirIcon repoType={workingDirectoryDisplay.repoType} size={13} />- <Text ellipsis fontSize={12} style={{ color: cssVar.colorTextDescription }}>- {workingDirectoryDisplay.label}- </Text>- </Flexbox>- ) : undefined;+ const workingDirectoryDisplay = useMemo(+ () => (showWorkingDirectory ? getWorkingDirectoryDisplay(metadata) : undefined),+ [metadata, showWorkingDirectory],+ );+ const workingDirectoryNode = workingDirectoryDisplay ? (+ <Flexbox horizontal align={'center'} gap={4} style={{ overflow: 'hidden' }}>+ <DirIcon repoType={workingDirectoryDisplay.repoType} size={13} />+ <Text ellipsis fontSize={12} style={{ color: cssVar.colorTextDescription }}>+ {workingDirectoryDisplay.label}+ </Text>+ </Flexbox>+ ) : undefined;// Surface the unread dot right away during the masked tail instead of a// blank icon gap until markTopicUnread's persisted 'unread' lands. Skipped@@ -288,13 +289,14 @@ const TopicItemRow = memo<TopicItemRowProps>(const isRunningTailUnread = isMaskedRunningTail && !isTopicActive;const hasUnread = id && (isUnreadCompleted || isRunningTailUnread);- const unreadIcon = <UnreadDot />;useEffect(() => {if (!activeAgentId || !id || !isUnreadCompleted || hasLocalRunningRuntime) return;- void prefetchMessages({ agentId: activeAgentId, scope: 'main', topicId: id });- }, [activeAgentId, hasLocalRunningRuntime, id, isUnreadCompleted, prefetchMessages]);+ void useChatStore+ .getState()+ .prefetchMessages({ agentId: activeAgentId, scope: 'main', topicId: id });+ }, [activeAgentId, hasLocalRunningRuntime, id, isUnreadCompleted]);// Surface a WeChat-style red "[Draft]" hint when this topic holds unsent// input. Drafts live in localStorage keyed by messageMapKey; the default@@ -311,6 +313,11 @@ const TopicItemRow = memo<TopicItemRowProps>(</Text>) : undefined;+ // Codex-style hover detail card: when the topic carries git context, hovering+ // the row reveals a card on the right with repo / branch / worktree / PR / CI —+ // keeping the row itself clean.+ const metaCard = useMemo(() => getTopicMetaCard(metadata), [metadata]);+// For default topic (no id)if (!id) {return (@@ -348,11 +355,6 @@ const TopicItemRow = memo<TopicItemRowProps>();}- // Codex-style hover detail card: when the topic carries git context, hovering- // the row reveals a card on the right with repo / branch / worktree / PR / CI —- // keeping the row itself clean.- const metaCard = getTopicMetaCard(metadata);-// Execution / attention state. In workspace mode this moves to the row's// trailing side so the leading slot can carry the creator identity.const statusIconNode = (() => {@@ -394,7 +396,7 @@ const TopicItemRow = memo<TopicItemRowProps>(// Unread is the third `pending` attention state (see `resolveStatusBucket`// in `@lobechat/utils/client/topic`), so it ranks with its two siblings// above — and above the PR marker, which shares this single icon slot.- if (hasUnread) return unreadIcon;+ if (hasUnread) return <UnreadDot />;// Persisted execution state is the topic's primary status. Keep every// non-idle state above git metadata so scheduled / paused / completed// topics cannot be mistaken for merely open / merged / closed PRs.@@ -528,7 +530,7 @@ TopicItemRow.displayName = 'TopicItemRow';* navigation; passing them as props would defeat the row's memo.*/const TopicItem = memo<TopicItemProps>((props) => {- const { active, id, threadId } = props;+ const { id } = props;const {focusTopicPopup,navigateToTopic,@@ -538,6 +540,12 @@ const TopicItem = memo<TopicItemProps>((props) => {urlTopicId,} = useTopicNavigation();+ // Active/thread state is subscribed here instead of arriving as props:+ // threading it through the group accordion re-rendered every group (and its+ // motion chain) on each topic switch, when only the two affected rows change.+ const active = useChatStore((s) => (id ? s.activeTopicId === id : !s.activeTopicId));+ const hasActiveThread = useChatStore((s) => !!s.activeThreadId);+const navRef = useRef<TopicNavigationActions>({ focusTopicPopup, navigateToTopic });useEffect(() => {navRef.current = { focusTopicPopup, navigateToTopic };@@ -552,11 +560,15 @@ const TopicItem = memo<TopicItemProps>((props) => {navRef={navRef}showThreadList={Boolean(id && id === urlTopicId)}isTopicActive={Boolean(- (active || isRouteTopicActive) && !threadId && (!isInAgentSubRoute || isRouteTopicActive),+ (active || isRouteTopicActive) &&+ !hasActiveThread &&+ (!isInAgentSubRoute || isRouteTopicActive),)}/>);-});+ // A list refresh rebuilds every topic/metadata object even when only one+ // topic changed — deep-compare props so unchanged rows still bail out.+}, isEqual);TopicItem.displayName = 'TopicItem';diff --git a/src/features/AgentSidebar/Topic/List/TopicListSkeleton.tsx b/src/features/AgentSidebar/Topic/List/TopicListSkeleton.tsxnew file mode 100644index 00000000000..354ee3701ca--- /dev/null+++ b/src/features/AgentSidebar/Topic/List/TopicListSkeleton.tsx@@ -0,0 +1,74 @@+'use client';++import { Flexbox, Skeleton } from '@lobehub/ui';+import { cssVar } from 'antd-style';+import { memo } from 'react';++// Mirrors the grouped topic list frame (12px group caption + icon-led 36px+// rows) so the deferred-mount frame reads as the layout it resolves into,+// unlike the avatar-style generic SkeletonList.+const GROUPS = [+ { header: 44, rows: ['82%', '58%', '70%'] },+ { header: 60, rows: ['64%', '76%', '48%', '68%'] },+];++const RowSkeleton = memo<{ width: string }>(({ width }) => (+ <Flexbox horizontal align={'center'} gap={8} height={36} paddingInline={4}>+ <Skeleton.Button+ size={'small'}+ style={{+ borderRadius: cssVar.borderRadiusSM,+ height: 16,+ maxHeight: 16,+ maxWidth: 16,+ minWidth: 16,+ }}+ />+ <Flexbox flex={1}>+ <Skeleton.Button+ active+ size={'small'}+ style={{+ borderRadius: cssVar.borderRadius,+ height: 14,+ margin: 0,+ maxHeight: 14,+ opacity: 0.5,+ padding: 0,+ width,+ }}+ />+ </Flexbox>+ </Flexbox>+));++RowSkeleton.displayName = 'TopicRowSkeleton';++const TopicListSkeleton = memo(() => (+ <Flexbox gap={2}>+ {GROUPS.map((group, i) => (+ <Flexbox gap={1} key={i} paddingBlock={4} paddingInline={'8px 4px'}>+ <Flexbox horizontal align={'center'} height={24}>+ <Skeleton.Button+ size={'small'}+ style={{+ borderRadius: cssVar.borderRadiusSM,+ height: 12,+ maxHeight: 12,+ maxWidth: group.header,+ minWidth: group.header,+ opacity: 0.6,+ }}+ />+ </Flexbox>+ {group.rows.map((width) => (+ <RowSkeleton key={width} width={width} />+ ))}+ </Flexbox>+ ))}+ </Flexbox>+));++TopicListSkeleton.displayName = 'TopicListSkeleton';++export default TopicListSkeleton;diff --git a/src/features/AgentSidebar/Topic/List/index.tsx b/src/features/AgentSidebar/Topic/List/index.tsxindex 3ef63a58f7a..2ae7556fe18 100644--- a/src/features/AgentSidebar/Topic/List/index.tsx+++ b/src/features/AgentSidebar/Topic/List/index.tsx@@ -5,7 +5,7 @@ import { useTranslation } from 'react-i18next';import urlJoin from 'url-join';import EmptyNavItem from '@/features/NavPanel/components/EmptyNavItem';-import SkeletonList from '@/features/NavPanel/components/SkeletonList';+import { useDeferredMount } from '@/hooks/useDeferredMount';import { useFetchChatTopics } from '@/hooks/useFetchChatTopics';import { usePermission } from '@/hooks/usePermission';import { useQueryRoute } from '@/hooks/useQueryRoute';@@ -18,6 +18,7 @@ import ByProjectMode from '../TopicListContent/ByProjectMode';import ByStatusMode from '../TopicListContent/ByStatusMode';import ByTimeMode from '../TopicListContent/ByTimeMode';import FlatMode from '../TopicListContent/FlatMode';+import TopicListSkeleton from './TopicListSkeleton';const TopicList = memo(() => {const { t } = useTranslation('topic');@@ -36,8 +37,13 @@ const TopicList = memo(() => {useFetchChatTopics();+ // Route transitions must paint instantly: the mount commit shows a skeleton+ // frame and the real list renders in a deferred (interruptible) follow-up+ // pass, off the navigation's critical path.+ const listReady = useDeferredMount();+// Show skeleton when current session's topic data is not yet loaded- if (isUndefinedTopics) return <SkeletonList />;+ if (isUndefinedTopics || !listReady) return <TopicListSkeleton />;return (<>diff --git a/src/features/AgentSidebar/Topic/TopicListContent/ByProjectMode/GroupItem.test.tsx b/src/features/AgentSidebar/Topic/TopicListContent/ByProjectMode/GroupItem.test.tsxindex 0571049d95c..4c9036a4481 100644--- a/src/features/AgentSidebar/Topic/TopicListContent/ByProjectMode/GroupItem.test.tsx+++ b/src/features/AgentSidebar/Topic/TopicListContent/ByProjectMode/GroupItem.test.tsx@@ -165,7 +165,6 @@ describe('Project topic group item', () => {render(<GroupItemexpanded- activeTopicId={undefined}group={{children: [],id: 'project:/Users/me/project',diff --git a/src/features/AgentSidebar/Topic/TopicListContent/ByProjectMode/GroupItem.tsx b/src/features/AgentSidebar/Topic/TopicListContent/ByProjectMode/GroupItem.tsxindex 1fa8b01e9c1..337f360f391 100644--- a/src/features/AgentSidebar/Topic/TopicListContent/ByProjectMode/GroupItem.tsx+++ b/src/features/AgentSidebar/Topic/TopicListContent/ByProjectMode/GroupItem.tsx@@ -155,142 +155,135 @@ const CollapsedUnreadDot = memo<{ count: number }>(({ count }) => {CollapsedUnreadDot.displayName = 'CollapsedProjectUnreadDot';-const GroupItem = memo<GroupItemComponentProps>(- ({ group, activeTopicId, activeThreadId, expanded }) => {- const { t } = useTranslation('topic');- const { id, title, children } = group;+const GroupItem = memo<GroupItemComponentProps>(({ group, expanded }) => {+ const { t } = useTranslation('topic');+ const { id, title, children } = group;- const workingDirectory = useMemo(- () =>- id.startsWith(PROJECT_GROUP_PREFIX) ? id.slice(PROJECT_GROUP_PREFIX.length) : undefined,- [id],- );+ const workingDirectory = useMemo(+ () => (id.startsWith(PROJECT_GROUP_PREFIX) ? id.slice(PROJECT_GROUP_PREFIX.length) : undefined),+ [id],+ );- const agentId = useAgentStore((s) => s.activeAgentId);- 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;- const router = useQueryRoute();- const activeWorkspaceSlug = useActiveWorkspaceSlug();- const agencyConfig = useAgentStore(- agentByIdSelectors.getAgencyConfigById(currentAgentId ?? ''),- );- const isHeterogeneous = useAgentStore((s) =>- currentAgentId ? agentByIdSelectors.isAgentHeterogeneousById(currentAgentId)(s) : false,- );- const isWorkspaceAgent = useAgentStore((s) =>- currentAgentId ? agentByIdSelectors.isWorkspaceAgentById(currentAgentId)(s) : false,- );- const { commitAgentDefault } = useCommitWorkingDirectory(currentAgentId ?? '');+ const agentId = useAgentStore((s) => s.activeAgentId);+ 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;+ const router = useQueryRoute();+ const activeWorkspaceSlug = useActiveWorkspaceSlug();+ const agencyConfig = useAgentStore(agentByIdSelectors.getAgencyConfigById(currentAgentId ?? ''));+ const isHeterogeneous = useAgentStore((s) =>+ currentAgentId ? agentByIdSelectors.isAgentHeterogeneousById(currentAgentId)(s) : false,+ );+ const isWorkspaceAgent = useAgentStore((s) =>+ currentAgentId ? agentByIdSelectors.isWorkspaceAgentById(currentAgentId)(s) : false,+ );+ const { commitAgentDefault } = useCommitWorkingDirectory(currentAgentId ?? '');- const handleAddTopic = useCallback(async () => {- if (!workingDirectory || !currentAgentId || !targetAgentId) return;- // Write the agent's per-device default so the new topic inherits this- // directory at creation time — the same high-precedence slot the picker- // uses, not the legacy per-agent fallback that gets shadowed by it.- await commitAgentDefault(workingDirectory);- useChatStore.getState().switchTopic(null, { skipRefreshMessage: true });- router.push(- buildPrefixedAgentRoutePath(AGENT_CHAT_URL(targetAgentId), agentRoute, activeWorkspaceSlug),- );- }, [- workingDirectory,- currentAgentId,- targetAgentId,- commitAgentDefault,- router,- agentRoute,- activeWorkspaceSlug,- ]);+ const handleAddTopic = useCallback(async () => {+ if (!workingDirectory || !currentAgentId || !targetAgentId) return;+ // Write the agent's per-device default so the new topic inherits this+ // directory at creation time — the same high-precedence slot the picker+ // uses, not the legacy per-agent fallback that gets shadowed by it.+ await commitAgentDefault(workingDirectory);+ useChatStore.getState().switchTopic(null, { skipRefreshMessage: true });+ router.push(+ buildPrefixedAgentRoutePath(AGENT_CHAT_URL(targetAgentId), agentRoute, activeWorkspaceSlug),+ );+ }, [+ workingDirectory,+ currentAgentId,+ targetAgentId,+ commitAgentDefault,+ router,+ agentRoute,+ activeWorkspaceSlug,+ ]);- // Web can add a topic in a directory too when the agent targets a bound- // device — the write goes to `workingDirByDevice`, no Electron dependency.- const deviceRoutingAvailable = useIsGatewayModeEnabled(currentAgentId);- const effectiveTarget = resolveExecutionTarget(agencyConfig, {- clientExecutionAvailable: isDesktop,- deviceRoutingAvailable,- isHetero: isHeterogeneous,- workspaceScoped: isWorkspaceAgent,- });- const isDeviceMode = effectiveTarget === 'device' && !!agencyConfig?.boundDeviceId;- const canAddTopic = (isDesktop || isDeviceMode) && !!workingDirectory;+ // Web can add a topic in a directory too when the agent targets a bound+ // device — the write goes to `workingDirByDevice`, no Electron dependency.+ const deviceRoutingAvailable = useIsGatewayModeEnabled(currentAgentId);+ const effectiveTarget = resolveExecutionTarget(agencyConfig, {+ clientExecutionAvailable: isDesktop,+ deviceRoutingAvailable,+ isHetero: isHeterogeneous,+ workspaceScoped: isWorkspaceAgent,+ });+ const isDeviceMode = effectiveTarget === 'device' && !!agencyConfig?.boundDeviceId;+ const canAddTopic = (isDesktop || isDeviceMode) && !!workingDirectory;- const statusCounts = useChatStore(- (s) => getProjectTopicStatusCounts(children, operationSelectors.visiblyRunningTopicIds(s)),- isEqual,- );- const childTopicIds = useMemo(() => children.map((topic) => topic.id), [children]);- const unreadCount = useChatStore(- operationSelectors.unreadCompletedCountForTopics(childTopicIds),- );- const hasCollapsedStatus = !expanded && hasProjectTopicStatusCounts(statusCounts);- const hasCollapsedUnread = !expanded && unreadCount > 0;- const hasCollapsedIndicators = hasCollapsedStatus || hasCollapsedUnread;- const ProjectFolderIcon = expanded ? FolderOpenIcon : FolderClosedIcon;- const action =- canAddTopic || hasCollapsedIndicators ? (- <Flexbox horizontal align={'center'} gap={4}>- {hasCollapsedStatus && <CollapsedStatusBadges counts={statusCounts} />}- {hasCollapsedUnread && <CollapsedUnreadDot count={unreadCount} />}- {canAddTopic && (- <span className={hasCollapsedIndicators ? styles.addTopicAction : undefined}>- <ActionIcon- icon={PlusIcon}- size={'small'}- title={t('actions.addNewTopicInProject', { directory: title })}- tooltipProps={{ placement: 'right' }}- onClick={(e) => {- e.stopPropagation();- void handleAddTopic();- }}- />- </span>- )}- </Flexbox>- ) : undefined;+ const statusCounts = useChatStore(+ (s) => getProjectTopicStatusCounts(children, operationSelectors.visiblyRunningTopicIds(s)),+ isEqual,+ );+ const childTopicIds = useMemo(() => children.map((topic) => topic.id), [children]);+ const unreadCount = useChatStore(operationSelectors.unreadCompletedCountForTopics(childTopicIds));+ const hasCollapsedStatus = !expanded && hasProjectTopicStatusCounts(statusCounts);+ const hasCollapsedUnread = !expanded && unreadCount > 0;+ const hasCollapsedIndicators = hasCollapsedStatus || hasCollapsedUnread;+ const ProjectFolderIcon = expanded ? FolderOpenIcon : FolderClosedIcon;+ const action =+ canAddTopic || hasCollapsedIndicators ? (+ <Flexbox horizontal align={'center'} gap={4}>+ {hasCollapsedStatus && <CollapsedStatusBadges counts={statusCounts} />}+ {hasCollapsedUnread && <CollapsedUnreadDot count={unreadCount} />}+ {canAddTopic && (+ <span className={hasCollapsedIndicators ? styles.addTopicAction : undefined}>+ <ActionIcon+ icon={PlusIcon}+ size={'small'}+ title={t('actions.addNewTopicInProject', { directory: title })}+ tooltipProps={{ placement: 'right' }}+ onClick={(e) => {+ e.stopPropagation();+ void handleAddTopic();+ }}+ />+ </span>+ )}+ </Flexbox>+ ) : undefined;- return (- <AccordionItem- action={action}- alwaysShowAction={hasCollapsedIndicators}- itemKey={id}- paddingBlock={4}- paddingInline={4}- title={- <Flexbox horizontal align="center" gap={8} height={24} style={{ overflow: 'hidden' }}>- <Center flex={'none'} height={24} width={28}>- <Icon- color={cssVar.colorTextTertiary}- icon={ProjectFolderIcon}- size={{ size: 15, strokeWidth: 1.5 }}- />- </Center>- <Text ellipsis fontSize={14} style={{ color: cssVar.colorTextSecondary, flex: 1 }}>- {title}- </Text>- </Flexbox>- }- >- <Flexbox gap={1} paddingBlock={1}>- {children.map((topic) => (- <TopicItem- active={activeTopicId === topic.id}- fav={topic.favorite}- id={topic.id}- key={topic.id}- metadata={topic.metadata}- status={topic.status}- threadId={activeThreadId}- title={topic.title}- userId={topic.userId}+ return (+ <AccordionItem+ action={action}+ alwaysShowAction={hasCollapsedIndicators}+ itemKey={id}+ paddingBlock={4}+ paddingInline={4}+ title={+ <Flexbox horizontal align="center" gap={8} height={24} style={{ overflow: 'hidden' }}>+ <Center flex={'none'} height={24} width={28}>+ <Icon+ color={cssVar.colorTextTertiary}+ icon={ProjectFolderIcon}+ size={{ size: 15, strokeWidth: 1.5 }}/>- ))}+ </Center>+ <Text ellipsis fontSize={14} style={{ color: cssVar.colorTextSecondary, flex: 1 }}>+ {title}+ </Text></Flexbox>- </AccordionItem>- );- },-);+ }+ >+ <Flexbox gap={1} paddingBlock={1}>+ {children.map((topic) => (+ <TopicItem+ fav={topic.favorite}+ id={topic.id}+ key={topic.id}+ metadata={topic.metadata}+ status={topic.status}+ title={topic.title}+ userId={topic.userId}+ />+ ))}+ </Flexbox>+ </AccordionItem>+ );+}, isEqual);++GroupItem.displayName = 'TopicByProjectGroupItem';export default GroupItem;diff --git a/src/features/AgentSidebar/Topic/TopicListContent/ByStatusMode/GroupItem.tsx b/src/features/AgentSidebar/Topic/TopicListContent/ByStatusMode/GroupItem.tsxindex 7036b810628..6d85b11ad1c 100644--- a/src/features/AgentSidebar/Topic/TopicListContent/ByStatusMode/GroupItem.tsx+++ b/src/features/AgentSidebar/Topic/TopicListContent/ByStatusMode/GroupItem.tsx@@ -1,4 +1,5 @@import { AccordionItem, Center, Flexbox, Icon, Text } from '@lobehub/ui';+import isEqual from 'fast-deep-equal';import { memo } from 'react';import {@@ -18,7 +19,7 @@ const STATUS_ICON: Record<string, ExecutionStatusVisual> = {...TOPIC_GROUP_VISUALS,};-const GroupItem = memo<GroupItemComponentProps>(({ group, activeTopicId, activeThreadId }) => {+const GroupItem = memo<GroupItemComponentProps>(({ group }) => {const { id, title, children } = group;const statusIcon = STATUS_ICON[id];@@ -44,13 +45,11 @@ const GroupItem = memo<GroupItemComponentProps>(({ group, activeTopicId, activeT{children.map((topic) => (<TopicItemshowWorkingDirectory- active={activeTopicId === topic.id}fav={topic.favorite}id={topic.id}key={topic.id}metadata={topic.metadata}status={topic.status}- threadId={activeThreadId}title={topic.title}userId={topic.userId}/>@@ -58,6 +57,8 @@ const GroupItem = memo<GroupItemComponentProps>(({ group, activeTopicId, activeT</Flexbox></AccordionItem>);-});+}, isEqual);++GroupItem.displayName = 'TopicByStatusGroupItem';export default GroupItem;diff --git a/src/features/AgentSidebar/Topic/TopicListContent/ByTimeMode/GroupItem.tsx b/src/features/AgentSidebar/Topic/TopicListContent/ByTimeMode/GroupItem.tsxindex 2be33b25440..0250cd6d0bb 100644--- a/src/features/AgentSidebar/Topic/TopicListContent/ByTimeMode/GroupItem.tsx+++ b/src/features/AgentSidebar/Topic/TopicListContent/ByTimeMode/GroupItem.tsx@@ -1,5 +1,6 @@import { AccordionItem, Flexbox, Text } from '@lobehub/ui';import dayjs from 'dayjs';+import isEqual from 'fast-deep-equal';import { memo, useMemo } from 'react';import { useTranslation } from 'react-i18next';@@ -9,7 +10,7 @@ import { type GroupItemComponentProps } from '../GroupedAccordion';const preformat = (id: string) =>id.startsWith('20') ? (id.includes('-') ? dayjs(id).format('MMMM') : id) : undefined;-const GroupItem = memo<GroupItemComponentProps>(({ group, activeTopicId, activeThreadId }) => {+const GroupItem = memo<GroupItemComponentProps>(({ group }) => {const { t } = useTranslation('topic');const { id, title, children } = group;@@ -31,13 +32,11 @@ const GroupItem = memo<GroupItemComponentProps>(({ group, activeTopicId, activeT<Flexbox gap={1} paddingBlock={1}>{children.map((topic) => (<TopicItem- active={activeTopicId === topic.id}fav={topic.favorite}id={topic.id}key={topic.id}metadata={topic.metadata}status={topic.status}- threadId={activeThreadId}title={topic.title}userId={topic.userId}/>@@ -45,6 +44,8 @@ const GroupItem = memo<GroupItemComponentProps>(({ group, activeTopicId, activeT</Flexbox></AccordionItem>);-});+}, isEqual);++GroupItem.displayName = 'TopicByTimeGroupItem';export default GroupItem;diff --git a/src/features/AgentSidebar/Topic/TopicListContent/FlatMode/index.tsx b/src/features/AgentSidebar/Topic/TopicListContent/FlatMode/index.tsxindex dc59dd7a738..b49a453b9a3 100644--- a/src/features/AgentSidebar/Topic/TopicListContent/FlatMode/index.tsx+++ b/src/features/AgentSidebar/Topic/TopicListContent/FlatMode/index.tsx@@ -25,15 +25,11 @@ const FlatMode = memo(() => {const topicSortBy = useUserStore(preferenceSelectors.topicSortBy);const topicIncludeCompleted = useUserStore(preferenceSelectors.topicIncludeCompleted);- const [activeTopicId, activeThreadId, hasMore, isExpandingPageSize, activeAgentId] = useChatStore(- (s) => [- s.activeTopicId,- s.activeThreadId,- topicSelectors.hasMoreTopicsForSidebar(s),- topicSelectors.isExpandingPageSize(s),- s.activeAgentId,- ],- );+ const [hasMore, isExpandingPageSize, activeAgentId] = useChatStore((s) => [+ topicSelectors.hasMoreTopicsForSidebar(s),+ topicSelectors.isExpandingPageSize(s),+ s.activeAgentId,+ ]);const activeTopicList = useChatStore(topicSelectors.displayTopicsForSidebar(topicPageSize, topicSortBy, topicIncludeCompleted),@@ -44,13 +40,11 @@ const FlatMode = memo(() => {<Flexbox gap={1}>{activeTopicList?.map((topic) => (<TopicItem- active={activeTopicId === topic.id}fav={topic.favorite}id={topic.id}key={topic.id}metadata={topic.metadata}status={topic.status}- threadId={activeThreadId}title={topic.title}userId={topic.userId}/>diff --git a/src/features/AgentSidebar/Topic/TopicListContent/GroupedAccordion.tsx b/src/features/AgentSidebar/Topic/TopicListContent/GroupedAccordion.tsxindex 869c107706b..101a2e1a699 100644--- a/src/features/AgentSidebar/Topic/TopicListContent/GroupedAccordion.tsx+++ b/src/features/AgentSidebar/Topic/TopicListContent/GroupedAccordion.tsx@@ -21,8 +21,6 @@ import { useAgentTopicGroupMode } from '../hooks/useAgentTopicGroupMode';import { useNavigateToAgentTopics } from '../hooks/useTopicNavigation';export interface GroupItemComponentProps {- activeThreadId?: string;- activeTopicId?: string;expanded: boolean;group: GroupedTopic;}@@ -44,7 +42,6 @@ const GroupedAccordion = memo<GroupedAccordionProps>(({ GroupItem }) => {topicSelectors.isExpandingPageSize(s),s.activeAgentId,]);- const [activeTopicId, activeThreadId] = useChatStore((s) => [s.activeTopicId, s.activeThreadId]);const groupSelector = useMemo(() =>@@ -69,13 +66,7 @@ const GroupedAccordion = memo<GroupedAccordionProps>(({ GroupItem }) => {onExpandedChange={(keys) => setExpandedKeys(keys as string[])}>{groupTopics.map((group) => (- <GroupItem- activeThreadId={activeThreadId}- activeTopicId={activeTopicId}- expanded={expandedKeys.includes(group.id)}- group={group}- key={group.id}- />+ <GroupItem expanded={expandedKeys.includes(group.id)} group={group} key={group.id} />))}</Accordion>{isExpandingPageSize && <SkeletonList rows={3} />}diff --git a/src/features/AgentSidebar/Topic/TopicListContent/SearchResult/index.tsx b/src/features/AgentSidebar/Topic/TopicListContent/SearchResult/index.tsxindex f7accc5a1c3..02eae3a61d7 100644--- a/src/features/AgentSidebar/Topic/TopicListContent/SearchResult/index.tsx+++ b/src/features/AgentSidebar/Topic/TopicListContent/SearchResult/index.tsx@@ -13,10 +13,7 @@ import TopicItem from '../../List/Item';const SearchResult = memo(() => {const { t } = useTranslation('topic');- const [activeTopicId, isSearchingTopic] = useChatStore((s) => [- s.activeTopicId,- topicSelectors.isSearchingTopic(s),- ]);+ const isSearchingTopic = useChatStore((s) => topicSelectors.isSearchingTopic(s));const topics = useChatStore(topicSelectors.searchTopics, isEqual);if (isSearchingTopic) return <SkeletonList />;@@ -32,7 +29,6 @@ const SearchResult = memo(() => {<>{topics.map((topic) => (<TopicItem- active={activeTopicId === topic.id}fav={topic.favorite}id={topic.id}key={topic.id}diff --git a/src/features/AgentTasks/AgentTaskDetail/TaskVerifyConfig.tsx b/src/features/AgentTasks/AgentTaskDetail/TaskVerifyConfig.tsxindex e3f47e51055..72c9a251edf 100644--- a/src/features/AgentTasks/AgentTaskDetail/TaskVerifyConfig.tsx+++ b/src/features/AgentTasks/AgentTaskDetail/TaskVerifyConfig.tsx@@ -32,6 +32,7 @@ import { openVerifyCriterionModal } from '@/features/AgentTasks/AgentTaskDetail/import { VerifyCriterionEditor } from '@/features/AgentTasks/AgentTaskDetail/VerifyCriterionModal/VerifyCriterionForm';import { useRubrics } from '@/features/Verify/hooks';import { usePermission } from '@/hooks/usePermission';+import { useSingleton } from '@/hooks/useSingleton';import { type VerifyCriterionDraft, verifyService } from '@/services/verify';import { useAgentStore } from '@/store/agent';import { agentByIdSelectors, agentSelectors } from '@/store/agent/selectors';@@ -158,7 +159,7 @@ const TaskVerifyConfig = memo(() => {// Hydrate the working list once per task from the persisted criterion ids.const hydratedTaskRef = useRef<string | null>(null);- const criterionIdsRef = useRef(new Map<string, string>());+ const criterionIds = useSingleton(() => new Map<string, string>());useEffect(() => {if (!taskId) return;if (hydratedTaskRef.current === taskId) return;@@ -166,7 +167,7 @@ const TaskVerifyConfig = memo(() => {setRequirement(verify?.requirement ?? '');setEnabled(verify?.enabled !== false);setShowTemplatePicker(false);- criterionIdsRef.current.clear();+ criterionIds.clear();const ids = verify?.verifyCriteriaIds ?? [];if (ids.length === 0) {@@ -195,13 +196,14 @@ const TaskVerifyConfig = memo(() => {c.id,),);- criterionIdsRef.current = new Map(- ordered.flatMap((draft) => (draft.criterionId ? [[draft.id, draft.criterionId]] : [])),- );+ criterionIds.clear();+ for (const draft of ordered) {+ if (draft.criterionId) criterionIds.set(draft.id, draft.criterionId);+ }setDrafts(ordered);}).finally(() => setHydrated(true));- }, [taskId, verify?.verifyCriteriaIds, verify?.requirement, verify?.enabled]);+ }, [criterionIds, taskId, verify?.verifyCriteriaIds, verify?.requirement, verify?.enabled]);// ---- debounced persistence ----const saveTimerRef = useRef<ReturnType<typeof setTimeout>>(undefined);@@ -224,7 +226,7 @@ const TaskVerifyConfig = memo(() => {.filter((d) => d.title.trim().length > 0).map((draft) => ({...draft,- criterionId: criterionIdsRef.current.get(draft.id) ?? draft.criterionId,+ criterionId: criterionIds.get(draft.id) ?? draft.criterionId,}));const requirement = payload.requirement.trim() || null;if (cleaned.length === 0) {@@ -244,7 +246,7 @@ const TaskVerifyConfig = memo(() => {);existing.forEach((draft, index) => {draft.criterionId = localIds[index];- criterionIdsRef.current.set(draft.id, localIds[index]);+ criterionIds.set(draft.id, localIds[index]);});await Promise.all(existing.map(@@ -280,7 +282,7 @@ const TaskVerifyConfig = memo(() => {);additions.forEach((draft, index) => {draft.criterionId = createdIds[index];- criterionIdsRef.current.set(draft.id, createdIds[index]);+ criterionIds.set(draft.id, createdIds[index]);});const ids = cleaned.map(({ criterionId }) => criterionId!);await useTaskStore.getState().updateVerifyConfig(taskId, {@@ -291,7 +293,7 @@ const TaskVerifyConfig = memo(() => {setDrafts((current) =>current.map((draft) => ({...draft,- criterionId: criterionIdsRef.current.get(draft.id) ?? draft.criterionId,+ criterionId: criterionIds.get(draft.id) ?? draft.criterionId,})),);}@@ -300,7 +302,7 @@ const TaskVerifyConfig = memo(() => {} finally {savingRef.current = false;}- }, [taskId]);+ }, [criterionIds, taskId]);const persist = useCallback((nextDrafts: DraftItem[], nextEnabled: boolean, nextRequirement: string) => {diff --git a/src/features/ChatInput/ActionBar/Token/TokenDetails.tsx b/src/features/ChatInput/ActionBar/Token/TokenDetails.tsxnew file mode 100644index 00000000000..ce604bca3fc--- /dev/null+++ b/src/features/ChatInput/ActionBar/Token/TokenDetails.tsx@@ -0,0 +1,105 @@+import { Center, Flexbox, Tooltip } from '@lobehub/ui';+import { cssVar } from 'antd-style';+import numeral from 'numeral';+import { memo } from 'react';+import { useTranslation } from 'react-i18next';++import { useUserStore } from '@/store/user';+import { userGeneralSettingsSelectors } from '@/store/user/selectors';++import TokenProgress from './TokenProgress';+import { type TokenBreakdown } from './useTokenBreakdown';++interface TokenDetailsProps {+ breakdown: TokenBreakdown;+}++const TokenDetails = memo<TokenDetailsProps>(({ breakdown }) => {+ const { t } = useTranslation(['chat', 'components']);++ const { chatsToken, historySummaryToken, maxTokens, systemRoleToken, toolsToken, totalToken } =+ breakdown;+ const isDevMode = useUserStore((s) => userGeneralSettingsSelectors.config(s).isDevMode);++ return (+ <Flexbox gap={12} style={{ minWidth: 200 }}>+ <Flexbox horizontal align={'center'} gap={4} justify={'space-between'} width={'100%'}>+ <div style={{ color: cssVar.colorTextDescription }}>{t('tokenDetails.title')}</div>+ <Tooltip+ styles={{ root: { maxWidth: 'unset', pointerEvents: 'none' } }}+ title={t('ModelSelect.featureTag.tokens', {+ ns: 'components',+ tokens: numeral(maxTokens).format('0,0'),+ })}+ >+ <Center+ height={20}+ paddingInline={4}+ style={{+ background: cssVar.colorFillTertiary,+ borderRadius: 4,+ color: cssVar.colorTextSecondary,+ fontFamily: cssVar.fontFamilyCode,+ fontSize: 11,+ }}+ >+ TOKEN+ </Center>+ </Tooltip>+ </Flexbox>+ {isDevMode && (+ <TokenProgress+ showIcon+ data={[+ {+ color: cssVar.magenta,+ id: 'systemRole',+ title: t('tokenDetails.systemRole'),+ value: systemRoleToken,+ },+ {+ color: cssVar.geekblue,+ id: 'tools',+ title: t('tokenDetails.tools'),+ value: toolsToken,+ },+ {+ color: cssVar.orange,+ id: 'historySummary',+ title: t('tokenDetails.historySummary'),+ value: historySummaryToken,+ },+ {+ color: cssVar.gold,+ id: 'chats',+ title: t('tokenDetails.chats'),+ value: chatsToken,+ },+ ]}+ />+ )}+ <TokenProgress+ showIcon={isDevMode}+ showTotal={t('tokenDetails.total')}+ data={[+ {+ color: cssVar.colorSuccess,+ id: 'used',+ title: t('tokenDetails.used'),+ value: totalToken,+ },+ {+ color: cssVar.colorFill,+ id: 'rest',+ title: t('tokenDetails.rest'),+ value: maxTokens - totalToken,+ },+ ]}+ />+ </Flexbox>+ );+});++TokenDetails.displayName = 'ContextWindowTokenDetails';++export default TokenDetails;diff --git a/src/features/ChatInput/ActionBar/Token/TokenTag.tsx b/src/features/ChatInput/ActionBar/Token/TokenTag.tsxindex c49f297986f..18396328af1 100644--- a/src/features/ChatInput/ActionBar/Token/TokenTag.tsx+++ b/src/features/ChatInput/ActionBar/Token/TokenTag.tsx@@ -1,240 +1,40 @@-import { ToolNameResolver } from '@lobechat/context-engine';-import { pluginPrompts } from '@lobechat/prompts';-import { Center, Flexbox, Tooltip } from '@lobehub/ui';import { TokenTag } from '@lobehub/ui/chat';-import { cssVar } from 'antd-style';-import numeral from 'numeral';-import { memo, useCallback } from 'react';+import { memo, useMemo } from 'react';import { useTranslation } from 'react-i18next';-import { createAgentToolsEngine } from '@/helpers/toolEngineering';-import { useModelContextWindowTokens } from '@/hooks/useModelContextWindowTokens';-import { useModelSupportToolUse } from '@/hooks/useModelSupportToolUse';-import { useTokenCount } from '@/hooks/useTokenCount';-import { useAgentStore } from '@/store/agent';-import { agentByIdSelectors, chatConfigByIdSelectors } from '@/store/agent/selectors';-import { useAiInfraStore } from '@/store/aiInfra';-import { aiModelSelectors, aiProviderSelectors } from '@/store/aiInfra/selectors';-import { useChatStore } from '@/store/chat';-import { topicSelectors } from '@/store/chat/selectors';-import { useToolStore } from '@/store/tool';-import { pluginHelpers } from '@/store/tool/helpers';import { useUserStore } from '@/store/user';-import { settingsSelectors, userGeneralSettingsSelectors } from '@/store/user/selectors';+import { userGeneralSettingsSelectors } from '@/store/user/selectors';-import { useAgentId } from '../../hooks/useAgentId';-import { useEffectiveModel } from '../../hooks/useEffectiveModel';-import { useChatInputStore } from '../../store';import ActionPopover from '../components/ActionPopover';-import TokenProgress from './TokenProgress';-import { getToolContextRefreshKey, getToolExcludeDefaultToolIds } from './utils';--const toolNameResolver = new ToolNameResolver();+import TokenDetails from './TokenDetails';+import { useTokenBreakdown } from './useTokenBreakdown';const Token = memo(() => {- const { t } = useTranslation(['chat', 'components']);-- const [input, contextWindowMessages] = useChatInputStore((s) => [- s.markdownContent,- s.contextWindowMessages,- ]);- const historySummary = useChatStore(- (s) => topicSelectors.currentActiveTopicSummary(s)?.content || '',- );-- const agentId = useAgentId();- const { model, provider } = useEffectiveModel(agentId);- const [- activeAgentId,- systemRole,- enableAgentMode,- searchMode,- useModelBuiltinSearch,- skillActivateMode,- agentMemoryEnabled,- runtimeMode,- hasEnabledKnowledgeBases,- ] = useAgentStore((s) => {- const chatConfig = chatConfigByIdSelectors.getChatConfigById(agentId)(s);-- return [- s.activeAgentId,- agentByIdSelectors.getAgentSystemRoleById(agentId)(s),- chatConfig.enableAgentMode,- chatConfig.searchMode,- chatConfig.useModelBuiltinSearch,- chatConfigByIdSelectors.getSkillActivateModeById(agentId)(s),- chatConfig.memory?.enabled,- chatConfigByIdSelectors.getRuntimeModeById(agentId)(s),- agentByIdSelectors- .getAgentKnowledgeBasesById(agentId)(s)- .some((item) => item.enabled),- ];- });- const globalMemoryEnabled = useUserStore(settingsSelectors.memoryEnabled);- const effectiveMemoryEnabled = agentMemoryEnabled ?? globalMemoryEnabled;- const [isProviderHasBuiltinSearch, isModelHasBuiltinSearch, isModelBuiltinSearchInternal] =- useAiInfraStore((s) => [- aiProviderSelectors.isProviderHasBuiltinSearch(provider)(s),- aiModelSelectors.isModelHasBuiltinSearch(model, provider)(s),- aiModelSelectors.isModelBuiltinSearchInternal(model, provider)(s),- ]);- const toolContextRefreshKey = getToolContextRefreshKey({- agentId: activeAgentId || agentId,- enableAgentMode,- hasEnabledKnowledgeBases,- isModelBuiltinSearchInternal,- isModelHasBuiltinSearch,- isProviderHasBuiltinSearch,- memoryEnabled: effectiveMemoryEnabled,- runtimeMode,- searchMode,- skillActivateMode,- useModelBuiltinSearch,- });-- const maxTokens = useModelContextWindowTokens(model, provider);-- // Tool usage token- const canUseTool = useModelSupportToolUse(model, provider);- const pluginIds = useAgentStore((s) => agentByIdSelectors.getAgentPluginsById(agentId)(s));-- const toolsString = useToolStore(- useCallback(() => {- const toolsEngine = createAgentToolsEngine({ model, provider });-- const { tools, enabledManifests } = toolsEngine.generateToolsDetailed({- excludeDefaultToolIds: getToolExcludeDefaultToolIds(skillActivateMode),- model,- provider,- toolIds: pluginIds,- });- const schemaNumber = tools?.map((i) => JSON.stringify(i)).join('') || '';-- // Generate plugin system roles from enabledManifests- const toolsSystemRole =- enabledManifests.length > 0- ? pluginPrompts({- tools: enabledManifests.map((manifest) => ({- apis: manifest.api.map((api) => ({- desc: api.description,- name: toolNameResolver.generate(manifest.identifier, api.name, manifest.type),- })),- identifier: manifest.identifier,- name: pluginHelpers.getPluginTitle(manifest.meta) || manifest.identifier,- systemRole: manifest.systemRole,- })),- })- : '';-- return toolsSystemRole + schemaNumber;- // toolContextRefreshKey tracks implicit createAgentToolsEngine inputs from other stores.- // eslint-disable-next-line react-hooks/exhaustive-deps- }, [model, pluginIds, provider, skillActivateMode, toolContextRefreshKey]),- );-- const toolsToken = useTokenCount(canUseTool ? toolsString : '');-- // Chat usage token- const inputTokenCount = useTokenCount(input);-- const messageString =- contextWindowMessages- ?.map((message) => (typeof message.content === 'string' ? message.content : ''))- .join('') || '';- const chatsToken = useTokenCount(messageString) + inputTokenCount;-- // SystemRole token- const systemRoleToken = useTokenCount(systemRole);- const historySummaryToken = useTokenCount(historySummary);-- // Total token- const totalToken = systemRoleToken + historySummaryToken + toolsToken + chatsToken;+ const { t } = useTranslation('chat');+ const { chatsToken, historySummaryToken, maxTokens, systemRoleToken, toolsToken, totalToken } =+ useTokenBreakdown();const isDevMode = useUserStore((s) => userGeneralSettingsSelectors.config(s).isDevMode);+ const content = useMemo(+ () => (+ <TokenDetails+ breakdown={{+ chatsToken,+ historySummaryToken,+ maxTokens,+ systemRoleToken,+ toolsToken,+ totalToken,+ }}+ />+ ),+ [chatsToken, historySummaryToken, maxTokens, systemRoleToken, toolsToken, totalToken],+ );// Keep the composer quiet for regular users until context pressure is real;// dev mode always shows the tag for inspection.if (!isDevMode && maxTokens > 0 && totalToken / maxTokens <= 0.5) return null;- const content = (- <Flexbox gap={12} style={{ minWidth: 200 }}>- <Flexbox horizontal align={'center'} gap={4} justify={'space-between'} width={'100%'}>- <div style={{ color: cssVar.colorTextDescription }}>{t('tokenDetails.title')}</div>- <Tooltip- styles={{ root: { maxWidth: 'unset', pointerEvents: 'none' } }}- title={t('ModelSelect.featureTag.tokens', {- ns: 'components',- tokens: numeral(maxTokens).format('0,0'),- })}- >- <Center- height={20}- paddingInline={4}- style={{- background: cssVar.colorFillTertiary,- borderRadius: 4,- color: cssVar.colorTextSecondary,- fontFamily: cssVar.fontFamilyCode,- fontSize: 11,- }}- >- TOKEN- </Center>- </Tooltip>- </Flexbox>- {isDevMode && (- <TokenProgress- showIcon- data={[- {- color: cssVar.magenta,- id: 'systemRole',- title: t('tokenDetails.systemRole'),- value: systemRoleToken,- },- {- color: cssVar.geekblue,- id: 'tools',- title: t('tokenDetails.tools'),- value: toolsToken,- },- {- color: cssVar.orange,- id: 'historySummary',- title: t('tokenDetails.historySummary'),- value: historySummaryToken,- },- {- color: cssVar.gold,- id: 'chats',- title: t('tokenDetails.chats'),- value: chatsToken,- },- ]}- />- )}- <TokenProgress- showIcon={isDevMode}- showTotal={t('tokenDetails.total')}- data={[- {- color: cssVar.colorSuccess,- id: 'used',- title: t('tokenDetails.used'),- value: totalToken,- },- {- color: cssVar.colorFill,- id: 'rest',- title: t('tokenDetails.rest'),- value: maxTokens - totalToken,- },- ]}- />- </Flexbox>- );-return (<ActionPopover content={content}><TokenTag@@ -255,4 +55,6 @@ const Token = memo(() => {);});+Token.displayName = 'ContextWindowToken';+export default Token;diff --git a/src/features/ChatInput/ActionBar/Token/useTokenBreakdown.ts b/src/features/ChatInput/ActionBar/Token/useTokenBreakdown.tsnew file mode 100644index 00000000000..18ce8b97729--- /dev/null+++ b/src/features/ChatInput/ActionBar/Token/useTokenBreakdown.ts@@ -0,0 +1,190 @@+import { ToolNameResolver } from '@lobechat/context-engine';+import { pluginPrompts } from '@lobechat/prompts';+import { debounce } from 'es-toolkit/compat';+import { startTransition, useEffect, useMemo, useState } from 'react';++import { createAgentToolsEngine } from '@/helpers/toolEngineering';+import { useModelContextWindowTokens } from '@/hooks/useModelContextWindowTokens';+import { useModelSupportToolUse } from '@/hooks/useModelSupportToolUse';+import { useTokenCount } from '@/hooks/useTokenCount';+import { useAgentStore } from '@/store/agent';+import { agentByIdSelectors, chatConfigByIdSelectors } from '@/store/agent/selectors';+import { useAiInfraStore } from '@/store/aiInfra';+import { aiModelSelectors, aiProviderSelectors } from '@/store/aiInfra/selectors';+import { useChatStore } from '@/store/chat';+import { topicSelectors } from '@/store/chat/selectors';+import { useToolStore } from '@/store/tool';+import { pluginHelpers } from '@/store/tool/helpers';+import { useUserStore } from '@/store/user';+import { settingsSelectors } from '@/store/user/selectors';++import { useAgentId } from '../../hooks/useAgentId';+import { useEffectiveModel } from '../../hooks/useEffectiveModel';+import { useStoreApi } from '../../store';+import { getToolContextRefreshKey, getToolExcludeDefaultToolIds } from './utils';++const toolNameResolver = new ToolNameResolver();++type ChatInputStoreApi = ReturnType<typeof useStoreApi>;++interface ComposerSource {+ input: string;+ messages: string;+}++const readComposerSource = (storeApi: ChatInputStoreApi): ComposerSource => {+ const state = storeApi.getState();+ return {+ input: state.markdownContent || '',+ messages:+ state.contextWindowMessages+ ?.map((message) => (typeof message.content === 'string' ? message.content : ''))+ .join('') || '',+ };+};++// A render subscription to `markdownContent` would re-render the tag on every+// keystroke at urgent priority. Read the composer imperatively behind a+// debounce instead, and publish through a transition so token counting never+// competes with typing.+const useComposerSource = (): ComposerSource => {+ const storeApi = useStoreApi();+ const [source, setSource] = useState<ComposerSource>(() => readComposerSource(storeApi));++ useEffect(() => {+ const update = debounce(() => {+ const next = readComposerSource(storeApi);+ startTransition(() => {+ setSource((prev) =>+ prev.input === next.input && prev.messages === next.messages ? prev : next,+ );+ });+ }, 300);+ update();+ const unsubscribe = storeApi.subscribe(update);+ return () => {+ unsubscribe();+ update.cancel();+ };+ }, [storeApi]);++ return source;+};++export interface TokenBreakdown {+ chatsToken: number;+ historySummaryToken: number;+ maxTokens: number;+ systemRoleToken: number;+ toolsToken: number;+ totalToken: number;+}++export const useTokenBreakdown = (): TokenBreakdown => {+ const { input, messages } = useComposerSource();+ const historySummary = useChatStore(+ (s) => topicSelectors.currentActiveTopicSummary(s)?.content || '',+ );++ const agentId = useAgentId();+ const { model, provider } = useEffectiveModel(agentId);+ const [+ activeAgentId,+ systemRole,+ enableAgentMode,+ searchMode,+ useModelBuiltinSearch,+ skillActivateMode,+ agentMemoryEnabled,+ runtimeMode,+ hasEnabledKnowledgeBases,+ ] = useAgentStore((s) => {+ const chatConfig = chatConfigByIdSelectors.getChatConfigById(agentId)(s);++ return [+ s.activeAgentId,+ agentByIdSelectors.getAgentSystemRoleById(agentId)(s),+ chatConfig.enableAgentMode,+ chatConfig.searchMode,+ chatConfig.useModelBuiltinSearch,+ chatConfigByIdSelectors.getSkillActivateModeById(agentId)(s),+ chatConfig.memory?.enabled,+ chatConfigByIdSelectors.getRuntimeModeById(agentId)(s),+ agentByIdSelectors+ .getAgentKnowledgeBasesById(agentId)(s)+ .some((item) => item.enabled),+ ];+ });+ const globalMemoryEnabled = useUserStore(settingsSelectors.memoryEnabled);+ const effectiveMemoryEnabled = agentMemoryEnabled ?? globalMemoryEnabled;+ const [isProviderHasBuiltinSearch, isModelHasBuiltinSearch, isModelBuiltinSearchInternal] =+ useAiInfraStore((s) => [+ aiProviderSelectors.isProviderHasBuiltinSearch(provider)(s),+ aiModelSelectors.isModelHasBuiltinSearch(model, provider)(s),+ aiModelSelectors.isModelBuiltinSearchInternal(model, provider)(s),+ ]);+ const toolContextRefreshKey = getToolContextRefreshKey({+ agentId: activeAgentId || agentId,+ enableAgentMode,+ hasEnabledKnowledgeBases,+ isModelBuiltinSearchInternal,+ isModelHasBuiltinSearch,+ isProviderHasBuiltinSearch,+ memoryEnabled: effectiveMemoryEnabled,+ runtimeMode,+ searchMode,+ skillActivateMode,+ useModelBuiltinSearch,+ });++ const maxTokens = useModelContextWindowTokens(model, provider);++ const canUseTool = useModelSupportToolUse(model, provider);+ const pluginIds = useAgentStore((s) => agentByIdSelectors.getAgentPluginsById(agentId)(s));+ const installedPlugins = useToolStore((s) => s.installedPlugins);++ const toolsString = useMemo(() => {+ const toolsEngine = createAgentToolsEngine({ model, provider });++ const { tools, enabledManifests } = toolsEngine.generateToolsDetailed({+ excludeDefaultToolIds: getToolExcludeDefaultToolIds(skillActivateMode),+ model,+ provider,+ toolIds: pluginIds,+ });+ const schemaNumber = tools?.map((i) => JSON.stringify(i)).join('') || '';++ const toolsSystemRole =+ enabledManifests.length > 0+ ? pluginPrompts({+ tools: enabledManifests.map((manifest) => ({+ apis: manifest.api.map((api) => ({+ desc: api.description,+ name: toolNameResolver.generate(manifest.identifier, api.name, manifest.type),+ })),+ identifier: manifest.identifier,+ name: pluginHelpers.getPluginTitle(manifest.meta) || manifest.identifier,+ systemRole: manifest.systemRole,+ })),+ })+ : '';++ return toolsSystemRole + schemaNumber;+ // installedPlugins + toolContextRefreshKey track the implicit+ // createAgentToolsEngine inputs read via getState() (tool manifests plus+ // agent/user/aiInfra config), so the engine only re-runs when they change+ // instead of on every render.+ }, [installedPlugins, model, pluginIds, provider, skillActivateMode, toolContextRefreshKey]);++ const toolsToken = useTokenCount(canUseTool ? toolsString : '');++ const inputTokenCount = useTokenCount(input);+ const chatsToken = useTokenCount(messages) + inputTokenCount;++ const systemRoleToken = useTokenCount(systemRole);+ const historySummaryToken = useTokenCount(historySummary);++ const totalToken = systemRoleToken + historySummaryToken + toolsToken + chatsToken;++ return { chatsToken, historySummaryToken, maxTokens, systemRoleToken, toolsToken, totalToken };+};diff --git a/src/features/ChatInput/ActionBar/Tools/ScrollSignalContext.tsx b/src/features/ChatInput/ActionBar/Tools/ScrollSignalContext.tsxindex 58967a99c57..30db00c1f03 100644--- a/src/features/ChatInput/ActionBar/Tools/ScrollSignalContext.tsx+++ b/src/features/ChatInput/ActionBar/Tools/ScrollSignalContext.tsx@@ -10,6 +10,8 @@ import {useRef,} from 'react';+import { useSingleton } from '@/hooks/useSingleton';+type ScrollSubscriber = () => void;type Subscribe = (cb: ScrollSubscriber) => () => void;@@ -33,18 +35,21 @@ export const ScrollSignalProvider = ({className,style,}: ScrollSignalProviderProps & { ref?: React.RefObject<HTMLDivElement | null> }) => {- const listenersRef = useRef<Set<ScrollSubscriber>>(new Set());+ const listeners = useSingleton(() => new Set<ScrollSubscriber>());- const subscribe = useCallback<Subscribe>((cb) => {- listenersRef.current.add(cb);- return () => {- listenersRef.current.delete(cb);- };- }, []);+ const subscribe = useCallback<Subscribe>(+ (cb) => {+ listeners.add(cb);+ return () => {+ listeners.delete(cb);+ };+ },+ [listeners],+ );const handleScroll = useCallback(() => {- listenersRef.current.forEach((cb) => cb());- }, []);+ listeners.forEach((cb) => cb());+ }, [listeners]);return (<ScrollSignalContext value={subscribe}>diff --git a/src/features/ChatInput/ActionBar/index.test.ts b/src/features/ChatInput/ActionBar/index.test.tsindex b7a9c03bf84..9b5e7790f21 100644--- a/src/features/ChatInput/ActionBar/index.test.ts+++ b/src/features/ChatInput/ActionBar/index.test.ts@@ -1,6 +1,65 @@-import { describe, expect, it } from 'vitest';+/**+ * @vitest-environment happy-dom+ */+import { render, screen } from '@testing-library/react';+import { createElement, type ReactNode } from 'react';+import { beforeEach, describe, expect, it, vi } from 'vitest';import { filterChatOnlyActions } from './filterChatOnlyActions';+import Token from './Token/TokenTag';++const tokenMocks = vi.hoisted(() => ({+ useTokenBreakdown: vi.fn(),+}));++vi.mock('@lobehub/ui', () => {+ const Primitive = ({ children }: { children?: ReactNode }) => createElement('div', {}, children);++ return { Center: Primitive, Flexbox: Primitive, Tooltip: Primitive };+});++vi.mock('@lobehub/ui/chat', () => ({+ TokenTag: ({ value }: { value: number }) =>+ createElement('div', { 'data-testid': 'token-tag' }, value),+}));++vi.mock('antd-style', () => ({+ cssVar: new Proxy({}, { get: (_, key) => String(key) }),+}));++vi.mock('react-i18next', () => ({+ useTranslation: () => ({ t: (key: string) => key }),+}));++vi.mock('@/store/user', () => ({+ useUserStore: (selector: (state: object) => unknown) => selector({}),+}));++vi.mock('@/store/user/selectors', () => ({+ userGeneralSettingsSelectors: { config: () => ({ isDevMode: true }) },+}));++vi.mock('./components/ActionPopover', () => ({+ default: ({ children, content }: { children?: ReactNode; content?: ReactNode }) =>+ createElement('div', {}, children, content),+}));++vi.mock('./Token/TokenProgress', () => ({+ default: ({ data }: { data: { id: string; value: number }[] }) =>+ createElement(+ 'div',+ { 'data-testid': `token-progress-${data[0].id}` },+ data.map(({ id, value }) => `${id}:${value}`).join(','),+ ),+}));++vi.mock('./Token/useTokenBreakdown', () => ({+ useTokenBreakdown: tokenMocks.useTokenBreakdown,+}));++beforeEach(() => {+ tokenMocks.useTokenBreakdown.mockReset();+});describe('filterChatOnlyActions', () => {it('keeps runtime mode, attachments, formatting, and chat operations while hiding configuration actions', () => {@@ -23,3 +82,31 @@ describe('filterChatOnlyActions', () => {expect(filterChatOnlyActions(['modelLabel', 'plus'])).toEqual(['modelLabel', 'plus']);});});++describe('Context window token', () => {+ it('reuses the settled tag breakdown when rendering details', () => {+ tokenMocks.useTokenBreakdown+ .mockReturnValueOnce({+ chatsToken: 3000,+ historySummaryToken: 500,+ maxTokens: 8000,+ systemRoleToken: 1500,+ toolsToken: 1000,+ totalToken: 6000,+ })+ .mockReturnValue({+ chatsToken: 0,+ historySummaryToken: 0,+ maxTokens: 8000,+ systemRoleToken: 0,+ toolsToken: 0,+ totalToken: 0,+ });++ render(createElement(Token));++ expect(tokenMocks.useTokenBreakdown).toHaveBeenCalledTimes(1);+ expect(screen.getByTestId('token-tag')).toHaveTextContent('6000');+ expect(screen.getByTestId('token-progress-used')).toHaveTextContent('used:6000,rest:2000');+ });+});diff --git a/src/features/ChatInput/ChatInputProvider.tsx b/src/features/ChatInput/ChatInputProvider.tsxindex 144ff08eff8..c7115c819c9 100644--- a/src/features/ChatInput/ChatInputProvider.tsx+++ b/src/features/ChatInput/ChatInputProvider.tsx@@ -31,6 +31,7 @@ export const ChatInputProvider = memo<ChatInputProviderProps>(allowExpand = true,slashPlacement,getMessages,+ resolveSendBlocked,}) => {const editor = useEditor();const slashMenuRef = useRef<HTMLDivElement>(null);@@ -68,6 +69,7 @@ export const ChatInputProvider = memo<ChatInputProviderProps>(leftActions={leftActions}mentionItems={mentionItems}mobile={mobile}+ resolveSendBlocked={resolveSendBlocked}rightActions={rightActions}sendButtonProps={sendButtonProps}sendMenu={sendMenu}diff --git a/src/features/ChatInput/InputEditor/index.tsx b/src/features/ChatInput/InputEditor/index.tsxindex c637152a9cd..a733976c8b3 100644--- a/src/features/ChatInput/InputEditor/index.tsx+++ b/src/features/ChatInput/InputEditor/index.tsx@@ -22,6 +22,7 @@ import { usePasteFile, useUploadFiles } from '@/components/DragUploadZone';import { useEnterToSend } from '@/hooks/useEnterToSend';import { useIMECompositionEvent } from '@/hooks/useIMECompositionEvent';import { usePermission } from '@/hooks/usePermission';+import { useSingleton } from '@/hooks/useSingleton';import { aiChatService } from '@/services/aiChat';import { useAgentStore } from '@/store/agent';import { agentByIdSelectors } from '@/store/agent/selectors';@@ -271,18 +272,20 @@ const InputEditor = memo<{storeApi.getState().clearInputCompletionError();}, [inputCompletionConfig.model, inputCompletionConfig.provider, storeApi]);- const getMessagesRef = useRef(storeApi.getState().getMessages);+ const getMessagesRef = useSingleton(() => ({+ current: storeApi.getState().getMessages,+ }));useEffect(() => {return storeApi.subscribe((s) => {getMessagesRef.current = s.getMessages;});- }, [storeApi]);+ }, [getMessagesRef, storeApi]);// Map each in-flight suggestion to its tracing row so the Tab/Esc/typing// callbacks below can report `recordFeedback` against the correct id.// Keyed by editor-provided `suggestionId`; entries are dropped on// accept/reject (the plugin guarantees one of those eventually fires).- const tracingIdBySuggestionRef = useRef<Map<string, string>>(new Map());+ const tracingIdBySuggestion = useSingleton(() => new Map<string, string>());const handleAutoComplete = useCallback(async ({@@ -357,11 +360,11 @@ const InputEditor = memo<{if (!completion) return null;if (suggestionId && envelope?.tracingId) {- tracingIdBySuggestionRef.current.set(suggestionId, envelope.tracingId);+ tracingIdBySuggestion.set(suggestionId, envelope.tracingId);}return completion;},- [isComposingRef, storeApi, agentId],+ [agentId, getMessagesRef, isComposingRef, storeApi, tracingIdBySuggestion],);const handleSuggestionAccepted = useCallback(@@ -374,9 +377,9 @@ const InputEditor = memo<{suggestionId: string;visibleMs: number;}) => {- const tracingId = tracingIdBySuggestionRef.current.get(suggestionId);+ const tracingId = tracingIdBySuggestion.get(suggestionId);if (!tracingId) return;- tracingIdBySuggestionRef.current.delete(suggestionId);+ tracingIdBySuggestion.delete(suggestionId);aiChatService.recordTracingFeedback({data: { acceptedText, visibleMs },@@ -388,7 +391,7 @@ const InputEditor = memo<{console.warn('[InputCompletion] recordFeedback (accepted) failed', err);});},- [],+ [tracingIdBySuggestion],);const handleSuggestionRejected = useCallback(@@ -401,9 +404,9 @@ const InputEditor = memo<{suggestionId: string;visibleMs: number;}) => {- const tracingId = tracingIdBySuggestionRef.current.get(suggestionId);+ const tracingId = tracingIdBySuggestion.get(suggestionId);if (!tracingId) return;- tracingIdBySuggestionRef.current.delete(suggestionId);+ tracingIdBySuggestion.delete(suggestionId);// IME composition starts by dispatching KEY_ESCAPE_COMMAND from this// component (see onCompositionStart below); that arrives here with// reason='esc' but it isn't a real reject — recode as neutral so the@@ -423,7 +426,7 @@ const InputEditor = memo<{console.warn('[InputCompletion] recordFeedback (rejected) failed', err);});},- [isComposingRef],+ [isComposingRef, tracingIdBySuggestion],);const autoCompletePlugin = useMemo(diff --git a/src/features/ChatInput/StoreUpdater.test.tsx b/src/features/ChatInput/StoreUpdater.test.tsxindex ee5487fdeac..4ea05625937 100644--- a/src/features/ChatInput/StoreUpdater.test.tsx+++ b/src/features/ChatInput/StoreUpdater.test.tsx@@ -1,8 +1,10 @@import { type MenuProps } from '@lobehub/ui';import { render } from '@testing-library/react';-import { type PropsWithChildren, useEffect, useRef } from 'react';+import { type PropsWithChildren, useEffect } from 'react';import { describe, expect, it, vi } from 'vitest';+import { useSingleton } from '@/hooks/useSingleton';+import { createStore, Provider, useChatInputStore } from './store';import StoreUpdater from './StoreUpdater';@@ -26,9 +28,9 @@ const Probe = ({};const TestHarness = ({ children }: PropsWithChildren) => {- const storeRef = useRef(createStore());+ const store = useSingleton(createStore);- return <Provider createStore={() => storeRef.current}>{children}</Provider>;+ return <Provider createStore={() => store}>{children}</Provider>;};describe('ChatInput StoreUpdater', () => {diff --git a/src/features/ChatInput/StoreUpdater.tsx b/src/features/ChatInput/StoreUpdater.tsxindex 515f9a42e06..2e62881474d 100644--- a/src/features/ChatInput/StoreUpdater.tsx+++ b/src/features/ChatInput/StoreUpdater.tsx@@ -1,7 +1,7 @@'use client';import { type ForwardedRef } from 'react';-import { memo, useEffect, useImperativeHandle } from 'react';+import { memo, useEffect, useImperativeHandle, useLayoutEffect } from 'react';import { createStoreUpdater } from 'zustand-utils';import { type ChatInputEditor } from './hooks/useChatInputEditor';@@ -33,6 +33,7 @@ const StoreUpdater = memo<StoreUpdaterProps>(allowExpand,slashPlacement,getMessages,+ resolveSendBlocked,}) => {const storeApi = useStoreApi();const useStoreUpdater = createStoreUpdater(storeApi);@@ -41,7 +42,15 @@ const StoreUpdater = memo<StoreUpdaterProps>(useStoreUpdater('agentId', agentId);useStoreUpdater('contextSelectionKey', contextSelectionKey);useStoreUpdater('contextWindowMessages', contextWindowMessages);- useStoreUpdater('draftKey', draftKey);++ // Sync draftKey before paint: the draft-transition subscriber+ // (useChatInputDraft) swaps the editor document on this change, and doing+ // it post-paint would flash the previous topic's draft for one frame.+ useLayoutEffect(() => {+ if (draftKey !== undefined && storeApi.getState().draftKey !== draftKey) {+ storeApi.setState({ draftKey });+ }+ }, [draftKey, storeApi]);useStoreUpdater('mobile', mobile!);useStoreUpdater('mentionItems', mentionItems);useStoreUpdater('leftActions', leftActions!);@@ -52,6 +61,7 @@ const StoreUpdater = memo<StoreUpdaterProps>(useStoreUpdater('getMessages', getMessages);useStoreUpdater('sendButtonProps', sendButtonProps);+ useStoreUpdater('resolveSendBlocked', resolveSendBlocked);useStoreUpdater('onSend', onSend);useStoreUpdater('onMarkdownContentChange', onMarkdownContentChange);diff --git a/src/features/ChatInput/hooks/useChatInputDraft.test.tsx b/src/features/ChatInput/hooks/useChatInputDraft.test.tsxindex 2ff9de20e3e..9244f8b0362 100644--- a/src/features/ChatInput/hooks/useChatInputDraft.test.tsx+++ b/src/features/ChatInput/hooks/useChatInputDraft.test.tsx@@ -64,6 +64,119 @@ describe('useChatInputDraft', () => {expect(setDocument).toHaveBeenCalledWith('json', draftJson);});+ it('saves the old draft, clears the editor and restores the new draft on draftKey change', () => {+ const oldJson = { root: { children: [{ text: 'old topic draft' }] } };+ const newJson = { root: { children: [{ text: 'new topic draft' }] } };+ let markdown = 'old topic draft';+ let empty = false;+ const editor = {+ cleanDocument: vi.fn(() => {+ markdown = '';+ empty = true;+ }),+ focus: vi.fn(),+ getDocument: vi.fn((type: string) => (type === 'markdown' ? markdown : oldJson)),+ get isEmpty() {+ return empty;+ },+ setDocument: vi.fn(),+ } as unknown as IEditor;+ const store = createStore({ draftKey: 'main_agt_a_tpc_1', editor });+ const wrapper = ({ children }: { children: ReactNode }) => (+ <Provider createStore={() => store}>{children}</Provider>+ );+ saveDraft('main_agt_a_tpc_2', newJson);++ const { result } = renderHook(() => useChatInputDraft(), { wrapper });++ act(() => {+ result.current.saveDraftDebounced();+ store.setState({ draftKey: 'main_agt_a_tpc_2' });+ });++ expect(getDraft('main_agt_a_tpc_1')).toEqual(oldJson);+ expect(editor.cleanDocument).toHaveBeenCalledTimes(1);+ expect(editor.setDocument).toHaveBeenCalledWith('json', newJson);++ act(() => {+ vi.runAllTimers();+ });++ expect(getDraft('main_agt_a_tpc_1')).toEqual(oldJson);+ expect(getDraft('main_agt_a_tpc_2')).toEqual(newJson);+ });++ it('focuses the editor after switching to another draft key', () => {+ const focus = vi.fn();+ const editor = {+ cleanDocument: vi.fn(),+ focus,+ getDocument: vi.fn((type: string) => (type === 'markdown' ? '' : undefined)),+ isEmpty: true,+ setDocument: vi.fn(),+ } as unknown as IEditor;+ const store = createStore({ draftKey: 'main_agt_a_tpc_1', editor });+ const wrapper = ({ children }: { children: ReactNode }) => (+ <Provider createStore={() => store}>{children}</Provider>+ );++ renderHook(() => useChatInputDraft(), { wrapper });++ expect(focus).not.toHaveBeenCalled();++ act(() => {+ store.setState({ draftKey: 'main_agt_a_tpc_2' });+ });++ expect(focus).toHaveBeenCalledTimes(1);+ });++ it('does not auto-focus on mobile after switching draft key', () => {+ const focus = vi.fn();+ const editor = {+ cleanDocument: vi.fn(),+ focus,+ getDocument: vi.fn((type: string) => (type === 'markdown' ? '' : undefined)),+ isEmpty: true,+ setDocument: vi.fn(),+ } as unknown as IEditor;+ const store = createStore({ draftKey: 'main_agt_a_tpc_1', editor, mobile: true });+ const wrapper = ({ children }: { children: ReactNode }) => (+ <Provider createStore={() => store}>{children}</Provider>+ );++ renderHook(() => useChatInputDraft(), { wrapper });++ act(() => {+ store.setState({ draftKey: 'main_agt_a_tpc_2' });+ });++ expect(focus).not.toHaveBeenCalled();+ });++ it('removes the old draft when leaving with an emptied editor', () => {+ const editor = {+ cleanDocument: vi.fn(),+ focus: vi.fn(),+ getDocument: vi.fn((type: string) => (type === 'markdown' ? '' : undefined)),+ isEmpty: true,+ setDocument: vi.fn(),+ } as unknown as IEditor;+ const store = createStore({ draftKey: 'main_agt_a_tpc_1', editor });+ const wrapper = ({ children }: { children: ReactNode }) => (+ <Provider createStore={() => store}>{children}</Provider>+ );+ saveDraft('main_agt_a_tpc_1', { root: { children: [{ text: 'stale' }] } });++ renderHook(() => useChatInputDraft(), { wrapper });++ act(() => {+ store.setState({ draftKey: 'main_agt_a_tpc_2' });+ });++ expect(getDraft('main_agt_a_tpc_1')).toBeUndefined();+ });+it('does not overwrite current editor input when restoring a draft', () => {const setDocument = vi.fn();const editor = {diff --git a/src/features/ChatInput/hooks/useChatInputDraft.ts b/src/features/ChatInput/hooks/useChatInputDraft.tsindex cbafce81f07..24d8dbc510a 100644--- a/src/features/ChatInput/hooks/useChatInputDraft.ts+++ b/src/features/ChatInput/hooks/useChatInputDraft.ts@@ -10,21 +10,29 @@ const SAVE_DEBOUNCE_MS = 500;export const useChatInputDraft = () => {const storeApi = useStoreApi();+ const persistDraftFor = useCallback(+ (draftKey: string) => {+ const { editor, getMarkdownContent, getJSONState } = storeApi.getState();+ if (!editor) return;++ if (getMarkdownContent().trim().length === 0) {+ removeDraft(draftKey);+ return;+ }++ const json = getJSONState();+ if (json) saveDraft(draftKey, json);+ },+ [storeApi],+ );+const saveDraftDebounced = useMemo(() =>debounce(() => {- const { draftKey, editor, getMarkdownContent, getJSONState } = storeApi.getState();- if (!draftKey || !editor) return;-- if (getMarkdownContent().trim().length === 0) {- removeDraft(draftKey);- return;- }-- const json = getJSONState();- if (json) saveDraft(draftKey, json);+ const { draftKey } = storeApi.getState();+ if (draftKey) persistDraftFor(draftKey);}, SAVE_DEBOUNCE_MS),- [storeApi],+ [persistDraftFor, storeApi],);useEffect(() => () => saveDraftDebounced.flush(), [saveDraftDebounced]);@@ -42,5 +50,28 @@ export const useChatInputDraft = () => {[storeApi],);+ // The store instance survives topic switches, so a draftKey change is the+ // conversation boundary: persist under the key the content was typed for+ // (cancelling the pending debounce, which would otherwise save it under the+ // new key), then swap the editor document in place. Focus last — the+ // document swap would drop any focus applied earlier in the switch, and on+ // mobile focusing would pop the keyboard on every switch.+ useEffect(+ () =>+ storeApi.subscribe((state, prevState) => {+ if (state.draftKey === prevState.draftKey) return;++ saveDraftDebounced.cancel();+ if (prevState.draftKey) persistDraftFor(prevState.draftKey);++ const { editor } = state;+ if (!editor) return;+ editor.cleanDocument();+ restoreDraft(editor);+ if (!state.mobile) editor.focus();+ }),+ [persistDraftFor, restoreDraft, saveDraftDebounced, storeApi],+ );+return { restoreDraft, saveDraftDebounced };};diff --git a/src/features/ChatInput/store/action.test.ts b/src/features/ChatInput/store/action.test.tsindex 416c91aa4d9..a954534e205 100644--- a/src/features/ChatInput/store/action.test.ts+++ b/src/features/ChatInput/store/action.test.ts@@ -131,6 +131,65 @@ describe('ChatInput store actions', () => {expect(dispatchCommand).not.toHaveBeenCalled();});+ // Regression: sendButtonProps.disabled mirrors editor content through the+ // editor's debounced onChange, so a fast type→Enter arrives while the+ // mirror still reads "empty" and used to be silently dropped.+ it('sends via resolveSendBlocked even when the stale disabled mirror says blocked', () => {+ const onSend = vi.fn();+ const editor = {+ cleanDocument: vi.fn(),+ focus: vi.fn(),+ getDocument: vi.fn((type: string) => (type === 'markdown' ? 'Hello' : { root: {} })),+ };+ const store = createStore({+ editor: editor as unknown as IEditor,+ onSend,+ resolveSendBlocked: () => false,+ sendButtonProps: { disabled: true, generating: false, onStop: vi.fn() },+ });++ store.getState().handleSendButton();++ expect(onSend).toHaveBeenCalledOnce();+ });++ it('blocks the send when resolveSendBlocked reports blocked', () => {+ const onSend = vi.fn();+ const editor = {+ cleanDocument: vi.fn(),+ focus: vi.fn(),+ getDocument: vi.fn((type: string) => (type === 'markdown' ? 'Hello' : { root: {} })),+ };+ const store = createStore({+ editor: editor as unknown as IEditor,+ onSend,+ resolveSendBlocked: () => true,+ sendButtonProps: { disabled: false, generating: false, onStop: vi.fn() },+ });++ store.getState().handleSendButton();++ expect(onSend).not.toHaveBeenCalled();+ });++ it('keeps gating on sendButtonProps.disabled when no resolver is provided', () => {+ const onSend = vi.fn();+ const editor = {+ cleanDocument: vi.fn(),+ focus: vi.fn(),+ getDocument: vi.fn((type: string) => (type === 'markdown' ? 'Hello' : { root: {} })),+ };+ const store = createStore({+ editor: editor as unknown as IEditor,+ onSend,+ sendButtonProps: { disabled: true, generating: false, onStop: vi.fn() },+ });++ store.getState().handleSendButton();++ expect(onSend).not.toHaveBeenCalled();+ });+it('does not record history when no send handler is configured', () => {const editor = {cleanDocument: vi.fn(),diff --git a/src/features/ChatInput/store/action.ts b/src/features/ChatInput/store/action.tsindex 8927738cde0..8cd33f362a7 100644--- a/src/features/ChatInput/store/action.ts+++ b/src/features/ChatInput/store/action.ts@@ -58,7 +58,9 @@ export const store: CreateStore = (publicState) => (set, get) => ({handleSendButton: () => {const editor = get().editor;if (!editor) return;- if (get().sendButtonProps?.disabled) return;++ const { resolveSendBlocked, sendButtonProps } = get();+ if (resolveSendBlocked ? resolveSendBlocked() : sendButtonProps?.disabled) return;// Drop any pending AI input-completion ghost before serializing the message.// The suggestion is materialized as real placeholder nodes inside thediff --git a/src/features/ChatInput/store/initialState.ts b/src/features/ChatInput/store/initialState.tsindex b2fc89b868f..75d5b273076 100644--- a/src/features/ChatInput/store/initialState.ts+++ b/src/features/ChatInput/store/initialState.ts@@ -67,6 +67,15 @@ export interface PublicState {mobile?: boolean;onMarkdownContentChange?: (content: string) => void;onSend?: SendButtonHandler;+ /**+ * Live send gate consulted by `handleSendButton` instead of+ * `sendButtonProps.disabled`. The disabled flag mirrors editor content+ * through the editor's debounced onChange, so a fast type→Enter arrives+ * while the mirror still reads "empty" and the send would be silently+ * dropped. Only hosts whose onSend re-validates its own gates should+ * provide this.+ */+ resolveSendBlocked?: () => boolean;rightActions: ActionKeys[];sendButtonProps?: SendButtonProps;sendMenu?: MenuProps;diff --git a/src/features/Conversation/ChatInput/index.tsx b/src/features/Conversation/ChatInput/index.tsxindex d582d895639..4893259ddaa 100644--- a/src/features/Conversation/ChatInput/index.tsx+++ b/src/features/Conversation/ChatInput/index.tsx@@ -293,6 +293,33 @@ const ChatInput = memo<ChatInputProps>(// disableSend hard-blocks regardless of content (host surface is read-only).const disabled =isInputEmpty || isUploadingFiles || (!!disableQueue && isInputQueueBlocked) || !!disableSend;++ // `disabled` above lags the editor: `inputMessage` mirrors content through+ // the editor's debounced onChange, so a fast type→Enter arrives while the+ // mirror still reads empty and the send would be silently dropped. Gate+ // Enter/click on live state instead — handleSend re-validates all of these+ // at trigger time, so this only mirrors the visual disabled semantics.+ const customDisabled = customSendButtonProps?.disabled;+ const resolveSendBlocked = useCallback(() => {+ if (disableSend) return true;+ if (customDisabled !== undefined) return customDisabled;++ const fileStore = useFileStore.getState();+ if (fileChatSelectors.isUploadingFiles(fileStore)) return true;++ const { context: liveContext, editor } = storeApi.getState();+ if (+ disableQueue &&+ operationSelectors.isInputLoadingByContext(liveContext)(useChatStore.getState())+ )+ return true;++ const hasText = String(editor?.getMarkdownContent?.() || '').trim().length > 0;+ const hasFiles = fileChatSelectors.chatUploadFileList(fileStore).length > 0;+ const hasContextSelections =+ fileChatSelectors.chatContextSelections(messageMapKey(liveContext))(fileStore).length > 0;+ return !hasText && !hasFiles && !hasContextSelections;+ }, [customDisabled, disableQueue, disableSend, storeApi]);const shouldUsePlainSendButton = !showSendMenu && !!sendMenu;const businessAlerts = useBusinessChatInputAlerts();const businessSendAreaPrefix = getBusinessChatInputSendAreaPrefix(sendAreaPrefix);@@ -449,6 +476,7 @@ const ChatInput = memo<ChatInputProps>(getMessages={getMessages}leftActions={leftActions}mentionItems={mentionItems}+ resolveSendBlocked={resolveSendBlocked}rightActions={rightActions}sendButtonProps={sendButtonProps}sendMenu={showSendMenu ? sendMenu : undefined}diff --git a/src/features/Conversation/ChatList/components/VirtualizedList.tsx b/src/features/Conversation/ChatList/components/VirtualizedList.tsxindex d4af69f8a65..0a4293cbcbb 100644--- a/src/features/Conversation/ChatList/components/VirtualizedList.tsx+++ b/src/features/Conversation/ChatList/components/VirtualizedList.tsx@@ -88,6 +88,7 @@ const VirtualizedList = memo<VirtualizedListProps>(spacerActive,spacerHeight,} = useConversationScroll({+ contextKey,dataSource,headerOffset,isSecondLastMessageFromUser,diff --git a/src/features/Conversation/ChatList/hooks/useConversationScroll.test.ts b/src/features/Conversation/ChatList/hooks/useConversationScroll.test.tsindex ad66de7515b..8181e4ab8ee 100644--- a/src/features/Conversation/ChatList/hooks/useConversationScroll.test.ts+++ b/src/features/Conversation/ChatList/hooks/useConversationScroll.test.ts@@ -156,6 +156,7 @@ describe('useConversationScroll — pin behavior', () => {};const renderScrollHook = (props: {+ contextKey?: string;dataSource: string[];headerOffset?: number;isSecondLastMessageFromUser: boolean;@@ -173,8 +174,9 @@ describe('useConversationScroll — pin behavior', () => {installStoreMock();const hook = renderHook(- ({ dataSource, isSecondLastMessageFromUser }) =>+ ({ contextKey, dataSource, isSecondLastMessageFromUser }) =>useConversationScroll({+ contextKey,dataSource,headerOffset: props.headerOffset,isSecondLastMessageFromUser,@@ -182,18 +184,23 @@ describe('useConversationScroll — pin behavior', () => {}),{initialProps: {+ contextKey: props.contextKey,dataSource: props.dataSource,isSecondLastMessageFromUser: props.isSecondLastMessageFromUser,},},);- const rerender = (next: { dataSource: string[]; isSecondLastMessageFromUser: boolean }) => {+ const rerender = (next: {+ contextKey?: string;+ dataSource: string[];+ isSecondLastMessageFromUser: boolean;+ }) => {currentFixture = {...currentFixture,displayMessages: deriveDisplayMessages(next.isSecondLastMessageFromUser),};- hook.rerender(next);+ hook.rerender({ contextKey: undefined, ...next });};return { ...hook, rerender };@@ -290,6 +297,58 @@ describe('useConversationScroll — pin behavior', () => {expect(scrollToIndex).not.toHaveBeenCalled();});+ it('does not treat a topic switch as a send even when the length delta is +2', () => {+ const { rerender } = renderScrollHook({+ contextKey: 'main_agt_1_tpc_a',+ dataSource: [assistantId, 'prev'],+ isSecondLastMessageFromUser: false,+ });++ rerender({+ contextKey: 'main_agt_1_tpc_b',+ dataSource: ['m0', 'm1', userId, assistantId],+ isSecondLastMessageFromUser: true,+ });++ expect(scrollToIndex).not.toHaveBeenCalled();+ });++ it('deactivates a live spacer when the context switches', async () => {+ const { result, rerender } = renderScrollHook({+ contextKey: 'main_agt_1_tpc_a',+ dataSource: [assistantId, 'prev'],+ isSecondLastMessageFromUser: false,+ fixture: {+ virtuaScrollMethods: {+ getItemOffset: (i: number) => i * 100,+ getItemSize: () => 80,+ getScrollOffset: () => 0,+ getViewportSize: () => 800,+ },+ },+ });++ rerender({+ contextKey: 'main_agt_1_tpc_a',+ dataSource: ['m0', 'm1', userId, assistantId],+ isSecondLastMessageFromUser: true,+ });+ await act(async () => {+ await vi.advanceTimersByTimeAsync(50);+ });++ expect(result.current.spacerActive).toBe(true);++ rerender({+ contextKey: 'main_agt_1_tpc_b',+ dataSource: ['x0', 'x1', 'x2'],+ isSecondLastMessageFromUser: false,+ });++ expect(result.current.spacerActive).toBe(false);+ expect(result.current.listData).toEqual(['x0', 'x1', 'x2']);+ });+it('does not throw or scroll when virtuaRef is not ready at send time', () => {virtuaRef.current = null;diff --git a/src/features/Conversation/ChatList/hooks/useConversationScroll.ts b/src/features/Conversation/ChatList/hooks/useConversationScroll.tsindex d52276136a1..1b175a6b42c 100644--- a/src/features/Conversation/ChatList/hooks/useConversationScroll.ts+++ b/src/features/Conversation/ChatList/hooks/useConversationScroll.ts@@ -1,6 +1,14 @@import { type AssistantContentBlock, type UIChatMessage } from '@lobechat/types';import debug from 'debug';-import { type RefObject, useCallback, useEffect, useMemo, useRef, useState } from 'react';+import {+ type RefObject,+ useCallback,+ useEffect,+ useLayoutEffect,+ useMemo,+ useRef,+ useState,+} from 'react';import { type VListHandle } from 'virtua';import { dataSelectors, messageStateSelectors, useConversationStore } from '../../store';@@ -418,6 +426,14 @@ const useScrollShrink = ({// `scrollToIndex` once. The old 0/32/96ms timer fan-out is gone.// ---------------------------------------------------------------------------export interface UseConversationScrollOptions {+ /**+ * Conversation identity. The hook instance survives in-place topic switches+ * (the provider is not keyed by context), so a change here means the whole+ * dataSource was swapped for another conversation: send-detection and any+ * live spacer/pin state must reset instead of reading the new list through+ * the old topic's indices.+ */+ contextKey?: string;dataSource: string[];/*** Number of synthetic rows prepended to the VList before the messages@@ -445,6 +461,7 @@ export interface UseConversationScrollResult {}export const useConversationScroll = ({+ contextKey,dataSource,headerOffset = 0,isSecondLastMessageFromUser,@@ -509,6 +526,24 @@ export const useConversationScroll = ({setScrollReduction,});+ // useLayoutEffect: runs before the passive send-detection effect in the+ // switch commit, so seeding prevLengthRef with the new list's length keeps a+ // coincidental +2 length delta from being read as "message pair appended" —+ // and a live spacer row is dropped before the new topic paints.+ const prevContextKeyRef = useRef(contextKey);+ useLayoutEffect(() => {+ if (prevContextKeyRef.current === contextKey) return;+ prevContextKeyRef.current = contextKey;++ prevLengthRef.current = dataSource.length;+ clearPin('context switch');+ setUserMessageIndex(null);+ setAssistantMessageIndex(null);+ setMounted(false);+ setScrollReduction(() => 0);+ prevScrollOffsetRef.current = null;+ }, [contextKey]);+// --- send detection: single source of truth ---useEffect(() => {const newMessageCount = dataSource.length - prevLengthRef.current;diff --git a/src/features/Conversation/ChatList/hooks/useTopicScrollPersist.test.ts b/src/features/Conversation/ChatList/hooks/useTopicScrollPersist.test.tsindex 7a0798b4f24..c2eab7bca9f 100644--- a/src/features/Conversation/ChatList/hooks/useTopicScrollPersist.test.ts+++ b/src/features/Conversation/ChatList/hooks/useTopicScrollPersist.test.ts@@ -315,6 +315,69 @@ describe('useTopicScrollPersist', () => {});});+ describe('in-place context switch', () => {+ it('re-stamps the topic being left and restores the new topic snapshot', async () => {+ const fixedNow = 1_000_000_000_000;+ vi.setSystemTime(fixedNow);+ saveScrollSnapshot('main_agt_1_tpc_b', {+ atBottom: false,+ offset: 3000,+ savedAt: fixedNow,+ });+ const handle = createFakeVList({ scrollSize: 6000, viewportSize: 800 });+ handle.scrollTo.mockImplementation((offset: number) => {+ handle.scrollOffset = offset;+ });++ const { result, rerender } = renderHook(+ ({ contextKey, length }: { contextKey: string; length: number }) =>+ useTopicScrollPersist({+ contextKey,+ dataSourceLength: length,+ virtuaRef: refOf(handle),+ }),+ { initialProps: { contextKey: 'main_agt_1_tpc_a', length: 50 } },+ );++ await advanceFrames(4);+ act(() => {+ result.current.recordScroll(1200, false);+ });+ await vi.advanceTimersByTimeAsync(300);++ vi.setSystemTime(fixedNow + 60_000);+ rerender({ contextKey: 'main_agt_1_tpc_b', length: 30 });+ await advanceFrames(6);++ const persistedA = loadScrollSnapshot('main_agt_1_tpc_a');+ expect(persistedA?.offset).toBe(1200);+ expect(persistedA?.savedAt).toBe(fixedNow + 60_000);+ expect(handle.scrollTo).toHaveBeenCalledWith(3000);+ });++ it('falls back to the bottom when the new topic has no snapshot', async () => {+ const handle = createFakeVList({ scrollSize: 6000, viewportSize: 800 });++ const { rerender } = renderHook(+ ({ contextKey, length }: { contextKey: string; length: number }) =>+ useTopicScrollPersist({+ contextKey,+ dataSourceLength: length,+ virtuaRef: refOf(handle),+ }),+ { initialProps: { contextKey: 'main_agt_1_tpc_a', length: 50 } },+ );++ await advanceFrames(4);+ handle.scrollToIndex.mockClear();++ rerender({ contextKey: 'main_agt_1_tpc_b', length: 30 });+ await advanceFrames(4);++ expect(handle.scrollToIndex).toHaveBeenCalledWith(29, { align: 'end' });+ });+ });+describe('leave-time re-stamp', () => {it('refreshes savedAt on unmount using the last scrolled position', async () => {const fixedNow = 1_000_000_000_000;diff --git a/src/features/Conversation/ChatList/hooks/useTopicScrollPersist.ts b/src/features/Conversation/ChatList/hooks/useTopicScrollPersist.tsindex 10a973c42ef..9bc392c5f47 100644--- a/src/features/Conversation/ChatList/hooks/useTopicScrollPersist.ts+++ b/src/features/Conversation/ChatList/hooks/useTopicScrollPersist.ts@@ -37,11 +37,13 @@ interface UseTopicScrollPersistOptions {/*** Persists per-topic chat scroll position to localStorage.*- * In practice `ChatList` shows a SkeletonList while `messagesInit` is false,- * so VirtualizedList unmounts on every topic switch and this hook is- * re-initialized fresh. The contextKey-change branch below still exists for- * the in-place draft → real-id promotion path, where the same instance- * survives the key change.+ * The provider is not keyed by context, so switching to a topic whose messages+ * are already cached keeps VirtualizedList mounted and lands in the+ * contextKey-change branch below: re-stamp the topic being left, then restore+ * (or scroll to bottom) for the new one. Switching to an uncached topic still+ * unmounts VirtualizedList behind ChatList's SkeletonList and re-initializes+ * the hook fresh. The draft → real-id promotion path also flows through the+ * contextKey-change branch, preserving scroll instead of restoring.*/export const useTopicScrollPersist = ({contextKey,diff --git a/src/features/Conversation/ConversationProvider.test.tsx b/src/features/Conversation/ConversationProvider.test.tsxindex bf835cbb0c2..d0b101190d5 100644--- a/src/features/Conversation/ConversationProvider.test.tsx+++ b/src/features/Conversation/ConversationProvider.test.tsx@@ -2,7 +2,7 @@* @vitest-environment happy-dom*/import type { ConversationContext, UIChatMessage } from '@lobechat/types';-import { fireEvent, render, screen } from '@testing-library/react';+import { act, fireEvent, render, screen } from '@testing-library/react';import type { ReactNode } from 'react';import { beforeEach, describe, expect, it, vi } from 'vitest';@@ -10,7 +10,7 @@ import { messageMapKey } from '@/store/chat/utils/messageMapKey';import ChatList from './ChatList';import { ConversationProvider } from './ConversationProvider';-import { dataSelectors, useConversationStore } from './store';+import { dataSelectors, useConversationStore, useConversationStoreApi } from './store';const chatListMocks = vi.hoisted(() => ({isStreaming: false,@@ -198,6 +198,101 @@ describe('ConversationProvider', () => {chatListMocks.refreshError.isRetrying = false;});+ it('keeps the same store instance across context changes', () => {+ const apis: unknown[] = [];+ const ApiProbe = () => {+ apis.push(useConversationStoreApi());+ return null;+ };++ const { rerender } = render(+ <ConversationProvider hasInitMessages context={oldContext} messages={oldMessages}>+ <ApiProbe />+ </ConversationProvider>,+ );++ rerender(+ <ConversationProvider context={nextContext} hasInitMessages={false}>+ <ApiProbe />+ </ConversationProvider>,+ );++ expect(new Set(apis).size).toBe(1);+ });++ it('resets conversation-ephemeral state in place while preserving infra fields', () => {+ let api: ReturnType<typeof useConversationStoreApi> | undefined;+ const ApiCapture = () => {+ api = useConversationStoreApi();+ return null;+ };++ const { rerender } = render(+ <ConversationProvider hasInitMessages context={oldContext} messages={oldMessages}>+ <ApiCapture />+ </ConversationProvider>,+ );++ const fakeEditor = { focus: vi.fn() };+ const fakeScrollMethods = {+ getItemOffset: vi.fn(),+ getItemSize: vi.fn(),+ getScrollOffset: vi.fn(),+ getScrollSize: vi.fn(),+ getTotalCount: vi.fn(),+ getViewportSize: vi.fn(),+ scrollTo: vi.fn(),+ scrollToIndex: vi.fn(),+ };++ act(() => {+ api!.setState({+ activeIndex: 3,+ atBottom: false,+ chatInputOverlayHeight: 48,+ editor: fakeEditor,+ heteroOverloadRetryAttempts: { msg_old: 2 },+ heteroOverloadWaitOpIds: { msg_old: 'op_1' },+ inputMessage: 'unsent draft',+ isScrolling: true,+ messageEditingIds: ['msg_old'],+ messageLoadingIds: ['msg_old'],+ scheduledSendAt: '2026-08-07T10:00:00.000Z',+ selectedMessageIds: ['msg_old'],+ selectionAnchorId: 'msg_old',+ selectionMode: true,+ virtuaScrollMethods: fakeScrollMethods,+ visibleItems: new Map([[0, { bottom: 1, ratio: 1, top: 0 }]]),+ });+ });++ rerender(+ <ConversationProvider context={nextContext} hasInitMessages={false}>+ <ApiCapture />+ </ConversationProvider>,+ );++ const state = api!.getState();++ expect(state.selectionMode).toBe(false);+ expect(state.selectedMessageIds).toEqual([]);+ expect(state.selectionAnchorId).toBeUndefined();+ expect(state.messageEditingIds).toEqual([]);+ expect(state.messageLoadingIds).toEqual([]);+ expect(state.heteroOverloadRetryAttempts).toEqual({});+ expect(state.heteroOverloadWaitOpIds).toEqual({});+ expect(state.inputMessage).toBe('');+ expect(state.scheduledSendAt).toBeUndefined();+ expect(state.activeIndex).toBeNull();+ expect(state.atBottom).toBe(true);+ expect(state.isScrolling).toBe(false);+ expect(state.visibleItems.size).toBe(0);++ expect(state.editor).toBe(fakeEditor);+ expect(state.virtuaScrollMethods).toBe(fakeScrollMethods);+ expect(state.chatInputOverlayHeight).toBe(48);+ });+it('does not expose the previous local conversation store after context changes', () => {const snapshots: Snapshot[] = [];@@ -213,13 +308,14 @@ describe('ConversationProvider', () => {</ConversationProvider>,);- const mismatchedNextContextSnapshots = snapshots.filter(- (snapshot) =>- snapshot.expectedContextKey === messageMapKey(nextContext) &&- snapshot.actualContextKey !== snapshot.expectedContextKey,- );-- expect(mismatchedNextContextSnapshots).toEqual([]);+ // The in-place reset lands in a layout effect, so one intermediate commit+ // renders with the new context props against the old store state. React+ // flushes the resulting store update synchronously before paint — what must+ // hold is that the *final* (painted) frame is fully consistent.+ const lastSnapshot = snapshots.at(-1)!;+ expect(lastSnapshot.expectedContextKey).toBe(messageMapKey(nextContext));+ expect(lastSnapshot.actualContextKey).toBe(messageMapKey(nextContext));+ expect(lastSnapshot.displayMessageIds).toEqual([]);});it('renders the message skeleton before the first request settles', () => {diff --git a/src/features/Conversation/ConversationProvider.tsx b/src/features/Conversation/ConversationProvider.tsxindex 6570977d065..6b69522df34 100644--- a/src/features/Conversation/ConversationProvider.tsx+++ b/src/features/Conversation/ConversationProvider.tsx@@ -127,7 +127,6 @@ export const ConversationProvider = memo<ConversationProviderProps>(return (<Provider- key={contextKey}createStore={() =>createStore({composerTarget: resolvedComposerTarget,diff --git a/src/features/Conversation/Messages/AssistantGroup/Tool/Detail/Intervention/index.tsx b/src/features/Conversation/Messages/AssistantGroup/Tool/Detail/Intervention/index.tsxindex 1efed4091f7..abc987b5905 100644--- a/src/features/Conversation/Messages/AssistantGroup/Tool/Detail/Intervention/index.tsx+++ b/src/features/Conversation/Messages/AssistantGroup/Tool/Detail/Intervention/index.tsx@@ -1,9 +1,10 @@import { getBuiltinIntervention } from '@lobechat/builtin-tools/interventions';import { safeParseJSON } from '@lobechat/utils';import { Flexbox } from '@lobehub/ui';-import { memo, Suspense, useCallback, useMemo, useRef, useState } from 'react';+import { memo, Suspense, useCallback, useMemo, useState } from 'react';import { createPortal } from 'react-dom';+import { useSingleton } from '@/hooks/useSingleton';import { useUserStore } from '@/store/user';import { toolInterventionSelectors } from '@/store/user/selectors';@@ -38,27 +39,24 @@ const Intervention = memo<InterventionProps>(const [isEditing, setIsEditing] = useState(false);const updatePluginArguments = useConversationStore((s) => s.updatePluginArguments);- // Store beforeApprove callbacks from intervention components (support multiple registrations)- // Use Map with id as key for reliable cleanup- const beforeApproveCallbacksRef = useRef<Map<string, () => void | Promise<void>>>(new Map());+ const beforeApproveCallbacks = useSingleton(+ () => new Map<string, () => void | Promise<void>>(),+ );- // Register a callback to be called before approvalconst registerBeforeApprove = useCallback((callbackId: string, callback: () => void | Promise<void>) => {- beforeApproveCallbacksRef.current.set(callbackId, callback);- // Return cleanup function to unregister+ beforeApproveCallbacks.set(callbackId, callback);return () => {- beforeApproveCallbacksRef.current.delete(callbackId);+ beforeApproveCallbacks.delete(callbackId);};},- [],+ [beforeApproveCallbacks],);- // Handler to be called before approve action - calls all registered callbacksconst handleBeforeApprove = useCallback(async () => {- const callbacks = Array.from(beforeApproveCallbacksRef.current.values());+ const callbacks = Array.from(beforeApproveCallbacks.values());await Promise.all(callbacks.map((cb) => cb()));- }, []);+ }, [beforeApproveCallbacks]);const handleCancel = useCallback(() => {setIsEditing(false);diff --git a/src/features/Conversation/StoreUpdater.tsx b/src/features/Conversation/StoreUpdater.tsxindex a4c573369f1..51d5f6fece3 100644--- a/src/features/Conversation/StoreUpdater.tsx+++ b/src/features/Conversation/StoreUpdater.tsx@@ -8,6 +8,7 @@ import { createStoreUpdater } from 'zustand-utils';import { messageMapKey } from '@/store/chat/utils/messageMapKey';import { useConversationStoreApi } from './store';+import { createEphemeralResetState } from './store/initialState';import {type ActionsBarConfig,type ComposerTarget,@@ -98,6 +99,7 @@ const StoreUpdater = memo<StoreUpdaterProps>(// Update context first so replaceMessages uses the correct context// when calling onMessagesChange (otherwise writes to the old topic key)storeApi.setState({+ ...createEphemeralResetState(),context,dbMessages: messages ?? [],displayMessages: [],diff --git a/src/features/Conversation/WorkingSidebar/Files/__tests__/index.test.tsx b/src/features/Conversation/WorkingSidebar/Files/__tests__/index.test.tsxindex afde40ea244..b614417fab3 100644--- a/src/features/Conversation/WorkingSidebar/Files/__tests__/index.test.tsx+++ b/src/features/Conversation/WorkingSidebar/Files/__tests__/index.test.tsx@@ -191,25 +191,14 @@ vi.mock('react-i18next', () => ({}));vi.mock('@lobehub/ui', () => ({+ ActionIcon: ({ onClick }: { onClick?: () => void }) => (+ <button type={'button'} onClick={onClick} />+ ),Center: ({ children }: { children?: ReactNode }) => <div>{children}</div>,copyToClipboard: vi.fn(),Empty: ({ description }: { description?: ReactNode }) => <div>{description}</div>,Flexbox: ({ children }: { children?: ReactNode }) => <div>{children}</div>,- SearchBar: ({- onChange,- placeholder,- value,- }: {- onChange?: (e: { target: { value: string } }) => void;- placeholder?: string;- value?: string;- }) => (- <input- placeholder={placeholder}- value={value}- onChange={(e) => onChange?.({ target: { value: e.target.value } })}- />- ),+ Icon: () => <span />,stopPropagation: vi.fn(),}));diff --git a/src/features/Conversation/WorkingSidebar/Files/index.tsx b/src/features/Conversation/WorkingSidebar/Files/index.tsxindex 9649c25e859..7616855d564 100644--- a/src/features/Conversation/WorkingSidebar/Files/index.tsx+++ b/src/features/Conversation/WorkingSidebar/Files/index.tsx@@ -1,11 +1,19 @@'use client';import type { ProjectFileIndexEntry } from '@lobechat/electron-client-ipc';-import { Center, copyToClipboard, Empty, Flexbox, SearchBar, stopPropagation } from '@lobehub/ui';-import { toast } from '@lobehub/ui/base-ui';+import {+ ActionIcon,+ Center,+ copyToClipboard,+ Empty,+ Flexbox,+ Icon,+ stopPropagation,+} from '@lobehub/ui';+import { Input, toast } from '@lobehub/ui/base-ui';import type { GitStatusEntry } from '@pierre/trees';import { createStaticStyles } from 'antd-style';-import { FileIcon } from 'lucide-react';+import { FileIcon, SearchIcon, XIcon } from 'lucide-react';import type { DragEvent } from 'react';import { memo, useCallback, useEffect, useMemo, useRef, useState } from 'react';import { useTranslation } from 'react-i18next';@@ -125,6 +133,41 @@ const getAncestorIds = (filePath: string): string[] => {return ancestors;};+interface FilesSearchBarProps {+ onDebouncedChange: (query: string) => void;+}++// Keystrokes stay local to this component: only the debounced query reaches+// the tree host, so typing never re-renders the ExplorerTree subtree.+const FilesSearchBar = memo<FilesSearchBarProps>(({ onDebouncedChange }) => {+ const { t } = useTranslation('chat');+ const [searchQuery, setSearchQuery] = useState('');++ useEffect(() => {+ const timer = setTimeout(() => onDebouncedChange(searchQuery), FILE_SEARCH_DEBOUNCE_MS);+ return () => clearTimeout(timer);+ }, [onDebouncedChange, searchQuery]);++ return (+ <Input+ placeholder={t('workingPanel.files.searchPlaceholder')}+ prefix={<Icon icon={SearchIcon} size={13} />}+ size={'small'}+ style={{ width: '100%' }}+ value={searchQuery}+ suffix={+ searchQuery ? (+ <ActionIcon icon={XIcon} size={12} onClick={() => setSearchQuery('')} />+ ) : undefined+ }+ onChange={(e) => setSearchQuery(e.target.value)}+ onKeyDown={stopPropagation}+ />+ );+});++FilesSearchBar.displayName = 'FilesSearchBar';+const Files = memo<FilesProps>(({ deviceId, workingDirectory }) => {const { t } = useTranslation('chat');const isRemote = !!deviceId;@@ -137,7 +180,6 @@ const Files = memo<FilesProps>(({ deviceId, workingDirectory }) => {const projectRoot = data?.root ?? workingDirectory;const entries = useMemo(() => data?.entries ?? [], [data]);- const [searchQuery, setSearchQuery] = useState('');const [debouncedQuery, setDebouncedQuery] = useState('');const [searchEntries, setSearchEntries] = useState<ProjectFileIndexEntry[] | undefined>();const [isSearching, setIsSearching] = useState(false);@@ -176,11 +218,6 @@ const Files = memo<FilesProps>(({ deviceId, workingDirectory }) => {const [expandedIds, setExpandedIds] = useState<string[]>([]);- useEffect(() => {- const timer = setTimeout(() => setDebouncedQuery(searchQuery), FILE_SEARCH_DEBOUNCE_MS);- return () => clearTimeout(timer);- }, [searchQuery]);-useEffect(() => {if (!normalizedDebouncedQuery) {setIsSearching(false);@@ -369,16 +406,7 @@ const Files = memo<FilesProps>(({ deviceId, workingDirectory }) => {return (<Flexbox height={'100%'} style={{ overflow: 'hidden' }} width={'100%'}><div className={styles.subheader}>- <SearchBar- allowClear- placeholder={t('workingPanel.files.searchPlaceholder')}- size={'small'}- style={{ width: '100%' }}- styles={{ input: { width: '100%' } }}- value={searchQuery}- onChange={(e) => setSearchQuery(e.target.value)}- onKeyDown={stopPropagation}- />+ <FilesSearchBar onDebouncedChange={setDebouncedQuery} /></div>{isEmpty && isFiltering && isSearching ? (<Center flex={1}>@@ -389,9 +417,7 @@ const Files = memo<FilesProps>(({ deviceId, workingDirectory }) => {<Emptyicon={FileIcon}description={t(- isFiltering && debouncedQuery === searchQuery- ? 'workingPanel.files.noSearchResults'- : 'workingPanel.files.empty',+ isFiltering ? 'workingPanel.files.noSearchResults' : 'workingPanel.files.empty',)}/></Center>diff --git a/src/features/Conversation/WorkingSidebar/ResourcesSection/AgentDocumentsGroup.tsx b/src/features/Conversation/WorkingSidebar/ResourcesSection/AgentDocumentsGroup.tsxindex f168999c46e..158e2fe0472 100644--- a/src/features/Conversation/WorkingSidebar/ResourcesSection/AgentDocumentsGroup.tsx+++ b/src/features/Conversation/WorkingSidebar/ResourcesSection/AgentDocumentsGroup.tsx@@ -2,6 +2,7 @@ import {AGENT_DOCUMENT_CATEGORY,AGENT_DOCUMENT_WEB_CATEGORY,buildAgentSkillIdentifier,+ EMPTY_ARRAY,} from '@lobechat/const';import { ActionIcon, Center, Empty, Flexbox, Text } from '@lobehub/ui';import { confirmModal, toast } from '@lobehub/ui/base-ui';@@ -11,8 +12,8 @@ import dayjs from 'dayjs';import relativeTime from 'dayjs/plugin/relativeTime';import type { LucideIcon } from 'lucide-react';import { EyeIcon, FileTextIcon, GlobeIcon, PencilIcon, Trash2Icon } from 'lucide-react';-import type { CSSProperties, MouseEvent } from 'react';-import { memo, useEffect, useMemo, useState } from 'react';+import type { CSSProperties, DragEvent, MouseEvent } from 'react';+import { memo, useCallback, useEffect, useMemo, useState } from 'react';import { useTranslation } from 'react-i18next';import { useParams } from 'react-router';@@ -344,7 +345,7 @@ const AgentDocumentsGroup = memo<AgentDocumentsGroupProps>(} = useProjectSkills(showProjectSkills ? workingDirectory : undefined, deviceId);const {- data = [],+ data = EMPTY_ARRAY,error,isLoading,mutate,@@ -377,6 +378,139 @@ const AgentDocumentsGroup = memo<AgentDocumentsGroupProps>([skillBundleViews],);+ const openAgentDocument = useCallback(+ (documentId: string, agentDocumentId?: string) => {+ if (!agentId) return;+ if (resolvedOpenMode === 'portal') {+ openDocument(+ documentId,+ agentDocumentId ?? data.find((doc) => doc.documentId === documentId)?.id,+ );+ return;+ }+ navigate(buildAgentDocumentPath(agentId, documentId));+ },+ [agentId, data, navigate, openDocument, resolvedOpenMode],+ );++ // Open the SKILL.md (skills/index child) when present; fall back to the+ // bundle itself (orphan bundles surface for recovery).+ const openAgentSkill = useCallback(+ (item: SkillListItem) => {+ const view = skillBundleViews.find((v) => v.bundle.documentId === item.id);+ const indexChild = data.find((doc) => doc.parentId === item.id && doc.isSkillIndex);+ const targetDocId = indexChild?.documentId ?? view?.bundle.documentId ?? item.id;+ openAgentDocument(targetDocId);+ },+ [data, openAgentDocument, skillBundleViews],+ );++ const openAgentSkillFile = useCallback(+ (item: SkillListItem, relativePath: string) => {+ const view = skillBundleViews.find((v) => v.bundle.documentId === item.id);+ const childDocId = view?.pathToDocumentId.get(relativePath);+ if (!childDocId) return;+ openAgentDocument(childDocId);+ },+ [openAgentDocument, skillBundleViews],+ );++ // The runtime resolves these via the `agent-skills:<filename>` identifier+ // (built from the shared const helper so the prefix stays in lockstep with+ // the server-side resolver). Display label keeps the human-readable title.+ const handleAgentSkillDragStart = useCallback(+ (item: SkillListItem, event: DragEvent) => {+ const view = skillBundleViews.find((v) => v.bundle.documentId === item.id);+ const filename = view?.bundle.filename;+ if (!filename) return;+ startSkillDrag(event, {+ category: 'agentSkill',+ label: item.name,+ type: buildAgentSkillIdentifier(filename),+ });+ },+ [skillBundleViews],+ );++ // Agent skills are document bundles, so view / rename / delete map onto the+ // agent-document service (`item.id` is the bundle's documentId; the service+ // keys off the row id carried on the bundle).+ const getAgentSkillActions = useCallback(+ (item: SkillListItem): SkillRowAction[] => {+ const view = skillBundleViews.find((v) => v.bundle.documentId === item.id);+ const rowId = view?.bundle.id;+ return [+ {+ icon: EyeIcon,+ key: 'view',+ label: t('workingPanel.skills.actions.view'),+ onClick: openAgentSkill,+ sfSymbol: 'eye',+ },+ {+ disabled: !rowId,+ icon: PencilIcon,+ key: 'rename',+ label: t('workingPanel.skills.actions.rename'),+ onClick: () => {+ if (!rowId) return;+ openRenameSkillModal({+ currentName: item.name,+ onSubmit: async (newName) => {+ try {+ await agentDocumentService.renameDocument({+ agentId: agentId!,+ id: rowId,+ newTitle: newName,+ });+ await mutate();+ return undefined;+ } catch (error) {+ return error instanceof Error+ ? error.message+ : t('workingPanel.skills.rename.error');+ }+ },+ });+ },+ sfSymbol: 'pencil',+ },+ {+ danger: true,+ disabled: !rowId,+ icon: Trash2Icon,+ key: 'delete',+ label: t('workingPanel.skills.actions.delete'),+ onClick: () => {+ if (!rowId) return;+ confirmModal({+ cancelText: tCommon('cancel'),+ content: t('workingPanel.skills.delete.agentConfirm', { name: item.name }),+ okButtonProps: { danger: true },+ okText: tCommon('delete'),+ onOk: async () => {+ try {+ await agentDocumentService.removeDocument({ agentId: agentId!, id: rowId });+ await mutate();+ toast.success(t('workingPanel.skills.delete.success'));+ } catch (error) {+ toast.error(+ error instanceof Error+ ? error.message+ : t('workingPanel.skills.delete.error'),+ );+ }+ },+ title: t('workingPanel.skills.delete.title'),+ });+ },+ sfSymbol: 'trash',+ },+ ];+ },+ [agentId, mutate, openAgentSkill, skillBundleViews, t, tCommon],+ );+if (!agentId) return null;if (isLoading) {@@ -401,131 +535,18 @@ const AgentDocumentsGroup = memo<AgentDocumentsGroupProps>();}- const openAgentDocument = (documentId: string, agentDocumentId?: string) => {- if (!agentId) return;- if (resolvedOpenMode === 'portal') {- openDocument(- documentId,- agentDocumentId ?? data.find((doc) => doc.documentId === documentId)?.id,- );- return;- }- navigate(buildAgentDocumentPath(agentId, documentId));- };-const backToChat = () => {if (!agentId) return;navigate(`/agent/${agentId}`);};- // Open the SKILL.md (skills/index child) when present; fall back to the- // bundle itself (orphan bundles surface for recovery).- const openAgentSkill = (item: SkillListItem) => {- const view = skillBundleViews.find((v) => v.bundle.documentId === item.id);- const indexChild = data.find((doc) => doc.parentId === item.id && doc.isSkillIndex);- const targetDocId = indexChild?.documentId ?? view?.bundle.documentId ?? item.id;- openAgentDocument(targetDocId);- };-- // Agent skills are document bundles, so view / rename / delete map onto the- // agent-document service (`item.id` is the bundle's documentId; the service- // keys off the row id carried on the bundle).- const getAgentSkillActions = (item: SkillListItem): SkillRowAction[] => {- const view = skillBundleViews.find((v) => v.bundle.documentId === item.id);- const rowId = view?.bundle.id;- return [- {- icon: EyeIcon,- key: 'view',- label: t('workingPanel.skills.actions.view'),- onClick: openAgentSkill,- sfSymbol: 'eye',- },- {- disabled: !rowId,- icon: PencilIcon,- key: 'rename',- label: t('workingPanel.skills.actions.rename'),- onClick: () => {- if (!rowId) return;- openRenameSkillModal({- currentName: item.name,- onSubmit: async (newName) => {- try {- await agentDocumentService.renameDocument({- agentId: agentId!,- id: rowId,- newTitle: newName,- });- await mutate();- return undefined;- } catch (error) {- return error instanceof Error- ? error.message- : t('workingPanel.skills.rename.error');- }- },- });- },- sfSymbol: 'pencil',- },- {- danger: true,- disabled: !rowId,- icon: Trash2Icon,- key: 'delete',- label: t('workingPanel.skills.actions.delete'),- onClick: () => {- if (!rowId) return;- confirmModal({- cancelText: tCommon('cancel'),- content: t('workingPanel.skills.delete.agentConfirm', { name: item.name }),- okButtonProps: { danger: true },- okText: tCommon('delete'),- onOk: async () => {- try {- await agentDocumentService.removeDocument({ agentId: agentId!, id: rowId });- await mutate();- toast.success(t('workingPanel.skills.delete.success'));- } catch (error) {- toast.error(- error instanceof Error ? error.message : t('workingPanel.skills.delete.error'),- );- }- },- title: t('workingPanel.skills.delete.title'),- });- },- sfSymbol: 'trash',- },- ];- };-const renderAgentSkillsList = () => (<SkillsListgetRowActions={getAgentSkillActions}items={skillItems}+ onOpenFile={openAgentSkillFile}onOpenSkill={openAgentSkill}- onOpenFile={(item, relativePath) => {- const view = skillBundleViews.find((v) => v.bundle.documentId === item.id);- const docId = view?.pathToDocumentId.get(relativePath);- if (!docId) return;- openAgentDocument(docId);- }}- onSkillDragStart={(item, event) => {- // The runtime resolves these via the `agent-skills:<filename>`- // identifier (built from the shared const helper so the prefix stays- // in lockstep with the server-side resolver). Display label keeps- // the human-readable title.- const view = skillBundleViews.find((v) => v.bundle.documentId === item.id);- const filename = view?.bundle.filename;- if (!filename) return;- startSkillDrag(event, {- category: 'agentSkill',- label: item.name,- type: buildAgentSkillIdentifier(filename),- });- }}+ onSkillDragStart={handleAgentSkillDragStart}/>);diff --git a/src/features/Conversation/WorkingSidebar/ResourcesSection/DeviceLevelSkills.tsx b/src/features/Conversation/WorkingSidebar/ResourcesSection/DeviceLevelSkills.tsxindex ab69049c844..cade7901899 100644--- a/src/features/Conversation/WorkingSidebar/ResourcesSection/DeviceLevelSkills.tsx+++ b/src/features/Conversation/WorkingSidebar/ResourcesSection/DeviceLevelSkills.tsx@@ -1,8 +1,22 @@+import type React from 'react';import { memo } from 'react';import { useTranslation } from 'react-i18next';import { startSkillDrag } from '@/features/ChatInput/InputEditor/ActionTag/skillDragData';-import { SkillSection, SkillsList, useProjectSkills } from '@/features/SkillsList';+import {+ type SkillListItem,+ SkillSection,+ SkillsList,+ useProjectSkills,+} from '@/features/SkillsList';++const handleSkillDragStart = (item: SkillListItem, event: React.DragEvent) => {+ startSkillDrag(event, {+ category: 'projectSkill',+ label: item.name,+ type: item.name,+ });+};interface DeviceLevelSkillsProps {/** Bound remote device id; when set, skills are scanned over RPC. */@@ -42,13 +56,7 @@ const DeviceLevelSkills = memo<DeviceLevelSkillsProps>(items={deviceItems}onOpenFile={onOpenFile}onOpenSkill={onOpenSkill}- onSkillDragStart={(item, event) => {- startSkillDrag(event, {- category: 'projectSkill',- label: item.name,- type: item.name,- });- }}+ onSkillDragStart={handleSkillDragStart}/>);diff --git a/src/features/Conversation/WorkingSidebar/ResourcesSection/ProjectLevelSkills.tsx b/src/features/Conversation/WorkingSidebar/ResourcesSection/ProjectLevelSkills.tsxindex bb55ad6cdc4..bf4c215eb4e 100644--- a/src/features/Conversation/WorkingSidebar/ResourcesSection/ProjectLevelSkills.tsx+++ b/src/features/Conversation/WorkingSidebar/ResourcesSection/ProjectLevelSkills.tsx@@ -1,8 +1,24 @@+import type React from 'react';import { memo } from 'react';import { useTranslation } from 'react-i18next';import { startSkillDrag } from '@/features/ChatInput/InputEditor/ActionTag/skillDragData';-import { SkillSection, SkillsList, useProjectSkills } from '@/features/SkillsList';+import {+ type SkillListItem,+ SkillSection,+ SkillsList,+ useProjectSkills,+} from '@/features/SkillsList';++// Project skills are resolved by the underlying CLI agent itself, so+// we serialize them as a literal `/skill-name` (projectSkill chip).+const handleSkillDragStart = (item: SkillListItem, event: React.DragEvent) => {+ startSkillDrag(event, {+ category: 'projectSkill',+ label: item.name,+ type: item.name,+ });+};interface ProjectLevelSkillsProps {/** Bound remote device id; when set, skills are scanned over RPC. */@@ -42,15 +58,7 @@ const ProjectLevelSkills = memo<ProjectLevelSkillsProps>(items={projectItems}onOpenFile={onOpenFile}onOpenSkill={onOpenSkill}- onSkillDragStart={(item, event) => {- // Project skills are resolved by the underlying CLI agent itself, so- // we serialize them as a literal `/skill-name` (projectSkill chip).- startSkillDrag(event, {- category: 'projectSkill',- label: item.name,- type: item.name,- });- }}+ onSkillDragStart={handleSkillDragStart}/>);diff --git a/src/features/Conversation/WorkingSidebar/ResourcesSection/SkillsGroup.tsx b/src/features/Conversation/WorkingSidebar/ResourcesSection/SkillsGroup.tsxindex 9b3fa0ed3e6..c6c0f0431bb 100644--- a/src/features/Conversation/WorkingSidebar/ResourcesSection/SkillsGroup.tsx+++ b/src/features/Conversation/WorkingSidebar/ResourcesSection/SkillsGroup.tsx@@ -1,9 +1,25 @@import { isDesktop } from '@lobechat/const';+import type React from 'react';import { memo } from 'react';import { useTranslation } from 'react-i18next';import { startSkillDrag } from '@/features/ChatInput/InputEditor/ActionTag/skillDragData';-import { SkillSection, SkillsList, useProjectSkills } from '@/features/SkillsList';+import {+ type SkillListItem,+ SkillSection,+ SkillsList,+ useProjectSkills,+} from '@/features/SkillsList';++// Filesystem skills are resolved by the underlying runtime registry, so+// we serialize them as a literal `/skill-name` (projectSkill chip).+const handleSkillDragStart = (item: SkillListItem, event: React.DragEvent) => {+ startSkillDrag(event, {+ category: 'projectSkill',+ label: item.name,+ type: item.name,+ });+};interface SkillsGroupProps {/** Bound remote device id; when set, skills are scanned over RPC. */@@ -35,15 +51,7 @@ const SkillsGroup = memo<SkillsGroupProps>(({ deviceId, workingDirectory }) => {items={items}onOpenFile={onOpenFile}onOpenSkill={onOpenSkill}- onSkillDragStart={(item, event) => {- // Filesystem skills are resolved by the underlying runtime registry, so- // we serialize them as a literal `/skill-name` (projectSkill chip).- startSkillDrag(event, {- category: 'projectSkill',- label: item.name,- type: item.name,- });- }}+ onSkillDragStart={handleSkillDragStart}/>);diff --git a/src/features/Conversation/WorkingSidebar/ResourcesSection/UserLevelSkills.tsx b/src/features/Conversation/WorkingSidebar/ResourcesSection/UserLevelSkills.tsxindex 68ffbef05fc..9a077befa1b 100644--- a/src/features/Conversation/WorkingSidebar/ResourcesSection/UserLevelSkills.tsx+++ b/src/features/Conversation/WorkingSidebar/ResourcesSection/UserLevelSkills.tsx@@ -2,7 +2,8 @@ import { confirmModal, createModal, toast } from '@lobehub/ui/base-ui';import isEqual from 'fast-deep-equal';import { t as translate } from 'i18next';import { EyeIcon, PencilIcon, Trash2Icon } from 'lucide-react';-import { lazy, memo, Suspense, useMemo } from 'react';+import type React from 'react';+import { lazy, memo, Suspense, useCallback, useMemo } from 'react';import { useTranslation } from 'react-i18next';import { startSkillDrag } from '@/features/ChatInput/InputEditor/ActionTag/skillDragData';@@ -19,6 +20,14 @@ import { agentSkillsSelectors } from '@/store/tool/selectors';const AgentSkillDetail = lazy(() => import('@/features/AgentSkillDetail'));+const handleSkillDragStart = (item: SkillListItem, event: React.DragEvent) => {+ startSkillDrag(event, {+ category: 'skill',+ label: item.name,+ type: item.id,+ });+};+const openSkillDetailModal = (skillId: string) =>createModal({content: (@@ -81,77 +90,88 @@ const UserLevelSkills = memo<UserLevelSkillsProps>(({ hideHeader }) => {const deleteAgentSkill = useToolStore((s) => s.deleteAgentSkill);const { allowed: canEdit } = usePermission('edit_own_content');- const getRowActions = (item: SkillListItem): SkillRowAction[] => {- const skill = agentSkills.find((s) => s.identifier === item.id);- if (!skill) return [];-- const actions: SkillRowAction[] = [- {- icon: EyeIcon,- key: 'view',- label: t('workingPanel.skills.actions.view'),- onClick: () => openSkillDetailModal(skill.id),- sfSymbol: 'eye',- },- ];-- // Only user-authored skills carry an editable name; market imports are- // pinned to their source manifest.- if (skill.source === 'user') {+ const getRowActions = useCallback(+ (item: SkillListItem): SkillRowAction[] => {+ const skill = agentSkills.find((s) => s.identifier === item.id);+ if (!skill) return [];++ const actions: SkillRowAction[] = [+ {+ icon: EyeIcon,+ key: 'view',+ label: t('workingPanel.skills.actions.view'),+ onClick: () => openSkillDetailModal(skill.id),+ sfSymbol: 'eye',+ },+ ];++ // Only user-authored skills carry an editable name; market imports are+ // pinned to their source manifest.+ if (skill.source === 'user') {+ actions.push({+ disabled: !canEdit,+ icon: PencilIcon,+ key: 'rename',+ label: t('workingPanel.skills.actions.rename'),+ onClick: () => {+ openRenameSkillModal({+ currentName: skill.name,+ onSubmit: async (newName) => {+ try {+ await updateAgentSkill({ id: skill.id, name: newName });+ return undefined;+ } catch (error) {+ return error instanceof Error+ ? error.message+ : t('workingPanel.skills.rename.error');+ }+ },+ });+ },+ sfSymbol: 'pencil',+ });+ }+actions.push({+ danger: true,disabled: !canEdit,- icon: PencilIcon,- key: 'rename',- label: t('workingPanel.skills.actions.rename'),+ icon: Trash2Icon,+ key: 'delete',+ label: t('workingPanel.skills.actions.delete'),onClick: () => {- openRenameSkillModal({- currentName: skill.name,- onSubmit: async (newName) => {+ confirmModal({+ cancelText: tCommon('cancel'),+ content: t('workingPanel.skills.delete.userConfirm', { name: skill.name }),+ okButtonProps: { danger: true },+ okText: tCommon('delete'),+ onOk: async () => {try {- await updateAgentSkill({ id: skill.id, name: newName });- return undefined;+ await deleteAgentSkill(skill.id);+ toast.success(t('workingPanel.skills.delete.success'));} catch (error) {- return error instanceof Error- ? error.message- : t('workingPanel.skills.rename.error');+ toast.error(+ error instanceof Error ? error.message : t('workingPanel.skills.delete.error'),+ );}},+ title: t('workingPanel.skills.delete.title'),});},- sfSymbol: 'pencil',+ sfSymbol: 'trash',});- }-- actions.push({- danger: true,- disabled: !canEdit,- icon: Trash2Icon,- key: 'delete',- label: t('workingPanel.skills.actions.delete'),- onClick: () => {- confirmModal({- cancelText: tCommon('cancel'),- content: t('workingPanel.skills.delete.userConfirm', { name: skill.name }),- okButtonProps: { danger: true },- okText: tCommon('delete'),- onOk: async () => {- try {- await deleteAgentSkill(skill.id);- toast.success(t('workingPanel.skills.delete.success'));- } catch (error) {- toast.error(- error instanceof Error ? error.message : t('workingPanel.skills.delete.error'),- );- }- },- title: t('workingPanel.skills.delete.title'),- });- },- sfSymbol: 'trash',- });- return actions;- };+ return actions;+ },+ [agentSkills, canEdit, deleteAgentSkill, t, tCommon, updateAgentSkill],+ );++ const onOpenSkill = useCallback(+ (item: SkillListItem) => {+ const skill = agentSkills.find((s) => s.identifier === item.id);+ if (skill) openSkillDetailModal(skill.id);+ },+ [agentSkills],+ );if (items.length === 0) return null;@@ -159,17 +179,8 @@ const UserLevelSkills = memo<UserLevelSkillsProps>(({ hideHeader }) => {<SkillsListgetRowActions={getRowActions}items={items}- onOpenSkill={(item) => {- const skill = agentSkills.find((s) => s.identifier === item.id);- if (skill) openSkillDetailModal(skill.id);- }}- onSkillDragStart={(item, event) => {- startSkillDrag(event, {- category: 'skill',- label: item.name,- type: item.id,- });- }}+ onOpenSkill={onOpenSkill}+ onSkillDragStart={handleSkillDragStart}/>);diff --git a/src/features/Conversation/WorkingSidebar/__tests__/index.test.tsx b/src/features/Conversation/WorkingSidebar/__tests__/index.test.tsxindex 3b7beb3c625..b06bea5a912 100644--- a/src/features/Conversation/WorkingSidebar/__tests__/index.test.tsx+++ b/src/features/Conversation/WorkingSidebar/__tests__/index.test.tsx@@ -133,6 +133,7 @@ vi.mock('../Review', () => ({}));vi.mock('../ProgressSection', () => ({ default: () => <div /> }));vi.mock('../ResourcesSection', () => ({ default: () => <div /> }));+vi.mock('@/features/NavPanel/components/SkeletonList', () => ({ default: () => <div /> }));vi.mock('../ParamsSection', () => ({default: () => {if (paramsSectionState.suspend) throw paramsSectionState.pending;diff --git a/src/features/Conversation/WorkingSidebar/index.tsx b/src/features/Conversation/WorkingSidebar/index.tsxindex 7ba76d7797c..798bb003ccf 100644--- a/src/features/Conversation/WorkingSidebar/index.tsx+++ b/src/features/Conversation/WorkingSidebar/index.tsx@@ -24,6 +24,7 @@ import {XIcon,} from 'lucide-react';import {+ Activity,lazy,memo,type ReactNode,@@ -41,12 +42,14 @@ import { useActiveWorkspaceId } from '@/business/client/hooks/useActiveWorkspaceimport { DESKTOP_HEADER_ICON_SMALL_SIZE } from '@/const/layoutTokens';import { isDesktop } from '@/const/version';import { useRepoType } from '@/features/ChatInput/ControlBar/useRepoType';+import SkeletonList from '@/features/NavPanel/components/SkeletonList';import { getPortalViewWidth } from '@/features/Portal/portalWidth';import TopicCommentsSidebar from '@/features/Portal/TopicComments/Sidebar';import RightPanel from '@/features/RightPanel';import { resolveTargetDeviceId } from '@/helpers/agentWorkingDirectory';import { resolveExecutionTarget } from '@/helpers/executionTarget';import { useIsGatewayModeEnabled } from '@/helpers/gatewayMode';+import { useDeferredMount } from '@/hooks/useDeferredMount';import { useEffectiveAgencyConfig } from '@/hooks/useEffectiveAgencyConfig';import { useEffectiveWorkingDirectory } from '@/hooks/useEffectiveWorkingDirectory';import { useLocalStorageState } from '@/hooks/useLocalStorageState';@@ -170,6 +173,9 @@ interface AgentWorkingSidebarProps {const AgentWorkingSidebar = memo<AgentWorkingSidebarProps>(({ availableWidth }) => {const { t } = useTranslation(['chat', 'setting']);+ // Keep the panel frame + tabs on the navigation commit; the pane contents+ // mount in a deferred follow-up pass behind a skeleton.+ const contentReady = useDeferredMount();const [storedWidth,legacyPortalWidth,@@ -889,111 +895,125 @@ const AgentWorkingSidebar = memo<AgentWorkingSidebarProps>(({ availableWidth })/></Flexbox><Flexbox className={styles.body} width={'100%'}>- <Flexbox className={activeTab === 'overview' ? styles.pane : styles.paneHidden}>- <Overview- active={Boolean(showRightPanel) && activeTab === 'overview'}- deviceId={remoteDeviceId}- environmentAvailable={filesystemEnvironmentAvailable}- repoType={environmentRepoType}- workingDirectory={environmentWorkingDirectory}- onOpenTab={openTab}- />- </Flexbox>- {commentsAvailable && (- <Flexbox- className={activeTab === 'comments' ? styles.pane : styles.paneHidden}- style={{ overflow: 'hidden' }}- >- <TopicCommentsSidebar />- </Flexbox>- )}- {paramsAvailable && activeTab === 'params' && (- <Flexbox className={styles.pane}>- <Suspense- fallback={- <Skeleton- active- className={styles.paramsLoading}- paragraph={{ rows: 6 }}- title={false}- />- }- >- <ParamsSection />- </Suspense>- </Flexbox>- )}- {reviewAvailable && (- <Flexbox className={activeTab === 'review' ? styles.pane : styles.paneHidden}>- <Review- active={activeTab === 'review'}- composerTarget={composerTarget}- deviceId={remoteDeviceId}- showTree={showReviewTree}- workingDirectory={workingDirectory}- onToggleTree={() => setShowReviewTree((v) => !v)}- />- </Flexbox>- )}- {filesAvailable && (- <Flexbox className={activeTab === 'files' ? styles.pane : styles.paneHidden}>- <Files deviceId={remoteDeviceId} workingDirectory={workingDirectory} />- </Flexbox>- )}- {browserAvailable &&- openedTabs.filter(isBrowserTab).map((tab) => {- const sessionId =- tab === BROWSER_TAB_KEY- ? browserSessionId- : `${browserSessionId}:tab:${tab.slice(BROWSER_TAB_PREFIX.length)}`;-- return (+ {!contentReady && <SkeletonList paddingBlock={8} paddingInline={8} rows={6} />}+ {contentReady && (+ <>+ <Flexbox className={activeTab === 'overview' ? styles.pane : styles.paneHidden}>+ <Overview+ active={Boolean(showRightPanel) && activeTab === 'overview'}+ deviceId={remoteDeviceId}+ environmentAvailable={filesystemEnvironmentAvailable}+ repoType={environmentRepoType}+ workingDirectory={environmentWorkingDirectory}+ onOpenTab={openTab}+ />+ </Flexbox>+ {commentsAvailable && (<Flexbox- className={activeTab === tab ? styles.pane : styles.paneHidden}- key={sessionId}+ className={activeTab === 'comments' ? styles.pane : styles.paneHidden}+ style={{ overflow: 'hidden' }}>- <BrowserPane- agentId={activeAgentId}+ <TopicCommentsSidebar />+ </Flexbox>+ )}+ {paramsAvailable && activeTab === 'params' && (+ <Flexbox className={styles.pane}>+ <Suspense+ fallback={+ <Skeleton+ active+ className={styles.paramsLoading}+ paragraph={{ rows: 6 }}+ title={false}+ />+ }+ >+ <ParamsSection />+ </Suspense>+ </Flexbox>+ )}+ {reviewAvailable && (+ <Flexbox className={activeTab === 'review' ? styles.pane : styles.paneHidden}>+ <Review+ active={activeTab === 'review'}composerTarget={composerTarget}- sessionId={sessionId}- onMetadataChange={(metadata) => {- const metadataKey = `${openTabsContextKey}:${tab}`;- setBrowserTabMetadata((current) =>- current[metadataKey]?.faviconUrl === metadata.faviconUrl &&- current[metadataKey]?.title === metadata.title &&- current[metadataKey]?.url === metadata.url- ? current- : { ...current, [metadataKey]: metadata },- );- }}+ deviceId={remoteDeviceId}+ showTree={showReviewTree}+ workingDirectory={workingDirectory}+ onToggleTree={() => setShowReviewTree((v) => !v)}/></Flexbox>- );- })}- {businessTabs.map((tab) => (- <Flexbox- className={activeTab === tab.key ? styles.pane : styles.paneHidden}- key={tab.key}- >- {tab.pane}- </Flexbox>- ))}- {['skills', ...(isHetero ? [] : ['documents', 'web'])].map((resourceTab) => (- <Flexbox- className={activeTab === resourceTab ? styles.pane : styles.paneHidden}- key={resourceTab}- width={'100%'}- >- <ResourcesSection- deviceId={remoteDeviceId}- enabled={showRightPanel && activeTab === resourceTab}- filter={resourceTab as 'skills' | 'documents' | 'web'}- />- </Flexbox>- ))}- <Flexbox className={activeTab === 'works' ? styles.pane : styles.paneHidden}>- <WorksSection active={showRightPanel && activeTab === 'works'} />- </Flexbox>+ )}+ {filesAvailable && (+ <Activity mode={showRightPanel && activeTab === 'files' ? 'visible' : 'hidden'}>+ <Flexbox className={styles.pane}>+ <Files deviceId={remoteDeviceId} workingDirectory={workingDirectory} />+ </Flexbox>+ </Activity>+ )}+ {browserAvailable &&+ openedTabs.filter(isBrowserTab).map((tab) => {+ const sessionId =+ tab === BROWSER_TAB_KEY+ ? browserSessionId+ : `${browserSessionId}:tab:${tab.slice(BROWSER_TAB_PREFIX.length)}`;++ return (+ <Flexbox+ className={activeTab === tab ? styles.pane : styles.paneHidden}+ key={sessionId}+ >+ <BrowserPane+ agentId={activeAgentId}+ composerTarget={composerTarget}+ sessionId={sessionId}+ onMetadataChange={(metadata) => {+ const metadataKey = `${openTabsContextKey}:${tab}`;+ setBrowserTabMetadata((current) =>+ current[metadataKey]?.faviconUrl === metadata.faviconUrl &&+ current[metadataKey]?.title === metadata.title &&+ current[metadataKey]?.url === metadata.url+ ? current+ : { ...current, [metadataKey]: metadata },+ );+ }}+ />+ </Flexbox>+ );+ })}+ {businessTabs.map((tab) => (+ <Flexbox+ className={activeTab === tab.key ? styles.pane : styles.paneHidden}+ key={tab.key}+ >+ {tab.pane}+ </Flexbox>+ ))}+ {/* Resource/works panes stay mounted to keep their state, but hidden ones+ go through Activity so their updates render at background priority+ instead of blocking visible commits (BrowserPane must NOT move here —+ hiding it would unmount the effects keeping its session alive). */}+ {['skills', ...(isHetero ? [] : ['documents', 'web'])].map((resourceTab) => (+ <Activity+ key={resourceTab}+ mode={showRightPanel && activeTab === resourceTab ? 'visible' : 'hidden'}+ >+ <Flexbox className={styles.pane} width={'100%'}>+ <ResourcesSection+ deviceId={remoteDeviceId}+ enabled={showRightPanel && activeTab === resourceTab}+ filter={resourceTab as 'skills' | 'documents' | 'web'}+ />+ </Flexbox>+ </Activity>+ ))}+ <Activity mode={showRightPanel && activeTab === 'works' ? 'visible' : 'hidden'}>+ <Flexbox className={styles.pane}>+ <WorksSection active={showRightPanel && activeTab === 'works'} />+ </Flexbox>+ </Activity>+ </>+ )}</Flexbox></Flexbox></RightPanel>diff --git a/src/features/Conversation/store/action.ts b/src/features/Conversation/store/action.tsindex 06a2e59acd6..ebe8bab3b91 100644--- a/src/features/Conversation/store/action.ts+++ b/src/features/Conversation/store/action.ts@@ -51,14 +51,16 @@ export interface CreateStoreParams {* Messages to seed the freshly-created store with, already known by the parent* (ConversationArea reads them from ChatStore's `dbMessagesMap`). Seeding at* creation — rather than waiting for StoreUpdater's post-mount effect — is what- * keeps a store *remount* from painting an empty/skeleton frame first.+ * keeps a store *mount* from painting an empty/skeleton frame first.*- * Why this matters: ConversationProvider keys `<Provider>` by `contextKey`, so a- * topic switch (e.g. group's first message creates a new topic) recreates the- * store from scratch. Without a seed the new store starts `messagesInit: false`- * with no messages and only gets populated by a post-paint effect — one blank- * frame, i.e. the "message disappears then reappears" flicker. `undefined` means- * "not fetched yet" (stay uninitialized); `[]` means "loaded, empty".+ * The store instance now survives topic switches (the Provider is not keyed by+ * context — StoreUpdater resets state in place instead), so this only covers+ * genuine mounts: first navigation to a surface, or hosts that key the whole+ * provider themselves (e.g. eval bench). Without a seed such a mount starts+ * `messagesInit: false` and only gets populated by a post-paint effect — one+ * blank frame, i.e. the "message disappears then reappears" flicker.+ * `undefined` means "not fetched yet" (stay uninitialized); `[]` means+ * "loaded, empty".*/initialMessages?: UIChatMessage[];skipFetch?: boolean;diff --git a/src/features/Conversation/store/initialState.ts b/src/features/Conversation/store/initialState.tsindex 973116d1906..e0892396fe4 100644--- a/src/features/Conversation/store/initialState.ts+++ b/src/features/Conversation/store/initialState.ts@@ -76,3 +76,27 @@ export const initialState: State = {onMessagesChange: undefined,operationState: DEFAULT_OPERATION_STATE,};++/**+ * State patch applied in place on context switch (the Provider is NOT keyed by+ * context, so the store instance survives). Deliberately excludes fields owned+ * by still-mounted UI infra — `editor`, `chatInputOverlayHeight`,+ * `virtuaScrollMethods` — which stay valid across the switch and are managed by+ * their components' own mount/unmount lifecycles.+ */+export const createEphemeralResetState = (): Partial<State> => ({+ activeIndex: null,+ atBottom: true,+ heteroOverloadRetryAttempts: {},+ heteroOverloadWaitOpIds: {},+ inputMessage: '',+ isScrolling: false,+ messageEditingIds: [],+ messageLoadingIds: [],+ pendingArgsUpdates: new Map(),+ scheduledSendAt: undefined,+ selectedMessageIds: [],+ selectionAnchorId: undefined,+ selectionMode: false,+ visibleItems: new Map(),+});diff --git a/src/features/Conversation/store/slices/data/action.test.ts b/src/features/Conversation/store/slices/data/action.test.tsindex 42c2ead7548..d34649755bc 100644--- a/src/features/Conversation/store/slices/data/action.test.ts+++ b/src/features/Conversation/store/slices/data/action.test.ts@@ -335,6 +335,39 @@ describe('DataSlice', () => {// …but nothing is echoed back to the external store.expect(onMessagesChange).not.toHaveBeenCalled();});++ it('discards an async replacement when the store has switched conversations', () => {+ const oldContext = { agentId: 'agent-1', threadId: null, topicId: 'topic-old' };+ const currentContext = { agentId: 'agent-1', threadId: null, topicId: 'topic-current' };+ const currentMessages: UIChatMessage[] = [+ {+ content: 'current topic',+ createdAt: 2000,+ id: 'msg-current',+ role: 'user',+ updatedAt: 2000,+ },+ ];+ const store = createStore({ context: currentContext, initialMessages: currentMessages });+ const onMessagesChange = vi.fn();+ store.setState({ onMessagesChange });++ store.getState().replaceMessages(+ [+ {+ content: 'late old topic result',+ createdAt: 1000,+ id: 'msg-old',+ role: 'assistant',+ updatedAt: 1000,+ },+ ],+ { expectedContext: oldContext },+ );++ expect(store.getState().dbMessages).toEqual(currentMessages);+ expect(onMessagesChange).not.toHaveBeenCalled();+ });});describe('selectors', () => {@@ -636,6 +669,54 @@ describe('DataSlice', () => {});});+ it('discards a fetch result that resolves after switching conversations', async () => {+ let resolveFetch!: (messages: UIChatMessage[]) => void;+ vi.mocked(messageService.getMessages).mockReturnValue(+ new Promise((resolve) => {+ resolveFetch = resolve;+ }),+ );++ const oldContext = { agentId: 'test-session', threadId: null, topicId: 'topic-old' };+ const currentContext = { agentId: 'test-session', threadId: null, topicId: 'topic-current' };+ const currentMessages: UIChatMessage[] = [+ {+ content: 'current topic',+ createdAt: 2000,+ id: 'msg-current',+ role: 'user',+ updatedAt: 2000,+ },+ ];+ const store = createStore({ context: oldContext });+ const onMessagesChange = vi.fn();+ store.setState({ onMessagesChange });++ store.getState().useFetchMessages(oldContext);+ store.setState({+ context: currentContext,+ dbMessages: currentMessages,+ displayMessages: currentMessages,+ messagesInit: true,+ });++ await act(async () => {+ resolveFetch([+ {+ content: 'late old topic result',+ createdAt: 1000,+ id: 'msg-old',+ role: 'assistant',+ updatedAt: 1000,+ },+ ]);+ await Promise.resolve();+ });++ expect(store.getState().dbMessages).toEqual(currentMessages);+ expect(onMessagesChange).not.toHaveBeenCalled();+ });+it('should pass null threadId when provided as null', async () => {const mockMessages: UIChatMessage[] = [{diff --git a/src/features/Conversation/store/slices/data/action.ts b/src/features/Conversation/store/slices/data/action.tsindex 0a10c68ea59..a6b30a7395a 100644--- a/src/features/Conversation/store/slices/data/action.ts+++ b/src/features/Conversation/store/slices/data/action.ts@@ -16,6 +16,7 @@ import { operationSelectors } from '@/store/chat/selectors';import { messageMapKey } from '@/store/chat/utils/messageMapKey';import { type Store as ConversationStore } from '../../action';+import { isSameConversationContext } from '../../utils/contextGuard';import { type MessageDispatch } from './reducer';import { messagesReducer } from './reducer';import { dataSelectors } from './selectors';@@ -62,6 +63,8 @@ export interface DataAction {* Used for syncing after database operations (optimistic update pattern)** @param messages - New messages array from database+ * @param options.expectedContext - Context captured when an async operation started.+ * The replacement is discarded if the shared store has since switched context.* @param options.skipOnMessagesChange - Set when the messages came FROM the* external store (StoreUpdater prop sync). Echoing them back through* `onMessagesChange` re-writes the SWR message cache with whatever the@@ -72,7 +75,7 @@ export interface DataAction {*/replaceMessages: (messages: UIChatMessage[],- options?: { skipOnMessagesChange?: boolean },+ options?: { expectedContext?: ConversationContext; skipOnMessagesChange?: boolean },) => void;/**@@ -169,7 +172,20 @@ export const dataSlice: StateCreator<},replaceMessages: (messages, options) => {- const contextKey = messageMapKey(get().context);+ const currentContext = get().context;+ const contextKey = messageMapKey(currentContext);+ if (+ options?.expectedContext &&+ !isSameConversationContext(options.expectedContext, currentContext)+ ) {+ log(+ '[replaceMessages] dropped stale result | requestContextKey=%s | storeContextKey=%s',+ messageMapKey(options.expectedContext),+ contextKey,+ );+ return;+ }+const prevDbMessages = get().dbMessages;// Parse messages using conversation-flow@@ -191,7 +207,9 @@ export const dataSlice: StateCreator<// Sync changes to external store (ChatStore) — skipped for external prop// sync, which would only echo the external store's own data back and// poison the SWR cache (see interface doc).- if (!options?.skipOnMessagesChange) get().onMessagesChange?.(messages, get().context);+ if (!options?.skipOnMessagesChange) {+ get().onMessagesChange?.(messages, options?.expectedContext ?? currentContext);+ }},switchMessageBranch: async (messageId, branchIndex) => {@@ -215,6 +233,8 @@ export const dataSlice: StateCreator<// only local optimistic updates. Fetching would return empty array and overwrite local data.const shouldFetch = !skipFetch && !!context.agentId && !!context.topicId;const contextKey = messageMapKey(context);+ const storeContextKeyAtRequest = messageMapKey(get().context);+ const onMessagesChange = get().onMessagesChange;log('[useFetchMessages] hook | contextKey=%s | shouldFetch=%s | skipFetch=%s | agentId=%s | topicId=%s',@@ -239,6 +259,16 @@ export const dataSlice: StateCreator<if (!data) return;if (!context.topicId) return;+ const storeContextKey = messageMapKey(get().context);+ if (storeContextKeyAtRequest !== storeContextKey) {+ log(+ '[useFetchMessages] dropped stale result | requestStoreContextKey=%s | storeContextKey=%s',+ storeContextKeyAtRequest,+ storeContextKey,+ );+ return;+ }+// Defense-in-depth gate: drop any SWR onData while the// topic is streaming. DB fan-out for chunk writes is async and lags// the WS push by anywhere from 100ms to several seconds; an SWR@@ -257,7 +287,6 @@ export const dataSlice: StateCreator<const prevDbMessages = get().dbMessages;const mergedMessages = mergeFetchedMessagesWithLocalState(data, prevDbMessages);- const storeContextKey = messageMapKey(get().context);// Parse messages using conversation-flowconst { flatList } = parse(mergedMessages);@@ -279,14 +308,15 @@ export const dataSlice: StateCreator<messagesInit: true,});- // Call onMessagesChange callback with the request context (not current context)- // This ensures data is stored to the correct topic even if user switched topics.+ // Use the callback and context captured when this fetch was registered.+ // The store-context guard above rejects results after a topic switch;+ // capturing the callback also prevents routing through a later handler instance.// `source: 'fetch'` marks this as a server-snapshot echo: handlers must// NOT write it through the SWR cache — at mount, this fires with the// stale cached list while the revalidation is in flight, and a cache// mutate here trips SWR's mutation race guard, discarding the fresh// result (conversation locks on the stale/partial list).- get().onMessagesChange?.(mergedMessages, context, { source: 'fetch' });+ onMessagesChange?.(mergedMessages, context, { source: 'fetch' });},},);diff --git a/src/features/Conversation/store/slices/generation/action.test.ts b/src/features/Conversation/store/slices/generation/action.test.tsindex 46653639ab4..4961bf20808 100644--- a/src/features/Conversation/store/slices/generation/action.test.ts+++ b/src/features/Conversation/store/slices/generation/action.test.ts@@ -7,6 +7,7 @@ import { agentSelectors } from '@/store/agent/selectors';import * as agentDispatcher from '@/store/chat/slices/agentRun/actions/dispatch/agentDispatcher';import * as heterogeneousAgentExecutor from '@/store/chat/slices/agentRun/actions/transports/hetero/heterogeneousAgentExecutor';import { INPUT_LOADING_OPERATION_TYPES } from '@/store/chat/slices/operation/types';+import { messageMapKey } from '@/store/chat/utils/messageMapKey';import { type ConversationContext, type ConversationHooks } from '../../../types';import { createStore } from '../../index';@@ -650,22 +651,26 @@ describe('Generation Actions', () => {// The old message is already deleted, so bailing here would be destructive// data loss — regeneration must proceed regardless (Stop is best-effort in// this sub-second window and applies to the fresh run instead).+ let operationCount = 0;const chatState: any = {messagesMap: {},operations: {},operationsByMessage: {},cancelOperations: mockCancelOperations,cancelOperation: mockCancelOperation,- regenerateUserMessage: mockRegenerateUserMessage,switchMessageBranch: mockSwitchMessageBranch,- startOperation: mockStartOperation,+ startOperation: vi.fn(() => {+ const operationId = operationCount++ === 0 ? 'outer-op-id' : 'inner-op-id';+ chatState.operations[operationId] = { id: operationId, status: 'running' };+ return { operationId };+ }),completeOperation: mockCompleteOperation,failOperation: mockFailOperation,executeClientAgent: mockExecuteClientAgent,isGatewayModeEnabled: mockIsGatewayModeEnabled,};chatState.deleteMessage = vi.fn().mockImplementation(async () => {- chatState.operations = { 'test-op-id': { id: 'test-op-id', status: 'cancelled' } };+ chatState.operations['outer-op-id'] = { id: 'outer-op-id', status: 'cancelled' };});vi.mocked(useChatStore.getState).mockReturnValue(chatState);@@ -687,25 +692,114 @@ describe('Generation Actions', () => {} as any);});- // delAndRegenerate calls the slice's OWN regenerateUserMessage (via get()),- // not the useChatStore mock — spy on it to assert (and short-circuit) it.- const regenSpy = vi- .spyOn(store.getState(), 'regenerateUserMessage')- .mockResolvedValue(undefined);-await act(async () => {await store.getState().delAndRegenerateMessage('msg-2');});// Delete ran, and regeneration completes atomically despite the cancelled// outer op — no orphaned deletion.- expect(chatState.deleteMessage).toHaveBeenCalledWith('msg-2', { operationId: 'test-op-id' });- expect(regenSpy).toHaveBeenCalledWith('msg-1');- expect(mockCompleteOperation).toHaveBeenCalled();+ expect(chatState.deleteMessage).toHaveBeenCalledWith('msg-2', {+ operationId: 'outer-op-id',+ });+ expect(mockExecuteClientAgent).toHaveBeenCalledWith(+ expect.objectContaining({+ context,+ parentMessageId: 'msg-1',+ parentOperationId: 'inner-op-id',+ }),+ );+ expect(mockCompleteOperation).toHaveBeenCalledWith('inner-op-id');+ expect(mockCompleteOperation).toHaveBeenCalledWith('outer-op-id');+ });++ it('regenerates in the originating conversation when the context switches during deletion', async () => {+ const { useChatStore } = await import('@/store/chat');+ const oldContext: ConversationContext = {+ agentId: 'session-1',+ groupId: 'group-1',+ threadId: null,+ topicId: 'topic-old',+ };+ const currentContext: ConversationContext = {+ agentId: 'session-1',+ groupId: 'group-1',+ threadId: null,+ topicId: 'topic-current',+ };+ const oldUserMessage = { content: 'old prompt', id: 'user-old', role: 'user' };+ const oldAssistantMessage = {+ content: 'old response',+ id: 'assistant-old',+ parentId: 'user-old',+ role: 'assistant',+ };+ const currentMessages = [{ content: 'current prompt', id: 'user-current', role: 'user' }];+ const oldContextKey = messageMapKey(oldContext);+ let resolveDelete!: () => void;+ const deleteGate = new Promise<void>((resolve) => {+ resolveDelete = resolve;+ });+ const chatState: any = {+ dbMessagesMap: { [oldContextKey]: [oldUserMessage, oldAssistantMessage] },+ messagesMap: { [oldContextKey]: [oldUserMessage, oldAssistantMessage] },+ operations: {},+ operationsByMessage: {},+ cancelOperations: mockCancelOperations,+ cancelOperation: mockCancelOperation,+ completeOperation: mockCompleteOperation,+ deleteMessage: vi.fn().mockImplementation(async () => {+ await deleteGate;+ chatState.dbMessagesMap[oldContextKey] = [oldUserMessage];+ chatState.messagesMap[oldContextKey] = [oldUserMessage];+ }),+ executeClientAgent: mockExecuteClientAgent,+ failOperation: mockFailOperation,+ isGatewayModeEnabled: mockIsGatewayModeEnabled,+ startOperation: mockStartOperation,+ switchMessageBranch: mockSwitchMessageBranch,+ };+ vi.mocked(useChatStore.getState).mockReturnValue(chatState);++ const store = createStore({ context: oldContext });+ store.setState({+ dbMessages: [oldUserMessage, oldAssistantMessage],+ displayMessages: [oldUserMessage, oldAssistantMessage],+ } as any);++ const regeneratePromise = store.getState().delAndRegenerateMessage('assistant-old');++ act(() => {+ store.setState({+ context: currentContext,+ dbMessages: currentMessages,+ displayMessages: currentMessages,+ } as any);+ });++ await act(async () => {+ resolveDelete();+ await regeneratePromise;+ });++ expect(mockSwitchMessageBranch).toHaveBeenCalledWith('user-old', 0, {+ operationId: 'test-op-id',+ });+ expect(mockExecuteClientAgent).toHaveBeenCalledWith(+ expect.objectContaining({+ context: oldContext,+ messages: [oldUserMessage],+ parentMessageId: 'user-old',+ parentMessageType: 'user',+ }),+ );+ expect(store.getState().context).toEqual(currentContext);+ expect(store.getState().dbMessages).toEqual(currentMessages);});it('settles the wrapper op via failOperation when regeneration throws (no stuck loading)', async () => {const { useChatStore } = await import('@/store/chat');+ let operationCount = 0;+ const executeClientAgent = vi.fn().mockRejectedValue(new Error('boom'));const chatState: any = {messagesMap: {},operations: {},@@ -714,10 +808,14 @@ describe('Generation Actions', () => {cancelOperation: mockCancelOperation,deleteMessage: vi.fn().mockResolvedValue(undefined),switchMessageBranch: mockSwitchMessageBranch,- startOperation: mockStartOperation,+ startOperation: vi.fn(() => {+ const operationId = operationCount++ === 0 ? 'outer-op-id' : 'inner-op-id';+ chatState.operations[operationId] = { id: operationId, status: 'running' };+ return { operationId };+ }),completeOperation: mockCompleteOperation,failOperation: mockFailOperation,- executeClientAgent: mockExecuteClientAgent,+ executeClientAgent,isGatewayModeEnabled: mockIsGatewayModeEnabled,};vi.mocked(useChatStore.getState).mockReturnValue(chatState);@@ -740,20 +838,15 @@ describe('Generation Actions', () => {} as any);});- // Regeneration blows up mid-retry. Because `regenerate` now drives input- // loading + queue blocking, the wrapper op MUST be settled — otherwise the- // input wedges in loading forever and future sends queue behind it.- vi.spyOn(store.getState(), 'regenerateUserMessage').mockRejectedValue(new Error('boom'));-await act(async () => {await expect(store.getState().delAndRegenerateMessage('msg-2')).rejects.toThrow('boom');});expect(mockFailOperation).toHaveBeenCalledWith(- 'test-op-id',+ 'outer-op-id',expect.objectContaining({ type: 'RegenerateError' }),);- expect(mockCompleteOperation).not.toHaveBeenCalled();+ expect(mockCompleteOperation).not.toHaveBeenCalledWith('outer-op-id');});});diff --git a/src/features/Conversation/store/slices/generation/action.ts b/src/features/Conversation/store/slices/generation/action.tsindex e7f5a627c89..386e99c13d7 100644--- a/src/features/Conversation/store/slices/generation/action.ts+++ b/src/features/Conversation/store/slices/generation/action.ts@@ -246,6 +246,179 @@ export interface HeteroContinuationScheduleParams {};}+interface RegenerateUserMessageSource {+ context: ConversationContext;+ displayMessages: ConversationStore['displayMessages'];+ hooks: ConversationStore['hooks'];+ readDbMessages: () => ConversationStore['dbMessages'];+}++const captureRegenerateUserMessageSource = (+ get: () => ConversationStore,+): RegenerateUserMessageSource => {+ const { context, dbMessages, displayMessages, hooks } = get();+ const contextKey = messageMapKey(context);++ return {+ context,+ displayMessages,+ hooks,+ readDbMessages: () => {+ const currentState = get();+ if (messageMapKey(currentState.context) === contextKey) return currentState.dbMessages;++ return useChatStore.getState().dbMessagesMap[contextKey] ?? dbMessages;+ },+ };+};++const regenerateUserMessageFromSource = async (+ messageId: string,+ source: RegenerateUserMessageSource,+) => {+ const { context, displayMessages, hooks, readDbMessages } = source;+ const chatStore = useChatStore.getState();++ // Check if already regenerating via operation system+ const isRegenerating = operationSelectors.isMessageProcessing(messageId)(chatStore);+ if (isRegenerating) return;++ // Find the message in the captured conversation messages. The source remains+ // bound to the initiating context even if StoreUpdater reuses this store for+ // another topic while an earlier delete or preflight request is in flight.+ const currentIndex = displayMessages.findIndex((c) => c.id === messageId);+ const item = displayMessages[currentIndex];+ if (!item) return;+ // Start the interim regenerate op BEFORE the async preflight below+ // (document-context resolve + onBeforeRegenerate hook). In page / bound-+ // document contexts those reads are real round trips, so creating the op+ // afterwards would leave the input/Stop state dead during exactly the+ // pre-generation window the INPUT_LOADING_OPERATION_TYPES whitelist covers.+ // Complete it if any preflight guard bails out before generation starts.+ const { operationId } = chatStore.startOperation({+ context: { ...context, messageId },+ type: 'regenerate',+ });++ try {+ const initialContext = mergeAgentRuntimeInitialContexts(+ await resolveActiveTopicDocumentInitialContext(context),+ buildRetryInitialContext(item.editorData),+ );++ // Get context messages up to and including the target message+ const contextMessages = displayMessages.slice(0, currentIndex + 1);+ if (contextMessages.length <= 0) {+ chatStore.completeOperation(operationId);+ return;+ }++ // ===== Hook: onBeforeRegenerate =====+ if (hooks.onBeforeRegenerate) {+ const shouldProceed = await hooks.onBeforeRegenerate(messageId);+ if (shouldProceed === false) {+ chatStore.completeOperation(operationId);+ return;+ }+ }++ // If the user hit Stop during the preflight awaits above, stopGenerating has+ // already cancelled this interim op (cancelOperation flips its status but+ // keeps the record). Bail out before switching branches or starting a run —+ // otherwise the Stop is swallowed and a new assistant turn starts anyway. No+ // child runtime exists yet, so cancelOperation had nothing to propagate to;+ // this is the only place that can honour the Stop.+ const preflightOp = operationSelectors.getOperationById(operationId)(useChatStore.getState());+ if (preflightOp && preflightOp.status !== 'running') return;++ // Read the database messages from the captured conversation. If the shared+ // ConversationStore has switched context, the source falls back to the old+ // context's ChatStore bucket instead of observing the new topic.+ const dbMessages = readDbMessages();+ const childrenCount = dbMessages.filter((m) => m.parentId === messageId).length;+ const nextBranchIndex = childrenCount;++ // Switch to the new branch so the UI shows the incoming response immediately+ await chatStore.switchMessageBranch(messageId, nextBranchIndex, {+ operationId,+ });++ // Re-check after switchMessageBranch: it is another await round-trip, so a+ // Stop pressed during it lands *after* the preflight guard above. Bail+ // before starting the runtime so the Stop isn't swallowed. The branch is+ // already switched, which is harmless — no assistant turn has started yet.+ const postSwitchOp = operationSelectors.getOperationById(operationId)(useChatStore.getState());+ if (postSwitchOp && postSwitchOp.status !== 'running') return;++ const { agencyConfig, workspaceScoped } = getEffectiveAgencyConfig(context.agentId);+ const heterogeneousProvider = agencyConfig?.heterogeneousProvider;+ const runtimeType = selectRuntimeType({+ boundDeviceId: agencyConfig?.boundDeviceId,+ executionTarget: agencyConfig?.executionTarget,+ heterogeneousProvider,+ isGatewayMode: chatStore.isGatewayModeEnabled(context.agentId),+ isWorkspaceAgent: workspaceScoped,+ });++ // ── Gateway mode: trigger server-side regeneration ──+ if (runtimeType === 'gateway') {+ // Keep the regenerate operation running until the gateway session completes,+ // so isMessageRegenerating stays true and duplicate clicks are blocked.+ await chatStore.executeGatewayAgent({+ context,+ message: item.content,+ onComplete: () =>+ settleGenerationEntry(chatStore, operationId, () =>+ hooks.onRegenerateComplete?.(messageId),+ ),+ parentMessageId: messageId,+ });++ return;+ }++ // ── Hetero mode: re-run the local CLI against the original user prompt ──+ // Creates a fresh assistant row branched off the existing user message so+ // the CC / Codex turn replaces the previous attempt without rewriting+ // history, and resumes the same session id (when the cwd still matches)+ // so prior context is preserved.+ if (runtimeType === 'hetero' && heterogeneousProvider) {+ await runHeterogeneousFromExistingMessage(chatStore, {+ context,+ heterogeneousProvider,+ // Forward the original user message's images so regenerate re-runs+ // the CLI with the same vision input as the first attempt. Without+ // this, regenerate silently drops attachments (the send path reads+ // imageList off the persisted user message; this path must too).+ imageList: item.imageList,+ parentMessageId: messageId,+ parentOperationId: operationId,+ prompt: item.content,+ });+ settleGenerationEntry(chatStore, operationId, () => hooks.onRegenerateComplete?.(messageId));+ return;+ }++ // ── Client mode: run agent locally ──+ await chatStore.executeClientAgent({+ context,+ initialContext,+ messages: contextMessages,+ parentMessageId: messageId,+ parentMessageType: 'user',+ parentOperationId: operationId,+ });++ settleGenerationEntry(chatStore, operationId, () => hooks.onRegenerateComplete?.(messageId));+ } catch (error) {+ chatStore.failOperation(operationId, {+ message: error instanceof Error ? error.message : String(error),+ type: 'RegenerateError',+ });+ throw error;+ }+};+/*** Generation Actions*@@ -739,7 +912,8 @@ export const generationSlice: StateCreator<},delAndRegenerateMessage: async (messageId: string) => {- const { context, displayMessages } = get();+ const regenerationSource = captureRegenerateUserMessageSource(get);+ const { context, displayMessages } = regenerationSource;const chatStore = useChatStore.getState();// Find the assistant message and get parent user message ID before deletion@@ -768,7 +942,7 @@ export const generationSlice: StateCreator<// nothing regenerated — destructive data loss. Stop pressed in this// sub-second window is best-effort; complete the retry atomically and honor// the next Stop (on the fresh run) normally.- await get().regenerateUserMessage(userId);+ await regenerateUserMessageFromSource(userId, regenerationSource);chatStore.completeOperation(operationId);} catch (error) {// Settle the wrapper op on failure. `regenerate` now drives input-loading +@@ -921,152 +1095,8 @@ export const generationSlice: StateCreator<await get().regenerateUserMessage(userId);},- regenerateUserMessage: async (messageId: string) => {- const { context, displayMessages, hooks } = get();- const chatStore = useChatStore.getState();-- // Check if already regenerating via operation system- const isRegenerating = operationSelectors.isMessageProcessing(messageId)(chatStore);- if (isRegenerating) return;-- // Find the message in current conversation messages- const currentIndex = displayMessages.findIndex((c) => c.id === messageId);- const item = displayMessages[currentIndex];- if (!item) return;- // Start the interim regenerate op BEFORE the async preflight below- // (document-context resolve + onBeforeRegenerate hook). In page / bound-- // document contexts those reads are real round trips, so creating the op- // afterwards would leave the input/Stop state dead during exactly the- // pre-generation window the INPUT_LOADING_OPERATION_TYPES whitelist covers.- // Complete it if any preflight guard bails out before generation starts.- const { operationId } = chatStore.startOperation({- context: { ...context, messageId },- type: 'regenerate',- });-- try {- const initialContext = mergeAgentRuntimeInitialContexts(- await resolveActiveTopicDocumentInitialContext(context),- buildRetryInitialContext(item.editorData),- );-- // Get context messages up to and including the target message- const contextMessages = displayMessages.slice(0, currentIndex + 1);- if (contextMessages.length <= 0) {- chatStore.completeOperation(operationId);- return;- }-- // ===== Hook: onBeforeRegenerate =====- if (hooks.onBeforeRegenerate) {- const shouldProceed = await hooks.onBeforeRegenerate(messageId);- if (shouldProceed === false) {- chatStore.completeOperation(operationId);- return;- }- }-- // If the user hit Stop during the preflight awaits above, stopGenerating has- // already cancelled this interim op (cancelOperation flips its status but- // keeps the record). Bail out before switching branches or starting a run —- // otherwise the Stop is swallowed and a new assistant turn starts anyway. No- // child runtime exists yet, so cancelOperation had nothing to propagate to;- // this is the only place that can honour the Stop.- const preflightOp = operationSelectors.getOperationById(operationId)(useChatStore.getState());- if (preflightOp && preflightOp.status !== 'running') return;-- // Calculate next branch index by counting children of this user message- // We need to count how many assistant messages have this user message as parent- const { dbMessages } = get();- const childrenCount = dbMessages.filter((m) => m.parentId === messageId).length;- // New branch index = current children count (since index is 0-based)- const nextBranchIndex = childrenCount;-- // Switch to the new branch so the UI shows the incoming response immediately- await chatStore.switchMessageBranch(messageId, nextBranchIndex, {- operationId,- });-- // Re-check after switchMessageBranch: it is another await round-trip, so a- // Stop pressed during it lands *after* the preflight guard above. Bail- // before starting the runtime so the Stop isn't swallowed. The branch is- // already switched, which is harmless — no assistant turn has started yet.- const postSwitchOp = operationSelectors.getOperationById(operationId)(- useChatStore.getState(),- );- if (postSwitchOp && postSwitchOp.status !== 'running') return;-- const { agencyConfig, workspaceScoped } = getEffectiveAgencyConfig(context.agentId);- const heterogeneousProvider = agencyConfig?.heterogeneousProvider;- const runtimeType = selectRuntimeType({- boundDeviceId: agencyConfig?.boundDeviceId,- executionTarget: agencyConfig?.executionTarget,- heterogeneousProvider,- isGatewayMode: chatStore.isGatewayModeEnabled(context.agentId),- isWorkspaceAgent: workspaceScoped,- });-- // ── Gateway mode: trigger server-side regeneration ──- if (runtimeType === 'gateway') {- // Keep the regenerate operation running until the gateway session completes,- // so isMessageRegenerating stays true and duplicate clicks are blocked.- await chatStore.executeGatewayAgent({- context,- message: item.content,- onComplete: () =>- settleGenerationEntry(chatStore, operationId, () =>- hooks.onRegenerateComplete?.(messageId),- ),- parentMessageId: messageId,- });-- return;- }-- // ── Hetero mode: re-run the local CLI against the original user prompt ──- // Creates a fresh assistant row branched off the existing user message so- // the CC / Codex turn replaces the previous attempt without rewriting- // history, and resumes the same session id (when the cwd still matches)- // so prior context is preserved.- if (runtimeType === 'hetero' && heterogeneousProvider) {- await runHeterogeneousFromExistingMessage(chatStore, {- context,- heterogeneousProvider,- // Forward the original user message's images so regenerate re-runs- // the CLI with the same vision input as the first attempt. Without- // this, regenerate silently drops attachments (the send path reads- // imageList off the persisted user message; this path must too).- imageList: item.imageList,- parentMessageId: messageId,- parentOperationId: operationId,- prompt: item.content,- });- settleGenerationEntry(chatStore, operationId, () =>- hooks.onRegenerateComplete?.(messageId),- );- return;- }-- // ── Client mode: run agent locally ──- // Execute agent runtime with full context from ConversationStore- await chatStore.executeClientAgent({- context,- initialContext,- messages: contextMessages,- parentMessageId: messageId,- parentMessageType: 'user',- parentOperationId: operationId,- });-- settleGenerationEntry(chatStore, operationId, () => hooks.onRegenerateComplete?.(messageId));- } catch (error) {- chatStore.failOperation(operationId, {- message: error instanceof Error ? error.message : String(error),- type: 'RegenerateError',- });- throw error;- }- },+ regenerateUserMessage: async (messageId: string) =>+ regenerateUserMessageFromSource(messageId, captureRegenerateUserMessageSource(get)),resendThreadMessage: async (messageId: string) => {// Resend is essentially regenerating the user message in thread contextdiff --git a/src/features/Conversation/store/slices/message/action/crud.test.ts b/src/features/Conversation/store/slices/message/action/crud.test.tsindex d7731d47414..b7cb2201913 100644--- a/src/features/Conversation/store/slices/message/action/crud.test.ts+++ b/src/features/Conversation/store/slices/message/action/crud.test.ts@@ -96,6 +96,72 @@ describe('Message CRUD Actions', () => {expect(result).toBeUndefined();});++ it('discards a create result that resolves after switching conversations', async () => {+ let resolveCreate!: (result: any) => void;+ vi.spyOn(messageServiceModule.messageService, 'createMessage').mockReturnValue(+ new Promise((resolve) => {+ resolveCreate = resolve;+ }),+ );++ const oldContext = {+ agentId: 'test-session',+ threadId: null,+ topicId: 'topic-old',+ };+ const currentContext = {+ agentId: 'test-session',+ threadId: null,+ topicId: 'topic-current',+ };+ const currentMessages: UIChatMessage[] = [+ {+ content: 'current topic',+ createdAt: 2000,+ id: 'msg-current',+ role: 'user',+ updatedAt: 2000,+ },+ ];+ const store = createTestStore(oldContext);+ const onMessagesChange = vi.fn();+ store.setState({ onMessagesChange });++ const createPromise = store.getState().createMessage({+ content: 'old topic message',+ role: 'user',+ });+ onMessagesChange.mockClear();+ store.setState({+ context: currentContext,+ dbMessages: currentMessages,+ displayMessages: currentMessages,+ messageLoadingIds: [],+ messagesInit: true,+ });++ let result: string | undefined;+ await act(async () => {+ resolveCreate({+ id: 'msg-old',+ messages: [+ {+ content: 'late old topic result',+ createdAt: 1000,+ id: 'msg-old',+ role: 'user',+ updatedAt: 1000,+ },+ ],+ });+ result = await createPromise;+ });++ expect(result).toBeUndefined();+ expect(store.getState().dbMessages).toEqual(currentMessages);+ expect(onMessagesChange).not.toHaveBeenCalled();+ });});describe('createTempMessage', () => {diff --git a/src/features/Conversation/store/slices/message/action/crud.ts b/src/features/Conversation/store/slices/message/action/crud.tsindex d5128d1781e..95f60beeeea 100644--- a/src/features/Conversation/store/slices/message/action/crud.ts+++ b/src/features/Conversation/store/slices/message/action/crud.ts@@ -21,6 +21,7 @@ import { type StateCreator } from 'zustand';import { messageService } from '@/services/message';import { type Store as ConversationStore } from '../../../action';+import { isSameConversationContext } from '../../../utils/contextGuard';import { dataSelectors } from '../../data/selectors';/**@@ -185,7 +186,7 @@ export const messageCRUDSlice: StateCreator<const result = await messageService.updateMessage(messageId, { tools: [tool] }, context);if (result?.success && result.messages) {- replaceMessages(result.messages);+ replaceMessages(result.messages, { expectedContext: context });}},@@ -196,7 +197,7 @@ export const messageCRUDSlice: StateCreator<await messageService.removeMessagesByAssistant(context.agentId, context.topicId ?? undefined);// Clear local state- replaceMessages([]);+ replaceMessages([], { expectedContext: context });},// ===== Create ===== //@@ -216,11 +217,15 @@ export const messageCRUDSlice: StateCreator<});// Replace with server response- replaceMessages(result.messages);+ if (!isSameConversationContext(context, get().context)) return undefined;+ replaceMessages(result.messages, { expectedContext: context });+internal_toggleMessageLoading(false, tempId);return result.id;} catch (e) {+ if (!isSameConversationContext(context, get().context)) return undefined;+internal_toggleMessageLoading(false, tempId);// Update temp message with error@@ -286,7 +291,7 @@ export const messageCRUDSlice: StateCreator<const result = await messageService.removeMessage(id, context);if (result?.success && result.messages) {- replaceMessages(result.messages);+ replaceMessages(result.messages, { expectedContext: context });}},@@ -326,7 +331,7 @@ export const messageCRUDSlice: StateCreator<: await messageService.removeMessages(ids, context);if (result?.success && result.messages) {- replaceMessages(result.messages);+ replaceMessages(result.messages, { expectedContext: context });}},@@ -340,7 +345,7 @@ export const messageCRUDSlice: StateCreator<const result = await messageService.removeMessages(ids, context);if (result?.success && result.messages) {- replaceMessages(result.messages);+ replaceMessages(result.messages, { expectedContext: context });}},@@ -366,7 +371,7 @@ export const messageCRUDSlice: StateCreator<const result = await messageService.removeMessage(id, context);if (result?.success && result.messages) {- replaceMessages(result.messages);+ replaceMessages(result.messages, { expectedContext: context });}},@@ -390,7 +395,7 @@ export const messageCRUDSlice: StateCreator<);if (result?.success && result.messages) {- replaceMessages(result.messages);+ replaceMessages(result.messages, { expectedContext: context });}}},@@ -432,7 +437,7 @@ export const messageCRUDSlice: StateCreator<);if (result?.success && result.messages) {- replaceMessages(result.messages);+ replaceMessages(result.messages, { expectedContext: context });}},@@ -450,7 +455,7 @@ export const messageCRUDSlice: StateCreator<const result = await messageService.updateMessage(id, { error }, context);if (result?.success && result.messages) {- replaceMessages(result.messages);+ replaceMessages(result.messages, { expectedContext: context });}},@@ -464,7 +469,7 @@ export const messageCRUDSlice: StateCreator<const result = await messageService.updateMessageMetadata(id, metadata, context);if (result?.success && result.messages) {- replaceMessages(result.messages);+ replaceMessages(result.messages, { expectedContext: context });}},@@ -482,7 +487,7 @@ export const messageCRUDSlice: StateCreator<const result = await messageService.updateMessagePlugin(id, value, context);if (result?.success && result.messages) {- replaceMessages(result.messages);+ replaceMessages(result.messages, { expectedContext: context });}},@@ -493,7 +498,7 @@ export const messageCRUDSlice: StateCreator<const result = await messageService.updateMessagePluginError(id, error, context);if (result?.success && result.messages) {- replaceMessages(result.messages);+ replaceMessages(result.messages, { expectedContext: context });}},@@ -504,7 +509,7 @@ export const messageCRUDSlice: StateCreator<const result = await messageService.updateMessageRAG(id, data, context);if (result?.success && result.messages) {- replaceMessages(result.messages);+ replaceMessages(result.messages, { expectedContext: context });}},@@ -529,7 +534,7 @@ export const messageCRUDSlice: StateCreator<);if (result?.success && result.messages) {- replaceMessages(result.messages);+ replaceMessages(result.messages, { expectedContext: context });}}},@@ -600,7 +605,7 @@ export const messageCRUDSlice: StateCreator<const updatePromise = (async () => {const result = await messageService.updateToolArguments(toolCallId, nextValue, context);if (result?.success && result.messages) {- replaceMessages(result.messages);+ replaceMessages(result.messages, { expectedContext: context });}})();@@ -616,16 +621,18 @@ export const messageCRUDSlice: StateCreator<try {await updatePromise;} finally {- // Remove the completed promise- set(- (state) => {- const newMap = new Map(state.pendingArgsUpdates);- newMap.delete(toolCallId);- return { pendingArgsUpdates: newMap };- },- false,- 'updatePluginArguments/complete',- );+ if (isSameConversationContext(context, get().context)) {+ // Remove the completed promise+ set(+ (state) => {+ const newMap = new Map(state.pendingArgsUpdates);+ newMap.delete(toolCallId);+ return { pendingArgsUpdates: newMap };+ },+ false,+ 'updatePluginArguments/complete',+ );+ }}},diff --git a/src/features/Conversation/store/slices/message/action/index.ts b/src/features/Conversation/store/slices/message/action/index.tsindex 20e073ab3f3..1466122d38a 100644--- a/src/features/Conversation/store/slices/message/action/index.ts+++ b/src/features/Conversation/store/slices/message/action/index.ts@@ -6,6 +6,7 @@ import type { StateCreator } from 'zustand';import { getEffectiveConversationModel } from '@/features/Conversation/store/utils/effectiveModel';import type { Store as ConversationStore } from '../../../action';+import { isSameConversationContext } from '../../../utils/contextGuard';import { type MessageCRUDAction, messageCRUDSlice } from './crud';import { type MessageReactionAction, messageReactionSlice } from './reaction';import { sendMessage } from './sendMessage';@@ -72,6 +73,7 @@ export const messageSlice: StateCreator<threadId: threadId ?? undefined,topicId: topicId ?? undefined,});+ if (!isSameConversationContext(context, get().context)) return undefined;if (id) {// ===== Hook: onMessageCreated =====@@ -117,6 +119,7 @@ export const messageSlice: StateCreator<threadId: threadId ?? undefined,topicId: topicId ?? undefined,});+ if (!isSameConversationContext(context, get().context)) return undefined;if (id) {// ===== Hook: onMessageCreated =====diff --git a/src/features/Conversation/store/slices/message/action/state.test.ts b/src/features/Conversation/store/slices/message/action/state.test.tsindex b9dd59526ae..0e71cc758c7 100644--- a/src/features/Conversation/store/slices/message/action/state.test.ts+++ b/src/features/Conversation/store/slices/message/action/state.test.ts@@ -97,7 +97,13 @@ describe('MessageStateAction', () => {threadId: null,topicId: 'test-topic',});- expect(replaceMessagesSpy).toHaveBeenCalledWith(restoredMessages);+ expect(replaceMessagesSpy).toHaveBeenCalledWith(restoredMessages, {+ expectedContext: {+ agentId: 'test-agent',+ threadId: null,+ topicId: 'test-topic',+ },+ });});});@@ -328,7 +334,13 @@ describe('MessageStateAction', () => {await store.getState().toggleCompressedGroupExpanded('group-1');// Assert- expect(replaceMessagesSpy).toHaveBeenCalledWith(updatedMessages);+ expect(replaceMessagesSpy).toHaveBeenCalledWith(updatedMessages, {+ expectedContext: {+ agentId: 'test-agent',+ threadId: null,+ topicId: 'test-topic',+ },+ });});});});diff --git a/src/features/Conversation/store/slices/message/action/state.ts b/src/features/Conversation/store/slices/message/action/state.tsindex 7d1274fb1b9..ce9e9cbd172 100644--- a/src/features/Conversation/store/slices/message/action/state.ts+++ b/src/features/Conversation/store/slices/message/action/state.ts@@ -7,6 +7,7 @@ import { useChatStore } from '@/store/chat';import { cleanSpeakerTag } from '@/store/chat/utils/cleanSpeakerTag';import { type Store as ConversationStore } from '../../../action';+import { isSameConversationContext } from '../../../utils/contextGuard';import { dataSelectors } from '../../data/selectors';/**@@ -82,7 +83,7 @@ export const messageStateSlice: StateCreator<});// Replace messages with restored original messages- replaceMessages(messages);+ replaceMessages(messages, { expectedContext: context });},copyMessage: async (id, content) => {@@ -114,7 +115,7 @@ export const messageStateSlice: StateCreator<},modifyMessageContent: async (id, content, editorData) => {- const { hooks } = get();+ const { context, hooks } = get();// Get original content for hookconst originalMessage = dataSelectors.getDisplayMessageById(id)(get());@@ -122,6 +123,7 @@ export const messageStateSlice: StateCreator<// Update contentawait get().updateMessageContent(id, content, editorData ? { editorData } : undefined);+ if (!isSameConversationContext(context, get().context)) return;// ===== Hook: onMessageModified =====if (hooks.onMessageModified) {@@ -160,7 +162,7 @@ export const messageStateSlice: StateCreator<});// Sync with server data- replaceMessages(messages);+ replaceMessages(messages, { expectedContext: context });},toggleInspectExpanded: async (id, expanded) => {diff --git a/src/features/Conversation/store/utils/contextGuard.ts b/src/features/Conversation/store/utils/contextGuard.tsnew file mode 100644index 00000000000..9e1722615a3--- /dev/null+++ b/src/features/Conversation/store/utils/contextGuard.ts@@ -0,0 +1,8 @@+import { type ConversationContext } from '@lobechat/types';++import { messageMapKey } from '@/store/chat/utils/messageMapKey';++export const isSameConversationContext = (+ expected: ConversationContext,+ current: ConversationContext,+): boolean => messageMapKey(expected) === messageMapKey(current);diff --git a/src/features/ExplorerTree/view/ExplorerTree.tsx b/src/features/ExplorerTree/view/ExplorerTree.tsxindex 5d7f3d46aac..a8dcf029b2e 100644--- a/src/features/ExplorerTree/view/ExplorerTree.tsx+++ b/src/features/ExplorerTree/view/ExplorerTree.tsx@@ -10,13 +10,9 @@ import { FileTree as PierreFileTree, useFileTree, useFileTreeSelection } from '@import type { DragEvent, ForwardedRef, MouseEvent } from 'react';import { forwardRef, useImperativeHandle, useLayoutEffect, useMemo, useRef } from 'react';-import {- arrayEqual,- type NormalizedTree,- normalizeTree,- remapIdsToPaths,- remapPathsToIds,-} from '../adapter';+import { useSingleton } from '@/hooks/useSingleton';++import { arrayEqual, normalizeTree, remapIdsToPaths, remapPathsToIds } from '../adapter';import { extractName, toCanonicalTreePath } from '../adapter/path';import type {ExplorerTreeHandle,@@ -67,7 +63,9 @@ function ExplorerTreeInner<TData>(const propsRef = useRef(props);propsRef.current = props;- const adapterRef = useRef<NormalizedTree<TData>>(normalizeTree(props.nodes));+ const adapterRef = useSingleton(() => ({+ current: normalizeTree(props.nodes),+ }));// emitted values so we don't fire feedback loops on change listenersconst lastEmittedSelectedIds = useRef<string[]>(@@ -250,7 +248,7 @@ function ExplorerTreeInner<TData>(lastExpandedSignatureRef.current = signature;onChange(nextExpanded);});- }, [model]);+ }, [adapterRef, model]);const lastExpandedSignatureRef = useRef<string>('');@@ -278,7 +276,7 @@ function ExplorerTreeInner<TData>(} finally {suppressModelEventsRef.current = false;}- }, [props.selectedIds, model]);+ }, [adapterRef, props.selectedIds, model]);useLayoutEffect(() => {const expandedIds = props.expandedIds;@@ -304,7 +302,7 @@ function ExplorerTreeInner<TData>(} finally {suppressModelEventsRef.current = false;}- }, [props.expandedIds, model]);+ }, [adapterRef, props.expandedIds, model]);// nodes prop changes → resetPathsuseLayoutEffect(() => {@@ -398,7 +396,7 @@ function ExplorerTreeInner<TData>(} finally {suppressModelEventsRef.current = false;}- }, [props.nodes, model]);+ }, [adapterRef, props.nodes, model]);useImperativeHandle(ref,@@ -439,7 +437,7 @@ function ExplorerTreeInner<TData>(model.startRenaming(path);},}),- [model],+ [adapterRef, model],);const handleContextMenu = (event: MouseEvent<HTMLElement>) => {diff --git a/src/features/ModelSwitchPanel/components/List/index.tsx b/src/features/ModelSwitchPanel/components/List/index.tsxindex f655d5303d1..c9894a82f4e 100644--- a/src/features/ModelSwitchPanel/components/List/index.tsx+++ b/src/features/ModelSwitchPanel/components/List/index.tsx@@ -5,6 +5,7 @@ import { useTranslation } from 'react-i18next';import { useBusinessModelListGuard } from '@/business/client/hooks/useBusinessModelListGuard';import { useEnabledChatModels } from '@/hooks/useEnabledChatModels';+import { useSingleton } from '@/hooks/useSingleton';import type { EnabledProviderWithModels } from '@/types/aiProvider';import { FOOTER_HEIGHT, ITEM_HEIGHT, MAX_PANEL_HEIGHT, TOOLBAR_HEIGHT } from '../../const';@@ -77,16 +78,19 @@ export const List: FC<ListProps> = ({const listHeight = panelHeight - TOOLBAR_HEIGHT - FOOTER_HEIGHT;- const scrollListenersRef = useRef(new Set<() => void>());- const subscribeScroll = useCallback((cb: () => void) => {- scrollListenersRef.current.add(cb);- return () => {- scrollListenersRef.current.delete(cb);- };- }, []);+ const scrollListeners = useSingleton(() => new Set<() => void>());+ const subscribeScroll = useCallback(+ (cb: () => void) => {+ scrollListeners.add(cb);+ return () => {+ scrollListeners.delete(cb);+ };+ },+ [scrollListeners],+ );const handleListScroll = useCallback(() => {- scrollListenersRef.current.forEach((cb) => cb());- }, []);+ scrollListeners.forEach((cb) => cb());+ }, [scrollListeners]);useLayoutEffect(() => {if (hasInitializedPositionRef.current) return;diff --git a/src/features/NavPanel/NavPanelPortal.tsx b/src/features/NavPanel/NavPanelPortal.tsxindex c6f7733c25a..d4b8aa09198 100644--- a/src/features/NavPanel/NavPanelPortal.tsx+++ b/src/features/NavPanel/NavPanelPortal.tsx@@ -1,6 +1,8 @@'use client';-import { memo, type PropsWithChildren, useLayoutEffect, useRef } from 'react';+import { memo, type PropsWithChildren, useLayoutEffect } from 'react';++import { useSingleton } from '@/hooks/useSingleton';import { registerNavPanelContent, unregisterNavPanelContent } from './registry';@@ -13,18 +15,17 @@ interface NavPanelPortalProps extends PropsWithChildren {}export const NavPanelPortal = memo<NavPanelPortalProps>(({ children, navKey = 'default' }) => {- const ownerRef = useRef(Symbol('NavPanelPortal'));+ const owner = useSingleton(() => Symbol('NavPanelPortal'));useLayoutEffect(() => {if (!children) return;- const owner = ownerRef.current;registerNavPanelContent(navKey, owner, children);return () => {unregisterNavPanelContent(navKey, owner);};- }, [children, navKey]);+ }, [children, navKey, owner]);return null;});diff --git a/src/features/NavPanel/components/NavItem.tsx b/src/features/NavPanel/components/NavItem.tsxindex 32a08d215cd..4d0014786eb 100644--- a/src/features/NavPanel/components/NavItem.tsx+++ b/src/features/NavPanel/components/NavItem.tsx@@ -244,4 +244,6 @@ const NavItem = memo<NavItemProps>(},);+NavItem.displayName = 'NavItem';+export default NavItem;diff --git a/src/features/OllamaModelDownloader/useDownloadMonitor.ts b/src/features/OllamaModelDownloader/useDownloadMonitor.tsindex 9cdd48c0c7c..4c33b873e72 100644--- a/src/features/OllamaModelDownloader/useDownloadMonitor.ts+++ b/src/features/OllamaModelDownloader/useDownloadMonitor.ts@@ -1,5 +1,6 @@import { useEffect, useRef, useState } from 'react';+import { useSingleton } from '@/hooks/useSingleton';import { formatSpeed, formatTime } from '@/utils/format';export const useDownloadMonitor = (totalSize: number, completedSize: number) => {@@ -7,7 +8,7 @@ export const useDownloadMonitor = (totalSize: number, completedSize: number) =>const [remainingTime, setRemainingTime] = useState<string>('-');const lastCompletedRef = useRef(completedSize);- const lastTimedRef = useRef(Date.now());+ const lastTimedRef = useSingleton(() => ({ current: Date.now() }));useEffect(() => {const currentTime = Date.now();diff --git a/src/features/Onboarding/Classic/index.tsx b/src/features/Onboarding/Classic/index.tsxindex f33229d0fa8..883539482e2 100644--- a/src/features/Onboarding/Classic/index.tsx+++ b/src/features/Onboarding/Classic/index.tsx@@ -13,6 +13,7 @@ import InterestsStep from '@/features/Onboarding/steps/InterestsStep';import ProSettingsStep from '@/features/Onboarding/steps/ProSettingsStep';import { useIsMobile } from '@/hooks/useIsMobile';import { useOnboardingAgentTemplates } from '@/hooks/useOnboardingAgentTemplates';+import { useSingleton } from '@/hooks/useSingleton';import {trackOnboardingStepCompleted,trackOnboardingStepViewed,@@ -57,8 +58,8 @@ const ClassicOnboardingPage = memo(() => {const enableComposio = useServerConfigStore(serverConfigSelectors.enableComposio);const serverConfigInit = useServerConfigStore((s) => s.serverConfigInit);const shouldSkipProSettingsStep = serverConfigInit && !enableComposio;- const autoSkippedStepKeysRef = useRef<Set<string>>(new Set());- const viewedStepKeysRef = useRef<Set<string>>(new Set());+ const autoSkippedStepKeys = useSingleton(() => new Set<string>());+ const viewedStepKeys = useSingleton(() => new Set<string>());const legacyRemappedRef = useRef(false);useOnboardingAgentTemplates(isUserStateInit && commonStepsCompleted);@@ -92,16 +93,23 @@ const ClassicOnboardingPage = memo(() => {}const payload = CLASSIC_STEP_TRACKING[PRO_SETTINGS_STEP];- if (autoSkippedStepKeysRef.current.has(payload.step)) return;+ if (autoSkippedStepKeys.has(payload.step)) return;- autoSkippedStepKeysRef.current.add(payload.step);+ autoSkippedStepKeys.add(payload.step);trackOnboardingStepCompleted({...payload,action: 'auto_skip',skipped: true,});goToNextStep();- }, [commonStepsCompleted, currentStep, goToNextStep, isUserStateInit, shouldSkipProSettingsStep]);+ }, [+ autoSkippedStepKeys,+ commonStepsCompleted,+ currentStep,+ goToNextStep,+ isUserStateInit,+ shouldSkipProSettingsStep,+ ]);useEffect(() => {if (!isUserStateInit || !commonStepsCompleted) return;@@ -110,9 +118,9 @@ const ClassicOnboardingPage = memo(() => {}const payload = getClassicStepTrackingPayload(currentStep);- if (!payload || viewedStepKeysRef.current.has(payload.step)) return;+ if (!payload || viewedStepKeys.has(payload.step)) return;- viewedStepKeysRef.current.add(payload.step);+ viewedStepKeys.add(payload.step);trackOnboardingStepViewed(payload);}, [commonStepsCompleted,@@ -120,6 +128,7 @@ const ClassicOnboardingPage = memo(() => {isUserStateInit,serverConfigInit,shouldSkipProSettingsStep,+ viewedStepKeys,]);const goToNextStepFromFullName = useCallback(() => {diff --git a/src/features/Onboarding/index.tsx b/src/features/Onboarding/index.tsxindex 9738bfd4a4d..d93da2bef26 100644--- a/src/features/Onboarding/index.tsx+++ b/src/features/Onboarding/index.tsx@@ -1,7 +1,7 @@'use client';import { Flexbox } from '@lobehub/ui';-import { memo, useCallback, useEffect, useRef } from 'react';+import { memo, useCallback, useEffect } from 'react';import { useSearchParams } from 'react-router';import Loading from '@/components/Loading/BrandTextLoading';@@ -10,6 +10,7 @@ import OnboardingContainer from '@/features/Onboarding/Layout';import ResponseLanguageStep from '@/features/Onboarding/steps/ResponseLanguageStep';import TelemetryStep from '@/features/Onboarding/steps/TelemetryStep';import { useOnboardingAgentTemplates } from '@/hooks/useOnboardingAgentTemplates';+import { useSingleton } from '@/hooks/useSingleton';import {trackOnboardingStepCompleted,trackOnboardingStepViewed,@@ -30,7 +31,7 @@ const OnboardingPage = memo(() => {const [searchParams, setSearchParams] = useSearchParams();const step: 1 | 2 = searchParams.get('step') === '2' ? 2 : 1;const hasStepParam = searchParams.has('step');- const viewedStepKeysRef = useRef<Set<string>>(new Set());+ const viewedStepKeys = useSingleton(() => new Set<string>());useOnboardingAgentTemplates(isUserStateInit && (!commonStepsCompleted || hasStepParam));@@ -47,11 +48,11 @@ const OnboardingPage = memo(() => {if (!isUserStateInit || (commonStepsCompleted && !hasStepParam)) return;const payload = COMMON_STEP_TRACKING[step];- if (viewedStepKeysRef.current.has(payload.step)) return;+ if (viewedStepKeys.has(payload.step)) return;- viewedStepKeysRef.current.add(payload.step);+ viewedStepKeys.add(payload.step);trackOnboardingStepViewed(payload);- }, [commonStepsCompleted, hasStepParam, isUserStateInit, step]);+ }, [commonStepsCompleted, hasStepParam, isUserStateInit, step, viewedStepKeys]);const goNextFromTelemetry = useCallback(() => {trackOnboardingStepCompleted(COMMON_STEP_TRACKING[1]);diff --git a/src/features/SkillsList/SkillsList.tsx b/src/features/SkillsList/SkillsList.tsxindex 748b28aa68a..23444e5044f 100644--- a/src/features/SkillsList/SkillsList.tsx+++ b/src/features/SkillsList/SkillsList.tsx@@ -306,29 +306,33 @@ const TreeRow = memo<TreeRowProps>(({ depth, expanded, node, onOpenFile, onTogglTreeRow.displayName = 'SkillsListTreeRow';interface SkillRowProps {- actions: SkillRowAction[];expanded: boolean;+ getRowActions?: (item: SkillListItem) => SkillRowAction[];item: SkillListItem;- onDragStart?: (event: React.DragEvent) => void;- onOpenFile?: (relativePath: string) => void;- onOpenSkill?: () => void;- onToggle: () => void;+ onOpenFile?: (item: SkillListItem, relativePath: string) => void;+ onOpenSkill?: (item: SkillListItem) => void;+ onSkillDragStart?: (item: SkillListItem, event: React.DragEvent) => void;+ onToggle: (id: string) => void;reserveChevronSlot: boolean;}+// Rows receive the list-level handlers plus `item` (instead of pre-bound+// closures) so a parent re-render with unchanged data keeps every row's props+// referentially equal and the memo actually bails out.const SkillRow = memo<SkillRowProps>(({- actions,expanded,+ getRowActions,item,- onDragStart,onOpenFile,onOpenSkill,+ onSkillDragStart,onToggle,reserveChevronSlot,}) => {const files = item.files ?? EMPTY_ARRAY;const hasFiles = files.length > 0;+ const actions = useMemo(() => getRowActions?.(item) ?? EMPTY_ARRAY, [getRowActions, item]);const hasActions = actions.length > 0;const tree = useMemo(() => buildSkillTree(files), [files]);const [expandedFolders, setExpandedFolders] = useState<Set<string>>(() => new Set());@@ -342,6 +346,11 @@ const SkillRow = memo<SkillRowProps>(});}, []);+ const openFile = useCallback(+ (relativePath: string) => onOpenFile?.(item, relativePath),+ [item, onOpenFile],+ );+const contextMenuItems = useCallback((): (GenericItemType & { sfSymbol?: SFSymbol })[] =>actions.map((action) => ({@@ -361,7 +370,11 @@ const SkillRow = memo<SkillRowProps>(// a clean DOM-forwarding child. Nesting them (Tooltip around the trigger, or// vice versa) would drop `onContextMenu` / the ref on the way through.const nameNode = (- <Text ellipsis style={{ color: 'inherit', flex: 1, minWidth: 0 }} onClick={onOpenSkill}>+ <Text+ ellipsis+ style={{ color: 'inherit', flex: 1, minWidth: 0 }}+ onClick={onOpenSkill ? () => onOpenSkill(item) : undefined}+ >{item.name}</Text>);@@ -371,9 +384,9 @@ const SkillRow = memo<SkillRowProps>(horizontalalign={'center'}className={styles.item}- draggable={!!onDragStart}+ draggable={!!onSkillDragStart}gap={6}- onDragStart={onDragStart}+ onDragStart={onSkillDragStart ? (event) => onSkillDragStart(item, event) : undefined}>{hasFiles ? (<Flexbox@@ -382,7 +395,7 @@ const SkillRow = memo<SkillRowProps>(style={{ cursor: 'pointer', flexShrink: 0, height: 20, width: 20 }}onClick={(e) => {e.stopPropagation();- onToggle();+ onToggle(item.id);}}><Icon@@ -446,7 +459,7 @@ const SkillRow = memo<SkillRowProps>(expanded={expandedFolders}key={node.path}node={node}- onOpenFile={onOpenFile}+ onOpenFile={openFile}onToggleFolder={toggleFolder}/>))}@@ -479,15 +492,15 @@ const SkillsList = memo<SkillsListProps>(<Flexbox gap={2}>{items.map((item) => (<SkillRow- actions={getRowActions?.(item) ?? EMPTY_ARRAY}expanded={expanded.has(item.id)}+ getRowActions={getRowActions}item={item}key={item.id}reserveChevronSlot={reserveChevronSlot}- onDragStart={onSkillDragStart ? (event) => onSkillDragStart(item, event) : undefined}- onOpenFile={onOpenFile ? (relativePath) => onOpenFile(item, relativePath) : undefined}- onOpenSkill={onOpenSkill ? () => onOpenSkill(item) : undefined}- onToggle={() => toggle(item.id)}+ onOpenFile={onOpenFile}+ onOpenSkill={onOpenSkill}+ onSkillDragStart={onSkillDragStart}+ onToggle={toggle}/>))}</Flexbox>diff --git a/src/features/SkillsList/useProjectSkills.ts b/src/features/SkillsList/useProjectSkills.tsindex e9803ab6ddc..c02844d74af 100644--- a/src/features/SkillsList/useProjectSkills.ts+++ b/src/features/SkillsList/useProjectSkills.ts@@ -1,7 +1,7 @@import type { ListProjectSkillsResult, ProjectSkillItem } from '@lobechat/electron-client-ipc';import { EyeIcon, PencilIcon, Trash2Icon } from 'lucide-react';import path from 'pathe';-import { useMemo } from 'react';+import { useCallback, useMemo } from 'react';import { useTranslation } from 'react-i18next';import { useFetchProjectSkills } from '@/hooks/useFetchProjectSkills';@@ -86,64 +86,80 @@ export const useProjectSkills = (// (isLocalFileInCurrentScope) from dropping the tab and clears the desktop// preview protocol's approved-root / symlink-containment check// (resolveApprovedPreviewPath), so previews open instead of showing blank.- const openSkillFile = (skill: ProjectSkillItem, filePath: string) => {- openLocalFile({- allowExternalFilePreview: skill.scope === 'device',- // A bound device (remote, or this machine as a device) reads the preview- // over RPC, exactly like the Files tab; an undefined deviceId falls back to- // local Electron IPC. The old `isRemote` no-op predated remote preview.- deviceId,- filePath,- workingDirectory: skill.previewRoot || previewRoot,- });- };+ const openSkillFile = useCallback(+ (skill: ProjectSkillItem, filePath: string) => {+ openLocalFile({+ allowExternalFilePreview: skill.scope === 'device',+ // A bound device (remote, or this machine as a device) reads the preview+ // over RPC, exactly like the Files tab; an undefined deviceId falls back to+ // local Electron IPC. The old `isRemote` no-op predated remote preview.+ deviceId,+ filePath,+ workingDirectory: skill.previewRoot || previewRoot,+ });+ },+ [deviceId, openLocalFile, previewRoot],+ );- const onOpenFile = (item: SkillListItem, relativePath: string) => {- const skill = skillByDir.get(item.id);- if (!skill) return;- openSkillFile(skill, path.join(skill.skillDir, relativePath));- };+ const onOpenFile = useCallback(+ (item: SkillListItem, relativePath: string) => {+ const skill = skillByDir.get(item.id);+ if (!skill) return;+ openSkillFile(skill, path.join(skill.skillDir, relativePath));+ },+ [openSkillFile, skillByDir],+ );- const onOpenSkill = (item: SkillListItem) => {- const skill = skillByDir.get(item.id);- if (!skill) return;- openSkillFile(skill, skill.path);- };+ const onOpenSkill = useCallback(+ (item: SkillListItem) => {+ const skill = skillByDir.get(item.id);+ if (!skill) return;+ openSkillFile(skill, skill.path);+ },+ [openSkillFile, skillByDir],+ );- const getRowActions = (_item: SkillListItem): SkillRowAction[] => {- const comingSoon = t('workingPanel.skills.actions.comingSoon');- return [- {- // Preview works in every mode: local via IPC, bound device via RPC- // (matches the Files tab, which reads remote files over RPC).- icon: EyeIcon,- key: 'view',- label: t('workingPanel.skills.actions.view'),- onClick: onOpenSkill,- sfSymbol: 'eye',- },- {- // Renaming a filesystem skill needs an IPC/RPC that doesn't exist yet.- disabled: true,- icon: PencilIcon,- key: 'rename',- label: t('workingPanel.skills.actions.rename'),- onClick: () => {},- sfSymbol: 'pencil',- tooltip: comingSoon,- },- {- danger: true,- disabled: true,- icon: Trash2Icon,- key: 'delete',- label: t('workingPanel.skills.actions.delete'),- onClick: () => {},- sfSymbol: 'trash',- tooltip: comingSoon,- },- ];- };+ const getRowActions = useCallback(+ (_item: SkillListItem): SkillRowAction[] => {+ const comingSoon = t('workingPanel.skills.actions.comingSoon');+ return [+ {+ // Preview works in every mode: local via IPC, bound device via RPC+ // (matches the Files tab, which reads remote files over RPC).+ icon: EyeIcon,+ key: 'view',+ label: t('workingPanel.skills.actions.view'),+ onClick: onOpenSkill,+ sfSymbol: 'eye',+ },+ {+ // Renaming a filesystem skill needs an IPC/RPC that doesn't exist yet.+ disabled: true,+ icon: PencilIcon,+ key: 'rename',+ label: t('workingPanel.skills.actions.rename'),+ onClick: () => {},+ sfSymbol: 'pencil',+ tooltip: comingSoon,+ },+ {+ danger: true,+ disabled: true,+ icon: Trash2Icon,+ key: 'delete',+ label: t('workingPanel.skills.actions.delete'),+ onClick: () => {},+ sfSymbol: 'trash',+ tooltip: comingSoon,+ },+ ];+ },+ [onOpenSkill, t],+ );++ const retry = useCallback(() => {+ void mutate();+ }, [mutate]);return {deviceItems,@@ -151,9 +167,7 @@ export const useProjectSkills = (getRowActions,isLoading,items,- mutate: () => {- void mutate();- },+ mutate: retry,onOpenFile,onOpenSkill,projectItems,diff --git a/src/features/Verify/Acceptance/index.tsx b/src/features/Verify/Acceptance/index.tsxindex 18fa1364696..729d402ac7c 100644--- a/src/features/Verify/Acceptance/index.tsx+++ b/src/features/Verify/Acceptance/index.tsx@@ -42,7 +42,7 @@ import {X,XCircle,} from 'lucide-react';-import { memo, useCallback, useEffect, useMemo, useRef, useState } from 'react';+import { memo, useCallback, useEffect, useMemo, useState } from 'react';import { useTranslation } from 'react-i18next';import { useNavigate, useParams, useSearchParams } from 'react-router';@@ -52,6 +52,7 @@ import { openCheckEditModal } from '@/features/Conversation/ChatInput/VerifyTrayimport { openGoalModal } from '@/features/Conversation/ChatInput/VerifyTray/GoalModal';import NavItem from '@/features/NavPanel/components/NavItem';import { useLocalStorageState } from '@/hooks/useLocalStorageState';+import { useSingleton } from '@/hooks/useSingleton';// The workspace-scoped mutate — a bare `import { mutate } from 'swr'` misses// every `useClientDataSWR` subscriber (augmented keys + custom cache provider).import { mutate as globalMutate } from '@/libs/swr';@@ -386,7 +387,7 @@ const AcceptancePage = memo<AcceptancePageProps>(// Which aggregates have had their one-time defaults (expand/collapse + filter)// applied. A Set, not a single id, so returning to an already-seeded aggregate// does NOT re-apply defaults and clobber the toggles the user made.- const seededIdsRef = useRef<Set<string>>(new Set());+ const seededIds = useSingleton(() => new Set<string>());const [highlightRound, setHighlightRound] = useState<number | null>(null);const [ledgerExpand, setLedgerExpand] = useState(!isEmbedded);const [topicPanelOpen, setTopicPanelOpen] = useState(false);@@ -482,15 +483,15 @@ const AcceptancePage = memo<AcceptancePageProps>(// Exceptions and visually-evidenced checks start expanded (P-08) — a check// still awaiting the user's review shows its evidence (screenshots included)- // up front, not folded away. Seeded once per aggregate (see `seededIdsRef`),+ // up front, not folded away. Seeded once per aggregate (see `seededIds`),// and only after its checks have arrived, so the user's own toggling is never// overwritten and an aggregate whose checks stream in a beat late still seeds.// A check the user already accepted is settled business and stays folded// regardless of its evidence; groups accepted in full start collapsed too.useEffect(() => {if (!data || data.checks.length === 0) return;- if (seededIdsRef.current.has(acceptanceId ?? '')) return;- seededIdsRef.current.add(acceptanceId ?? '');+ if (seededIds.has(acceptanceId ?? '')) return;+ seededIds.add(acceptanceId ?? '');setExpanded(new Set(data.checks@@ -533,6 +534,7 @@ const AcceptancePage = memo<AcceptancePageProps>(t,isEmbedded,urlFilterRaw,+ seededIds,setSearchParams,setExpanded,setCollapsedGroups,diff --git a/src/hooks/useDeferredMount.ts b/src/hooks/useDeferredMount.tsnew file mode 100644index 00000000000..4f74e74a7e2--- /dev/null+++ b/src/hooks/useDeferredMount.ts@@ -0,0 +1,8 @@+import { useDeferredValue } from 'react';++// Returns `false` for the mount commit, then flips to `true` in a deferred+// (interruptible, background-priority) follow-up render — React 19's+// `useDeferredValue` initialValue trick. Gate a heavy subtree behind it with a+// skeleton so its mount happens right after the navigation frame paints+// instead of on the route transition's critical path.+export const useDeferredMount = (): boolean => useDeferredValue(true, false);diff --git a/src/hooks/usePlatform.ts b/src/hooks/usePlatform.tsindex 62e04f1fe64..2906067b113 100644--- a/src/hooks/usePlatform.ts+++ b/src/hooks/usePlatform.ts@@ -1,5 +1,6 @@-import { useMemo, useRef } from 'react';+import { useMemo } from 'react';+import { useSingleton } from '@/hooks/useSingleton';import {getBrowser,getPlatform,@@ -9,23 +10,21 @@ import {} from '@/utils/platform';export const usePlatform = () => {- const platform = useRef(getPlatform());- const browser = useRef(getBrowser());+ const platform = useSingleton(getPlatform);+ const browser = useSingleton(getBrowser);const platformInfo = {- isAndroid: platform.current?.toLowerCase() === 'android',- isApple: platform.current && ['mac os', 'ios'].includes(platform.current?.toLowerCase()),+ isAndroid: platform?.toLowerCase() === 'android',+ isApple: platform && ['mac os', 'ios'].includes(platform?.toLowerCase()),isArc: isArc(),- isChrome: browser.current?.toLowerCase() === 'chrome',- isChromium:- browser.current &&- ['chrome', 'edge', 'opera', 'brave'].includes(browser.current?.toLowerCase()),- isEdge: browser.current?.toLowerCase() === 'edge',- isFirefox: browser.current?.toLowerCase() === 'firefox',- isIOS: platform.current?.toLowerCase() === 'ios',- isMacOS: platform.current?.toLowerCase() === 'mac os',+ isChrome: browser?.toLowerCase() === 'chrome',+ isChromium: browser && ['chrome', 'edge', 'opera', 'brave'].includes(browser?.toLowerCase()),+ isEdge: browser?.toLowerCase() === 'edge',+ isFirefox: browser?.toLowerCase() === 'firefox',+ isIOS: platform?.toLowerCase() === 'ios',+ isMacOS: platform?.toLowerCase() === 'mac os',isPWA: isInStandaloneMode(),- isSafari: browser.current?.toLowerCase() === 'safari',+ isSafari: browser?.toLowerCase() === 'safari',isSonomaOrLaterSafari: isSonomaOrLaterSafari(),};diff --git a/src/hooks/useSingleton.test.ts b/src/hooks/useSingleton.test.tsnew file mode 100644index 00000000000..ac945c70104--- /dev/null+++ b/src/hooks/useSingleton.test.ts@@ -0,0 +1,42 @@+import { renderHook } from '@testing-library/react';+import { describe, expect, it, vi } from 'vitest';++import { useSingleton } from './useSingleton';++describe('useSingleton', () => {+ it('should call factory only once across re-renders', () => {+ const factory = vi.fn(() => ({ id: Math.random() }));++ const { result, rerender } = renderHook(() => useSingleton(factory));++ expect(factory).toHaveBeenCalledTimes(1);+ const first = result.current;++ rerender();+ rerender();++ expect(factory).toHaveBeenCalledTimes(1);+ expect(result.current).toBe(first);+ });++ it('should support undefined factory results', () => {+ const factory = vi.fn(() => undefined as undefined);++ const { result, rerender } = renderHook(() => useSingleton(factory));++ expect(result.current).toBeUndefined();+ rerender();+ expect(factory).toHaveBeenCalledTimes(1);+ });++ it('should create independent instances per hook call', () => {+ const { result } = renderHook(() => ({+ a: useSingleton(() => new Map<string, number>()),+ b: useSingleton(() => new Map<string, number>()),+ }));++ expect(result.current.a).not.toBe(result.current.b);+ result.current.a.set('x', 1);+ expect(result.current.b.has('x')).toBe(false);+ });+});diff --git a/src/hooks/useSingleton.ts b/src/hooks/useSingleton.tsnew file mode 100644index 00000000000..df62df924e5--- /dev/null+++ b/src/hooks/useSingleton.ts@@ -0,0 +1,9 @@+import { useRef } from 'react';++export const useSingleton = <T>(factory: () => T): T => {+ const ref = useRef<{ value: T } | null>(null);+ if (ref.current === null) {+ ref.current = { value: factory() };+ }+ return ref.current.value;+};diff --git a/src/hooks/useTokenCount.ts b/src/hooks/useTokenCount.tsindex d8fac7342b1..020130c5d25 100644--- a/src/hooks/useTokenCount.ts+++ b/src/hooks/useTokenCount.ts@@ -6,21 +6,22 @@ import { encodeAsync } from '@/utils/tokenizer';export const useTokenCount = (input: string = '') => {const [value, setNum] = useState(0);+ // The transition must wrap the setState itself — wrapping the debounce call+ // only demotes the timer scheduling while the eventual update still lands at+ // default priority.const debouncedEncode = useCallback(debounce((text: string) => {encodeAsync(text)- .then(setNum)+ .then((count) => startTransition(() => setNum(count))).catch(() => {- setNum(text.length);+ startTransition(() => setNum(text.length));});}, 300),[],);useEffect(() => {- startTransition(() => {- debouncedEncode(input || '');- });+ debouncedEncode(input || '');// Cleanup functionreturn () => {diff --git a/src/libs/getUILocaleAndResources.desktop.test.ts b/src/libs/getUILocaleAndResources.desktop.test.tsnew file mode 100644index 00000000000..440e804472e--- /dev/null+++ b/src/libs/getUILocaleAndResources.desktop.test.ts@@ -0,0 +1,39 @@+import { describe, expect, it, vi } from 'vitest';++const moduleEvaluation = vi.hoisted(() => ({+ businessResources: vi.fn(),+ builtinResources: vi.fn(),+}));++vi.mock('/locales/zh-CN/ui.json', () => {+ moduleEvaluation.businessResources();++ return { default: { business: 'localized' } };+});++vi.mock('@lobehub/ui/es/i18n/resources/index', () => {+ moduleEvaluation.builtinResources();++ return {+ en: { app: { builtin: 'English' } },+ zhCn: { app: { builtin: '中文' } },+ };+});++describe('getUILocaleAndResources.desktop', () => {+ it('evaluates UI locale resources only when the locale is requested', async () => {+ const { getUILocaleAndResources } = await import('./getUILocaleAndResources.desktop');++ expect(moduleEvaluation.businessResources).not.toHaveBeenCalled();+ expect(moduleEvaluation.builtinResources).not.toHaveBeenCalled();++ const result = await getUILocaleAndResources('zh-CN');++ expect(result).toEqual({+ locale: 'zh-CN',+ resources: { app: { builtin: '中文', business: 'localized' } },+ });+ expect(moduleEvaluation.businessResources).toHaveBeenCalledOnce();+ expect(moduleEvaluation.builtinResources).toHaveBeenCalledOnce();+ });+});diff --git a/src/libs/getUILocaleAndResources.desktop.ts b/src/libs/getUILocaleAndResources.desktop.tsindex 7a39c692acc..9207ee140fd 100644--- a/src/libs/getUILocaleAndResources.desktop.ts+++ b/src/libs/getUILocaleAndResources.desktop.ts@@ -1,5 +1,3 @@-import { en, zhCn } from '@lobehub/ui/es/i18n/resources/index';-import type { UILocaleResourceInput, UILocaleResources } from './getUILocaleAndResources.utils';import {mergeUILocaleResources,@@ -8,24 +6,43 @@ import {} from './getUILocaleAndResources.utils';type UILocaleModule = { default: UILocaleResourceInput };-type UILocaleModuleMap = Record<string, UILocaleModule>;+type UILocaleLoaderMap = Record<string, () => Promise<UILocaleModule>>;-// eager: true — UI locale fully inlined at build time-const uiLocaleModules = import.meta.glob('/locales/*/ui.json', {- eager: true,-}) as UILocaleModuleMap;+const uiLocaleLoaders = import.meta.glob('/locales/*/ui.json') as UILocaleLoaderMap;-const loadBusinessResources = (locale: string): UILocaleResources | null => {+const loadBusinessResources = async (locale: string): Promise<UILocaleResources | null> => {const key = `/locales/${locale}/ui.json`;- const mod = uiLocaleModules[key];- const resources = mod?.default;+ const loader = uiLocaleLoaders[key];+ if (!loader) return null;++ try {+ const mod = await loader();+ const resources = mod.default;++ return resources ? normalizeUILocaleResources(resources) : null;+ } catch {+ return null;+ }+};++const loadLobeUIBuiltinResources = async (locale: string): Promise<UILocaleResources | null> => {+ try {+ const { en, zhCn } = await import('@lobehub/ui/es/i18n/resources/index');- return resources ? normalizeUILocaleResources(resources) : null;+ if (locale.startsWith('zh')) return zhCn as UILocaleResources;+ return en as UILocaleResources;+ } catch {+ return null;+ }};-const loadLobeUIBuiltinResources = (locale: string): UILocaleResources | null => {- if (locale.startsWith('zh')) return zhCn as UILocaleResources;- return en as UILocaleResources;+const loadMergedResources = async (locale: string): Promise<UILocaleResources | null> => {+ const [builtinResources, businessResources] = await Promise.all([+ loadLobeUIBuiltinResources(locale),+ loadBusinessResources(locale),+ ]);++ return mergeUILocaleResources(builtinResources, businessResources);};export const getUILocaleAndResources = async (@@ -34,11 +51,7 @@ export const getUILocaleAndResources = async (const { normalizedLocale, uiLocale } = resolveUILocale(locale);const resources =- mergeUILocaleResources(- loadLobeUIBuiltinResources(normalizedLocale),- loadBusinessResources(normalizedLocale),- ) ??- mergeUILocaleResources(loadLobeUIBuiltinResources('en-US'), loadBusinessResources('en-US'));+ (await loadMergedResources(normalizedLocale)) ?? (await loadMergedResources('en-US'));if (!resources)throw new Error(diff --git a/src/routes/(main)/agent/features/Conversation/HeterogeneousChatInput/QuotaMenu/ClaudeCodeQuotaMenu.tsx b/src/routes/(main)/agent/features/Conversation/HeterogeneousChatInput/QuotaMenu/ClaudeCodeQuotaMenu.tsxindex 8000fd27ba2..3078e8feb6a 100644--- a/src/routes/(main)/agent/features/Conversation/HeterogeneousChatInput/QuotaMenu/ClaudeCodeQuotaMenu.tsx+++ b/src/routes/(main)/agent/features/Conversation/HeterogeneousChatInput/QuotaMenu/ClaudeCodeQuotaMenu.tsx@@ -1,10 +1,11 @@'use client';import type { ClaudeCodeQuotaSnapshot } from '@lobechat/electron-client-ipc';-import { memo, useCallback, useRef } from 'react';+import { memo, useCallback } from 'react';import { useTranslation } from 'react-i18next';import { useAgentId } from '@/features/ChatInput/hooks/useAgentId';+import { useSingleton } from '@/hooks/useSingleton';import { agentQuotaService } from '@/services/agentQuota';import { fetchClaudeCodeQuotaSnapshot } from '@/services/heteroAgentQuota';@@ -66,7 +67,7 @@ const ClaudeCodeQuotaMenu = memo<ClaudeCodeQuotaMenuProps>(({ deviceId, env }) =// menu has observed that device return the same external account identity.// This avoids painting another machine's pinned/first account on a device// switch while still preserving last-known-good data after later failures.- const trustedDeviceAccountsRef = useRef(new Map<string, string>());+ const trustedDeviceAccounts = useSingleton(() => new Map<string, string>());/*** DB-first: render the persisted windows from our own database, and go to the@@ -90,9 +91,7 @@ const ClaudeCodeQuotaMenu = memo<ClaudeCodeQuotaMenuProps>(({ deviceId, env }) =let accounts = initialAccounts;let claude = accounts.filter((a) => a.provider === 'claude-code');const pinnedId = bindings.find((b) => b.role === 'pinned')?.accountId;- const trustedExternalAccountId = deviceId- ? trustedDeviceAccountsRef.current.get(deviceId)- : undefined;+ const trustedExternalAccountId = deviceId ? trustedDeviceAccounts.get(deviceId) : undefined;let account = deviceId? claude.find((a) => a.externalAccountId === trustedExternalAccountId): (claude.find((a) => a.id === pinnedId) ?? claude[0]);@@ -117,7 +116,7 @@ const ClaudeCodeQuotaMenu = memo<ClaudeCodeQuotaMenuProps>(({ deviceId, env }) =const externalAccountId = live?.identity?.externalAccountId;if (live?.status === 'ok' && externalAccountId && live.readings?.length) {- if (deviceId) trustedDeviceAccountsRef.current.set(deviceId, externalAccountId);+ if (deviceId) trustedDeviceAccounts.set(deviceId, externalAccountId);// A revalidation inside the main-process cache's fresh window gets the// readings we already persisted echoed back (same capturedAt).@@ -162,7 +161,7 @@ const ClaudeCodeQuotaMenu = memo<ClaudeCodeQuotaMenuProps>(({ deviceId, env }) =if (merged && hasRenderableWindow(merged)) return merged;return live ?? merged ?? unavailableSnapshot();},- [deviceId, env, agentId],+ [agentId, deviceId, env, trustedDeviceAccounts],);const getWindows = useCallback(diff --git a/src/utils/i18n/loadI18nNamespaceModule.desktop.test.ts b/src/utils/i18n/loadI18nNamespaceModule.desktop.test.tsnew file mode 100644index 00000000000..f565cc629ce--- /dev/null+++ b/src/utils/i18n/loadI18nNamespaceModule.desktop.test.ts@@ -0,0 +1,38 @@+import { describe, expect, it, vi } from 'vitest';++const moduleEvaluation = vi.hoisted(() => ({+ defaultNamespace: vi.fn(),+ localizedNamespace: vi.fn(),+}));++vi.mock('/packages/locales/src/default/common.ts', () => {+ moduleEvaluation.defaultNamespace();++ return { default: { source: 'default' } };+});++vi.mock('/locales/zh-CN/common.json', () => {+ moduleEvaluation.localizedNamespace();++ return { default: { source: 'localized' } };+});++describe('loadI18nNamespaceModule.desktop', () => {+ it('evaluates only the requested locale namespace', async () => {+ const { loadI18nNamespaceModule } = await import('./loadI18nNamespaceModule.desktop');++ expect(moduleEvaluation.defaultNamespace).not.toHaveBeenCalled();+ expect(moduleEvaluation.localizedNamespace).not.toHaveBeenCalled();++ const result = await loadI18nNamespaceModule({+ defaultLang: 'en-US',+ lng: 'zh-CN',+ normalizeLocale: (locale) => locale ?? 'en-US',+ ns: 'common',+ });++ expect(result.default).toEqual({ source: 'localized' });+ expect(moduleEvaluation.localizedNamespace).toHaveBeenCalledOnce();+ expect(moduleEvaluation.defaultNamespace).not.toHaveBeenCalled();+ });+});diff --git a/src/utils/i18n/loadI18nNamespaceModule.desktop.ts b/src/utils/i18n/loadI18nNamespaceModule.desktop.tsindex 17f670b23c7..6bf77c3411c 100644--- a/src/utils/i18n/loadI18nNamespaceModule.desktop.ts+++ b/src/utils/i18n/loadI18nNamespaceModule.desktop.ts@@ -4,20 +4,14 @@ import type {} from './loadI18nNamespaceModule';type NamespaceModule = { default: Record<string, unknown> };-type NamespaceModuleMap = Record<string, NamespaceModule>;--// eager: true — all locale JSON inlined at build time, synchronous access at runtime-const defaultModules = import.meta.glob(- [- '/packages/locales/src/default/*.ts',- '!/packages/locales/src/default/*.vite.ts',- '!/packages/locales/src/default/index.ts',- ],- { eager: true },-) as NamespaceModuleMap;-const localeModules = import.meta.glob('/locales/*/*.json', {- eager: true,-}) as NamespaceModuleMap;+type NamespaceLoaderMap = Record<string, () => Promise<NamespaceModule>>;++const defaultLoaders = import.meta.glob([+ '/packages/locales/src/default/*.ts',+ '!/packages/locales/src/default/*.vite.ts',+ '!/packages/locales/src/default/index.ts',+]) as NamespaceLoaderMap;+const localeLoaders = import.meta.glob('/locales/*/*.json') as NamespaceLoaderMap;const getDefaultKey = (ns: string) => `/packages/locales/src/default/${ns}.ts`;const getLocaleKey = (lng: string, ns: string) => `/locales/${lng}/${ns}.json`;@@ -28,18 +22,18 @@ export const loadI18nNamespaceModule = async (const { defaultLang, normalizeLocale, lng, ns } = params;if (lng === defaultLang) {- const mod = defaultModules[getDefaultKey(ns)];- if (!mod) throw new Error(`Missing default namespace: ${ns}`);- return mod;+ const load = defaultLoaders[getDefaultKey(ns)];+ if (!load) throw new Error(`Missing default namespace: ${ns}`);+ return load();}const normalizedLng = normalizeLocale(lng);- const localeMod = localeModules[getLocaleKey(normalizedLng, ns)];- if (localeMod) return localeMod;+ const loadLocale = localeLoaders[getLocaleKey(normalizedLng, ns)];+ if (loadLocale) return loadLocale();- const defaultMod = defaultModules[getDefaultKey(ns)];- if (!defaultMod) throw new Error(`Missing default namespace: ${ns}`);- return defaultMod;+ const loadDefault = defaultLoaders[getDefaultKey(ns)];+ if (!loadDefault) throw new Error(`Missing default namespace: ${ns}`);+ return loadDefault();};export type {@@ -55,8 +49,8 @@ export const loadI18nNamespaceModuleWithFallback = async (return await loadI18nNamespaceModule(rest);} catch (error) {onFallback?.({ error, lng: rest.lng, ns: rest.ns });- const defaultMod = defaultModules[getDefaultKey(rest.ns)];- if (!defaultMod) throw error;- return defaultMod;+ const loadDefault = defaultLoaders[getDefaultKey(rest.ns)];+ if (!loadDefault) throw error;+ return loadDefault();}};diff --git a/src/utils/locale.desktop.test.ts b/src/utils/locale.desktop.test.tsnew file mode 100644index 00000000000..50f4f23aa4a--- /dev/null+++ b/src/utils/locale.desktop.test.ts@@ -0,0 +1,31 @@+import { describe, expect, it, vi } from 'vitest';++const moduleEvaluation = vi.hoisted(() => ({+ english: vi.fn(),+ simplifiedChinese: vi.fn(),+}));++vi.mock('antd/es/locale/en_US.js', () => {+ moduleEvaluation.english();++ return { default: { locale: 'en' } };+});++vi.mock('antd/es/locale/zh_CN.js', () => {+ moduleEvaluation.simplifiedChinese();++ return { default: { locale: 'zh-cn' } };+});++describe('getAntdLocale.desktop', () => {+ it('evaluates only the requested antd locale', async () => {+ const { getAntdLocale } = await import('./locale.desktop');++ expect(moduleEvaluation.english).not.toHaveBeenCalled();+ expect(moduleEvaluation.simplifiedChinese).not.toHaveBeenCalled();++ await expect(getAntdLocale('zh-CN')).resolves.toEqual({ locale: 'zh-cn' });+ expect(moduleEvaluation.simplifiedChinese).toHaveBeenCalledOnce();+ expect(moduleEvaluation.english).not.toHaveBeenCalled();+ });+});diff --git a/src/utils/locale.desktop.ts b/src/utils/locale.desktop.tsindex f76011df475..784e879ff2f 100644--- a/src/utils/locale.desktop.ts+++ b/src/utils/locale.desktop.ts@@ -1,9 +1,7 @@import { normalizeLocale } from '@/locales/resources';-// eager: true — antd locale fully inlined at build time-const antdLocaleModules = import.meta.glob(+const antdLocaleLoaders = import.meta.glob('/node_modules/antd/es/locale/{ar_EG,bg_BG,de_DE,en_US,es_ES,fa_IR,fr_FR,it_IT,ja_JP,ko_KR,nl_NL,pl_PL,pt_BR,ru_RU,tr_TR,vi_VN,zh_CN,zh_TW}.js',- { eager: true },);export const getAntdLocale = async (lang?: string) => {@@ -14,11 +12,12 @@ export const getAntdLocale = async (lang?: string) => {if (normalLang === 'ar') normalLang = 'ar-EG';const localePath = `/node_modules/antd/es/locale/${normalLang.replace('-', '_')}.js`;- const mod = antdLocaleModules[localePath];+ const loadLocale = antdLocaleLoaders[localePath];- if (!mod) {+ if (!loadLocale) {throw new Error(`Unsupported antd locale: ${normalLang}`);}- return (mod as any).default;+ const mod = (await loadLocale()) as Record<string, unknown>;+ return mod.default;};