🤯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.
TypeScript agentagent-collaborationagent-harnessloop-engineeringmcppersonal-assistantproactive-agentskillssuper-agenttask-management
♻️ refactor(agent): move the remaining agent store reads onto @lobechat/replica (#21303)
Arvin Xufc46d54f91a5
diff --git a/locales/en-US/chat.json b/locales/en-US/chat.jsonindex 710e109970c..b17a6542e00 100644--- a/locales/en-US/chat.json+++ b/locales/en-US/chat.json@@ -1565,6 +1565,8 @@"input.addAiPrefillUnsupported": "The current model doesn’t support ending the conversation with an assistant message. Follow it with a user message before sending.","input.addUser": "Add a user message","input.agentModeUnsupportedModel": "The current model doesn’t support agentic tool calling. Switch to a model with agent capability for the best experience.",+ "input.agentSlugMoved": "This link now opens a different agent. Switching to it — try again once it opens. Your draft is kept.",+ "input.agentSlugUnconfirmed": "Couldn’t confirm which agent this link opens. Check your connection, then try again.","input.costEstimate.creditsPerMillionTokens": "{{credits}} credits/M tokens","input.costEstimate.hint": "Estimated cost: ~{{credits}} credits","input.costEstimate.inputLabel": "Input",diff --git a/locales/zh-CN/chat.json b/locales/zh-CN/chat.jsonindex 92a40fd0165..82fa040e617 100644--- a/locales/zh-CN/chat.json+++ b/locales/zh-CN/chat.json@@ -1565,6 +1565,8 @@"input.addAiPrefillUnsupported": "当前模型不支持以助理消息结尾发送,请在其后继续添加一条用户消息再发送。","input.addUser": "添加一条用户消息","input.agentModeUnsupportedModel": "当前模型不支持 Agentic 工具调用,建议切换为具备 Agent 能力的模型以获得最佳体验。",+ "input.agentSlugMoved": "该链接现在指向另一个助理,正在切换,打开后请重试。输入框中的草稿会保留。",+ "input.agentSlugUnconfirmed": "暂时无法确认该链接对应的助理,请检查网络后重试。","input.costEstimate.creditsPerMillionTokens": "{{credits}} 积分/百万标记","input.costEstimate.hint": "预计费用:约{{credits}}积分","input.costEstimate.inputLabel": "输入",diff --git a/packages/locales/src/default/chat.ts b/packages/locales/src/default/chat.tsindex 493b4af8373..4fa66a0c32a 100644--- a/packages/locales/src/default/chat.ts+++ b/packages/locales/src/default/chat.ts@@ -920,6 +920,10 @@ export default {'input.addUser': 'Add a user message','input.agentModeUnsupportedModel':'The current model doesn’t support agentic tool calling. Switch to a model with agent capability for the best experience.',+ 'input.agentSlugMoved':+ 'This link now opens a different agent. Switching to it — try again once it opens. Your draft is kept.',+ 'input.agentSlugUnconfirmed':+ 'Couldn’t confirm which agent this link opens. Check your connection, then try again.','input.costEstimate.creditsPerMillionTokens': '{{credits}} credits/M tokens','input.costEstimate.hint': 'Estimated cost: ~{{credits}} credits','input.costEstimate.inputLabel': 'Input',diff --git a/src/features/AgentIdentityModal/useAgentIdentityForm.test.ts b/src/features/AgentIdentityModal/useAgentIdentityForm.test.tsindex 2fb19d8e552..7bd62ac8169 100644--- a/src/features/AgentIdentityModal/useAgentIdentityForm.test.ts+++ b/src/features/AgentIdentityModal/useAgentIdentityForm.test.ts@@ -5,6 +5,7 @@ import { useAgentIdentityForm } from './useAgentIdentityForm';const mocks = vi.hoisted(() => ({agentMap: {} as Record<string, { name?: string; slug?: string; title?: string }>,+ confirmAgentSlug: vi.fn(),refreshAgentConfig: vi.fn(),updateAgentMeta: vi.fn(),updateAgentSlug: vi.fn(),@@ -25,6 +26,7 @@ vi.mock('@/store/agent', () => ({useAgentStore: (selector: (state: unknown) => unknown) =>selector({agentMap: mocks.agentMap,+ internal_confirmAgentSlug: mocks.confirmAgentSlug,internal_refreshAgentConfig: mocks.refreshAgentConfig,}),}));@@ -108,6 +110,12 @@ describe('useAgentIdentityForm', () => {});expect(mocks.updateAgentSlug).toHaveBeenCalledExactlyOnceWith('agent-a', 'new-slug');+ // The local `slug → id` copy follows the rename, so neither slug route paints a stale agent.+ expect(mocks.confirmAgentSlug).toHaveBeenCalledExactlyOnceWith('agent-a', 'new-slug', {+ // The old slug's row may only be persisted, and the rename keeps its scope.+ previousSlug: 'old-slug',+ scope: expect.any(String),+ });expect(mocks.refreshAgentConfig).toHaveBeenCalledWith('agent-a');expect(onSaved).toHaveBeenCalled();});@@ -124,6 +132,7 @@ describe('useAgentIdentityForm', () => {expect(result.current.error).toBe('settingAgent.slug.error.taken');// A rejected slug must not leave name/role persisted behind a closed form.expect(mocks.updateAgentMeta).not.toHaveBeenCalled();+ expect(mocks.confirmAgentSlug).not.toHaveBeenCalled();expect(onSaved).not.toHaveBeenCalled();});diff --git a/src/features/AgentIdentityModal/useAgentIdentityForm.ts b/src/features/AgentIdentityModal/useAgentIdentityForm.tsindex ca2eb21012d..68795ad778c 100644--- a/src/features/AgentIdentityModal/useAgentIdentityForm.ts+++ b/src/features/AgentIdentityModal/useAgentIdentityForm.ts@@ -2,6 +2,7 @@ import { BUILTIN_AGENT_SLUGS } from '@lobechat/builtin-agents';import { useState } from 'react';import { useTranslation } from 'react-i18next';+import { cacheScope } from '@/libs/replica';import { agentService } from '@/services/agent';import { useAgentStore } from '@/store/agent';import { agentSelectors } from '@/store/agent/selectors';@@ -28,6 +29,7 @@ export const useAgentIdentityForm = ({ agentId, onSaved }: UseAgentIdentityFormOconst meta = useAgentStore(agentSelectors.getAgentMetaById(agentId));const slug = useAgentStore(agentSelectors.getAgentSlugById(agentId));const refreshAgentConfig = useAgentStore((s) => s.internal_refreshAgentConfig);+ const confirmAgentSlug = useAgentStore((s) => s.internal_confirmAgentSlug);const updateAgentMeta = useHomeStore((s) => s.updateAgentMeta);const [name, setName] = useState(meta.name || '');@@ -47,11 +49,16 @@ export const useAgentIdentityForm = ({ agentId, onSaved }: UseAgentIdentityFormOtry {const trimmedSlug = slugLocked ? slug : nextSlug.trim().toLowerCase();if (trimmedSlug && trimmedSlug !== (slug || '')) {+ // The rename belongs to the identity it was sent from, even if the user+ // switches workspace before it answers.+ const scope = cacheScope.get();const result = await agentService.updateAgentSlug(agentId, trimmedSlug);if (!result.success) {setError(t(`settingAgent.slug.error.${result.reason ?? 'invalid'}`));return;}+ // The old slug no longer names this agent; the new one does.+ confirmAgentSlug(agentId, trimmedSlug, { previousSlug: slug || undefined, scope });await refreshAgentConfig(agentId);}diff --git a/src/features/AgentProfileCard/AgentProfilePopup.tsx b/src/features/AgentProfileCard/AgentProfilePopup.tsxindex dbaecd130ea..3ea05c3245c 100644--- a/src/features/AgentProfileCard/AgentProfilePopup.tsx+++ b/src/features/AgentProfileCard/AgentProfilePopup.tsx@@ -1,6 +1,6 @@'use client';-import { agentDisplayName, type AgentItem } from '@lobechat/types';+import { agentDisplayName } from '@lobechat/types';import {ActionIcon,createStaticStyles,@@ -14,7 +14,6 @@ import { SkillsIcon } from '@lobehub/ui/icons';import { BookOpen, FileText, Settings, SquareTerminal } from 'lucide-react';import { memo, type PropsWithChildren, useState } from 'react';import { useTranslation } from 'react-i18next';-import useSWR from 'swr';import { ModelIcon } from '@/components/LobeIcons';import { ArticleSkeleton } from '@/components/Skeleton';@@ -22,14 +21,16 @@ import ModelSelect from '@/features/ModelSelect';import { useResourceAccess } from '@/features/ResourcePermission/useResourceAccess';import { useWorkspaceAwareNavigate } from '@/features/Workspace/useWorkspaceAwareNavigate';import { usePermission } from '@/hooks/usePermission';-import { agentProfileKeys } from '@/libs/swr/keys';-import { agentService } from '@/services/agent';import { useAgentGroupStore } from '@/store/agentGroup';import { useHomeStore } from '@/store/home';import { homeAgentListSelectors } from '@/store/home/selectors';import AgentProfileCard from '.';import { resolveAgentRuntimeLabel } from './runtime';+import {+ type AgentProfilePreview as AgentPreview,+ useAgentProfileDetail,+} from './useAgentProfileDetail';const styles = createStaticStyles(({ css, cssVar }) => ({footer: css`@@ -59,19 +60,6 @@ const styles = createStaticStyles(({ css, cssVar }) => ({`,}));-type AgentPreview = Pick<- AgentItem,- 'avatar' | 'backgroundColor' | 'description' | 'model' | 'name' | 'provider' | 'title'->;--interface FetchedAgent extends Partial<AgentPreview> {- agencyConfig?: { heterogeneousProvider?: { type?: string | null } | null } | null;- files?: unknown[];- id?: string;- knowledgeBases?: unknown[];- plugins?: string[];-}-interface AgentProfilePopupProps extends PropsWithChildren {/** Prefilled data for instant render; fetched data overrides once loaded. */agent?: Partial<AgentPreview>;@@ -101,11 +89,7 @@ const AgentProfilePopup = memo<AgentProfilePopupProps>(const updateMemberAgentConfig = useAgentGroupStore((s) => s.updateMemberAgentConfig);const listEntry = useHomeStore(homeAgentListSelectors.getAgentById(agentId));- const { data: fetched, isLoading } = useSWR(- open && canConfigure ? agentProfileKeys.detail(agentId) : null,- () => agentService.getAgentConfigById(agentId) as Promise<FetchedAgent | null>,- { revalidateOnFocus: false },- );+ const { detail: fetched, isLoading } = useAgentProfileDetail(agentId, open && !!canConfigure);const runtimeLabel = resolveAgentRuntimeLabel({fetchedType: fetched?.agencyConfig?.heterogeneousProvider?.type,diff --git a/src/features/AgentProfileCard/useAgentProfileDetail.test.ts b/src/features/AgentProfileCard/useAgentProfileDetail.test.tsnew file mode 100644index 00000000000..1733c67cf29--- /dev/null+++ b/src/features/AgentProfileCard/useAgentProfileDetail.test.ts@@ -0,0 +1,106 @@+/**+ * @vitest-environment happy-dom+ */+import { randomUUID } from 'node:crypto';++import { act, cleanup, renderHook, waitFor } from '@testing-library/react';+import type { PropsWithChildren } from 'react';+import { createElement, useEffect } from 'react';+import { SWRConfig, useSWRConfig } from 'swr';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';++import { IndexedDBQueryProjectionStorage } from '@/libs/queryProjectionStorage';+import { cacheScope } from '@/libs/replica';+import { setScopedMutate } from '@/libs/swr/mutate';+import { agentService } from '@/services/agent';+import { useAgentStore } from '@/store/agent';+import { initialAgentSliceState } from '@/store/agent/slices/agent/initialState';+import { useUserStore } from '@/store/user';++import { useAgentProfileDetail } from './useAgentProfileDetail';++const MutateBridge = () => {+ const { mutate } = useSWRConfig();+ useEffect(() => setScopedMutate(mutate), [mutate]);+ return null;+};++const wrapper = ({ children }: PropsWithChildren) =>+ createElement(+ SWRConfig,+ { value: { dedupingInterval: 0, provider: () => new Map() } },+ createElement(MutateBridge),+ children,+ );++/** The rows the agent config replica reads (`replica:<name>:v<version>`). */+const configStorage = new IndexedDBQueryProjectionStorage<unknown>({+ namespace: 'replica:agentConfig:v1',+});++describe('useAgentProfileDetail', () => {+ let scope = '';++ beforeEach(() => {+ scope = `profile-card-${randomUUID()}:personal`;+ vi.spyOn(cacheScope, 'get').mockImplementation(() => scope);+ vi.spyOn(cacheScope, 'use').mockImplementation(() => scope);+ vi.spyOn(cacheScope, 'canPersist').mockReturnValue(true);+ act(() => {+ useAgentStore.setState(initialAgentSliceState);+ useUserStore.setState({ isSignedIn: true } as any);+ });+ });++ afterEach(async () => {+ cleanup();+ await configStorage.remove({ queryKey: 'agt_writer', scope });+ vi.restoreAllMocks();+ });++ it('paints the card from the agent config replica before the network answers', async () => {+ await configStorage.set(+ { queryKey: 'agt_writer', scope },+ { data: { id: 'agt_writer', plugins: ['a', 'b'], title: 'Writer' }, updatedAt: 1 },+ );+ vi.spyOn(agentService, 'getAgentConfigById').mockImplementation(+ () => new Promise(() => {}) as any,+ );++ const { result } = renderHook(() => useAgentProfileDetail('agt_writer', true), { wrapper });++ await waitFor(() =>+ expect(result.current.detail).toMatchObject({ plugins: ['a', 'b'], title: 'Writer' }),+ );+ expect(result.current.isLoading).toBe(false);+ });++ it('shares the config the rest of the app already confirmed instead of fetching again', async () => {+ const lookup = vi+ .spyOn(agentService, 'getAgentConfigById')+ .mockResolvedValue({ id: 'agt_writer', title: 'Writer' } as any);++ renderHook(+ () => {+ // The conversation's own config sync and an open profile card at once.+ useAgentStore.getState().useHydrateAgentConfig(true, 'agt_writer');+ return useAgentProfileDetail('agt_writer', true);+ },+ { wrapper },+ );++ await waitFor(() =>+ expect(useAgentStore.getState().agentMap['agt_writer']).toMatchObject({ title: 'Writer' }),+ );+ expect(lookup).toHaveBeenCalledTimes(1);+ });++ it('reads and syncs nothing while the card is closed', () => {+ const lookup = vi.spyOn(agentService, 'getAgentConfigById');++ const { result } = renderHook(() => useAgentProfileDetail('agt_writer', false), { wrapper });++ expect(result.current.detail).toBeUndefined();+ expect(lookup).not.toHaveBeenCalled();+ });+});diff --git a/src/features/AgentProfileCard/useAgentProfileDetail.ts b/src/features/AgentProfileCard/useAgentProfileDetail.tsnew file mode 100644index 00000000000..7c00a647dde--- /dev/null+++ b/src/features/AgentProfileCard/useAgentProfileDetail.ts@@ -0,0 +1,35 @@+import type { AgentItem } from '@lobechat/types';++import { useAgentStore } from '@/store/agent';+import { useUserStore } from '@/store/user';+import { authSelectors } from '@/store/user/slices/auth/selectors';++export type AgentProfilePreview = Pick<+ AgentItem,+ 'avatar' | 'backgroundColor' | 'description' | 'model' | 'name' | 'provider' | 'title'+>;++export interface AgentProfileDetail extends Partial<AgentProfilePreview> {+ agencyConfig?: { heterogeneousProvider?: { type?: string | null } | null } | null;+ files?: unknown[];+ id?: string;+ knowledgeBases?: unknown[];+ plugins?: string[];+}++/**+ * The full agent behind a profile card, read from the agent's config replica:+ * the local copy paints the card at once and an open card confirms it in the+ * background. `enabled` gates both the read and the sync (a closed card, or a+ * viewer who may not configure the agent, gets neither).+ */+export const useAgentProfileDetail = (agentId: string, enabled: boolean) => {+ const isLogin = useUserStore(authSelectors.isLogin);+ const useHydrateAgentConfig = useAgentStore((s) => s.useHydrateAgentConfig);+ const { isLoading } = useHydrateAgentConfig(isLogin, enabled ? agentId : '');+ const detail = useAgentStore((s) =>+ enabled ? (s.agentMap[agentId] as AgentProfileDetail | undefined) : undefined,+ );++ return { detail, isLoading };+};diff --git a/src/features/AgentRoute/useResolvedAgentRouteId.test.ts b/src/features/AgentRoute/useResolvedAgentRouteId.test.tsindex dcee024fdd9..068d8a67f2e 100644--- a/src/features/AgentRoute/useResolvedAgentRouteId.test.ts+++ b/src/features/AgentRoute/useResolvedAgentRouteId.test.ts@@ -1,7 +1,23 @@+/**+ * @vitest-environment happy-dom+ */+import { randomUUID } from 'node:crypto';+import { BUILTIN_AGENT_SLUGS } from '@lobechat/builtin-agents';-import { describe, expect, it } from 'vitest';+import { act, cleanup, renderHook, waitFor } from '@testing-library/react';+import type { PropsWithChildren } from 'react';+import { createElement, useEffect } from 'react';+import { SWRConfig, useSWRConfig } from 'swr';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';++import { IndexedDBQueryProjectionStorage } from '@/libs/queryProjectionStorage';+import { cacheScope } from '@/libs/replica';+import { setScopedMutate } from '@/libs/swr/mutate';+import { agentService } from '@/services/agent';+import { useAgentStore } from '@/store/agent';+import { initialAgentSliceState } from '@/store/agent/slices/agent/initialState';-import { resolveInboxAgentRouteId } from './useResolvedAgentRouteId';+import { resolveInboxAgentRouteId, useResolvedAgentRouteId } from './useResolvedAgentRouteId';describe('resolveInboxAgentRouteId', () => {it('should use the stable inbox slug while the persisted agent ID is loading', () => {@@ -12,3 +28,81 @@ describe('resolveInboxAgentRouteId', () => {expect(resolveInboxAgentRouteId('inbox-agent-id')).toBe('inbox-agent-id');});});++const MutateBridge = () => {+ const { mutate } = useSWRConfig();+ useEffect(() => setScopedMutate(mutate), [mutate]);+ return null;+};++const wrapper = ({ children }: PropsWithChildren) =>+ createElement(+ SWRConfig,+ { value: { dedupingInterval: 0, provider: () => new Map() } },+ createElement(MutateBridge),+ children,+ );++/** The rows the slug lookup replica reads (`replica:<name>:v<version>`). */+const slugStorage = new IndexedDBQueryProjectionStorage<string>({+ namespace: 'replica:agentSlugId:v1',+});++describe('useResolvedAgentRouteId with a user-chosen slug', () => {+ let scope = '';++ beforeEach(() => {+ scope = `slug-route-${randomUUID()}:personal`;+ vi.spyOn(cacheScope, 'get').mockImplementation(() => scope);+ vi.spyOn(cacheScope, 'use').mockImplementation(() => scope);+ vi.spyOn(cacheScope, 'canPersist').mockReturnValue(true);+ act(() => useAgentStore.setState(initialAgentSliceState));+ });++ afterEach(async () => {+ cleanup();+ await slugStorage.remove({ queryKey: 'my-writer', scope });+ vi.restoreAllMocks();+ });++ // `/agent/<slug>` used to render nothing of the agent until the lookup answered.+ it('shows the agent from the local copy, and redirects only once the server confirms', async () => {+ await slugStorage.set({ queryKey: 'my-writer', scope }, { data: 'agt_writer', updatedAt: 1 });+ let resolveLookup!: (value: string | null) => void;+ vi.spyOn(agentService, 'resolveAgentIdBySlug').mockImplementation(+ () => new Promise((resolve) => (resolveLookup = resolve)),+ );++ const { result } = renderHook(() => useResolvedAgentRouteId('my-writer'), { wrapper });++ await waitFor(() => expect(result.current.agentId).toBe('agt_writer'));+ expect(result.current.isSlugRoute).toBe(true);+ // The slug may name another agent by now: no redirect on the local copy alone.+ expect(result.current.resolvedAgentId).toBeUndefined();++ await act(async () => resolveLookup('agt_writer'));++ await waitFor(() => expect(result.current.resolvedAgentId).toBe('agt_writer'));+ expect(result.current.agentId).toBe('agt_writer');+ });++ it('switches to the agent the server names when the slug moved', async () => {+ await slugStorage.set({ queryKey: 'my-writer', scope }, { data: 'agt_old', updatedAt: 1 });+ vi.spyOn(agentService, 'resolveAgentIdBySlug').mockResolvedValue('agt_new');++ const { result } = renderHook(() => useResolvedAgentRouteId('my-writer'), { wrapper });++ await waitFor(() => expect(result.current.resolvedAgentId).toBe('agt_new'));+ expect(result.current.agentId).toBe('agt_new');+ });++ it('never looks up an ordinary agent id', () => {+ const lookup = vi.spyOn(agentService, 'resolveAgentIdBySlug');++ const { result } = renderHook(() => useResolvedAgentRouteId('agt_plain'), { wrapper });++ expect(result.current.agentId).toBe('agt_plain');+ expect(result.current.isSlugRoute).toBe(false);+ expect(lookup).not.toHaveBeenCalled();+ });+});diff --git a/src/features/AgentRoute/useResolvedAgentRouteId.ts b/src/features/AgentRoute/useResolvedAgentRouteId.tsindex 438fa952752..f5ffc0e1654 100644--- a/src/features/AgentRoute/useResolvedAgentRouteId.ts+++ b/src/features/AgentRoute/useResolvedAgentRouteId.ts@@ -1,9 +1,7 @@import { BUILTIN_AGENT_SLUGS } from '@lobechat/builtin-agents';-import useSWR from 'swr';-import { agentService } from '@/services/agent';import { useAgentStore } from '@/store/agent';-import { builtinAgentSelectors } from '@/store/agent/selectors';+import { agentSelectors, builtinAgentSelectors } from '@/store/agent/selectors';const builtinAgentSlugs = new Set<string>(Object.values(BUILTIN_AGENT_SLUGS));@@ -13,7 +11,8 @@ const builtinAgentSlugs = new Set<string>(Object.values(BUILTIN_AGENT_SLUGS));* underscores). So the absence of one is what tells a slug route from an id* route — and a wrong guess only costs a lookup that resolves to null.*/-const looksLikeSlug = (routeAgentId?: string) => !!routeAgentId && !routeAgentId.includes('_');+export const looksLikeSlug = (routeAgentId?: string) =>+ !!routeAgentId && !routeAgentId.includes('_');/*** Keep the inbox route valid while its persisted agent ID is still loading.@@ -32,16 +31,24 @@ export const useResolvedAgentRouteId = (routeAgentId?: string) => {// the store. Gated on the shape check so an ordinary `/agent/<id>` route never// pays for a request.const isCustomSlug = !isBuiltinSlug && looksLikeSlug(routeAgentId);- const { data: slugAgentId } = useSWR(- isCustomSlug ? ['agent-id-by-slug', routeAgentId] : null,- () => agentService.resolveAgentIdBySlug(routeAgentId!),- { revalidateOnFocus: false },- );-- const resolvedAgentId = isBuiltinSlug ? builtinAgentId : (slugAgentId ?? undefined);+ const customSlug = isCustomSlug ? routeAgentId : undefined;+ const useResolveAgentSlug = useAgentStore((s) => s.useResolveAgentSlug);+ useResolveAgentSlug(customSlug);+ // The persisted `slug → id` paints the agent right away; the lookup confirms it.+ const slugAgentId = useAgentStore(agentSelectors.getAgentIdBySlug(customSlug));+ const isSlugConfirmed = useAgentStore(agentSelectors.isAgentSlugConfirmed(customSlug));++ const agentId = (isBuiltinSlug ? builtinAgentId : slugAgentId) || routeAgentId;+ // A slug can move to another agent between sessions, so a user-chosen slug is+ // only swapped for its id (the URL redirect) once the server confirmed it.+ const resolvedAgentId = isBuiltinSlug+ ? builtinAgentId+ : isSlugConfirmed+ ? slugAgentId+ : undefined;return {- agentId: resolvedAgentId || routeAgentId,+ agentId,isBuiltinSlug,/** The route param is a slug (builtin or user-chosen), so it must be swapped for an id. */isSlugRoute: isBuiltinSlug || isCustomSlug,diff --git a/src/features/AgentRoute/useSlugRouteSendGuard.test.ts b/src/features/AgentRoute/useSlugRouteSendGuard.test.tsnew file mode 100644index 00000000000..52896132117--- /dev/null+++ b/src/features/AgentRoute/useSlugRouteSendGuard.test.ts@@ -0,0 +1,146 @@+/**+ * @vitest-environment happy-dom+ */+import { toast } from '@lobehub/ui';+import { act, renderHook } from '@testing-library/react';+import { createElement, type PropsWithChildren } from 'react';+import { MemoryRouter, Route, Routes } from 'react-router';+import { beforeEach, describe, expect, it, vi } from 'vitest';++import { createReplicaState } from '@/libs/replica';+import { useAgentStore } from '@/store/agent';++import { checkSendOnSlugRoute, useSlugRouteSendGuard } from './useSlugRouteSendGuard';++vi.mock('@lobehub/ui', async (importOriginal) => ({+ ...(await importOriginal<object>()),+ toast: { error: vi.fn(), info: vi.fn() },+}));++const confirmedEntry = { source: 'server' } as any;+const storageEntry = { source: 'storage' } as any;++describe('checkSendOnSlugRoute', () => {+ const confirmAgentSlugTarget = vi.fn();++ beforeEach(() => {+ confirmAgentSlugTarget.mockReset();+ act(() =>+ useAgentStore.setState({+ agentSlugIdMap: {},+ agentSlugIdReplica: createReplicaState(),+ confirmAgentSlugTarget,+ } as any),+ );+ });++ const seed = (agentId: string, entry: unknown) =>+ act(() =>+ useAgentStore.setState({+ agentSlugIdMap: { 'my-writer': agentId },+ agentSlugIdReplica: { ...createReplicaState(), entries: { 'my-writer': entry } } as any,+ }),+ );++ it('never holds an id route or a builtin slug', async () => {+ await expect(checkSendOnSlugRoute('agt_plain')).resolves.toBe('ok');+ await expect(checkSendOnSlugRoute('inbox')).resolves.toBe('ok');+ expect(confirmAgentSlugTarget).not.toHaveBeenCalled();+ });++ it('sends at once when the server already confirmed the slug', async () => {+ seed('agt_writer', confirmedEntry);++ await expect(checkSendOnSlugRoute('my-writer')).resolves.toBe('ok');+ expect(confirmAgentSlugTarget).not.toHaveBeenCalled();+ });++ // Codex P1: the agent painted from the local copy may no longer own the slug.+ it('holds a send to the locally painted agent until the server names that same agent', async () => {+ seed('agt_writer', storageEntry);+ confirmAgentSlugTarget.mockResolvedValue('agt_writer');++ await expect(checkSendOnSlugRoute('my-writer')).resolves.toBe('ok');+ expect(confirmAgentSlugTarget).toHaveBeenCalledWith('my-writer');+ });++ it('blocks the send when the slug moved to another agent', async () => {+ seed('agt_old', storageEntry);+ confirmAgentSlugTarget.mockResolvedValue('agt_new');++ await expect(checkSendOnSlugRoute('my-writer')).resolves.toBe('moved');+ });++ it('blocks the send when the lookup fails or nothing names the slug', async () => {+ seed('agt_writer', storageEntry);+ confirmAgentSlugTarget.mockRejectedValueOnce(new Error('offline'));+ await expect(checkSendOnSlugRoute('my-writer')).resolves.toBe('unconfirmed');++ confirmAgentSlugTarget.mockResolvedValueOnce(undefined);+ await expect(checkSendOnSlugRoute('my-writer')).resolves.toBe('unconfirmed');+ });+});++describe('useSlugRouteSendGuard', () => {+ const confirmAgentSlugTarget = vi.fn();+ const routeWrapper = ({ children }: PropsWithChildren) =>+ createElement(+ MemoryRouter,+ { initialEntries: ['/agent/my-writer'] },+ createElement(Routes, null, createElement(Route, { element: children, path: '/agent/:aid' })),+ );++ beforeEach(() => {+ vi.mocked(toast.error).mockClear();+ vi.mocked(toast.info).mockClear();+ confirmAgentSlugTarget.mockReset();+ act(() =>+ useAgentStore.setState({+ agentSlugIdMap: { 'my-writer': 'agt_writer' },+ agentSlugIdReplica: {+ ...createReplicaState(),+ entries: { 'my-writer': { source: 'storage' } },+ } as any,+ confirmAgentSlugTarget,+ } as any),+ );+ });++ // Codex P2: a held send must say why instead of looking like a dead button.+ it('tells the sender when the slug could not be confirmed', async () => {+ confirmAgentSlugTarget.mockRejectedValue(new Error('offline'));+ const { result } = renderHook(() => useSlugRouteSendGuard(), { wrapper: routeWrapper });++ await expect(result.current.onBeforeSendMessage!({} as any)).resolves.toBe(false);+ expect(toast.error).toHaveBeenCalledOnce();+ expect(toast.info).not.toHaveBeenCalled();+ });++ it('tells the sender the route is switching when the slug moved', async () => {+ confirmAgentSlugTarget.mockResolvedValue('agt_other');+ const { result } = renderHook(() => useSlugRouteSendGuard(), { wrapper: routeWrapper });++ await expect(result.current.onBeforeSendMessage!({} as any)).resolves.toBe(false);+ expect(toast.info).toHaveBeenCalledOnce();+ expect(toast.error).not.toHaveBeenCalled();+ });++ // Codex P1: regenerate and continue start a generation too.+ it('holds regenerate and continue on an unconfirmed slug route as well', async () => {+ confirmAgentSlugTarget.mockResolvedValue('agt_other');+ const { result } = renderHook(() => useSlugRouteSendGuard(), { wrapper: routeWrapper });++ await expect(result.current.onBeforeRegenerate!('msg_1')).resolves.toBe(false);+ await expect(result.current.onBeforeContinue!('msg_1')).resolves.toBe(false);+ expect(confirmAgentSlugTarget).toHaveBeenCalledTimes(2);+ });++ it('lets a confirmed send through silently', async () => {+ confirmAgentSlugTarget.mockResolvedValue('agt_writer');+ const { result } = renderHook(() => useSlugRouteSendGuard(), { wrapper: routeWrapper });++ await expect(result.current.onBeforeSendMessage!({} as any)).resolves.toBeUndefined();+ expect(toast.error).not.toHaveBeenCalled();+ expect(toast.info).not.toHaveBeenCalled();+ });+});diff --git a/src/features/AgentRoute/useSlugRouteSendGuard.ts b/src/features/AgentRoute/useSlugRouteSendGuard.tsnew file mode 100644index 00000000000..2e206bb25f0--- /dev/null+++ b/src/features/AgentRoute/useSlugRouteSendGuard.ts@@ -0,0 +1,73 @@+import { BUILTIN_AGENT_SLUGS } from '@lobechat/builtin-agents';+import { toast } from '@lobehub/ui';+import { t } from 'i18next';+import { useMemo, useRef } from 'react';+import { useParams } from 'react-router';++import type { ConversationHooks } from '@/features/Conversation/types';+import { useAgentStore } from '@/store/agent';+import { agentSelectors } from '@/store/agent/selectors';++import { looksLikeSlug } from './useResolvedAgentRouteId';++const builtinAgentSlugs = new Set<string>(Object.values(BUILTIN_AGENT_SLUGS));++/** `ok`: send; `moved`: the slug names another agent now; `unconfirmed`: the lookup failed. */+export type SlugRouteSendCheck = 'moved' | 'ok' | 'unconfirmed';++/**+ * Whether a send on `/agent/<slug>` may go to the agent on screen.+ *+ * A user-chosen slug paints its agent from the persisted `slug → id` before the+ * lookup answers, and a slug can move to another agent between sessions. Until+ * the server confirms the slug, a send waits for that answer and goes through+ * only when it names the agent the conversation shows; otherwise the route is+ * about to switch agents and the draft stays in the composer.+ */+export const checkSendOnSlugRoute = async (+ slug: string | undefined,+): Promise<SlugRouteSendCheck> => {+ if (!slug || builtinAgentSlugs.has(slug) || !looksLikeSlug(slug)) return 'ok';++ const state = useAgentStore.getState();+ if (agentSelectors.isAgentSlugConfirmed(slug)(state)) return 'ok';++ const shownAgentId = agentSelectors.getAgentIdBySlug(slug)(state);++ try {+ const confirmedAgentId = await state.confirmAgentSlugTarget(slug);+ if (!shownAgentId || !confirmedAgentId) return 'unconfirmed';+ return confirmedAgentId === shownAgentId ? 'ok' : 'moved';+ } catch {+ return 'unconfirmed';+ }+};++/**+ * Conversation hooks that hold every generation on an unconfirmed slug route+ * (see `checkSendOnSlugRoute`): a send, a regenerate and a continue would all+ * run against the agent painted from the local copy.+ */+export const useSlugRouteSendGuard = (): ConversationHooks => {+ const { aid } = useParams<{ aid?: string }>();+ const aidRef = useRef(aid);+ aidRef.current = aid;++ return useMemo(() => {+ const guard = async (): Promise<false | undefined> => {+ const check = await checkSendOnSlugRoute(aidRef.current);+ if (check === 'ok') return;++ // Nothing is lost (a draft stays in the composer); say why, so the action never looks dead.+ if (check === 'moved') toast.info(t('input.agentSlugMoved', { ns: 'chat' }));+ else toast.error(t('input.agentSlugUnconfirmed', { ns: 'chat' }));+ return false;+ };++ return {+ onBeforeContinue: guard,+ onBeforeRegenerate: guard,+ onBeforeSendMessage: guard,+ };+ }, []);+};diff --git a/src/libs/swr/keys.ts b/src/libs/swr/keys.tsindex 07fc2d10d91..a3add050389 100644--- a/src/libs/swr/keys.ts+++ b/src/libs/swr/keys.ts@@ -232,8 +232,6 @@ export const agentBuilderKeys = {// ---- group --------------------------------------------------------------export const groupKeys = {- /** Agent picker for the "add member" modal. */- queryAgents: def('group:queryAgents', () => ['group:queryAgents']),/** Agent picker for the "create group" modal. */queryAgentsForCreate: def('group:queryAgentsForCreate', () => ['group:queryAgentsForCreate']),};@@ -329,11 +327,7 @@ export const briefKeys = {// ---- agent config / available / search ----------------------------------export const agentConfigKeys = {- available: def('agent:available', () => ['agent:available']),search: def('agent:search', (keyword?: string) => ['agent:search', keyword]),- serverDefaultHeterogeneousCapability: def('agent:serverDefaultHeterogeneousCapability', () => [- 'agent:serverDefaultHeterogeneousCapability',- ]),};// ---- aiModel ------------------------------------------------------------@@ -898,9 +892,6 @@ export const onboardingKeys = {export const agentHomeKeys = {topics: def('agentHome:topics', (agentId: string) => ['agentHome:topics', agentId]),};-export const agentProfileKeys = {- detail: def('agentProfile:detail', (agentId: string) => ['agentProfile:detail', agentId]),-};export const agentSignalKeys = {receipts: def('agentSignal:receipts', (agentId: string, topicId: string) => ['agentSignal:receipts',@@ -1007,7 +998,6 @@ export const swrKeys = {agentBuilder: agentBuilderKeys,agentDocument: agentDocumentSWRKeys,agentHome: agentHomeKeys,- agentProfile: agentProfileKeys,agentSignal: agentSignalKeys,aiModel: aiModelKeys,auth: authKeys,diff --git a/src/routes/(main)/agent/(chat)/topicListLoader.test.ts b/src/routes/(main)/agent/(chat)/topicListLoader.test.tsindex 5186f10b0da..46d3bd43ecd 100644--- a/src/routes/(main)/agent/(chat)/topicListLoader.test.ts+++ b/src/routes/(main)/agent/(chat)/topicListLoader.test.ts@@ -15,6 +15,13 @@ const preHydrateMessagesMock = vi.hoisted(() => vi.fn(async () => true));const preHydrateThreadsMock = vi.hoisted(() => vi.fn(async (_topicId?: string) => true));const builtinAgentIdMap = vi.hoisted(() => ({ inbox: 'agt_inbox' }) as Record<string, string>);const preHydrateBuiltinAgentMock = vi.hoisted(() => vi.fn(async () => true));+const agentSlugIdMap = vi.hoisted(() => ({}) as Record<string, string>);+const preHydrateAgentSlugMock = vi.hoisted(() =>+ vi.fn(async (slug: string) => {+ if (slug === 'my-writer') agentSlugIdMap[slug] = 'agt_writer';+ return agentSlugIdMap[slug];+ }),+);const preHydrateDeviceListMock = vi.hoisted(() => vi.fn(async () => true));const preHydrateVerifyRunsMock = vi.hoisted(() => vi.fn(async (_ids: string[]) => {}));const chatState = vi.hoisted(() => ({ dbMessagesMap: {} as Record<string, unknown[]> }));@@ -29,11 +36,20 @@ vi.mock('@/hooks/chatTopicListQuery', () => ({vi.mock('@/store/agent', () => ({useAgentStore: {- getState: () => ({ builtinAgentIdMap, preHydrateBuiltinAgent: preHydrateBuiltinAgentMock }),+ getState: () => ({+ agentSlugIdMap,+ builtinAgentIdMap,+ preHydrateAgentSlug: preHydrateAgentSlugMock,+ preHydrateBuiltinAgent: preHydrateBuiltinAgentMock,+ }),},}));vi.mock('@/store/agent/selectors', () => ({+ agentSelectors: {+ getAgentIdBySlug: (slug: string) => (state: { agentSlugIdMap: Record<string, string> }) =>+ state.agentSlugIdMap[slug],+ },builtinAgentSelectors: {getBuiltinAgentId: (slug: string) => (state: { builtinAgentIdMap: Record<string, string> }) =>state.builtinAgentIdMap[slug],@@ -67,6 +83,8 @@ describe('agent chat topic list loader', () => {preHydrateTopicListMock.mockResolvedValue(true);preHydrateBuiltinAgentMock.mockClear();preHydrateBuiltinAgentMock.mockResolvedValue(true);+ preHydrateAgentSlugMock.mockClear();+ for (const slug of Object.keys(agentSlugIdMap)) delete agentSlugIdMap[slug];preHydrateDeviceListMock.mockClear();preHydrateDeviceListMock.mockResolvedValue(true);getSidebarTopicListParamsMock.mockReset();@@ -116,6 +134,35 @@ describe('agent chat topic list loader', () => {await agentChatTopicListLoader(loaderArgs('agt_1'));expect(preHydrateBuiltinAgentMock).not.toHaveBeenCalled();+ expect(preHydrateAgentSlugMock).not.toHaveBeenCalled();+ });++ // A `/agent/<slug>` route used to wait on the network lookup before anything+ // resolved; the persisted `slug → id` now seeds the agent's topics pre-paint.+ it('resolves a user-chosen slug from its persisted id before the route commits', async () => {+ await expect(agentChatTopicListLoader(loaderArgs('my-writer'))).resolves.toBeNull();++ expect(preHydrateAgentSlugMock).toHaveBeenCalledWith('my-writer');+ expect(preHydrateBuiltinAgentMock).not.toHaveBeenCalled();+ expect(getSidebarTopicListParamsMock).toHaveBeenCalledWith({ agentId: 'agt_writer' });+ });++ it('falls back to the slug when nothing is persisted for it', async () => {+ await agentChatTopicListLoader(loaderArgs('unknown-slug'));++ expect(preHydrateAgentSlugMock).toHaveBeenCalledWith('unknown-slug');+ expect(getSidebarTopicListParamsMock).toHaveBeenCalledWith({ agentId: 'unknown-slug' });+ });++ it('does not let a stalled slug read block the route', async () => {+ vi.useFakeTimers();+ preHydrateAgentSlugMock.mockImplementationOnce(() => new Promise(() => {}));++ const settled = vi.fn();+ void agentChatTopicListLoader(loaderArgs('my-writer')).then(settled);++ await vi.advanceTimersByTimeAsync(PRE_PAINT_HYDRATE_TIMEOUT * 2);+ expect(settled).toHaveBeenCalled();});it('resolves a builtin slug to its agent id', async () => {diff --git a/src/routes/(main)/agent/(chat)/topicListLoader.ts b/src/routes/(main)/agent/(chat)/topicListLoader.tsindex de46470b977..09ee688e36e 100644--- a/src/routes/(main)/agent/(chat)/topicListLoader.ts+++ b/src/routes/(main)/agent/(chat)/topicListLoader.ts@@ -1,10 +1,11 @@import { BUILTIN_AGENT_SLUGS } from '@lobechat/builtin-agents';import type { LoaderFunctionArgs } from 'react-router';+import { looksLikeSlug } from '@/features/AgentRoute/useResolvedAgentRouteId';import { getSidebarTopicListParams } from '@/hooks/chatTopicListQuery';import { PRE_PAINT_HYDRATE_TIMEOUT, settleWithin } from '@/libs/replica/prePaint';import { useAgentStore } from '@/store/agent';-import { builtinAgentSelectors } from '@/store/agent/selectors';+import { agentSelectors, builtinAgentSelectors } from '@/store/agent/selectors';import { useChatStore } from '@/store/chat';import { messageMapKey } from '@/store/chat/utils/messageMapKey';import { useDeviceStore } from '@/store/device';@@ -14,15 +15,17 @@ const builtinAgentSlugs = new Set<string>(Object.values(BUILTIN_AGENT_SLUGS));/*** Builtin slugs (`inbox`, …) resolve from the store; an id passes through. A- * user-chosen slug needs a server lookup, so it resolves only after the route- * redirects to the real id and the loader runs again — hydrating under the slug- * key is a harmless miss.+ * user-chosen slug resolves from its persisted `slug → id` (seeded by the+ * loader); with none, hydrating under the slug key is a harmless miss and the+ * route resolves it once the lookup answers.*/const resolveRouteAgentId = (routeAgentId?: string): string | undefined => {if (!routeAgentId) return undefined;- if (!builtinAgentSlugs.has(routeAgentId)) return routeAgentId;+ const state = useAgentStore.getState();+ if (builtinAgentSlugs.has(routeAgentId))+ return builtinAgentSelectors.getBuiltinAgentId(routeAgentId)(state);- return builtinAgentSelectors.getBuiltinAgentId(routeAgentId)(useAgentStore.getState());+ return agentSelectors.getAgentIdBySlug(routeAgentId)(state) ?? routeAgentId;};/**@@ -109,6 +112,13 @@ export const agentChatTopicListLoader = async ({ params }: LoaderFunctionArgs):useAgentStore.getState().preHydrateBuiltinAgent(params.aid),PRE_PAINT_HYDRATE_TIMEOUT,);+ } else if (looksLikeSlug(params.aid)) {+ // A user-chosen slug: seed its persisted `slug → id` the same way, so the+ // agent (and its topics / transcript below) paints before the lookup answers.+ await settleWithin(+ useAgentStore.getState().preHydrateAgentSlug(params.aid!),+ PRE_PAINT_HYDRATE_TIMEOUT,+ );}await Promise.all([diff --git a/src/routes/(main)/agent/features/Conversation/ConversationArea.tsx b/src/routes/(main)/agent/features/Conversation/ConversationArea.tsxindex f1e64dc97bb..a16d97323e1 100644--- a/src/routes/(main)/agent/features/Conversation/ConversationArea.tsx+++ b/src/routes/(main)/agent/features/Conversation/ConversationArea.tsx@@ -6,6 +6,7 @@ import { useTranslation } from 'react-i18next';import { useBusinessConversationAnalytics } from '@/business/client/hooks/useBusinessConversationAnalytics';import AgentHome from '@/features/AgentHome';+import { useSlugRouteSendGuard } from '@/features/AgentRoute/useSlugRouteSendGuard';import {TopicMigrationPlaceholder,useTopicMigrationPending,@@ -107,6 +108,9 @@ const Conversation = memo(() => {topicId: context.topicId ?? undefined,});const businessAnalyticsHooks = useBusinessConversationAnalytics(context);+ // First in the chain: a send on an unconfirmed `/agent/<slug>` must not reach+ // the agent painted from the local copy before the server confirms it.+ const slugRouteSendGuard = useSlugRouteSendGuard();// A topic still awaiting its transfer backfill shows a placeholder instead// of an empty (not-yet-migrated) history, and blocks sending — the server@@ -118,8 +122,8 @@ const Conversation = memo(() => {);const hooks = useMemo(- () => mergeConversationHooks(businessAnalyticsHooks, chatFollowUpHooks),- [businessAnalyticsHooks, chatFollowUpHooks],+ () => mergeConversationHooks(slugRouteSendGuard, businessAnalyticsHooks, chatFollowUpHooks),+ [slugRouteSendGuard, businessAnalyticsHooks, chatFollowUpHooks],);return (diff --git a/src/routes/(main)/agent/features/Conversation/HeterogeneousChatInput/ApiModeModelBar.tsx b/src/routes/(main)/agent/features/Conversation/HeterogeneousChatInput/ApiModeModelBar.tsxindex 473026b6ec3..b9ceff7f414 100644--- a/src/routes/(main)/agent/features/Conversation/HeterogeneousChatInput/ApiModeModelBar.tsx+++ b/src/routes/(main)/agent/features/Conversation/HeterogeneousChatInput/ApiModeModelBar.tsx@@ -18,7 +18,7 @@ import {} from '@/features/HeterogeneousAgent/modelPicker';import ModelSelect from '@/features/ModelSelect';import { useAgentStore } from '@/store/agent';-import { agentByIdSelectors } from '@/store/agent/selectors';+import { agentByIdSelectors, agentSelectors } from '@/store/agent/selectors';import { useAiInfraStore } from '@/store/aiInfra';import { useChatStore } from '@/store/chat';import { topicSelectors } from '@/store/chat/slices/topic/selectors';@@ -55,17 +55,20 @@ const ApiModeModelBar = memo<ApiModeModelBarProps>(({ agentId }) => {const useFetchServerDefaultCapability = useAgentStore((state) => state.useFetchServerDefaultHeterogeneousCapability,);- const serverCapability = useFetchServerDefaultCapability(- !!serverDefaultApiConfig && !!serverDefaultAgentType,- );+ const serverCapabilityEnabled = !!serverDefaultApiConfig && !!serverDefaultAgentType;+ const serverCapabilitySync = useFetchServerDefaultCapability(serverCapabilityEnabled);+ // The last confirmed capability paints at once; the sync only confirms it.+ const serverCapability = useAgentStore(agentSelectors.heteroServerDefaultCapability);+ const serverCapabilityLoading =+ serverCapabilityEnabled && !serverCapability && !serverCapabilitySync.error;const builtinAiModelList = useAiInfraStore((state) => state.builtinAiModelList);const serverDefaultModelOptions = useMemo(() => {const models =- serverCapability.data?.enabled === true && serverDefaultAgentType- ? resolveServerDefaultAgentModels(serverCapability.data.models, serverDefaultAgentType)+ serverCapability?.enabled === true && serverDefaultAgentType+ ? resolveServerDefaultAgentModels(serverCapability.models, serverDefaultAgentType): [];return buildServerDefaultModelOptions(models, builtinAiModelList);- }, [builtinAiModelList, serverCapability.data, serverDefaultAgentType]);+ }, [builtinAiModelList, serverCapability, serverDefaultAgentType]);if (!heterogeneousProvider ||@@ -105,7 +108,7 @@ const ApiModeModelBar = memo<ApiModeModelBarProps>(({ agentId }) => {<SelectclassName={modelPickerStyles.picker}labelRender={compactTriggerLabel}- loading={serverCapability.isLoading}+ loading={serverCapabilityLoading}options={serverDefaultModelOptions}popupMatchSelectWidth={false}size="small"diff --git a/src/routes/(main)/agent/profile/features/ProfileEditor/index.tsx b/src/routes/(main)/agent/profile/features/ProfileEditor/index.tsxindex 0fe211a35c0..c1da522624e 100644--- a/src/routes/(main)/agent/profile/features/ProfileEditor/index.tsx+++ b/src/routes/(main)/agent/profile/features/ProfileEditor/index.tsx@@ -163,23 +163,29 @@ const ProfileEditor = memo(() => {? heterogeneousProvider.type: undefined;const serverCapabilityEnabled = localDesktopAvailable && !!serverDefaultAgentType;- const serverCapability = useFetchServerDefaultCapability(serverCapabilityEnabled);+ const serverCapabilitySync = useFetchServerDefaultCapability(serverCapabilityEnabled);+ // The last confirmed capability paints at once; the sync only confirms it, and+ // a failed background refresh keeps it instead of turning into an error.+ const serverCapability = useAgentStore(agentSelectors.heteroServerDefaultCapability);+ const serverCapabilityError = !serverCapability && serverCapabilitySync.error;+ const serverCapabilityLoading =+ serverCapabilityEnabled && !serverCapability && !serverCapabilitySync.error;const serverDefaultModels =- serverCapability.data?.enabled === true && serverDefaultAgentType- ? resolveServerDefaultAgentModels(serverCapability.data.models, serverDefaultAgentType)+ serverCapability?.enabled === true && serverDefaultAgentType+ ? resolveServerDefaultAgentModels(serverCapability.models, serverDefaultAgentType): [];const serverDefaultAvailable = serverCapabilityEnabled && serverDefaultModels.length > 0;const serverDefaultUnavailableReason = !localDesktopAvailable? t('heterogeneousStatus.apiMode.localOnly')- : serverCapability.error+ : serverCapabilityError? t('heterogeneousStatus.apiMode.serverDefault.loadFailed')- : serverCapability.data?.enabled === false+ : serverCapability?.enabled === false? t(- serverCapability.data.reason === 'disabled'+ serverCapability.reason === 'disabled'? 'heterogeneousStatus.apiMode.serverDefault.disabled': 'heterogeneousStatus.apiMode.serverDefault.invalidConfiguration',)- : serverCapabilityEnabled && !serverCapability.isLoading && !serverDefaultAvailable+ : serverCapabilityEnabled && !serverCapabilityLoading && !serverDefaultAvailable? t('heterogeneousStatus.apiMode.serverDefault.unsupported'): undefined;const heterogeneousTabItems: TabsItem[] = heterogeneousProvider@@ -208,14 +214,14 @@ const ProfileEditor = memo(() => {apiModeWorkspaceBlocked={isWorkspaceAgent}provider={heterogeneousProvider}serverDefaultAvailable={serverDefaultAvailable}- serverDefaultLoading={serverCapabilityEnabled && serverCapability.isLoading}+ serverDefaultLoading={serverCapabilityLoading}serverDefaultModels={serverDefaultModels}serverDefaultUnavailableReason={serverDefaultUnavailableReason}onApiConfigChange={updateHeterogeneousApiConfig}onAuthModeChange={updateHeterogeneousAuthMode}onCommandChange={updateHeterogeneousCommand}onServerDefaultRetry={() => {- void serverCapability.mutate();+ void serverCapabilitySync.revalidate();}}/>),diff --git a/src/routes/(main)/group/_layout/Sidebar/AddGroupMemberModal/index.tsx b/src/routes/(main)/group/_layout/Sidebar/AddGroupMemberModal/index.tsxindex 0ee82266d5e..798bf6057e1 100644--- a/src/routes/(main)/group/_layout/Sidebar/AddGroupMemberModal/index.tsx+++ b/src/routes/(main)/group/_layout/Sidebar/AddGroupMemberModal/index.tsx@@ -1,19 +1,15 @@'use client';import { createStaticStyles, Divider, Flexbox } from '@lobehub/ui';-import { memo, useEffect, useMemo, useState } from 'react';+import { memo, useEffect, useState } from 'react';import { useTranslation } from 'react-i18next';-import useSWR from 'swr';import ImperativeModal from '@/components/ImperativeModal';-import { groupKeys } from '@/libs/swr/keys';-import { agentService } from '@/services/agent';-import { type AgentItemData } from './AgentItem';import AvailableAgentList from './AvailableAgentList';-import { selectAddableAgents } from './selectAddableAgents';import SelectedAgentList from './SelectedAgentList';import { useAgentSelectionStore } from './store';+import { useAddableGroupMembers } from './useAddableGroupMembers';const styles = createStaticStyles(({ css, cssVar }) => ({container: css`@@ -47,17 +43,11 @@ const AddGroupMemberModal = memo<AddGroupMemberModalProps>(const selectedAgentIds = useAgentSelectionStore((s) => s.selectedAgentIds);const clearSelection = useAgentSelectionStore((s) => s.clearSelection);- // Fetch non-virtual agents; the inbox is excluded unless a caller opts in- const { data: allAgents = [], isLoading: isLoadingAgents } = useSWR(- open ? groupKeys.queryAgents() : null,- () => agentService.queryAgents(),- );-- // Filter out existing members and the inbox, which cannot join a group- const availableAgents = useMemo<AgentItemData[]>(- () => selectAddableAgents(allAgents, existingMembers),- [allAgents, existingMembers],- );+ const {+ allAgents,+ availableAgents,+ isLoading: isLoadingAgents,+ } = useAddableGroupMembers(existingMembers);// Clear selection when modal closesuseEffect(() => {diff --git a/src/routes/(main)/group/_layout/Sidebar/AddGroupMemberModal/selectAddableAgents.test.ts b/src/routes/(main)/group/_layout/Sidebar/AddGroupMemberModal/selectAddableAgents.test.tsindex 80bbe1b4b06..50186a321b0 100644--- a/src/routes/(main)/group/_layout/Sidebar/AddGroupMemberModal/selectAddableAgents.test.ts+++ b/src/routes/(main)/group/_layout/Sidebar/AddGroupMemberModal/selectAddableAgents.test.ts@@ -1,6 +1,6 @@import { describe, expect, it } from 'vitest';-import { selectAddableAgents } from './selectAddableAgents';+import { selectAddableAgents, toPickableAgents } from './selectAddableAgents';describe('selectAddableAgents', () => {it('excludes the inbox, which addAgentsToGroup refuses', () => {@@ -21,3 +21,38 @@ describe('selectAddableAgents', () => {expect(selectAddableAgents(agents, ['a1']).map((a) => a.id)).toEqual(['a2']);});});++describe('toPickableAgents', () => {+ const item = (id: string, updatedAt: string, extra: Record<string, unknown> = {}) =>+ ({+ id,+ pinned: false,+ title: id,+ type: 'agent',+ updatedAt: new Date(updatedAt),+ ...extra,+ }) as any;++ it('keeps agents only, newest first, and flags builtins as the inbox', () => {+ const picked = toPickableAgents([+ item('old', '2026-01-01'),+ item('group', '2026-05-01', { type: 'group' }),+ item('inbox-agent', '2026-04-01', { slug: 'inbox' }),+ item('new', '2026-03-01'),+ item('old', '2026-01-01'),+ ]);++ expect(picked.map((a) => [a.id, a.isInbox])).toEqual([+ ['inbox-agent', true],+ ['new', false],+ ['old', false],+ ]);+ expect(selectAddableAgents(picked, []).map((a) => a.id)).toEqual(['new', 'old']);+ });++ it('drops a chat-group member avatar list that is not a single image', () => {+ const [picked] = toPickableAgents([item('a', '2026-01-01', { avatar: [{ avatar: 'x' }] })]);++ expect(picked.avatar).toBeNull();+ });+});diff --git a/src/routes/(main)/group/_layout/Sidebar/AddGroupMemberModal/selectAddableAgents.ts b/src/routes/(main)/group/_layout/Sidebar/AddGroupMemberModal/selectAddableAgents.tsindex fb0dfd59bfc..8b66aa89589 100644--- a/src/routes/(main)/group/_layout/Sidebar/AddGroupMemberModal/selectAddableAgents.ts+++ b/src/routes/(main)/group/_layout/Sidebar/AddGroupMemberModal/selectAddableAgents.ts@@ -1,5 +1,35 @@+import { BUILTIN_AGENT_SLUGS } from '@lobechat/builtin-agents';+import type { SidebarAgentItem } from '@lobechat/types';+import { type AvailableAgentItem } from '@/services/agent';+const builtinAgentSlugs = new Set<string>(Object.values(BUILTIN_AGENT_SLUGS));++/**+ * The picker's candidates from the sidebar agent list: agents only (no chat+ * groups, no builtins), most recently updated first like `queryAgents`.+ */+export const toPickableAgents = (items: SidebarAgentItem[]): AvailableAgentItem[] => {+ const seen = new Set<string>();++ return items+ .filter((item) => {+ if (item.type !== 'agent' || seen.has(item.id)) return false;+ seen.add(item.id);+ return true;+ })+ .sort((a, b) => new Date(b.updatedAt).getTime() - new Date(a.updatedAt).getTime())+ .map((item) => ({+ avatar: typeof item.avatar === 'string' ? item.avatar : null,+ backgroundColor: item.backgroundColor ?? null,+ description: item.description ?? null,+ id: item.id,+ isInbox: !!item.slug && builtinAgentSlugs.has(item.slug),+ name: item.name ?? null,+ title: item.title,+ }));+};+/*** Agents the user may pick as new group members.*diff --git a/src/routes/(main)/group/_layout/Sidebar/AddGroupMemberModal/useAddableGroupMembers.test.ts b/src/routes/(main)/group/_layout/Sidebar/AddGroupMemberModal/useAddableGroupMembers.test.tsnew file mode 100644index 00000000000..c02101fbca8--- /dev/null+++ b/src/routes/(main)/group/_layout/Sidebar/AddGroupMemberModal/useAddableGroupMembers.test.ts@@ -0,0 +1,76 @@+/**+ * @vitest-environment happy-dom+ */+import { act, renderHook } from '@testing-library/react';+import { beforeEach, describe, expect, it, vi } from 'vitest';++import { agentService } from '@/services/agent';+import { useHomeStore } from '@/store/home';+import { initialAgentListState } from '@/store/home/slices/agentList/initialState';++import { useAddableGroupMembers } from './useAddableGroupMembers';++vi.mock('@/services/agent', () => ({+ AVAILABLE_AGENTS_CONTEXT_QUERY_LIMIT: 12,+ agentService: { queryAgents: vi.fn(() => new Promise(() => {})) },+}));++// The sidebar list sync is the replica's concern; here the list is already local.+vi.mock('@/hooks/useFetchAgentList', () => ({+ useFetchAgentList: () => ({ error: undefined, isRevalidating: false, mutate: vi.fn() }),+}));++const sidebarAgent = (id: string, updatedAt: string, extra: Record<string, unknown> = {}) => ({+ avatar: null,+ description: null,+ id,+ pinned: false,+ title: id,+ type: 'agent' as const,+ updatedAt: new Date(updatedAt),+ ...extra,+});++describe('useAddableGroupMembers', () => {+ beforeEach(() => {+ vi.mocked(agentService.queryAgents).mockClear();+ act(() => useHomeStore.setState(initialAgentListState));+ });++ // The picker used to fetch `queryAgents` on every open and show a skeleton+ // until it answered; the sidebar replica already holds those agents locally.+ it('offers the agents from the local sidebar list without its own request', () => {+ act(() =>+ useHomeStore.setState({+ agentGroups: [+ {+ id: 'folder',+ items: [sidebarAgent('agt_old', '2026-01-01')],+ name: 'Folder',+ sort: 0,+ },+ ],+ isAgentListInit: true,+ pinnedAgents: [sidebarAgent('agt_new', '2026-03-01')],+ ungroupedAgents: [+ sidebarAgent('agt_member', '2026-02-01'),+ sidebarAgent('grp_chat', '2026-04-01', { type: 'group' }),+ ],+ }),+ );++ const { result } = renderHook(() => useAddableGroupMembers(['agt_member']));++ expect(result.current.isLoading).toBe(false);+ expect(result.current.availableAgents.map((agent) => agent.id)).toEqual(['agt_new', 'agt_old']);+ expect(agentService.queryAgents).not.toHaveBeenCalled();+ });++ it('treats a restored empty list as loading until the server confirms it', () => {+ act(() => useHomeStore.setState({ isAgentListInit: true }));++ const { result } = renderHook(() => useAddableGroupMembers([]));++ expect(result.current.isLoading).toBe(true);+ });+});diff --git a/src/routes/(main)/group/_layout/Sidebar/AddGroupMemberModal/useAddableGroupMembers.ts b/src/routes/(main)/group/_layout/Sidebar/AddGroupMemberModal/useAddableGroupMembers.tsnew file mode 100644index 00000000000..5458dfe8244--- /dev/null+++ b/src/routes/(main)/group/_layout/Sidebar/AddGroupMemberModal/useAddableGroupMembers.ts@@ -0,0 +1,33 @@+import isEqual from 'fast-deep-equal';+import { useMemo } from 'react';++import { useFetchAgentList } from '@/hooks/useFetchAgentList';+import { useHomeStore } from '@/store/home';+import { homeAgentListSelectors } from '@/store/home/selectors';++import { type AgentItemData } from './AgentItem';+import { selectAddableAgents, toPickableAgents } from './selectAddableAgents';++/**+ * Candidates for the "add member" picker, read from the sidebar agent list+ * replica: it already holds every non-virtual agent, so the local copy paints+ * the picker at once and the sync only confirms it.+ */+export const useAddableGroupMembers = (existingMembers: string[]) => {+ const { error } = useFetchAgentList();+ const sidebarAgents = useHomeStore(homeAgentListSelectors.allAgents, isEqual);+ const isAgentListInit = useHomeStore(homeAgentListSelectors.isAgentListInit);+ const isAgentListConfirmed = useHomeStore(homeAgentListSelectors.isAgentListConfirmed);++ const allAgents = useMemo(() => toPickableAgents(sidebarAgents), [sidebarAgents]);+ // Existing members and the inbox (which cannot join a group) are not offered.+ const availableAgents = useMemo<AgentItemData[]>(+ () => selectAddableAgents(allAgents, existingMembers),+ [allAgents, existingMembers],+ );++ // A restored empty list is not "you have no agents" until the server says so.+ const isLoading = !isAgentListInit || (allAgents.length === 0 && !isAgentListConfirmed && !error);++ return { allAgents, availableAgents, isLoading };+};diff --git a/src/services/chat/mecha/contextFactProviders.test.ts b/src/services/chat/mecha/contextFactProviders.test.tsindex 524503d29df..70ece604e76 100644--- a/src/services/chat/mecha/contextFactProviders.test.ts+++ b/src/services/chat/mecha/contextFactProviders.test.ts@@ -17,11 +17,16 @@ vi.mock('@/libs/trpc/client', () => ({}));vi.mock('@/services/agent', () => ({+ AVAILABLE_AGENTS_CONTEXT_QUERY_LIMIT: 12,agentService: { queryAgents: vi.fn() },}));beforeEach(() => {- useAgentStore.setState({ agentDocumentsMap: {}, availableAgents: undefined } as any);+ useAgentStore.setState({+ agentDocumentsMap: {},+ availableAgents: undefined,+ availableAgentsStale: false,+ } as any);useToolStore.setState({composioServers: [],installedPlugins: [],@@ -52,6 +57,17 @@ describe('createBrowserContextFactProviders', () => {expect(agentService.queryAgents).toHaveBeenCalledWith({ limit: 12 });});+ it('reads a fresh agent list once the agents changed', async () => {+ const providers = createBrowserContextFactProviders();+ vi.mocked(agentService.queryAgents).mockResolvedValue([{ id: 'agent-new' }] as any);++ useAgentStore.setState({ availableAgents: [{ id: 'agent-1' }] } as any);+ useAgentStore.getState().invalidateAvailableAgents();++ await expect(providers.listRecentAgents!(12)).resolves.toEqual([{ id: 'agent-new' }]);+ expect(agentService.queryAgents).toHaveBeenCalledTimes(1);+ });+it('treats only active Composio connections and every installed LobeHub skill provider as connected', async () => {useToolStore.setState({composioServers: [diff --git a/src/services/chat/mecha/contextFactProviders.ts b/src/services/chat/mecha/contextFactProviders.tsindex 56aca85ade1..e0ac245f3c8 100644--- a/src/services/chat/mecha/contextFactProviders.ts+++ b/src/services/chat/mecha/contextFactProviders.ts@@ -4,7 +4,6 @@ import { type AgentShareVisitorContext, getActivePluginIds } from '@lobechat/typimport { getActiveWorkspaceSlug } from '@/business/client/hooks/useActiveWorkspaceSlug';import { lambdaClient } from '@/libs/trpc/client';-import { agentService } from '@/services/agent';import { messageService } from '@/services/message';import { notebookService } from '@/services/notebook';import { sandboxStorageService } from '@/services/sandboxStorage';@@ -214,9 +213,9 @@ export const createBrowserContextFactProviders = ({name: provider.name,})),- // The prefetched list is reused when present so sending never waits on it.- listRecentAgents: async (limit) =>- getAgentStoreState().availableAgents ?? (await agentService.queryAgents({ limit })),+ // The local copy is reused when present so sending never waits on it; after+ // the agents change it is fetched fresh.+ listRecentAgents: () => getAgentStoreState().getAvailableAgents(),// Non-recommended builtins are uninstalled by default; the builder must// not present them as installed and pin unusable identifiers.diff --git a/src/store/agent/selectors/selectors.ts b/src/store/agent/selectors/selectors.tsindex 2f991f35cc4..cb4ff4845e0 100644--- a/src/store/agent/selectors/selectors.ts+++ b/src/store/agent/selectors/selectors.ts@@ -374,6 +374,16 @@ const currentAgentExecutionTarget = (s: AgentStoreState) =>const getAgentDocumentsById = (agentId: string) => (s: AgentStoreState) =>s.agentDocumentsMap[agentId];+/** The agent a user-chosen slug names, as known locally (persisted copy first). */+const getAgentIdBySlug = (slug?: string | null) => (s: AgentStoreState) =>+ slug ? s.agentSlugIdMap[slug] : undefined;++/** The server confirmed the slug's agent in this session (not only the persisted copy). */+const isAgentSlugConfirmed = (slug?: string | null) => (s: AgentStoreState) =>+ !!slug && !!s.agentSlugIdMap[slug] && s.agentSlugIdReplica.entries[slug]?.source === 'server';++const heteroServerDefaultCapability = (s: AgentStoreState) => s.heteroServerDefaultCapability;+export const agentSelectors = {currentAgentExecutionTarget,currentAgentHeterogeneousProviderType,@@ -406,6 +416,9 @@ export const agentSelectors = {displayableAgentPlugins,getAgentConfigById,getAgentDocumentsById,+ getAgentIdBySlug,+ heteroServerDefaultCapability,+ isAgentSlugConfirmed,getAgentFullBodyArtworkById,getAgentMetaById,getAgentProfileById,diff --git a/src/store/agent/slices/agent/action.test.ts b/src/store/agent/slices/agent/action.test.tsindex e148abfcc7b..a8e4d17a16d 100644--- a/src/store/agent/slices/agent/action.test.ts+++ b/src/store/agent/slices/agent/action.test.ts@@ -193,7 +193,7 @@ describe('AgentSlice Actions', () => {await result.current.createAgent({ config: { title: 'New Agent' } });});- expect(result.current.availableAgents).toBeUndefined();+ expect(result.current.availableAgentsStale).toBe(true);});it('should seed a personal name matching the user language', async () => {@@ -432,7 +432,7 @@ describe('AgentSlice Actions', () => {});describe('invalidateAvailableAgents', () => {- it('should clear cached available agents', () => {+ it('should stop trusting cached available agents', () => {const { result } = renderHook(() => useAgentStore());act(() => {@@ -454,7 +454,7 @@ describe('AgentSlice Actions', () => {result.current.invalidateAvailableAgents();});- expect(result.current.availableAgents).toBeUndefined();+ expect(result.current.availableAgentsStale).toBe(true);});});@@ -1275,7 +1275,7 @@ describe('AgentSlice Actions', () => {description: 'New Desc',title: 'New Title',});- expect(result.current.availableAgents).toBeUndefined();+ expect(result.current.availableAgentsStale).toBe(true);});it('rolls back and rethrows when an optimistic projection owns the failure UI', async () => {diff --git a/src/store/agent/slices/agent/action.ts b/src/store/agent/slices/agent/action.tsindex fc8c4e24c10..781de1f117e 100644--- a/src/store/agent/slices/agent/action.ts+++ b/src/store/agent/slices/agent/action.ts@@ -10,20 +10,19 @@ import { toast } from '@lobehub/ui';import isEqual from 'fast-deep-equal';import { t } from 'i18next';import { produce } from 'immer';-import type { SWRResponse } from 'swr';import type { PartialDeep } from 'type-fest';import { getActiveWorkspaceId } from '@/business/client/hooks/useActiveWorkspaceId';import { MESSAGE_CANCEL_FLAT } from '@/const/message';import { analyticsClient } from '@/libs/analytics/client';import {+ cacheScope,createReplicaSlice,recordLens,+ type ReplicaLens,type ReplicaSyncResult,revalidateReplica,} from '@/libs/replica';-import { mutate, useClientDataSWR, useClientDataSWRWithSync } from '@/libs/swr';-import { agentConfigKeys } from '@/libs/swr/keys';import { getCacheScope } from '@/libs/swr/useCacheScope';import type { AvailableAgentItem, CreateAgentParams, CreateAgentResult } from '@/services/agent';import { agentService, AVAILABLE_AGENTS_CONTEXT_QUERY_LIMIT } from '@/services/agent';@@ -49,7 +48,15 @@ import { heteroAgentDefaultName } from '../../utils/heteroAgentDefaultName';import { setLocalAgentWorkingDirectory } from '../../utils/localAgentWorkingDirectoryStorage';import { getSidebarAgentNames } from '../../utils/sidebarAgentNames';import type { AgentSliceState, LoadingState, SaveStatus } from './initialState';-import { agentConfigResource } from './projection';+import {+ agentConfigResource,+ agentSlugIdResource,+ AVAILABLE_AGENTS_KEY,+ availableAgentsResource,+ HETERO_SERVER_DEFAULT_CAPABILITY_KEY,+ heteroServerDefaultCapabilityResource,+ type ServerDefaultHeterogeneousCapability,+} from './projection';const AGENT_META_KEYS = ['avatar',@@ -119,6 +126,29 @@ export interface AgentConfigSyncResult extends ReplicaSyncResult {mutate: () => Promise<unknown>;}+const EMPTY_PARAMS = {} as Record<string, never>;++const isSlugConfirmed = (state: AgentStore, slug: string) =>+ !!state.agentSlugIdMap[slug] && state.agentSlugIdReplica.entries[slug]?.source === 'server';++/**+ * Several surfaces read the same one-entry replica (every open conversation, the+ * profile editor and the model bar): one request answers all of them, while a+ * write, a focus or a manual retry still refetches.+ */+const SHARED_READ_DEDUPING_INTERVAL = 10_000;++/** A store field that holds the whole value of a single-entry replica. */+const singleValueLens = <T>(+ field: keyof AgentStore & string,+ key: string,+): ReplicaLens<AgentStore, T> => ({+ clear: () => ({ [field]: undefined }) as Partial<AgentStore>,+ get: (state, entryKey) => (entryKey === key ? (state[field] as T | undefined) : undefined),+ keys: (state) => (state[field] === undefined ? [] : [key]),+ set: (_state, _key, data) => ({ [field]: data }) as Partial<AgentStore>,+});+/*** Agent Slice Actions* Handles agent CRUD operations (config/meta updates)@@ -135,6 +165,19 @@ export class AgentSliceActionImpl {readonly #updateAgentConfigControllers = new Map<string, AbortController>();readonly #updateAgentMetaControllers = new Map<string, AbortController>();readonly #config;+ readonly #slugId;+ readonly #available;+ readonly #heteroCapability;+ /** The refresh the chat context is waiting on, shared by concurrent sends of one scope. */+ #availableAgentsRefresh?: { promise: Promise<AvailableAgentItem[]>; scope: string };+ /** Bumped by every invalidation, so a read started before it cannot confirm the list. */+ #availableAgentsGeneration = 0;+ /**+ * Cache scopes whose list changed and is not confirmed yet, with the+ * generation of their latest change. Per scope like the replica data: a fresh+ * read in one identity never vouches for another identity's persisted copy.+ */+ readonly #staleAvailableAgentScopes = new Map<string, number>();constructor(set: Setter, get: () => AgentStore, _api?: unknown) {void _api;@@ -168,6 +211,39 @@ export class AgentSliceActionImpl {stateKey: 'agentConfigReplica',view: recordLens<AgentStore, PartialDeep<AgentItem>>('agentMap'),});+ this.#slugId = createReplicaSlice(agentSlugIdResource, {+ actionPrefix: 'agentSlugId',+ fetcher: ({ slug }) => agentService.resolveAgentIdBySlug(slug),+ get,+ // No visible agent owns the slug (anymore): drop the entry and its+ // persisted row, so the route stops painting the agent it used to name.+ isMissing: (agentId) => !agentId,+ merge: (incoming, confirmed) => (!incoming || incoming === confirmed ? undefined : incoming),+ set,+ stateKey: 'agentSlugIdReplica',+ view: recordLens<AgentStore, string>('agentSlugIdMap'),+ });+ this.#available = createReplicaSlice(availableAgentsResource, {+ actionPrefix: 'availableAgents',+ fetcher: () => agentService.queryAgents({ limit: AVAILABLE_AGENTS_CONTEXT_QUERY_LIMIT }),+ get,+ merge: (incoming, confirmed) => (isEqual(incoming, confirmed) ? undefined : incoming),+ set,+ stateKey: 'availableAgentsReplica',+ view: singleValueLens<AvailableAgentItem[]>('availableAgents', AVAILABLE_AGENTS_KEY),+ });+ this.#heteroCapability = createReplicaSlice(heteroServerDefaultCapabilityResource, {+ actionPrefix: 'heteroServerDefaultCapability',+ fetcher: () => aiAgentService.getServerDefaultHeterogeneousCapability(),+ get,+ merge: (incoming, confirmed) => (isEqual(incoming, confirmed) ? undefined : incoming),+ set,+ stateKey: 'heteroServerDefaultCapabilityReplica',+ view: singleValueLens<ServerDefaultHeterogeneousCapability>(+ 'heteroServerDefaultCapability',+ HETERO_SERVER_DEFAULT_CAPABILITY_KEY,+ ),+ });}/** Confirmed, persisted value of an agent's config. */@@ -518,10 +594,75 @@ export class AgentSliceActionImpl {return this.#toAgentConfigSyncResult(sync, agentId);};- useFetchServerDefaultHeterogeneousCapability = (enabled: boolean) =>- useClientDataSWR(enabled ? agentConfigKeys.serverDefaultHeterogeneousCapability() : null, () =>- aiAgentService.getServerDefaultHeterogeneousCapability(),- );+ /**+ * Fetch orchestration only; read the value through+ * `agentSelectors.heteroServerDefaultCapability`.+ */+ useFetchServerDefaultHeterogeneousCapability = (enabled: boolean): ReplicaSyncResult =>+ this.#heteroCapability.useSync(enabled ? EMPTY_PARAMS : null, {+ dedupingInterval: SHARED_READ_DEDUPING_INTERVAL,+ });++ /**+ * Resolve a user-chosen `/agent/<slug>` to its agent id. Fetch orchestration+ * only: read the id through `agentSelectors.getAgentIdBySlug` (the persisted+ * copy paints first) and wait for `agentSelectors.isAgentSlugConfirmed`+ * before redirecting to it — a slug can move to another agent between sessions.+ */+ useResolveAgentSlug = (slug: string | null | undefined): ReplicaSyncResult =>+ this.#slugId.useSync(slug ? { slug } : null, { revalidateOnFocus: false });++ /**+ * Seed a slug's persisted `slug → id` from the route loader, before the+ * route commits, so the first frame already knows which agent it shows.+ */+ preHydrateAgentSlug = async (slug: string): Promise<string | undefined> => {+ const scope = cacheScope.get();+ this.#slugId.ensureScope(scope);+ await this.#slugId.hydrate({ slug }, scope);++ return this.#get().agentSlugIdMap[slug];+ };++ /**+ * An agent's slug was renamed: the old slug no longer names it and the new+ * one does. Confirmed by the rename response, so no lookup is needed.+ */+ internal_confirmAgentSlug = (+ agentId: string,+ slug: string,+ {+ previousSlug,+ scope = cacheScope.get(),+ }: {+ /** The slug the agent had before the rename; its persisted row may not be loaded. */+ previousSlug?: string;+ /** The scope the rename was sent from: a response landing after a switch stays there. */+ scope?: string;+ } = {},+ ): void => {+ const staleSlugs = new Set<string>(previousSlug ? [previousSlug] : []);+ if (scope === cacheScope.get()) {+ for (const [cachedSlug, cachedAgentId] of Object.entries(this.#get().agentSlugIdMap)) {+ if (cachedAgentId === agentId) staleSlugs.add(cachedSlug);+ }+ }+ staleSlugs.delete(slug);+ // `remove` also drops the persisted row of a slug that is not loaded.+ for (const staleSlug of staleSlugs) void this.#slugId.remove(staleSlug, scope);+ // Dropped by the engine when `scope` is no longer the active one.+ this.#slugId.replace({ slug }, agentId, scope);+ };++ /**+ * The server's answer for a slug, joining the route's lookup when it is in+ * flight. Resolves `undefined` when no visible agent owns the slug.+ */+ confirmAgentSlugTarget = async (slug: string): Promise<string | undefined> => {+ if (isSlugConfirmed(this.#get(), slug)) return this.#get().agentSlugIdMap[slug];+ const { data } = await this.#slugId.fetch({ slug });+ return data ?? undefined;+ };/*** Re-trigger the agent config fetch after a failure. Clears the recorded@@ -604,22 +745,72 @@ export class AgentSliceActionImpl {return this.#toAgentConfigSyncResult(sync, agentId);};- useFetchAvailableAgents = (enabled: boolean): SWRResponse<AvailableAgentItem[]> => {- return useClientDataSWRWithSync<AvailableAgentItem[]>(- enabled ? agentConfigKeys.available() : null,- () => agentService.queryAgents({ limit: AVAILABLE_AGENTS_CONTEXT_QUERY_LIMIT }),- {- onData: (data) => {- this.#set({ availableAgents: data }, false, 'useFetchAvailableAgents');- },- revalidateOnFocus: false,- },- );- };+ /** Fetch orchestration only; read the list from `availableAgents`. */+ useFetchAvailableAgents = (enabled: boolean): ReplicaSyncResult =>+ this.#available.useSync(enabled ? EMPTY_PARAMS : null, {+ dedupingInterval: SHARED_READ_DEDUPING_INTERVAL,+ revalidateOnFocus: false,+ });+ /**+ * The agents changed (create / delete / sidebar refresh). Mounted+ * conversations refetch now; until a fresh list is confirmed, the chat+ * context does not trust the copy it holds.+ */invalidateAvailableAgents = (): void => {- this.#set({ availableAgents: undefined }, false, 'invalidateAvailableAgents');- void mutate(agentConfigKeys.available());+ this.#availableAgentsGeneration += 1;+ this.#staleAvailableAgentScopes.set(cacheScope.get(), this.#availableAgentsGeneration);+ // A read already in flight may hold the pre-change list: later callers start anew.+ this.#availableAgentsRefresh = undefined;+ this.#set({ availableAgentsStale: true }, false, 'invalidateAvailableAgents');+ void this.#available.revalidate(AVAILABLE_AGENTS_KEY);+ };++ /**+ * The list the chat context delegates to. The local copy answers at once;+ * after an invalidation (or with nothing local) it is fetched fresh, joining+ * a request already in flight when there is no invalidation to honour.+ */+ getAvailableAgents = async (): Promise<AvailableAgentItem[]> => {+ const scope = cacheScope.get();+ const current = this.#get().availableAgents;+ const stale = this.#staleAvailableAgentScopes.has(scope);+ if (current && !stale) return current;++ // Concurrent sends of one identity share one refresh; the list stays stale+ // until it lands. A send of another identity never joins it: its raw answer+ // would hand that identity's agents to this one.+ let refresh = this.#availableAgentsRefresh;+ if (refresh?.scope !== scope) {+ const generation = this.#availableAgentsGeneration;+ const promise = this.#available+ .fetch(EMPTY_PARAMS, { fresh: stale, scope })+ .then(({ data }) => {+ // Only a read started after this identity's latest change confirms+ // its list; the store flag mirrors the identity still active.+ const changedAt = this.#staleAvailableAgentScopes.get(scope);+ if (changedAt !== undefined && changedAt <= generation)+ this.#staleAvailableAgentScopes.delete(scope);+ const activeStale = this.#staleAvailableAgentScopes.has(cacheScope.get());+ if (scope === cacheScope.get() && this.#get().availableAgentsStale !== activeStale)+ this.#set({ availableAgentsStale: activeStale }, false, 'getAvailableAgents');+ return data;+ })+ .finally(() => {+ if (this.#availableAgentsRefresh?.promise === promise)+ this.#availableAgentsRefresh = undefined;+ });+ refresh = { promise, scope };+ this.#availableAgentsRefresh = refresh;+ }++ try {+ return await refresh.promise;+ } catch (error) {+ // A failed refresh keeps the last confirmed list usable (and still stale).+ if (current) return current;+ throw error;+ }};ensureAgentDocuments = async (diff --git a/src/store/agent/slices/agent/initialState.ts b/src/store/agent/slices/agent/initialState.tsindex 221c228bfd9..f669feef541 100644--- a/src/store/agent/slices/agent/initialState.ts+++ b/src/store/agent/slices/agent/initialState.ts@@ -8,6 +8,7 @@ import { type AgentItem } from '@/types/agent';import { type MetaData } from '@/types/meta';import { readAllLocalAgentWorkingDirectories } from '../../utils/localAgentWorkingDirectoryStorage';+import type { ServerDefaultHeterogeneousCapability } from './projection';export type LoadingState = Record<Partial<keyof MetaData> | string, boolean>;export type SaveStatus = 'idle' | 'saving' | 'saved';@@ -34,7 +35,23 @@ export interface AgentSliceState {*/agentNotFoundMap: Record<string, boolean>;agentSettingInstance?: AgentSettingsInstance | null;+ /** Replica view of user-chosen slugs: `slug → agent id`. */+ agentSlugIdMap: Record<string, string>;+ /** Replica bookkeeping of `agentSlugIdMap`. */+ agentSlugIdReplica: ReplicaState<string>;+ /** Replica view of the recently updated agents the chat context can delegate to. */availableAgents?: AvailableAgentItem[];+ /** Replica bookkeeping of `availableAgents`. */+ availableAgentsReplica: ReplicaState<AvailableAgentItem[]>;+ /**+ * The agents changed (create / delete / sidebar refresh) since+ * `availableAgents` was confirmed: the chat context reads a fresh list.+ */+ availableAgentsStale: boolean;+ /** Replica view of the server-default heterogeneous capability. */+ heteroServerDefaultCapability?: ServerDefaultHeterogeneousCapability;+ /** Replica bookkeeping of `heteroServerDefaultCapability`. */+ heteroServerDefaultCapabilityReplica: ReplicaState<ServerDefaultHeterogeneousCapability>;/*** Whether the agent panel is pinned (UI state)*/@@ -83,7 +100,13 @@ export const initialAgentSliceState: AgentSliceState = {agentDocumentsMap: {},agentMap: {},agentNotFoundMap: {},+ agentSlugIdMap: {},+ agentSlugIdReplica: createReplicaState(),availableAgents: undefined,+ availableAgentsReplica: createReplicaState(),+ availableAgentsStale: false,+ heteroServerDefaultCapability: undefined,+ heteroServerDefaultCapabilityReplica: createReplicaState(),isAgentPinned: false,lastUpdatedTime: null,localAgentWorkingDirectoryMap: readAllLocalAgentWorkingDirectories(),diff --git a/src/store/agent/slices/agent/persistedReads.test.ts b/src/store/agent/slices/agent/persistedReads.test.tsnew file mode 100644index 00000000000..307efa31422--- /dev/null+++ b/src/store/agent/slices/agent/persistedReads.test.ts@@ -0,0 +1,128 @@+/**+ * @vitest-environment happy-dom+ *+ * A reload paints the agent store's remaining server reads from the local copy+ * while the network is still out: the available-agents list and the+ * server-default heterogeneous capability. Seeded through the storage rows the+ * replicas read (`replica:<name>:v<version>`), so the hooks under test are the+ * ones the app has always mounted.+ */+import { randomUUID } from 'node:crypto';++import { act, cleanup, renderHook, waitFor } from '@testing-library/react';+import type { PropsWithChildren } from 'react';+import { createElement, useEffect } from 'react';+import { SWRConfig, useSWRConfig } from 'swr';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';++import {+ IndexedDBQueryProjectionStorage,+ LocalStorageQueryProjectionStorage,+} from '@/libs/queryProjectionStorage';+import { cacheScope } from '@/libs/replica';+import { setScopedMutate } from '@/libs/swr/mutate';+import { agentService } from '@/services/agent';+import { aiAgentService } from '@/services/aiAgent';++import { useAgentStore } from '../../store';+import { initialAgentSliceState } from './initialState';++vi.mock('@/services/agent', () => ({+ AVAILABLE_AGENTS_CONTEXT_QUERY_LIMIT: 12,+ agentService: { queryAgents: vi.fn() },+}));++vi.mock('@/services/aiAgent', () => ({+ aiAgentService: { getServerDefaultHeterogeneousCapability: vi.fn() },+}));++const MutateBridge = () => {+ const { mutate } = useSWRConfig();+ useEffect(() => setScopedMutate(mutate), [mutate]);+ return null;+};++const wrapper = ({ children }: PropsWithChildren) =>+ createElement(+ SWRConfig,+ { value: { dedupingInterval: 0, provider: () => new Map() } },+ createElement(MutateBridge),+ children,+ );++/** The network never answers: whatever paints came from the device. */+const pending = () => new Promise<never>(() => {}) as Promise<any>;++const availableAgentsStorage = new IndexedDBQueryProjectionStorage<unknown>({+ namespace: 'replica:availableAgents:v1',+});+const capabilityStorage = new LocalStorageQueryProjectionStorage<unknown>({+ namespace: 'replica:heteroServerDefaultCapability:v1',+});++const cachedAgents = [+ {+ avatar: null,+ backgroundColor: null,+ description: null,+ id: 'agt_cached',+ name: null,+ title: 'Cached agent',+ },+];++const cachedCapability = {+ agents: ['claude-code'],+ enabled: true,+ model: 'lobehub-default',+ models: { 'claude-code': ['claude-sonnet'] },+};++describe('agent store reads after a reload', () => {+ let scope = '';++ beforeEach(() => {+ scope = `agent-reload-${randomUUID()}:personal`;+ vi.spyOn(cacheScope, 'get').mockImplementation(() => scope);+ vi.spyOn(cacheScope, 'use').mockImplementation(() => scope);+ vi.spyOn(cacheScope, 'canPersist').mockReturnValue(true);+ act(() => useAgentStore.setState(initialAgentSliceState));+ });++ afterEach(async () => {+ cleanup();+ await availableAgentsStorage.remove({ queryKey: 'recent', scope });+ await capabilityStorage.remove({ queryKey: 'default', scope });+ vi.restoreAllMocks();+ });++ it('paints the available agents from the local copy before the network answers', async () => {+ await availableAgentsStorage.set(+ { queryKey: 'recent', scope },+ { data: cachedAgents, updatedAt: 1 },+ );+ vi.mocked(agentService.queryAgents).mockImplementation(pending);++ renderHook(() => useAgentStore.getState().useFetchAvailableAgents(true), { wrapper });++ await waitFor(() => expect(useAgentStore.getState().availableAgents).toEqual(cachedAgents));+ });++ it('paints the server-default capability from the local copy before the network answers', async () => {+ await capabilityStorage.set(+ { queryKey: 'default', scope },+ { data: cachedCapability, updatedAt: 1 },+ );+ vi.mocked(aiAgentService.getServerDefaultHeterogeneousCapability).mockImplementation(pending);++ renderHook(() => useAgentStore.getState().useFetchServerDefaultHeterogeneousCapability(true), {+ wrapper,+ });++ await waitFor(() =>+ expect((useAgentStore.getState() as any).heteroServerDefaultCapability).toEqual(+ cachedCapability,+ ),+ );+ });+});diff --git a/src/store/agent/slices/agent/projection.ts b/src/store/agent/slices/agent/projection.tsindex 4343bfdd0df..1f49e54bca9 100644--- a/src/store/agent/slices/agent/projection.ts+++ b/src/store/agent/slices/agent/projection.ts@@ -1,6 +1,8 @@import type { PartialDeep } from 'type-fest';import { defineReplica } from '@/libs/replica';+import type { AvailableAgentItem } from '@/services/agent';+import type { aiAgentService } from '@/services/aiAgent';import type { AgentItem, LobeAgentConfig } from '@/types/agent';export interface AgentConfigParams {@@ -20,3 +22,60 @@ export const agentConfigResource = defineReplica<name: 'agentConfig',version: 1,});++/** Custom agent slugs whose `slug → id` lookup survives a reload, most recently used first. */+const MAX_PERSISTED_AGENT_SLUGS = 50;++export interface AgentSlugParams {+ /** A user-chosen agent slug (`/agent/<slug>`); builtin slugs resolve elsewhere. */+ slug: string;+}++/**+ * `slug → agent id` for user-chosen slugs, keyed by the slug. The fetch+ * resolves `null` when no agent visible to the viewer owns the slug, which+ * drops the entry. Persisted so a `/agent/<slug>` route paints the agent from+ * the local copy instead of waiting on the lookup; the network still confirms+ * before the route redirects to the id.+ */+export const agentSlugIdResource = defineReplica<AgentSlugParams, string, string | null>({+ key: ({ slug }) => slug,+ name: 'agentSlugId',+ persist: { maxEntries: MAX_PERSISTED_AGENT_SLUGS },+ version: 1,+});++/** The available-agents list is one entry per scope. */+export const AVAILABLE_AGENTS_KEY = 'recent';++/**+ * The most recently updated agents, which the chat context lists as delegation+ * targets. One entry per scope (`availableAgents` is its view).+ */+export const availableAgentsResource = defineReplica<Record<string, never>, AvailableAgentItem[]>({+ key: () => AVAILABLE_AGENTS_KEY,+ name: 'availableAgents',+ version: 1,+});++/** The server-default heterogeneous capability is one entry per scope. */+export const HETERO_SERVER_DEFAULT_CAPABILITY_KEY = 'default';++export type ServerDefaultHeterogeneousCapability = Awaited<+ ReturnType<typeof aiAgentService.getServerDefaultHeterogeneousCapability>+>;++/**+ * Whether the server offers its own models to external agents (and which).+ * Small and slow-changing, so the profile editor and the API-mode model bar+ * paint the last answer while the network confirms.+ */+export const heteroServerDefaultCapabilityResource = defineReplica<+ Record<string, never>,+ ServerDefaultHeterogeneousCapability+>({+ key: () => HETERO_SERVER_DEFAULT_CAPABILITY_KEY,+ name: 'heteroServerDefaultCapability',+ storage: 'localStorage',+ version: 1,+});diff --git a/src/store/agent/slices/agent/replica.test.ts b/src/store/agent/slices/agent/replica.test.tsnew file mode 100644index 00000000000..0cd6c1b06a7--- /dev/null+++ b/src/store/agent/slices/agent/replica.test.ts@@ -0,0 +1,558 @@+/**+ * @vitest-environment happy-dom+ *+ * The agent store's remaining reads are replicas: a custom `/agent/<slug>`+ * lookup, the available-agents list the chat context delegates to, and the+ * server-default heterogeneous capability. Each paints its persisted copy+ * before the network answers, is partitioned by scope, and keeps the last+ * confirmed value when a background refresh fails.+ */+import { randomUUID } from 'node:crypto';++import { act, cleanup, renderHook, waitFor } from '@testing-library/react';+import type { PropsWithChildren } from 'react';+import { createElement, useEffect } from 'react';+import { SWRConfig, useSWRConfig } from 'swr';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';++import { cacheScope } from '@/libs/replica';+import { setScopedMutate } from '@/libs/swr/mutate';+import { agentService } from '@/services/agent';+import { aiAgentService } from '@/services/aiAgent';++import { useAgentStore } from '../../store';+import { initialAgentSliceState } from './initialState';+import {+ agentSlugIdResource,+ availableAgentsResource,+ heteroServerDefaultCapabilityResource,+} from './projection';++vi.mock('@/services/agent', () => ({+ AVAILABLE_AGENTS_CONTEXT_QUERY_LIMIT: 12,+ agentService: {+ queryAgents: vi.fn(),+ resolveAgentIdBySlug: vi.fn(),+ },+}));++vi.mock('@/services/aiAgent', () => ({+ aiAgentService: { getServerDefaultHeterogeneousCapability: vi.fn() },+}));++const MutateBridge = () => {+ const { mutate } = useSWRConfig();+ useEffect(() => setScopedMutate(mutate), [mutate]);+ return null;+};++const wrapper = ({ children }: PropsWithChildren) =>+ createElement(+ SWRConfig,+ { value: { dedupingInterval: 0, provider: () => new Map() } },+ createElement(MutateBridge),+ children,+ );++/** Never-resolving fetch: the first frame can only come from storage. */+const pending = () => new Promise<never>(() => {}) as Promise<any>;++const agentItem = (id: string, title = id) => ({+ avatar: null,+ backgroundColor: null,+ description: null,+ id,+ name: null,+ title,+});++const SLUG_KEY = (slug: string) => agentSlugIdResource.storageKey({ slug });+const AVAILABLE_KEY = availableAgentsResource.storageKey({});+const CAPABILITY_KEY = heteroServerDefaultCapabilityResource.storageKey({});++const enabledCapability = {+ agents: ['claude-code'],+ enabled: true,+ model: 'lobehub-default',+ models: { 'claude-code': ['claude-sonnet'] },+} as any;++describe('agent store replicas', () => {+ const scopes = new Set<string>();+ let scope = '';+ const useScope = (next: string) => {+ scope = next;+ scopes.add(next);+ vi.spyOn(cacheScope, 'get').mockImplementation(() => scope);+ vi.spyOn(cacheScope, 'use').mockImplementation(() => scope);+ vi.spyOn(cacheScope, 'canPersist').mockReturnValue(true);+ };++ beforeEach(() => {+ useScope(`agent-store-user-${randomUUID()}:personal`);+ act(() => useAgentStore.setState(initialAgentSliceState));+ vi.mocked(agentService.queryAgents).mockReset();+ vi.mocked(agentService.resolveAgentIdBySlug).mockReset();+ vi.mocked(aiAgentService.getServerDefaultHeterogeneousCapability).mockReset();+ });++ afterEach(async () => {+ cleanup();+ await Promise.all(+ [...scopes].flatMap((value) => [+ agentSlugIdResource.storage!.remove({ queryKey: SLUG_KEY('my-writer'), scope: value }),+ agentSlugIdResource.storage!.remove({ queryKey: SLUG_KEY('new-writer'), scope: value }),+ availableAgentsResource.storage!.remove({ queryKey: AVAILABLE_KEY, scope: value }),+ heteroServerDefaultCapabilityResource.storage!.remove({+ queryKey: CAPABILITY_KEY,+ scope: value,+ }),+ ]),+ );+ scopes.clear();+ vi.restoreAllMocks();+ });++ describe('agent slug', () => {+ it('paints the persisted slug → id, then confirms it from the server', async () => {+ await agentSlugIdResource.storage!.set(+ { queryKey: SLUG_KEY('my-writer'), scope },+ { data: 'agt_writer', updatedAt: 1 },+ );+ let resolveLookup!: (value: string | null) => void;+ vi.mocked(agentService.resolveAgentIdBySlug).mockImplementation(+ () => new Promise((resolve) => (resolveLookup = resolve)),+ );++ renderHook(() => useAgentStore.getState().useResolveAgentSlug('my-writer'), { wrapper });++ await waitFor(() =>+ expect(useAgentStore.getState().agentSlugIdMap['my-writer']).toBe('agt_writer'),+ );+ // Painted from storage only: the redirect must still wait for the server.+ expect(useAgentStore.getState().agentSlugIdReplica.entries['my-writer'].source).toBe(+ 'storage',+ );++ await act(async () => resolveLookup('agt_writer'));+ await waitFor(() =>+ expect(useAgentStore.getState().agentSlugIdReplica.entries['my-writer'].source).toBe(+ 'server',+ ),+ );+ expect(agentService.resolveAgentIdBySlug).toHaveBeenCalledWith('my-writer');+ });++ it('follows a slug that moved to another agent between sessions', async () => {+ await agentSlugIdResource.storage!.set(+ { queryKey: SLUG_KEY('my-writer'), scope },+ { data: 'agt_old', updatedAt: 1 },+ );+ vi.mocked(agentService.resolveAgentIdBySlug).mockResolvedValue('agt_new');++ renderHook(() => useAgentStore.getState().useResolveAgentSlug('my-writer'), { wrapper });++ await waitFor(() =>+ expect(useAgentStore.getState().agentSlugIdMap['my-writer']).toBe('agt_new'),+ );+ await waitFor(async () =>+ expect(+ (await agentSlugIdResource.storage!.get({ queryKey: SLUG_KEY('my-writer'), scope }))+ ?.data,+ ).toBe('agt_new'),+ );+ });++ it('drops a slug no agent owns anymore from memory and storage', async () => {+ await agentSlugIdResource.storage!.set(+ { queryKey: SLUG_KEY('my-writer'), scope },+ { data: 'agt_writer', updatedAt: 1 },+ );+ vi.mocked(agentService.resolveAgentIdBySlug).mockResolvedValue(null);++ renderHook(() => useAgentStore.getState().useResolveAgentSlug('my-writer'), { wrapper });++ await waitFor(() => expect(agentService.resolveAgentIdBySlug).toHaveBeenCalled());+ await waitFor(() =>+ expect(useAgentStore.getState().agentSlugIdMap['my-writer']).toBeUndefined(),+ );+ await waitFor(async () =>+ expect(+ await agentSlugIdResource.storage!.get({ queryKey: SLUG_KEY('my-writer'), scope }),+ ).toBeUndefined(),+ );+ });++ it('keeps the confirmed id when a background lookup fails', async () => {+ vi.mocked(agentService.resolveAgentIdBySlug).mockResolvedValueOnce('agt_writer');+ const sync = renderHook(() => useAgentStore.getState().useResolveAgentSlug('my-writer'), {+ wrapper,+ });+ await waitFor(() =>+ expect(useAgentStore.getState().agentSlugIdMap['my-writer']).toBe('agt_writer'),+ );++ vi.mocked(agentService.resolveAgentIdBySlug).mockRejectedValue(new Error('offline'));+ await act(async () => {+ await sync.result.current.revalidate();+ });++ expect(useAgentStore.getState().agentSlugIdMap['my-writer']).toBe('agt_writer');+ });++ it('never shows the previous identity’s slug after a scope switch', async () => {+ await agentSlugIdResource.storage!.set(+ { queryKey: SLUG_KEY('my-writer'), scope },+ { data: 'agt_a', updatedAt: 1 },+ );+ vi.mocked(agentService.resolveAgentIdBySlug).mockImplementation(pending);+ const sync = renderHook(() => useAgentStore.getState().useResolveAgentSlug('my-writer'), {+ wrapper,+ });+ await waitFor(() =>+ expect(useAgentStore.getState().agentSlugIdMap['my-writer']).toBe('agt_a'),+ );++ useScope(`agent-store-user-${randomUUID()}:personal`);+ sync.rerender();++ await waitFor(() =>+ expect(useAgentStore.getState().agentSlugIdMap['my-writer']).toBeUndefined(),+ );+ });++ it('pre-hydrates the persisted slug for a route loader without the network', async () => {+ await agentSlugIdResource.storage!.set(+ { queryKey: SLUG_KEY('my-writer'), scope },+ { data: 'agt_writer', updatedAt: 1 },+ );++ let agentId: string | undefined;+ await act(async () => {+ agentId = await useAgentStore.getState().preHydrateAgentSlug('my-writer');+ });++ expect(agentId).toBe('agt_writer');+ expect(agentService.resolveAgentIdBySlug).not.toHaveBeenCalled();+ });++ it('moves the local copy with a slug rename, so the old slug stops naming the agent', async () => {+ await agentSlugIdResource.storage!.set(+ { queryKey: SLUG_KEY('my-writer'), scope },+ { data: 'agt_writer', updatedAt: 1 },+ );+ await act(async () => {+ await useAgentStore.getState().preHydrateAgentSlug('my-writer');+ });++ act(() => useAgentStore.getState().internal_confirmAgentSlug('agt_writer', 'new-writer'));++ expect(useAgentStore.getState().agentSlugIdMap).toEqual({ 'new-writer': 'agt_writer' });+ await waitFor(async () =>+ expect(+ await agentSlugIdResource.storage!.get({ queryKey: SLUG_KEY('my-writer'), scope }),+ ).toBeUndefined(),+ );+ await waitFor(async () =>+ expect(+ (await agentSlugIdResource.storage!.get({ queryKey: SLUG_KEY('new-writer'), scope }))+ ?.data,+ ).toBe('agt_writer'),+ );+ });++ // Codex P2: after a reload the old slug may sit only in storage.+ it('drops the previous slug’s persisted row on a rename even when it is not loaded', async () => {+ await agentSlugIdResource.storage!.set(+ { queryKey: SLUG_KEY('my-writer'), scope },+ { data: 'agt_writer', updatedAt: 1 },+ );++ act(() =>+ useAgentStore+ .getState()+ .internal_confirmAgentSlug('agt_writer', 'new-writer', { previousSlug: 'my-writer' }),+ );++ await waitFor(async () =>+ expect(+ await agentSlugIdResource.storage!.get({ queryKey: SLUG_KEY('my-writer'), scope }),+ ).toBeUndefined(),+ );+ let hydrated: string | undefined;+ await act(async () => {+ hydrated = await useAgentStore.getState().preHydrateAgentSlug('my-writer');+ });+ expect(hydrated).toBeUndefined();+ });++ // Codex P2: a rename answered after a workspace switch belongs to the old scope.+ it('never writes a rename confirmed after a scope switch into the new scope', async () => {+ const renamedIn = scope;+ useScope(`agent-store-user-${randomUUID()}:personal`);++ act(() =>+ useAgentStore+ .getState()+ .internal_confirmAgentSlug('agt_writer', 'new-writer', { scope: renamedIn }),+ );++ expect(useAgentStore.getState().agentSlugIdMap['new-writer']).toBeUndefined();+ await new Promise((resolve) => setTimeout(resolve, 20));+ expect(+ await agentSlugIdResource.storage!.get({ queryKey: SLUG_KEY('new-writer'), scope }),+ ).toBeUndefined();+ });+ });++ describe('available agents', () => {+ it('paints the persisted list before the network answers, then replaces it', async () => {+ await availableAgentsResource.storage!.set(+ { queryKey: AVAILABLE_KEY, scope },+ { data: [agentItem('agt_cached')], updatedAt: 1 },+ );+ let resolveList!: (value: any) => void;+ vi.mocked(agentService.queryAgents).mockImplementation(+ () => new Promise((resolve) => (resolveList = resolve)),+ );++ renderHook(() => useAgentStore.getState().useFetchAvailableAgents(true), { wrapper });++ await waitFor(() =>+ expect(useAgentStore.getState().availableAgents).toEqual([agentItem('agt_cached')]),+ );++ await act(async () => resolveList([agentItem('agt_fresh')]));+ await waitFor(() =>+ expect(useAgentStore.getState().availableAgents).toEqual([agentItem('agt_fresh')]),+ );+ expect(agentService.queryAgents).toHaveBeenCalledWith({ limit: 12 });+ });++ it('sends one request for every conversation that mounts the sync', async () => {+ vi.mocked(agentService.queryAgents).mockResolvedValue([agentItem('agt_1')]);++ // One app-wide SWR cache whose default window is 0 (`useClientDataSWR`):+ // the shared window has to come from the sync itself.+ const cache = new Map();+ const sharedWrapper = ({ children }: PropsWithChildren) =>+ createElement(+ SWRConfig,+ { value: { dedupingInterval: 0, provider: () => cache } },+ createElement(MutateBridge),+ children,+ );++ renderHook(+ () => {+ useAgentStore.getState().useFetchAvailableAgents(true);+ useAgentStore.getState().useFetchAvailableAgents(true);+ },+ { wrapper: sharedWrapper },+ );+ await waitFor(() =>+ expect(useAgentStore.getState().availableAgents).toEqual([agentItem('agt_1')]),+ );+ // A conversation opened right after reuses the answer instead of asking again.+ renderHook(() => useAgentStore.getState().useFetchAvailableAgents(true), {+ wrapper: sharedWrapper,+ });+ await act(async () => {+ await new Promise((resolve) => setTimeout(resolve, 20));+ });++ expect(agentService.queryAgents).toHaveBeenCalledTimes(1);+ });++ it('lets the chat context reuse the confirmed list until the agents change', async () => {+ act(() => useAgentStore.setState({ availableAgents: [agentItem('agt_1')] }));++ await expect(useAgentStore.getState().getAvailableAgents()).resolves.toEqual([+ agentItem('agt_1'),+ ]);+ expect(agentService.queryAgents).not.toHaveBeenCalled();++ vi.mocked(agentService.queryAgents).mockResolvedValue([agentItem('agt_2')]);+ act(() => useAgentStore.getState().invalidateAvailableAgents());+ let fresh: unknown;+ await act(async () => {+ fresh = await useAgentStore.getState().getAvailableAgents();+ });++ expect(fresh).toEqual([agentItem('agt_2')]);+ expect(agentService.queryAgents).toHaveBeenCalledTimes(1);+ expect(useAgentStore.getState().availableAgentsStale).toBe(false);+ });++ it('keeps the last list for the chat context when the refresh after a change fails', async () => {+ act(() => useAgentStore.setState({ availableAgents: [agentItem('agt_1')] }));+ act(() => useAgentStore.getState().invalidateAvailableAgents());+ vi.mocked(agentService.queryAgents).mockRejectedValueOnce(new Error('offline'));++ let listed: unknown;+ await act(async () => {+ listed = await useAgentStore.getState().getAvailableAgents();+ });++ expect(listed).toEqual([agentItem('agt_1')]);+ // Still untrusted: the next send tries a fresh list again.+ expect(useAgentStore.getState().availableAgentsStale).toBe(true);+ });++ // Codex P2: a second send while the fresh read is in flight must not get the stale list.+ it('shares one fresh read between concurrent sends and stays stale until it lands', async () => {+ act(() => useAgentStore.setState({ availableAgents: [agentItem('agt_old')] }));+ act(() => useAgentStore.getState().invalidateAvailableAgents());+ let resolveList!: (value: any) => void;+ vi.mocked(agentService.queryAgents).mockImplementation(+ () => new Promise((resolve) => (resolveList = resolve)),+ );++ const first = useAgentStore.getState().getAvailableAgents();+ const second = useAgentStore.getState().getAvailableAgents();+ expect(useAgentStore.getState().availableAgentsStale).toBe(true);++ await act(async () => resolveList([agentItem('agt_new')]));++ await expect(first).resolves.toEqual([agentItem('agt_new')]);+ await expect(second).resolves.toEqual([agentItem('agt_new')]);+ expect(agentService.queryAgents).toHaveBeenCalledTimes(1);+ expect(useAgentStore.getState().availableAgentsStale).toBe(false);+ });++ it('does not let a read from before a change confirm the list', async () => {+ act(() => useAgentStore.setState({ availableAgents: [agentItem('agt_old')] }));+ act(() => useAgentStore.getState().invalidateAvailableAgents());+ const answers: ((value: any) => void)[] = [];+ vi.mocked(agentService.queryAgents).mockImplementation(+ () => new Promise((resolve) => answers.push(resolve)),+ );++ const before = useAgentStore.getState().getAvailableAgents();+ // Another agent is created while that read is in flight.+ act(() => useAgentStore.getState().invalidateAvailableAgents());+ const after = useAgentStore.getState().getAvailableAgents();++ await act(async () => answers[0]([agentItem('agt_mid')]));+ await before;+ expect(useAgentStore.getState().availableAgentsStale).toBe(true);++ await act(async () => answers[1]([agentItem('agt_new')]));+ await expect(after).resolves.toEqual([agentItem('agt_new')]);+ expect(useAgentStore.getState().availableAgentsStale).toBe(false);+ });++ // Codex P1: a refresh started under identity A must never answer a send of identity B.+ it('never hands a refresh started in another identity to this one', async () => {+ act(() => useAgentStore.getState().invalidateAvailableAgents());+ const answers: ((value: any) => void)[] = [];+ vi.mocked(agentService.queryAgents).mockImplementation(+ () => new Promise((resolve) => answers.push(resolve)),+ );++ const inA = useAgentStore.getState().getAvailableAgents();+ useScope(`agent-store-user-${randomUUID()}:personal`);+ const inB = useAgentStore.getState().getAvailableAgents();++ expect(agentService.queryAgents).toHaveBeenCalledTimes(2);+ await act(async () => answers[0]([agentItem('agt_private_to_a')]));+ await act(async () => answers[1]([agentItem('agt_of_b')]));++ await expect(inB).resolves.toEqual([agentItem('agt_of_b')]);+ await inA.catch(() => undefined);+ });++ // Codex P2: a fresh read in identity B must not vouch for identity A's persisted list.+ it('keeps a change in one identity stale until that identity confirms it', async () => {+ const scopeA = scope;+ act(() => useAgentStore.setState({ availableAgents: [agentItem('agt_deleted')] }));+ act(() => useAgentStore.getState().invalidateAvailableAgents());++ useScope(`agent-store-user-${randomUUID()}:personal`);+ vi.mocked(agentService.queryAgents).mockResolvedValueOnce([agentItem('agt_of_b')]);+ act(() => useAgentStore.setState({ availableAgents: undefined }));+ await act(async () => {+ await useAgentStore.getState().getAvailableAgents();+ });++ // Back in A, its pre-change persisted copy is restored.+ useScope(scopeA);+ act(() => useAgentStore.setState({ availableAgents: [agentItem('agt_deleted')] }));+ vi.mocked(agentService.queryAgents).mockResolvedValueOnce([agentItem('agt_kept')]);+ let listed: unknown;+ await act(async () => {+ listed = await useAgentStore.getState().getAvailableAgents();+ });++ expect(listed).toEqual([agentItem('agt_kept')]);+ expect(agentService.queryAgents).toHaveBeenCalledTimes(2);+ });++ it('keeps the last list when a background refresh fails', async () => {+ vi.mocked(agentService.queryAgents).mockResolvedValueOnce([agentItem('agt_1')]);+ const sync = renderHook(() => useAgentStore.getState().useFetchAvailableAgents(true), {+ wrapper,+ });+ await waitFor(() =>+ expect(useAgentStore.getState().availableAgents).toEqual([agentItem('agt_1')]),+ );++ vi.mocked(agentService.queryAgents).mockRejectedValue(new Error('offline'));+ await act(async () => {+ await sync.result.current.revalidate();+ });++ expect(useAgentStore.getState().availableAgents).toEqual([agentItem('agt_1')]);+ });+ });++ describe('server-default heterogeneous capability', () => {+ it('paints the persisted capability before the network answers', async () => {+ await heteroServerDefaultCapabilityResource.storage!.set(+ { queryKey: CAPABILITY_KEY, scope },+ { data: enabledCapability, updatedAt: 1 },+ );+ vi.mocked(aiAgentService.getServerDefaultHeterogeneousCapability).mockImplementation(pending);++ renderHook(+ () => useAgentStore.getState().useFetchServerDefaultHeterogeneousCapability(true),+ { wrapper },+ );++ await waitFor(() =>+ expect(useAgentStore.getState().heteroServerDefaultCapability).toEqual(enabledCapability),+ );+ });++ it('keeps the last capability when a background refresh fails', async () => {+ vi.mocked(aiAgentService.getServerDefaultHeterogeneousCapability).mockResolvedValueOnce(+ enabledCapability,+ );+ const sync = renderHook(+ () => useAgentStore.getState().useFetchServerDefaultHeterogeneousCapability(true),+ { wrapper },+ );+ await waitFor(() =>+ expect(useAgentStore.getState().heteroServerDefaultCapability).toEqual(enabledCapability),+ );++ vi.mocked(aiAgentService.getServerDefaultHeterogeneousCapability).mockRejectedValue(+ new Error('offline'),+ );+ await act(async () => {+ await sync.result.current.revalidate();+ });++ expect(useAgentStore.getState().heteroServerDefaultCapability).toEqual(enabledCapability);+ });++ it('does not fetch while no surface needs it', () => {+ renderHook(+ () => useAgentStore.getState().useFetchServerDefaultHeterogeneousCapability(false),+ { wrapper },+ );++ expect(aiAgentService.getServerDefaultHeterogeneousCapability).not.toHaveBeenCalled();+ });+ });+});diff --git a/src/store/home/slices/agentList/selectors.ts b/src/store/home/slices/agentList/selectors.tsindex ffc29ee1773..72573ab20cd 100644--- a/src/store/home/slices/agentList/selectors.ts+++ b/src/store/home/slices/agentList/selectors.ts@@ -1,6 +1,8 @@import { type SidebarAgentItem, type SidebarGroup } from '@/database/repositories/home';import { type HomeStore } from '@/store/home/store';+import { AGENT_LIST_KEY } from './projection';+/*** Get all pinned agents*/@@ -73,6 +75,10 @@ const privateUngroupedAgentsCount = (s: HomeStore): number => s.privateUngrouped*/const isAgentListInit = (s: HomeStore): boolean => s.isAgentListInit;+/** The server confirmed the list in this session (not only the persisted copy). */+const isAgentListConfirmed = (s: HomeStore): boolean =>+ s.isAgentListInit && s.agentListReplica.entries[AGENT_LIST_KEY]?.source === 'server';+/*** Get all agents (pinned + grouped + ungrouped + private)*/@@ -119,6 +125,7 @@ export const homeAgentListSelectors = {getAgentById,hasCustomAgents,hasPrivateAgents,+ isAgentListConfirmed,isAgentListInit,pinnedAgents,privateAgentGroups,