Skip to content

๐Ÿคฏ LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.

โ™ป๏ธ refactor(expertise): move My rules and Self-evolving reads onto @lobechat/replica (#22786)

Arvin Xubbe3a5398c24
diff --git a/src/features/MemoryRules/DetailPanel.tsx b/src/features/MemoryRules/DetailPanel.tsx
index 14492f2b583..03b810a6ac2 100644
--- a/src/features/MemoryRules/DetailPanel.tsx
+++ b/src/features/MemoryRules/DetailPanel.tsx
@@ -45,6 +45,7 @@ import { docsFilePath, docsPagePath } from '@/features/ResourceHome/paths';
import RightPanel from '@/features/RightPanel';
import { buildWorkspaceAwarePath } from '@/features/Workspace/workspaceAwarePath';
import type { RuleGroup, RuleItem, UpdateRuleInput } from '@/services/expertise';
+import { expertiseActions } from '@/store/expertise';
import { DIRECTION_ICON } from './DirectionToggle';
import Field from './Field';
@@ -260,9 +261,9 @@ const RuleDocument = ({
data: sources,
error: sourcesError,
isLoading: sourcesLoading,
- mutate: retrySources,
+ revalidate: retrySources,
} = useRuleSources(rule.id);
- const { data: revisions, mutate: mutateRevisions } = useRuleRevisions(rule.id);
+ const { data: revisions } = useRuleRevisions(rule.id);
const [exception, setException] = useState('');
const [titleDraft, setTitleDraft] = useState(rule.title);
const [busy, setBusy] = useState(false);
@@ -285,7 +286,7 @@ const RuleDocument = ({
setBusy(true);
try {
const saved = await onUpdate(patch);
- if (saved) await mutateRevisions();
+ if (saved) await expertiseActions.refreshRuleRevisions(rule.id);
return saved;
} finally {
setBusy(false);
@@ -530,11 +531,12 @@ const RuleDocument = ({
<div className={styles.heading}>
<span>{t('rules.sources.title')}</span>
</div>
- {/* "No sources" is only said once the list has actually come back empty; loading and a
- failed request each say what they are, so nothing reads as lost evidence. */}
- {sourcesLoading && !sources ? (
+ {/* "No sources" is only said once the server has said the list is empty โ€” a restored
+ empty copy is still loading; loading and a failed request each say what they are, so
+ nothing reads as lost evidence. */}
+ {sourcesLoading && !sources?.length ? (
<SkeletonText rows={2} />
- ) : sourcesError && !sources ? (
+ ) : sourcesError && !sources?.length ? (
<Flexbox horizontal align={'center'} gap={8}>
<span className={styles.muted}>{t('rules.sources.loadFailed')}</span>
<Button size={'small'} type={'link'} onClick={() => void retrySources()}>
diff --git a/src/features/MemoryRules/hooks.test.ts b/src/features/MemoryRules/hooks.test.ts
new file mode 100644
index 00000000000..3490aa7a61b
--- /dev/null
+++ b/src/features/MemoryRules/hooks.test.ts
@@ -0,0 +1,207 @@
+/**
+ * My rules reads the reviewer's rule sheet and a rule's evidence / edits from
+ * local replicas: a reload paints the last copy from IndexedDB before the
+ * network answers, then the server's answer replaces it. Each test "reloads"
+ * by re-importing every module (a fresh store, engine and SWR cache) over the
+ * same IndexedDB.
+ */
+import { act, renderHook, waitFor } from '@testing-library/react';
+import { createElement, type ReactNode } from 'react';
+import { SWRConfig } from 'swr';
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+const services = vi.hoisted(() => ({
+ listRules: vi.fn(),
+ ruleRevisions: vi.fn(),
+ ruleSources: vi.fn(),
+}));
+const scope = vi.hoisted(() => ({ current: 'u1:personal' }));
+
+vi.mock('@/services/expertise', () => ({ expertiseService: services }));
+vi.mock('@/libs/swr/useCacheScope', () => ({
+ getCacheScope: () => scope.current,
+ isScopeTrusted: () => true,
+ useCacheScope: () => scope.current,
+}));
+
+const never = () => new Promise<never>(() => {});
+
+const sheet = (titles: string[]) => ({
+ backlogRounds: 0,
+ groups: [
+ {
+ domain: { id: 'd1', title: 'Review' },
+ rules: titles.map((title, i) => ({ id: `r${i}`, status: 'active', title })),
+ },
+ ],
+});
+
+const wrapper = ({ children }: { children: ReactNode }) =>
+ createElement(SWRConfig, { value: { dedupingInterval: 0, provider: () => new Map() } }, children);
+
+/** A fresh page: new store, replica engine and (empty) SWR cache. */
+const boot = async () => {
+ vi.resetModules();
+ return import('./hooks');
+};
+
+let run = 0;
+
+beforeEach(() => {
+ // Each test owns its partition, so persisted rows never leak between tests.
+ scope.current = `rules-${++run}:personal`;
+ for (const fn of Object.values(services)) fn.mockReset();
+});
+
+describe('useRules', () => {
+ it('paints the persisted rule sheet after a reload, before the network answers', async () => {
+ services.listRules.mockResolvedValueOnce(sheet(['Cite the source']));
+ const { useRules } = await boot();
+ const warm = renderHook(() => useRules(), { wrapper });
+ await waitFor(() => expect(warm.result.current.data?.groups[0].rules).toHaveLength(1));
+ warm.unmount();
+
+ // Reload: the server is slow to answer.
+ services.listRules.mockImplementation(never);
+ const { useRules: reloaded } = await boot();
+ const { result } = renderHook(() => reloaded(), { wrapper });
+
+ await waitFor(() =>
+ expect(result.current.data?.groups[0].rules[0].title).toBe('Cite the source'),
+ );
+ });
+
+ it('replaces the restored sheet with the server answer', async () => {
+ services.listRules.mockResolvedValueOnce(sheet(['Old rule']));
+ const { useRules } = await boot();
+ const warm = renderHook(() => useRules(), { wrapper });
+ await waitFor(() => expect(warm.result.current.data).toBeDefined());
+ warm.unmount();
+
+ let answer!: (value: unknown) => void;
+ services.listRules.mockImplementation(() => new Promise((resolve) => (answer = resolve)));
+ const { useRules: reloaded } = await boot();
+ const { result } = renderHook(() => reloaded(), { wrapper });
+ await waitFor(() => expect(result.current.data?.groups[0].rules[0].title).toBe('Old rule'));
+
+ await act(async () => answer(sheet(['New rule'])));
+ await waitFor(() => expect(result.current.data?.groups[0].rules[0].title).toBe('New rule'));
+ });
+
+ it('treats a restored empty sheet as unconfirmed until the server answers', async () => {
+ services.listRules.mockResolvedValueOnce({ backlogRounds: 0, groups: [] });
+ const { useRules } = await boot();
+ const warm = renderHook(() => useRules(), { wrapper });
+ await waitFor(() => expect(warm.result.current.isConfirmed).toBe(true));
+ warm.unmount();
+
+ let answer!: (value: unknown) => void;
+ services.listRules.mockImplementation(() => new Promise((resolve) => (answer = resolve)));
+ const { useRules: reloaded } = await boot();
+ const { result } = renderHook(() => reloaded(), { wrapper });
+
+ // The empty sheet is last session's: the page must not open on onboarding from it.
+ await waitFor(() => expect(result.current.data?.groups).toEqual([]));
+ expect(result.current.isConfirmed).toBe(false);
+
+ await act(async () => answer({ backlogRounds: 0, groups: [] }));
+ await waitFor(() => expect(result.current.isConfirmed).toBe(true));
+ });
+
+ it('keeps a restored empty sheet unsettled, so the page shows loading and then the error', async () => {
+ services.listRules.mockResolvedValueOnce({ backlogRounds: 0, groups: [] });
+ const { useRules } = await boot();
+ const warm = renderHook(() => useRules(), { wrapper });
+ await waitFor(() => expect(warm.result.current.isConfirmed).toBe(true));
+ warm.unmount();
+
+ let fail!: (error: unknown) => void;
+ services.listRules.mockImplementation(() => new Promise((_, reject) => (fail = reject)));
+ const { useRules: reloaded } = await boot();
+ const { result } = renderHook(() => reloaded(), { wrapper });
+
+ await waitFor(() => expect(result.current.data?.groups).toEqual([]));
+ expect(result.current.settled).toBeUndefined();
+ expect(result.current.isLoading).toBe(true);
+
+ await act(async () => fail(new Error('offline')));
+ await waitFor(() => expect(result.current.error).toBeTruthy());
+ // Nothing settled + an error: the boundary renders the error with Retry, not an empty sheet.
+ expect(result.current.settled).toBeUndefined();
+ expect(result.current.isLoading).toBe(false);
+ });
+
+ it('keeps the restored sheet when the background refresh fails', async () => {
+ services.listRules.mockResolvedValueOnce(sheet(['Kept rule']));
+ const { useRules } = await boot();
+ const warm = renderHook(() => useRules(), { wrapper });
+ await waitFor(() => expect(warm.result.current.data).toBeDefined());
+ warm.unmount();
+
+ services.listRules.mockRejectedValue(new Error('offline'));
+ const { useRules: reloaded } = await boot();
+ const { result } = renderHook(() => reloaded(), { wrapper });
+
+ await waitFor(() => expect(result.current.error).toBeTruthy());
+ expect(result.current.data?.groups[0].rules[0].title).toBe('Kept rule');
+ });
+
+ it("does not paint another identity's sheet", async () => {
+ services.listRules.mockResolvedValueOnce(sheet(['Mine']));
+ const { useRules } = await boot();
+ const warm = renderHook(() => useRules(), { wrapper });
+ await waitFor(() => expect(warm.result.current.data).toBeDefined());
+ warm.unmount();
+
+ // Someone else signs in on the same browser.
+ scope.current = `${scope.current}-other`;
+ services.listRules.mockImplementation(never);
+ const { useRules: reloaded } = await boot();
+ const { result } = renderHook(() => reloaded(), { wrapper });
+
+ await act(async () => {
+ await new Promise((resolve) => setTimeout(resolve, 50));
+ });
+ expect(result.current.data).toBeUndefined();
+ });
+});
+
+describe('useRuleSources', () => {
+ it("paints a rule's persisted evidence after a reload, but not as a confirmed empty list", async () => {
+ services.ruleSources.mockResolvedValueOnce([{ id: 's1', topicId: 't1' }]);
+ services.ruleSources.mockResolvedValueOnce([]);
+ const { useRuleSources } = await boot();
+ const a = renderHook(() => useRuleSources('r1'), { wrapper });
+ await waitFor(() => expect(a.result.current.data).toHaveLength(1));
+ a.unmount();
+ const b = renderHook(() => useRuleSources('r2'), { wrapper });
+ await waitFor(() => expect(b.result.current.data).toEqual([]));
+ b.unmount();
+
+ services.ruleSources.mockImplementation(never);
+ const { useRuleSources: reloaded } = await boot();
+ const withSources = renderHook(() => reloaded('r1'), { wrapper });
+ const withoutSources = renderHook(() => reloaded('r2'), { wrapper });
+
+ await waitFor(() => expect(withSources.result.current.data).toHaveLength(1));
+ await waitFor(() => expect(withoutSources.result.current.data).toEqual([]));
+ // "No sources" would read as lost evidence: a restored empty list is still loading.
+ expect(withoutSources.result.current.isLoading).toBe(true);
+ });
+});
+
+describe('useRuleRevisions', () => {
+ it("paints a rule's persisted edits after a reload", async () => {
+ services.ruleRevisions.mockResolvedValueOnce([{ id: 'v1', prevTitle: 'Before' }]);
+ const { useRuleRevisions } = await boot();
+ const warm = renderHook(() => useRuleRevisions('r1'), { wrapper });
+ await waitFor(() => expect(warm.result.current.data).toHaveLength(1));
+ warm.unmount();
+
+ services.ruleRevisions.mockImplementation(never);
+ const { useRuleRevisions: reloaded } = await boot();
+ const { result } = renderHook(() => reloaded('r1'), { wrapper });
+
+ await waitFor(() => expect(result.current.data).toEqual([{ id: 'v1', prevTitle: 'Before' }]));
+ });
+});
diff --git a/src/features/MemoryRules/hooks.ts b/src/features/MemoryRules/hooks.ts
index 3bd9de4e872..6869cb1a103 100644
--- a/src/features/MemoryRules/hooks.ts
+++ b/src/features/MemoryRules/hooks.ts
@@ -1,17 +1,36 @@
-import { useClientDataSWR } from '@/libs/swr';
-import { swrKeys } from '@/libs/swr/keys';
-import { expertiseService } from '@/services/expertise';
+import { expertiseActions, expertiseSelectors, useExpertiseStore } from '@/store/expertise';
-/** The reviewer's own rules by group, plus the backlog of rejected rounds nothing has read yet. */
-export const useRules = () =>
- useClientDataSWR(swrKeys.expertise.rules(), () => expertiseService.listRules());
+/**
+ * The reviewer's own rules by group, plus the backlog of rejected rounds nothing has read yet.
+ * Painted from the local replica on reload and revalidated in the background; `isConfirmed`
+ * says whether the server has answered yet, so an empty restored sheet is not onboarding.
+ */
+export const useRules = (enabled = true) => {
+ const { error, revalidate } = expertiseActions.useFetchRules(enabled);
+ const data = useExpertiseStore(expertiseSelectors.rules);
+ const isConfirmed = useExpertiseStore(expertiseSelectors.isRulesConfirmed);
+ // What the page may treat as settled: a restored sheet with no groups is last session's copy,
+ // not "you have no rules", so it stays loading (or shows the error) until the server answers.
+ const settled = isConfirmed || !!data?.groups.length ? data : undefined;
+ return {
+ data,
+ error,
+ isConfirmed,
+ isLoading: enabled && settled === undefined && !error,
+ revalidate,
+ settled,
+ };
+};
-export const useRuleSources = (lessonId?: string) =>
- useClientDataSWR(lessonId ? swrKeys.expertise.ruleSources(lessonId) : null, () =>
- expertiseService.ruleSources(lessonId!),
- );
+export const useRuleSources = (lessonId?: string) => {
+ const { error, revalidate } = expertiseActions.useFetchRuleSources(lessonId);
+ const data = useExpertiseStore(expertiseSelectors.ruleSources(lessonId));
+ const isConfirmed = useExpertiseStore(expertiseSelectors.isRuleSourcesConfirmed(lessonId));
+ return { data, error, isConfirmed, isLoading: !!lessonId && !isConfirmed && !error, revalidate };
+};
-export const useRuleRevisions = (lessonId?: string) =>
- useClientDataSWR(lessonId ? swrKeys.expertise.ruleRevisions(lessonId) : null, () =>
- expertiseService.ruleRevisions(lessonId!),
- );
+export const useRuleRevisions = (lessonId?: string) => {
+ const { error } = expertiseActions.useFetchRuleRevisions(lessonId);
+ const data = useExpertiseStore(expertiseSelectors.ruleRevisions(lessonId));
+ return { data, error };
+};
diff --git a/src/features/MemoryRules/index.tsx b/src/features/MemoryRules/index.tsx
index 2bb48fe0c23..606016af9a9 100644
--- a/src/features/MemoryRules/index.tsx
+++ b/src/features/MemoryRules/index.tsx
@@ -10,7 +10,13 @@ import Loading from '@/components/Loading/BrandTextLoading';
import NavHeader from '@/features/NavHeader';
import { SelfLearningLabOff, useSelfLearningSurface } from '@/features/SelfLearning/SurfaceGate';
import WideScreenContainer from '@/features/WideScreenContainer';
-import { expertiseService, type RuleItem, type UpdateRuleInput } from '@/services/expertise';
+import {
+ expertiseService,
+ type RuleItem,
+ type RulesOverview,
+ type UpdateRuleInput,
+} from '@/services/expertise';
+import { expertiseActions } from '@/store/expertise';
import { createComposeRuleModal } from './ComposeModal';
import DetailPanel from './DetailPanel';
@@ -43,13 +49,15 @@ import { useJudgeDirections } from './useJudgeDirections';
* so they share every control. What differs is reach: a rule of the reviewer's reaches every run,
* an agent's lesson only that agent's, so a lesson can only be moved or merged within its part.
*
- * Every write goes through the service and then re-reads the list; only the drag reorder and the
- * effect switch are applied optimistically, because both would visibly snap back otherwise.
+ * The sheet is a local replica: a reload paints the last one and revalidates it in the
+ * background. Every write goes through the service and then re-reads the list; the drag reorder,
+ * the effect / direction switches and archive / restore land on the replica at once and roll back
+ * if the call fails.
*/
const MemoryRules = () => {
const { t } = useTranslation('memory');
const { enabled, ready } = useSelfLearningSurface();
- const { data, error, isLoading, mutate } = useRules();
+ const { data, error, isConfirmed, isLoading, settled } = useRules(enabled);
const [selectedId, setSelectedId] = useState<string>();
const [titleEditing, setTitleEditing] = useState(false);
const [mergeFrom, setMergeFrom] = useState<string>();
@@ -79,7 +87,8 @@ const MemoryRules = () => {
() => partRules.filter((rule) => rule.status === 'retired'),
[partRules],
);
- const isEmpty = !isLoading && !error && all.length === 0;
+ // A restored sheet may be last session's empty one: only the server's answer can say "empty".
+ const isEmpty = isConfirmed && !error && all.length === 0;
// Display numbers follow the sheet order of the part on screen, not the per-group `P-nn` codes,
// which restart in every group and would repeat down the page.
@@ -94,7 +103,7 @@ const MemoryRules = () => {
const ruleCount = live.filter((rule) => sectionOf.get(rule.domainId)?.key === 'mine').length;
const lessonCount = live.length - ruleCount;
// "My rules" with nothing in it is the reviewer's first screen there, not an empty table.
- const mineOnboarding = !isLoading && !error && part.key === 'mine' && part.groups.length === 0;
+ const mineOnboarding = isConfirmed && !error && part.key === 'mine' && part.groups.length === 0;
const agentSections = sections.filter((section) => section.owner.kind === 'agent');
const onboardingAgents: RulesOnboardingAgents | undefined =
agentSections.length > 0 && agentSections[0].owner.kind === 'agent'
@@ -106,10 +115,11 @@ const MemoryRules = () => {
}
: undefined;
+ // Only rules the server confirmed lack a direction: a restored sheet may predate a judging.
useJudgeDirections(
- enabled,
+ enabled && isConfirmed,
live.filter((rule) => !rule.direction).map((rule) => rule.id),
- mutate,
+ expertiseActions.refreshRules,
);
// A selection or a merge in progress belongs to the part it started in; switching drops both,
@@ -121,20 +131,17 @@ const MemoryRules = () => {
setMergeFrom(undefined);
};
- const refresh = () => mutate();
+ const refresh = () => expertiseActions.refreshRules();
- const patchLocal = (id: string, patch: Partial<RuleItem>) =>
- mutate(
- (current) =>
- current && {
- ...current,
- groups: current.groups.map((group) => ({
- ...group,
- rules: group.rules.map((rule) => (rule.id === id ? { ...rule, ...patch } : rule)),
- })),
- },
- { revalidate: false },
- );
+ const patchRule =
+ (id: string, patch: Partial<RuleItem>) =>
+ (current: RulesOverview): RulesOverview => ({
+ ...current,
+ groups: current.groups.map((group) => ({
+ ...group,
+ rules: group.rules.map((rule) => (rule.id === id ? { ...rule, ...patch } : rule)),
+ })),
+ });
// Optimistic writes must not outlive a failed request: re-read the server's truth and say so.
const recover = async (error: unknown) => {
@@ -146,9 +153,13 @@ const MemoryRules = () => {
/** Resolves to whether the change was saved, so callers keep unsaved input on failure. */
const updateRule = async (id: string, patch: UpdateRuleInput) => {
try {
- if (patch.enforcement) await patchLocal(id, { enforcement: patch.enforcement });
- if (patch.direction) await patchLocal(id, { direction: patch.direction });
- await expertiseService.updateRule(id, patch);
+ const local: Partial<RuleItem> = {
+ ...(patch.enforcement && { enforcement: patch.enforcement }),
+ ...(patch.direction && { direction: patch.direction }),
+ };
+ await expertiseActions.patchRules(patchRule(id, local), () =>
+ expertiseService.updateRule(id, patch),
+ );
await refresh();
return true;
} catch (error) {
@@ -166,20 +177,18 @@ const MemoryRules = () => {
items.map((rule) => rule.id),
);
if (!move) return;
- await mutate(
- (current) =>
- current && {
+ try {
+ await expertiseActions.patchRules(
+ (current) => ({
...current,
groups: current.groups.map((group) =>
group.domain.id === domainId
? { ...group, rules: [...items, ...group.rules.filter((r) => r.status !== 'active')] }
: group,
),
- },
- { revalidate: false },
- );
- try {
- await expertiseService.reorderRule(domainId, move.id, move.beforeId);
+ }),
+ () => expertiseService.reorderRule(domainId, move.id, move.beforeId),
+ );
await refresh();
} catch (error) {
await recover(error);
@@ -197,7 +206,12 @@ const MemoryRules = () => {
};
const handlers = {
- archive: (id: string) => void run(() => expertiseService.archiveRule(id)),
+ archive: (id: string) =>
+ void run(() =>
+ expertiseActions.patchRules(patchRule(id, { status: 'retired' }), () =>
+ expertiseService.archiveRule(id),
+ ),
+ ),
// Rewording opens the document with the title already in edit mode.
edit: (id: string) => {
setSelectedId(id);
@@ -209,7 +223,12 @@ const MemoryRules = () => {
const moved = await expertiseService.moveRule(id, domainId);
if (moved && selectedId === id) setSelectedId(moved.id);
}),
- restore: (id: string) => void run(() => expertiseService.restoreRule(id)),
+ restore: (id: string) =>
+ void run(() =>
+ expertiseActions.patchRules(patchRule(id, { status: 'active' }), () =>
+ expertiseService.restoreRule(id),
+ ),
+ ),
};
const select = (id: string) => {
@@ -400,7 +419,7 @@ const MemoryRules = () => {
)}
<AsyncBoundary
- data={data}
+ data={settled}
error={error}
errorVariant={'page'}
isEmpty={isEmpty}
diff --git a/src/features/SelfLearning/CreateDomainPage.tsx b/src/features/SelfLearning/CreateDomainPage.tsx
index 70a55901325..97c7859522d 100644
--- a/src/features/SelfLearning/CreateDomainPage.tsx
+++ b/src/features/SelfLearning/CreateDomainPage.tsx
@@ -38,6 +38,7 @@ import { useWorkspaceAwareNavigate } from '@/features/Workspace/useWorkspaceAwar
import type { ExpertiseDomainDraft } from '@/services/expertise';
import { expertiseService } from '@/services/expertise';
import { useAgentStore } from '@/store/agent';
+import { expertiseActions } from '@/store/expertise';
import { shinyTextStyles } from '@/styles';
import { type AdjustmentTarget, mergeAdjustedBlock } from './createDomainAdjustment';
@@ -295,6 +296,8 @@ const CreateDomainPage = memo(() => {
title: draft.title.trim(),
});
if (storageKey) localStorage.removeItem(storageKey);
+ // The portrait the page opens on may be a local copy from before this direction existed.
+ void expertiseActions.refreshOverview(agentId);
navigate(urlJoin('/agent', agentId, 'self-evolving', id));
} catch {
toast.error(t('create.failed'));
diff --git a/src/features/SelfLearning/ExperienceList/index.tsx b/src/features/SelfLearning/ExperienceList/index.tsx
index 53a44828389..90bcb6cfaec 100644
--- a/src/features/SelfLearning/ExperienceList/index.tsx
+++ b/src/features/SelfLearning/ExperienceList/index.tsx
@@ -32,12 +32,15 @@ const ExperienceList = memo(() => {
const { t } = useTranslation('selfLearning');
const { domainId } = useParams();
const activeAgentId = useAgentStore((s) => s.activeAgentId);
- const { data, error, isLoading, mutate } = useExpertiseOverview(activeAgentId ?? undefined);
+ const { data, error, isConfirmed, revalidate } = useExpertiseOverview(activeAgentId ?? undefined);
const domain = useMemo(
() => data?.domains.find((d) => d.id === domainId),
[data?.domains, domainId],
);
+ // A direction missing from a restored portrait may just be newer than it: "not found" waits for
+ // the server's answer.
+ const settled = domain || isConfirmed ? data : undefined;
const habits = useMemo(
() => (domain ? domain.lessons.map((l) => ({ ...l, domainId: domain.id })) : []),
[domain],
@@ -71,18 +74,18 @@ const ExperienceList = memo(() => {
<Flexbox className={styles.body} flex={1} width={'100%'}>
<WideScreenContainer>
<AsyncBoundary
- data={data}
+ data={settled}
error={error}
errorVariant={'page'}
- isEmpty={!error && !isLoading && !domain}
- isLoading={isLoading}
+ isEmpty={isConfirmed && !error && !domain}
+ isLoading={!settled && !error}
loading={<Loading debugId={'SelfLearningExperience'} />}
empty={
<Center height={'100%'} style={{ minHeight: '50vh' }} width={'100%'}>
<Empty icon={DnaIcon} title={t('experience.notFound')} />
</Center>
}
- onRetry={() => mutate()}
+ onRetry={() => void revalidate()}
>
{domain && activeAgentId && (
<Flexbox gap={20} paddingBlock={'22px 64px'}>
@@ -100,12 +103,7 @@ const ExperienceList = memo(() => {
title={t('experience.emptyTitle')}
/>
) : (
- <HabitList
- defaultStableOpen
- agentId={activeAgentId}
- habits={habits}
- onChanged={() => void mutate()}
- />
+ <HabitList defaultStableOpen agentId={activeAgentId} habits={habits} />
)}
</Flexbox>
)}
diff --git a/src/features/SelfLearning/LessonDetail/index.tsx b/src/features/SelfLearning/LessonDetail/index.tsx
index ad6b3b44294..b83e50a3505 100644
--- a/src/features/SelfLearning/LessonDetail/index.tsx
+++ b/src/features/SelfLearning/LessonDetail/index.tsx
@@ -60,8 +60,12 @@ const LessonDetail = memo(() => {
const { t } = useTranslation('selfLearning');
const { domainId, lessonId } = useParams();
const activeAgentId = useAgentStore((s) => s.activeAgentId);
- const { data: domain, error: domainError, mutate: mutateDomain } = useExpertiseDomain(domainId);
- const { data, error, isLoading, mutate } = useExpertiseLesson(lessonId);
+ const {
+ data: domain,
+ error: domainError,
+ revalidate: revalidateDomain,
+ } = useExpertiseDomain(domainId);
+ const { data, error, isLoading, notFound, revalidate } = useExpertiseLesson(lessonId);
const domainPath =
activeAgentId && domainId
? urlJoin('/agent', activeAgentId, 'self-evolving', domainId)
@@ -102,10 +106,10 @@ const LessonDetail = memo(() => {
empty={<Empty title={t('rules.detail.notFound')} />}
error={error}
errorVariant={'page'}
- isEmpty={!error && !isLoading && !data}
+ isEmpty={notFound && !data}
isLoading={isLoading}
loading={<Loading debugId={'SelfLearningLesson'} />}
- onRetry={() => mutate()}
+ onRetry={() => void revalidate()}
>
{data && (
<Flexbox gap={20} paddingBlock={'14px 64px'}>
@@ -125,10 +129,10 @@ const LessonDetail = memo(() => {
</Text>
{data.lesson.layer && <Tag>{data.lesson.layer}</Tag>}
</Flexbox>
- {domainError && (
+ {!!domainError && (
<Text fontSize={12.5} type={'danger'}>
{t('rules.detail.domainUnavailable')} ยท{' '}
- <Text as={'button'} type={'info'} onClick={() => void mutateDomain()}>
+ <Text as={'button'} type={'info'} onClick={() => void revalidateDomain()}>
{t('rules.detail.retry')}
</Text>
</Text>
diff --git a/src/features/SelfLearning/Portrait/HabitList.tsx b/src/features/SelfLearning/Portrait/HabitList.tsx
index af5451f4555..371bc2f17bd 100644
--- a/src/features/SelfLearning/Portrait/HabitList.tsx
+++ b/src/features/SelfLearning/Portrait/HabitList.tsx
@@ -32,6 +32,7 @@ import urlJoin from 'url-join';
import { useWorkspaceAwareNavigate } from '@/features/Workspace/useWorkspaceAwareNavigate';
import type { ExpertiseHabit } from '@/services/expertise';
import { expertiseService } from '@/services/expertise';
+import { expertiseActions } from '@/store/expertise';
import { countTiers, type HabitTier, habitTier, TIER_ORDER } from '../helpers';
import LessonPreview from './LessonPreview';
@@ -45,7 +46,6 @@ interface HabitListProps {
/** Present when the list mixes several domains, so each row can say which one it belongs to. */
domainTitles?: Record<string, string>;
habits: (ExpertiseHabit & { domainId: string })[];
- onChanged: () => void;
/** Where the complete, unfolded list lives; renders a "view all" link in the header. */
viewAllPath?: string;
}
@@ -80,11 +80,10 @@ interface HabitRowProps {
agentId: string;
domainTitle?: string;
habit: ExpertiseHabit & { domainId: string };
- onChanged: () => void;
tier: HabitTier;
}
-const HabitRow = memo<HabitRowProps>(({ agentId, domainTitle, habit, onChanged, tier }) => {
+const HabitRow = memo<HabitRowProps>(({ agentId, domainTitle, habit, tier }) => {
const { t } = useTranslation('selfLearning');
const navigate = useWorkspaceAwareNavigate();
const [teaching, setTeaching] = useState(false);
@@ -119,7 +118,7 @@ const HabitRow = memo<HabitRowProps>(({ agentId, domainTitle, habit, onChanged,
await expertiseService.reviseLesson({ lessonId: habit.id, text });
toast.success(t('habit.teach.done'));
setTeaching(false);
- onChanged();
+ void expertiseActions.afterLessonWrite(agentId, habit.id);
} catch {
toast.error(t('habit.teach.failed'));
}
@@ -127,9 +126,9 @@ const HabitRow = memo<HabitRowProps>(({ agentId, domainTitle, habit, onChanged,
const retire = async () => {
try {
- await expertiseService.retireLesson(habit.id);
+ // Drops from the portrait (and its local copy) at once; comes back if the call fails.
+ await expertiseActions.retireLesson(agentId, habit.id);
toast.success(t('habit.teach.forgot'));
- onChanged();
} catch {
toast.error(t('habit.teach.failed'));
}
@@ -262,7 +261,7 @@ HabitRow.displayName = 'ExpertiseHabitRow';
* ๅ€ผๅพ—็œ‹็š„้ƒฝๅœจไธŠ้ข๏ผŒ็จณ็š„ๆ”ถ่ตทๆฅ โ€”โ€” ็”จๆˆทไธ้œ€่ฆๆœ‰็ฒพๅŠ›้€ๆก่ฟ‡ใ€‚
*/
const HabitList = memo<HabitListProps>(
- ({ agentId, defaultStableOpen = false, domainTitles, habits, onChanged, viewAllPath }) => {
+ ({ agentId, defaultStableOpen = false, domainTitles, habits, viewAllPath }) => {
const { t } = useTranslation('selfLearning');
const [search, setSearch] = useState('');
const [stableOpen, setStableOpen] = useState(defaultStableOpen);
@@ -334,7 +333,6 @@ const HabitList = memo<HabitListProps>(
habit={h}
key={h.id}
tier={tier}
- onChanged={onChanged}
/>
))}
</Fragment>
@@ -368,7 +366,6 @@ const HabitList = memo<HabitListProps>(
habit={h}
key={h.id}
tier={'stable'}
- onChanged={onChanged}
/>
))}
</Block>
diff --git a/src/features/SelfLearning/Portrait/LessonPreview.tsx b/src/features/SelfLearning/Portrait/LessonPreview.tsx
index d6f71d17992..0d4db58cbe2 100644
--- a/src/features/SelfLearning/Portrait/LessonPreview.tsx
+++ b/src/features/SelfLearning/Portrait/LessonPreview.tsx
@@ -78,13 +78,13 @@ interface LessonPreviewProps {
* ๆ‚ฌๅœไธ€ๆก็ป้ชŒๆ—ถๅฑ•ๅผ€็š„้ข„่งˆๅกใ€‚
*
* ๆธ…ๅ•ไธ€่กŒๅชๆ”พๅพ—ไธ‹ใ€Œๆ ‡้ข˜ + ้ ไธ้ ่ฐฑใ€๏ผŒไฝ†่ฆๅˆคๆ–ญไธ€ๆก็ป้ชŒๆ˜ฏๅฆๅฏไฟก๏ผŒ็œ‹็š„ๆ˜ฏๅฎƒ็š„็†็”ฑๅ’Œ็”จๆณ• โ€”โ€”
- * ้‚ฃไบ›ๅŽŸๆฅๅพ—้€ๆก็‚น่ฟ›่ฏฆๆƒ…้กตใ€‚่ฟ™้‡ŒๆŒ‰้œ€ๆ‹‰ๅŒไธ€ไปฝ่ฏฆๆƒ…๏ผˆSWR ็ผ“ๅญ˜๏ผŒ็œŸ็‚น่ฟ›ๅŽปๆ—ถไธไผšๅ†่ฏทๆฑ‚ไธ€ๆฌก๏ผ‰๏ผŒ
+ * ้‚ฃไบ›ๅŽŸๆฅๅพ—้€ๆก็‚น่ฟ›่ฏฆๆƒ…้กตใ€‚่ฟ™้‡ŒๆŒ‰้œ€ๆ‹‰ๅŒไธ€ไปฝ่ฏฆๆƒ…๏ผˆๆœฌๅœฐๅ‰ฏๆœฌ๏ผŒ็œŸ็‚น่ฟ›ๅŽปๆ—ถ็›ดๆŽฅ็”ปๅ‡บใ€ๅŽๅฐๅ†ๅˆทๆ–ฐ๏ผ‰๏ผŒ
* ๅชๆˆชๅ–ๅˆคๆ–ญ้œ€่ฆ็š„้ƒจๅˆ†๏ผšไธบไป€ไนˆใ€ๆ€Žไนˆ็”จใ€ๆœ€่ฟ‘ๅœจๅ“ชๅ‡ ๆฌกๅฎž่ทต้‡Œ้ชŒ่ฏ่ฟ‡ใ€‚
*/
const LessonPreview = memo<LessonPreviewProps>(({ code, layer, lessonId, lessonPath, title }) => {
const { t } = useTranslation('selfLearning');
const navigate = useWorkspaceAwareNavigate();
- const { data, error, isLoading, mutate } = useExpertiseLesson(lessonId);
+ const { data, error, isLoading, revalidate } = useExpertiseLesson(lessonId);
const sections = previewSections(data?.lesson.sections);
const evidence = data?.hits.slice(0, MAX_EVIDENCE) ?? [];
@@ -128,14 +128,14 @@ const LessonPreview = memo<LessonPreviewProps>(({ code, layer, lessonId, lessonP
{isLoading && !data && <SkeletonText rows={3} />}
- {/* Without this the card sits on "loadingโ€ฆ" forever: SWR clears isLoading on failure. */}
+ {/* Without this the card sits on "loadingโ€ฆ" forever after a failed read. */}
{!!error && !data && (
<Text
as={'button'}
className={styles.retry}
fontSize={12}
type={'info'}
- onClick={() => void mutate()}
+ onClick={() => void revalidate()}
>
{t('rules.detail.retry')}
</Text>
diff --git a/src/features/SelfLearning/hooks.test.ts b/src/features/SelfLearning/hooks.test.ts
new file mode 100644
index 00000000000..22a61b71e53
--- /dev/null
+++ b/src/features/SelfLearning/hooks.test.ts
@@ -0,0 +1,212 @@
+/**
+ * An agent's Self-evolving pages read its portrait, a direction, a lesson and
+ * the warm-up count from local replicas: a reload paints the last copy from
+ * IndexedDB before the network answers. Each test "reloads" by re-importing
+ * every module (a fresh store, engine and SWR cache) over the same IndexedDB.
+ */
+import { act, renderHook, waitFor } from '@testing-library/react';
+import { createElement, type ReactNode } from 'react';
+import { SWRConfig } from 'swr';
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+const services = vi.hoisted(() => ({
+ countHistory: vi.fn(),
+ getDomain: vi.fn(),
+ getLesson: vi.fn(),
+ listByAgent: vi.fn(),
+}));
+const scope = vi.hoisted(() => ({ current: 'u1:personal' }));
+
+vi.mock('@/services/expertise', () => ({ expertiseService: services }));
+vi.mock('@/libs/swr/useCacheScope', () => ({
+ getCacheScope: () => scope.current,
+ isScopeTrusted: () => true,
+ useCacheScope: () => scope.current,
+}));
+
+const never = () => new Promise<never>(() => {});
+
+const portrait = (titles: string[]) => ({
+ domains: titles.map((title, i) => ({ id: `d${i}`, lessons: [], runCount: 0, title })),
+});
+
+const lesson = (title: string) => ({ hits: [], lesson: { code: 'L-01', sections: [], title } });
+
+const wrapper = ({ children }: { children: ReactNode }) =>
+ createElement(SWRConfig, { value: { dedupingInterval: 0, provider: () => new Map() } }, children);
+
+/** A fresh page: new store, replica engine and (empty) SWR cache. */
+const boot = async () => {
+ vi.resetModules();
+ return import('./hooks');
+};
+
+let run = 0;
+
+beforeEach(() => {
+ scope.current = `self-learning-${++run}:personal`;
+ for (const fn of Object.values(services)) fn.mockReset();
+});
+
+describe('useExpertiseOverview', () => {
+ it("paints the agent's persisted portrait after a reload, then the server's", async () => {
+ services.listByAgent.mockResolvedValueOnce(portrait(['Code review']));
+ const { useExpertiseOverview } = await boot();
+ const warm = renderHook(() => useExpertiseOverview('agent-1'), { wrapper });
+ await waitFor(() => expect(warm.result.current.data?.domains).toHaveLength(1));
+ warm.unmount();
+
+ let answer!: (value: unknown) => void;
+ services.listByAgent.mockImplementation(() => new Promise((resolve) => (answer = resolve)));
+ const { useExpertiseOverview: reloaded } = await boot();
+ const { result } = renderHook(() => reloaded('agent-1'), { wrapper });
+
+ await waitFor(() => expect(result.current.data?.domains[0].title).toBe('Code review'));
+
+ await act(async () => answer(portrait(['Code review', 'Writing'])));
+ await waitFor(() => expect(result.current.data?.domains).toHaveLength(2));
+ });
+
+ it('keeps each agent under its own entry', async () => {
+ services.listByAgent.mockImplementation(async (agentId: string) => portrait([agentId]));
+ const { useExpertiseOverview } = await boot();
+ const { rerender, result } = renderHook(({ id }) => useExpertiseOverview(id), {
+ initialProps: { id: 'agent-1' },
+ wrapper,
+ });
+ await waitFor(() => expect(result.current.data?.domains[0].title).toBe('agent-1'));
+
+ rerender({ id: 'agent-2' });
+ await waitFor(() => expect(result.current.data?.domains[0].title).toBe('agent-2'));
+ });
+
+ it('treats a restored empty portrait as unconfirmed until the server answers', async () => {
+ services.listByAgent.mockResolvedValueOnce({ domains: [] });
+ const { useExpertiseOverview } = await boot();
+ const warm = renderHook(() => useExpertiseOverview('agent-1'), { wrapper });
+ await waitFor(() => expect(warm.result.current.isConfirmed).toBe(true));
+ warm.unmount();
+
+ services.listByAgent.mockImplementation(never);
+ const { useExpertiseOverview: reloaded } = await boot();
+ const { result } = renderHook(() => reloaded('agent-1'), { wrapper });
+
+ await waitFor(() => expect(result.current.data?.domains).toEqual([]));
+ expect(result.current.isConfirmed).toBe(false);
+ });
+
+ it('keeps the restored portrait when the background refresh fails', async () => {
+ services.listByAgent.mockResolvedValueOnce(portrait(['Kept']));
+ const { useExpertiseOverview } = await boot();
+ const warm = renderHook(() => useExpertiseOverview('agent-1'), { wrapper });
+ await waitFor(() => expect(warm.result.current.data).toBeDefined());
+ warm.unmount();
+
+ services.listByAgent.mockRejectedValue(new Error('offline'));
+ const { useExpertiseOverview: reloaded } = await boot();
+ const { result } = renderHook(() => reloaded('agent-1'), { wrapper });
+
+ await waitFor(() => expect(result.current.error).toBeTruthy());
+ expect(result.current.data?.domains[0].title).toBe('Kept');
+ });
+
+ it('answers the page, the warm-up and the habit list with one request', async () => {
+ services.listByAgent.mockResolvedValue(portrait(['One']));
+ const { useExpertiseOverview } = await boot();
+
+ // The portrait header, the warm-up poll and the experience list mount together.
+ const { result } = renderHook(
+ () => {
+ useExpertiseOverview('agent-1');
+ useExpertiseOverview('agent-1', 0);
+ return useExpertiseOverview('agent-1');
+ },
+ { wrapper },
+ );
+
+ await waitFor(() => expect(result.current.data).toBeDefined());
+ expect(services.listByAgent).toHaveBeenCalledTimes(1);
+ });
+});
+
+describe('useExpertiseLesson', () => {
+ it('paints a persisted lesson after a reload, before the network answers', async () => {
+ services.getLesson.mockResolvedValueOnce(lesson('Name the file'));
+ const { useExpertiseLesson } = await boot();
+ const warm = renderHook(() => useExpertiseLesson('l1'), { wrapper });
+ await waitFor(() => expect(warm.result.current.data).toBeDefined());
+ warm.unmount();
+
+ services.getLesson.mockImplementation(never);
+ const { useExpertiseLesson: reloaded } = await boot();
+ const { result } = renderHook(() => reloaded('l1'), { wrapper });
+
+ await waitFor(() => expect(result.current.data?.lesson.title).toBe('Name the file'));
+ });
+
+ it('says "not found" only once the server answers that the lesson is gone', async () => {
+ let answer!: (value: unknown) => void;
+ services.getLesson.mockImplementation(() => new Promise((resolve) => (answer = resolve)));
+ const { useExpertiseLesson } = await boot();
+ const { result } = renderHook(() => useExpertiseLesson('gone'), { wrapper });
+
+ await waitFor(() => expect(services.getLesson).toHaveBeenCalled());
+ expect(result.current.isLoading).toBe(true);
+ expect(result.current.notFound).toBe(false);
+
+ await act(async () => answer(null));
+ await waitFor(() => expect(result.current.notFound).toBe(true));
+ expect(result.current.isLoading).toBe(false);
+ });
+
+ it('drops a lesson the server says is gone from the local copy', async () => {
+ services.getLesson.mockResolvedValueOnce(lesson('Retired'));
+ const { useExpertiseLesson } = await boot();
+ const warm = renderHook(() => useExpertiseLesson('l1'), { wrapper });
+ await waitFor(() => expect(warm.result.current.data).toBeDefined());
+ warm.unmount();
+
+ services.getLesson.mockResolvedValueOnce(null);
+ const { useExpertiseLesson: second } = await boot();
+ const gone = renderHook(() => second('l1'), { wrapper });
+ await waitFor(() => expect(gone.result.current.notFound).toBe(true));
+ gone.unmount();
+
+ services.getLesson.mockImplementation(never);
+ const { useExpertiseLesson: third } = await boot();
+ const { result } = renderHook(() => third('l1'), { wrapper });
+ await act(async () => {
+ await new Promise((resolve) => setTimeout(resolve, 50));
+ });
+ expect(result.current.data).toBeUndefined();
+ });
+});
+
+describe('useExpertiseDomain / useHistoryCount', () => {
+ it('paint their persisted values after a reload', async () => {
+ services.getDomain.mockResolvedValueOnce({ domain: { id: 'd1', title: 'Review' } });
+ services.countHistory.mockResolvedValueOnce({ candidateCount: 7 });
+ const { useExpertiseDomain, useHistoryCount } = await boot();
+ const warm = renderHook(
+ () => ({ count: useHistoryCount('agent-1'), domain: useExpertiseDomain('d1') }),
+ { wrapper },
+ );
+ await waitFor(() => expect(warm.result.current.domain.data).toBeDefined());
+ await waitFor(() => expect(warm.result.current.count.data).toBeDefined());
+ warm.unmount();
+
+ services.getDomain.mockImplementation(never);
+ services.countHistory.mockImplementation(never);
+ const reloaded = await boot();
+ const { result } = renderHook(
+ () => ({
+ count: reloaded.useHistoryCount('agent-1'),
+ domain: reloaded.useExpertiseDomain('d1'),
+ }),
+ { wrapper },
+ );
+
+ await waitFor(() => expect(result.current.domain.data?.domain.title).toBe('Review'));
+ await waitFor(() => expect(result.current.count.data?.candidateCount).toBe(7));
+ });
+});
diff --git a/src/features/SelfLearning/hooks.ts b/src/features/SelfLearning/hooks.ts
index 79d993df0b8..67e2999afe4 100644
--- a/src/features/SelfLearning/hooks.ts
+++ b/src/features/SelfLearning/hooks.ts
@@ -1,29 +1,49 @@
-import { useClientDataSWR } from '@/libs/swr';
-import { swrKeys } from '@/libs/swr/keys';
-import { expertiseService } from '@/services/expertise';
+import { expertiseActions, expertiseSelectors, useExpertiseStore } from '@/store/expertise';
/**
- * The portrait query. `refreshInterval` is only set while a history warm-up is running so
- * newly learned habits stream in without a manual reload.
+ * The portrait query, painted from the local replica and revalidated in the background.
+ * `refreshInterval` is only set while a history warm-up is running so newly learned habits
+ * stream in without a manual reload. `isConfirmed` says whether the server has answered, so a
+ * restored empty portrait is not taken for "no directions yet".
*/
-export const useExpertiseOverview = (agentId?: string, refreshInterval?: number) =>
- useClientDataSWR(
- agentId ? swrKeys.expertise.overview(agentId) : null,
- () => expertiseService.listByAgent(agentId!),
- { refreshInterval },
- );
+export const useExpertiseOverview = (agentId?: string, refreshInterval?: number) => {
+ const { error, revalidate } = expertiseActions.useFetchOverview(agentId, refreshInterval);
+ const data = useExpertiseStore(expertiseSelectors.overview(agentId));
+ const isConfirmed = useExpertiseStore(expertiseSelectors.isOverviewConfirmed(agentId));
+ return {
+ data,
+ error,
+ isConfirmed,
+ isLoading: !!agentId && data === undefined && !error,
+ revalidate,
+ };
+};
-export const useExpertiseDomain = (domainId?: string) =>
- useClientDataSWR(domainId ? swrKeys.expertise.domain(domainId) : null, () =>
- expertiseService.getDomain(domainId!),
- );
+export const useExpertiseDomain = (domainId?: string) => {
+ const { error, revalidate } = expertiseActions.useFetchDomain(domainId);
+ const data = useExpertiseStore(expertiseSelectors.domain(domainId));
+ return { data, error, revalidate };
+};
-export const useExpertiseLesson = (lessonId?: string) =>
- useClientDataSWR(lessonId ? swrKeys.expertise.lesson(lessonId) : null, () =>
- expertiseService.getLesson(lessonId!),
- );
+/**
+ * One lesson. `notFound` is only true once the server answered that it is gone; until then a
+ * missing entry is still loading.
+ */
+export const useExpertiseLesson = (lessonId?: string) => {
+ const { error, revalidate } = expertiseActions.useFetchLesson(lessonId);
+ const data = useExpertiseStore(expertiseSelectors.lesson(lessonId));
+ const notFound = useExpertiseStore(expertiseSelectors.isLessonNotFound(lessonId));
+ return {
+ data,
+ error,
+ isLoading: !!lessonId && data === undefined && !notFound && !error,
+ notFound,
+ revalidate,
+ };
+};
-export const useHistoryCount = (agentId?: string) =>
- useClientDataSWR(agentId ? swrKeys.expertise.historyCount(agentId) : null, () =>
- expertiseService.countHistory(agentId!),
- );
+export const useHistoryCount = (agentId?: string) => {
+ const { error } = expertiseActions.useFetchHistoryCount(agentId);
+ const data = useExpertiseStore(expertiseSelectors.historyCount(agentId));
+ return { data, error };
+};
diff --git a/src/features/SelfLearning/index.tsx b/src/features/SelfLearning/index.tsx
index b234f9711ea..1dc009f593c 100644
--- a/src/features/SelfLearning/index.tsx
+++ b/src/features/SelfLearning/index.tsx
@@ -29,6 +29,7 @@ import { useWorkspaceAwareNavigate } from '@/features/Workspace/useWorkspaceAwar
import type { ExpertiseDomainItem } from '@/services/expertise';
import { expertiseService } from '@/services/expertise';
import { useAgentStore } from '@/store/agent';
+import { expertiseActions, useExpertiseStore } from '@/store/expertise';
import { countTiers, habitTier } from './helpers';
import { useExpertiseOverview, useHistoryCount } from './hooks';
@@ -65,18 +66,24 @@ const SelfLearning = memo(() => {
const [teachOpen, setTeachOpen] = useState(false);
const [teachDomainId, setTeachDomainId] = useState<string>();
- // Two-phase: read once to know how many lessons exist, then let the warm-up hook decide the poll.
- const first = useExpertiseOverview(activeAgentId ?? undefined);
- const learnedTotal = useMemo(
- () => first.data?.domains.reduce((a, d) => a + d.lessons.length, 0) ?? 0,
- [first.data],
+ // The portrait store tells how many lessons exist, and the warm-up hook decides the poll from
+ // that; both read the same replica entry, so this is one request.
+ const learnedTotal = useExpertiseStore(
+ (s) =>
+ (activeAgentId ? s.overviewMap[activeAgentId] : undefined)?.domains.reduce(
+ (a, d) => a + d.lessons.length,
+ 0,
+ ) ?? 0,
);
const warmup = useHistoryWarmup(activeAgentId ?? undefined, learnedTotal);
- const { data, error, mutate } = useExpertiseOverview(
+ const { data, error, isConfirmed, revalidate } = useExpertiseOverview(
activeAgentId ?? undefined,
warmup.refreshInterval,
);
const allDomains = useMemo(() => data?.domains ?? [], [data]);
+ // A restored portrait may be last session's empty one: it is not "no directions yet" until the
+ // server says so, so an empty local copy still reads as loading.
+ const settled = allDomains.length > 0 || isConfirmed ? data : undefined;
const scoped = useMemo(
() => (domainId ? allDomains.filter((d) => d.id === domainId) : allDomains),
[allDomains, domainId],
@@ -156,8 +163,7 @@ const SelfLearning = memo(() => {
? freshDomains.map((d) => d.title)
: [current?.title ?? scoped[0]?.title ?? ''];
// Only the warm-up card needs the candidate count, so it is not requested at all once every
- // direction has been practiced; when it is needed it batches with the portrait only on a
- // warm SWR cache (cold loads resolve the portrait first).
+ // direction has been practiced; a reload paints the last count from the local replica.
const { data: history } = useHistoryCount(showWarmup ? (activeAgentId ?? undefined) : undefined);
const teach = async (text: string) => {
@@ -167,7 +173,7 @@ const SelfLearning = memo(() => {
await expertiseService.teachLesson({ domainId: target, text });
toast.success(t('habit.teach.done'));
setTeachOpen(false);
- void mutate();
+ if (activeAgentId) void expertiseActions.afterLessonWrite(activeAgentId);
} catch {
toast.error(t('habit.teach.failed'));
}
@@ -190,9 +196,9 @@ const SelfLearning = memo(() => {
okText: t('domain.deleteConfirm.ok'),
onOk: async () => {
try {
- await expertiseService.deleteDomain(domain.id);
+ if (!activeAgentId) return;
+ await expertiseActions.deleteDomain(activeAgentId, domain.id);
toast.success(t('domain.deleted'));
- await mutate();
if (domainId && activeAgentId)
navigate(urlJoin('/agent', activeAgentId, 'self-evolving'));
} catch {
@@ -279,10 +285,11 @@ const SelfLearning = memo(() => {
<Flexbox className={styles.body} flex={1} width={'100%'}>
<WideScreenContainer>
<AsyncBoundary
- data={data}
+ data={settled}
error={error}
errorVariant={'page'}
- isEmpty={!error && allDomains.length === 0}
+ isEmpty={isConfirmed && !error && allDomains.length === 0}
+ isLoading={!settled && !error}
empty={
<Center height={'100%'} style={{ minHeight: '50vh' }} width={'100%'}>
<Empty
@@ -299,7 +306,7 @@ const SelfLearning = memo(() => {
/>
</Center>
}
- onRetry={() => mutate()}
+ onRetry={() => void revalidate()}
>
<Flexbox gap={20} paddingBlock={'22px 64px'}>
<Flexbox gap={4}>
@@ -363,7 +370,6 @@ const SelfLearning = memo(() => {
? urlJoin('/agent', activeAgentId, 'self-evolving', current.id, 'experience')
: undefined
}
- onChanged={() => void mutate()}
/>
)}
diff --git a/src/libs/swr/keys.frozen.test.ts b/src/libs/swr/keys.frozen.test.ts
index 0e82dcbbbe8..6c7a32259e4 100644
--- a/src/libs/swr/keys.frozen.test.ts
+++ b/src/libs/swr/keys.frozen.test.ts
@@ -65,13 +65,6 @@ const LEGACY_SWR_KEYS = [
'evalKeys.runs',
'evalKeys.testCaseDetail',
'evalKeys.testCases',
- 'expertiseKeys.domain',
- 'expertiseKeys.historyCount',
- 'expertiseKeys.lesson',
- 'expertiseKeys.overview',
- 'expertiseKeys.ruleRevisions',
- 'expertiseKeys.ruleSources',
- 'expertiseKeys.rules',
'favoriteKeys.status',
'fileKeys.ttsFile',
'forkKeys.groupSource',
diff --git a/src/libs/swr/keys.ts b/src/libs/swr/keys.ts
index a8369eda4af..4f96779b4b4 100644
--- a/src/libs/swr/keys.ts
+++ b/src/libs/swr/keys.ts
@@ -627,25 +627,6 @@ export const scmKeys = {
};
// ---- verify (deliverable judging) ---------------------------------------
-export const expertiseKeys = {
- domain: def('expertise:domain', (domainId: string) => ['expertise:domain', domainId]),
- historyCount: def('expertise:historyCount', (agentId: string) => [
- 'expertise:historyCount',
- agentId,
- ]),
- lesson: def('expertise:lesson', (lessonId: string) => ['expertise:lesson', lessonId]),
- overview: def('expertise:overview', (agentId: string) => ['expertise:overview', agentId]),
- ruleRevisions: def('expertise:ruleRevisions', (lessonId: string) => [
- 'expertise:ruleRevisions',
- lessonId,
- ]),
- ruleSources: def('expertise:ruleSources', (lessonId: string) => [
- 'expertise:ruleSources',
- lessonId,
- ]),
- rules: def('expertise:rules', () => ['expertise:rules']),
-};
-
export const verifyKeys = {
acceptancePurgePreview: def('verify:acceptancePurgePreview', (acceptanceId: string) => [
'verify:acceptancePurgePreview',
@@ -958,7 +939,6 @@ export const swrKeys = {
discover: discoverKeys,
electron: electronKeys,
eval: evalKeys,
- expertise: expertiseKeys,
favorite: favoriteKeys,
file: fileKeys,
fork: forkKeys,
diff --git a/src/routes/(main)/agent/self-learning/selfLearningLoader.ts b/src/routes/(main)/agent/self-learning/selfLearningLoader.ts
new file mode 100644
index 00000000000..da371cb6b68
--- /dev/null
+++ b/src/routes/(main)/agent/self-learning/selfLearningLoader.ts
@@ -0,0 +1,23 @@
+import type { LoaderFunctionArgs } from 'react-router';
+
+import { PRE_PAINT_HYDRATE_TIMEOUT, settleWithin } from '@/libs/replica/prePaint';
+import { expertiseActions } from '@/store/expertise';
+
+/**
+ * Route loader for an agent's Self-evolving pages (`/agent/:aid/self-evolving/*`).
+ *
+ * Seeds the persisted portrait โ€” and, on a lesson deep link, that lesson โ€”
+ * before the route commits, so the page paints the last copy instead of its
+ * loader while IndexedDB answers.
+ */
+export const selfLearningLoader = async ({ params }: LoaderFunctionArgs): Promise<null> => {
+ await settleWithin(
+ Promise.all([
+ params.aid ? expertiseActions.preHydrateOverview(params.aid) : undefined,
+ params.lessonId ? expertiseActions.preHydrateLesson(params.lessonId) : undefined,
+ ]),
+ PRE_PAINT_HYDRATE_TIMEOUT,
+ );
+
+ return null;
+};
diff --git a/src/routes/(main)/memory/rules/rulesLoader.ts b/src/routes/(main)/memory/rules/rulesLoader.ts
new file mode 100644
index 00000000000..d1fd583a442
--- /dev/null
+++ b/src/routes/(main)/memory/rules/rulesLoader.ts
@@ -0,0 +1,15 @@
+import { PRE_PAINT_HYDRATE_TIMEOUT, settleWithin } from '@/libs/replica/prePaint';
+import { expertiseActions } from '@/store/expertise';
+
+/**
+ * Route loader for My rules (`/memory/rules`).
+ *
+ * Route loaders run before React commits the route: the only point where the
+ * persisted rule sheet (an async IndexedDB read) can land before the page
+ * paints its loader.
+ */
+export const memoryRulesLoader = async (): Promise<null> => {
+ await settleWithin(expertiseActions.preHydrateRules(), PRE_PAINT_HYDRATE_TIMEOUT);
+
+ return null;
+};
diff --git a/src/spa/router/agentPageRoutes.tsx b/src/spa/router/agentPageRoutes.tsx
index 4588bf343f9..f67336f87d3 100644
--- a/src/spa/router/agentPageRoutes.tsx
+++ b/src/spa/router/agentPageRoutes.tsx
@@ -17,6 +17,7 @@ import {
} from '@/routes/(main)/agent/features/routeMeta';
import { agentDocumentListLoader } from '@/spa/router/agentDocumentListLoader';
import { channelDataLoader } from '@/spa/router/channelDataLoader';
+import { selfLearningLoader } from '@/spa/router/expertiseLoaders';
import { NoRouteSkeleton, routeMeta } from '@/spa/router/routeMeta';
import { scheduledTaskListLoader } from '@/spa/router/scheduledTaskListLoader';
import { dynamicElement, dynamicLayout, redirectElement } from '@/utils/router';
@@ -137,6 +138,7 @@ export const agentPageChildren: RouteObject[] = [
'Desktop > Chat > Self Learning',
),
handle: { meta: agentSelfLearningRouteMeta },
+ loader: selfLearningLoader,
path: 'self-evolving',
},
{
@@ -189,6 +191,7 @@ export const agentPageChildren: RouteObject[] = [
path: 'rules/:lessonId',
},
],
+ loader: selfLearningLoader,
path: 'self-evolving/:domainId',
},
// Legacy `/self-learning` deep-links keep their remaining path when redirected.
diff --git a/src/spa/router/expertiseLoaders.ts b/src/spa/router/expertiseLoaders.ts
new file mode 100644
index 00000000000..04f291e3c24
--- /dev/null
+++ b/src/spa/router/expertiseLoaders.ts
@@ -0,0 +1,13 @@
+import type { LoaderFunctionArgs } from 'react-router';
+
+// The route tables sit in the entry chunk's static graph; resolving the real
+// loaders on first use keeps the expertise store in the My rules and
+// Self-evolving routes' lazy chunks.
+
+export const memoryRulesLoader = () =>
+ import('@/routes/(main)/memory/rules/rulesLoader').then((module) => module.memoryRulesLoader());
+
+export const selfLearningLoader = (args: LoaderFunctionArgs) =>
+ import('@/routes/(main)/agent/self-learning/selfLearningLoader').then((module) =>
+ module.selfLearningLoader(args),
+ );
diff --git a/src/spa/router/expertiseLoaders.wiring.test.ts b/src/spa/router/expertiseLoaders.wiring.test.ts
new file mode 100644
index 00000000000..1676959be76
--- /dev/null
+++ b/src/spa/router/expertiseLoaders.wiring.test.ts
@@ -0,0 +1,56 @@
+// @vitest-environment happy-dom
+import type { LoaderFunctionArgs, RouteObject } from 'react-router';
+import { describe, expect, it, vi } from 'vitest';
+
+import { desktopRoutes } from './desktopRouter.config';
+import { memoryRulesLoader, selfLearningLoader } from './expertiseLoaders';
+
+const loaderModules = vi.hoisted(() => ({ evaluated: [] as string[] }));
+
+// Evaluating a real loader means the expertise store reached the entry chunk's
+// first-screen graph.
+vi.mock('@/routes/(main)/memory/rules/rulesLoader', () => {
+ loaderModules.evaluated.push('rules');
+ return { memoryRulesLoader: vi.fn(async () => null) };
+});
+vi.mock('@/routes/(main)/agent/self-learning/selfLearningLoader', () => {
+ loaderModules.evaluated.push('selfLearning');
+ return { selfLearningLoader: vi.fn(async () => null) };
+});
+
+const flatten = (routes: RouteObject[]): RouteObject[] =>
+ routes.flatMap((route) => [route, ...(route.children ? flatten(route.children) : [])]);
+
+describe('expertise loader wiring', () => {
+ it('does not load the store-backed loaders while the route tables load', () => {
+ expect(loaderModules.evaluated).toEqual([]);
+ });
+
+ it('pre-hydrates the rule sheet on the My rules route', () => {
+ const routes = flatten(desktopRoutes).filter(
+ (r) => r.path === 'rules' && r.loader === memoryRulesLoader,
+ );
+
+ expect(routes.length).toBeGreaterThan(0);
+ });
+
+ it("pre-hydrates the agent's portrait on every Self-evolving portrait route", () => {
+ const routes = flatten(desktopRoutes).filter(
+ (r) => r.path === 'self-evolving' || r.path === 'self-evolving/:domainId',
+ );
+
+ expect(routes.length).toBeGreaterThanOrEqual(2);
+ expect(routes.map((r) => r.loader)).toEqual(routes.map(() => selfLearningLoader));
+ });
+
+ it('delegates to the real loaders on first use', async () => {
+ const rules = await import('@/routes/(main)/memory/rules/rulesLoader');
+ const selfLearning = await import('@/routes/(main)/agent/self-learning/selfLearningLoader');
+ const args = { params: { aid: 'agent-1' } } as unknown as LoaderFunctionArgs;
+
+ await expect(memoryRulesLoader()).resolves.toBeNull();
+ await expect(selfLearningLoader(args)).resolves.toBeNull();
+ expect(rules.memoryRulesLoader).toHaveBeenCalled();
+ expect(selfLearning.selfLearningLoader).toHaveBeenCalledWith(args);
+ });
+});
diff --git a/src/spa/router/memoryRoutes.tsx b/src/spa/router/memoryRoutes.tsx
index f2ae694c496..3faee39d933 100644
--- a/src/spa/router/memoryRoutes.tsx
+++ b/src/spa/router/memoryRoutes.tsx
@@ -3,6 +3,7 @@ import type { RouteObject } from 'react-router';
import MemorySkeleton from '@/components/Skeleton/Memory';
import { activityListLoader } from '@/spa/router/activityListLoader';
+import { memoryRulesLoader } from '@/spa/router/expertiseLoaders';
import { identitiesListLoader } from '@/spa/router/identitiesListLoader';
import { preferenceListLoader } from '@/spa/router/preferenceListLoader';
import { routeMeta } from '@/spa/router/routeMeta';
@@ -71,6 +72,7 @@ export const memoryChildren: RouteObject[] = [
// Same icon the memory sidebar uses, so a desktop tab and the nav item agree.
meta: routeMeta({ icon: Scale, titleKey: 'navigation.memoryRules' }),
},
+ loader: memoryRulesLoader,
path: 'rules',
},
{
diff --git a/src/store/expertise/action.test.ts b/src/store/expertise/action.test.ts
new file mode 100644
index 00000000000..b30fccb5111
--- /dev/null
+++ b/src/store/expertise/action.test.ts
@@ -0,0 +1,219 @@
+/**
+ * Writes on the expertise replicas land on the local copy and its persisted
+ * row, not only on a best-effort refetch: a retired habit or deleted direction
+ * stays gone after a reload, and a failed write rolls back. Each "reload"
+ * re-imports every module over the same IndexedDB.
+ */
+import { act, renderHook, waitFor } from '@testing-library/react';
+import { createElement, type ReactNode } from 'react';
+import { SWRConfig } from 'swr';
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+const services = vi.hoisted(() => ({
+ deleteDomain: vi.fn(),
+ getDomain: vi.fn(),
+ listByAgent: vi.fn(),
+ listRules: vi.fn(),
+ retireLesson: vi.fn(),
+ updateRule: vi.fn(),
+}));
+const scope = vi.hoisted(() => ({ current: 'u1:personal' }));
+
+vi.mock('@/services/expertise', () => ({ expertiseService: services }));
+vi.mock('@/libs/swr/useCacheScope', () => ({
+ getCacheScope: () => scope.current,
+ isScopeTrusted: () => true,
+ useCacheScope: () => scope.current,
+}));
+
+const never = () => new Promise<never>(() => {});
+const settle = () =>
+ act(async () => {
+ await new Promise((resolve) => setTimeout(resolve, 50));
+ });
+
+const wrapper = ({ children }: { children: ReactNode }) =>
+ createElement(SWRConfig, { value: { dedupingInterval: 0, provider: () => new Map() } }, children);
+
+const portrait = () => ({
+ domains: [
+ {
+ id: 'd1',
+ lessons: [
+ { id: 'l1', title: 'Keep' },
+ { id: 'l2', title: 'Retire me' },
+ ],
+ runCount: 3,
+ title: 'Review',
+ },
+ { id: 'd2', lessons: [], runCount: 0, title: 'Drop me' },
+ ],
+});
+
+const sheet = () => ({
+ backlogRounds: 0,
+ groups: [
+ {
+ domain: { id: 'g1' },
+ rules: [{ direction: 'positive', enforcement: 'soft', id: 'r1', status: 'active' }],
+ },
+ ],
+});
+
+const boot = async () => {
+ vi.resetModules();
+ const store = await import('./index');
+ return store;
+};
+
+/** Mount the portrait sync, wait for it, and return the store module. */
+const loadPortrait = async () => {
+ const store = await boot();
+ const view = renderHook(() => store.expertiseActions.useFetchOverview('agent-1'), { wrapper });
+ await waitFor(() =>
+ expect(store.useExpertiseStore.getState().overviewMap['agent-1']).toBeDefined(),
+ );
+ return { store, view };
+};
+
+const lessonIds = (store: Awaited<ReturnType<typeof boot>>) =>
+ store.useExpertiseStore
+ .getState()
+ .overviewMap['agent-1']?.domains.flatMap((d) => d.lessons.map((l) => l.id));
+
+let run = 0;
+
+beforeEach(() => {
+ scope.current = `expertise-${++run}:personal`;
+ for (const fn of Object.values(services)) fn.mockReset();
+});
+
+describe('retireLesson', () => {
+ it('drops the habit from the portrait and from its persisted copy', async () => {
+ services.listByAgent.mockResolvedValueOnce(portrait());
+ const { store, view } = await loadPortrait();
+
+ services.retireLesson.mockResolvedValue(undefined);
+ // The server's answer after the write no longer lists the habit.
+ const after = portrait();
+ after.domains[0].lessons = [after.domains[0].lessons[0]];
+ services.listByAgent.mockResolvedValue(after);
+ await act(() => store.expertiseActions.retireLesson('agent-1', 'l2'));
+ expect(lessonIds(store)).toEqual(['l1']);
+ // Let the persisted write land before the "reload".
+ await settle();
+ view.unmount();
+
+ // Reload offline: the retired habit must not come back from the local copy.
+ services.listByAgent.mockImplementation(never);
+ const reloaded = await boot();
+ renderHook(() => reloaded.expertiseActions.useFetchOverview('agent-1'), { wrapper });
+ await waitFor(() =>
+ expect(reloaded.useExpertiseStore.getState().overviewMap['agent-1']).toBeDefined(),
+ );
+ expect(lessonIds(reloaded)).toEqual(['l1']);
+ });
+
+ it('puts the habit back when the call fails', async () => {
+ services.listByAgent.mockResolvedValueOnce(portrait());
+ const { store } = await loadPortrait();
+
+ services.retireLesson.mockRejectedValue(new Error('500'));
+ services.listByAgent.mockImplementation(never);
+ await act(async () => {
+ await expect(store.expertiseActions.retireLesson('agent-1', 'l2')).rejects.toThrow('500');
+ });
+
+ expect(lessonIds(store)).toEqual(['l1', 'l2']);
+ });
+});
+
+describe('deleteDomain', () => {
+ it('drops the direction and its detail entry, persisted', async () => {
+ services.listByAgent.mockResolvedValueOnce(portrait());
+ services.getDomain.mockResolvedValueOnce({ domain: { id: 'd2', title: 'Drop me' } });
+ const { store, view } = await loadPortrait();
+ const detail = renderHook(() => store.expertiseActions.useFetchDomain('d2'), { wrapper });
+ await waitFor(() => expect(store.useExpertiseStore.getState().domainMap.d2).toBeDefined());
+ detail.unmount();
+
+ services.deleteDomain.mockResolvedValue(undefined);
+ services.listByAgent.mockImplementation(never);
+ await act(async () => {
+ void store.expertiseActions.deleteDomain('agent-1', 'd2');
+ await new Promise((resolve) => setTimeout(resolve, 20));
+ });
+ expect(
+ store.useExpertiseStore.getState().overviewMap['agent-1']?.domains.map((d) => d.id),
+ ).toEqual(['d1']);
+ expect(store.useExpertiseStore.getState().domainMap.d2).toBeUndefined();
+ view.unmount();
+
+ services.getDomain.mockImplementation(never);
+ const reloaded = await boot();
+ renderHook(
+ () => {
+ reloaded.expertiseActions.useFetchOverview('agent-1');
+ reloaded.expertiseActions.useFetchDomain('d2');
+ },
+ { wrapper },
+ );
+ await waitFor(() =>
+ expect(reloaded.useExpertiseStore.getState().overviewMap['agent-1']).toBeDefined(),
+ );
+ await settle();
+ expect(
+ reloaded.useExpertiseStore.getState().overviewMap['agent-1']?.domains.map((d) => d.id),
+ ).toEqual(['d1']);
+ expect(reloaded.useExpertiseStore.getState().domainMap.d2).toBeUndefined();
+ });
+});
+
+describe('patchRules', () => {
+ it('shows the switch at once and rolls it back when the save fails', async () => {
+ services.listRules.mockResolvedValueOnce(sheet());
+ const store = await boot();
+ renderHook(() => store.expertiseActions.useFetchRules(), { wrapper });
+ await waitFor(() =>
+ expect(store.expertiseSelectors.rules(store.useExpertiseStore.getState())).toBeDefined(),
+ );
+
+ const enforcement = () =>
+ store.expertiseSelectors.rules(store.useExpertiseStore.getState())?.groups[0].rules[0]
+ .enforcement;
+ let fail!: (error: unknown) => void;
+ services.updateRule.mockImplementation(() => new Promise((_, reject) => (fail = reject)));
+
+ let pending!: Promise<unknown>;
+ act(() => {
+ pending = store.expertiseActions.patchRules(
+ (data) => ({
+ ...data,
+ groups: data.groups.map((g) => ({
+ ...g,
+ rules: g.rules.map((r) => ({ ...r, enforcement: 'hard' as never })),
+ })),
+ }),
+ () => services.updateRule('r1', { enforcement: 'hard' }),
+ );
+ });
+ expect(enforcement()).toBe('hard');
+
+ await act(async () => {
+ fail(new Error('500'));
+ await expect(pending).rejects.toThrow('500');
+ });
+ expect(enforcement()).toBe('soft');
+ });
+});
+
+describe('reset', () => {
+ it("clears every sheet so the next identity never sees the previous one's", async () => {
+ services.listByAgent.mockResolvedValueOnce(portrait());
+ const { store } = await loadPortrait();
+
+ act(() => store.expertiseActions.reset());
+
+ expect(store.useExpertiseStore.getState().overviewMap).toEqual({});
+ });
+});
diff --git a/src/store/expertise/action.ts b/src/store/expertise/action.ts
new file mode 100644
index 00000000000..6656e3f3fac
--- /dev/null
+++ b/src/store/expertise/action.ts
@@ -0,0 +1,305 @@
+import { cacheScope, createReplicaSlice, recordLens, type ReplicaSyncResult } from '@/libs/replica';
+import { subscribeCacheScope } from '@/libs/replica/cacheScopeEvents';
+import {
+ type ExpertiseDomainDetail,
+ type ExpertiseLessonDetail,
+ type ExpertiseOverview,
+ expertiseService,
+ type RuleRevision,
+ type RuleSource,
+ type RulesOverview,
+} from '@/services/expertise';
+import type { StoreSetter } from '@/store/types';
+import { setNamespace } from '@/utils/storeDebug';
+
+import { type ExpertiseState, initialState } from './initialState';
+import {
+ expertiseDomainResource,
+ type ExpertiseHistoryCount,
+ expertiseHistoryCountResource,
+ expertiseLessonResource,
+ expertiseOverviewResource,
+ expertiseRuleRevisionsResource,
+ expertiseRuleSourcesResource,
+ expertiseRulesResource,
+ RULES_KEY,
+} from './projection';
+import { useExpertiseStore } from './store';
+
+const n = setNamespace('expertise');
+
+type Setter = StoreSetter<ExpertiseState>;
+
+/**
+ * The portrait is read by the page header, the warm-up hook and the habit list
+ * at once, and a lesson by its hover preview and its page: one request answers
+ * every mounted reader. Explicit revalidations (retry, after a write) are not
+ * deduped.
+ */
+const EXPERTISE_DEDUPE_MS = 10_000;
+
+const SYNC_OPTIONS = { dedupingInterval: EXPERTISE_DEDUPE_MS };
+
+const withoutKey = (map: Record<string, true>, key: string): Record<string, true> => {
+ if (!map[key]) return map;
+ const next = { ...map };
+ delete next[key];
+ return next;
+};
+
+export class ExpertiseActionImpl {
+ readonly #domain;
+ readonly #get: () => ExpertiseState;
+ readonly #historyCount;
+ readonly #lesson;
+ readonly #overview;
+ readonly #ruleRevisions;
+ readonly #ruleSources;
+ readonly #rules;
+ readonly #set: Setter;
+
+ constructor(set: Setter, get: () => ExpertiseState) {
+ this.#set = set;
+ this.#get = get;
+
+ this.#rules = createReplicaSlice(expertiseRulesResource, {
+ actionPrefix: n('rules'),
+ fetcher: () => expertiseService.listRules(),
+ get,
+ set,
+ stateKey: 'rulesReplica',
+ view: recordLens<ExpertiseState, RulesOverview>('rulesMap'),
+ });
+ this.#ruleSources = createReplicaSlice(expertiseRuleSourcesResource, {
+ actionPrefix: n('ruleSources'),
+ fetcher: (lessonId) => expertiseService.ruleSources(lessonId),
+ get,
+ set,
+ stateKey: 'ruleSourcesReplica',
+ view: recordLens<ExpertiseState, RuleSource[]>('ruleSourcesMap'),
+ });
+ this.#ruleRevisions = createReplicaSlice(expertiseRuleRevisionsResource, {
+ actionPrefix: n('ruleRevisions'),
+ fetcher: (lessonId) => expertiseService.ruleRevisions(lessonId),
+ get,
+ set,
+ stateKey: 'ruleRevisionsReplica',
+ view: recordLens<ExpertiseState, RuleRevision[]>('ruleRevisionsMap'),
+ });
+ this.#overview = createReplicaSlice(expertiseOverviewResource, {
+ actionPrefix: n('overview'),
+ fetcher: (agentId) => expertiseService.listByAgent(agentId),
+ get,
+ set,
+ stateKey: 'overviewReplica',
+ view: recordLens<ExpertiseState, ExpertiseOverview>('overviewMap'),
+ });
+ this.#domain = createReplicaSlice(expertiseDomainResource, {
+ actionPrefix: n('domain'),
+ fetcher: (domainId) => expertiseService.getDomain(domainId),
+ get,
+ // `null` is a direction that is gone: drop the entry and its persisted row.
+ isMissing: (incoming) => !incoming,
+ merge: (incoming) => incoming ?? undefined,
+ set,
+ stateKey: 'domainReplica',
+ view: recordLens<ExpertiseState, ExpertiseDomainDetail>('domainMap'),
+ });
+ this.#lesson = createReplicaSlice(expertiseLessonResource, {
+ actionPrefix: n('lesson'),
+ effects: {
+ onApplied: (_detail, lessonId) => this.#setLessonNotFound(lessonId, false),
+ onMissing: (lessonId) => this.#setLessonNotFound(lessonId, true),
+ },
+ fetcher: (lessonId) => expertiseService.getLesson(lessonId),
+ get,
+ isMissing: (incoming) => !incoming,
+ merge: (incoming) => incoming ?? undefined,
+ set,
+ stateKey: 'lessonReplica',
+ view: recordLens<ExpertiseState, ExpertiseLessonDetail>('lessonMap'),
+ });
+ this.#historyCount = createReplicaSlice(expertiseHistoryCountResource, {
+ actionPrefix: n('historyCount'),
+ fetcher: (agentId) => expertiseService.countHistory(agentId),
+ get,
+ set,
+ stateKey: 'historyCountReplica',
+ view: recordLens<ExpertiseState, ExpertiseHistoryCount>('historyCountMap'),
+ });
+
+ // The not-found map is not a replica: a scope switch must not carry one
+ // workspace's "gone" over to another that may own the same id.
+ subscribeCacheScope(this.#forgetNotFoundOnScopeChange);
+ }
+
+ // โ”€โ”€โ”€ reads โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
+
+ /** The reviewer's rule sheet; data via `expertiseSelectors.rules`. */
+ useFetchRules = (enabled = true): ReplicaSyncResult =>
+ this.#rules.useSync(enabled ? RULES_KEY : null, SYNC_OPTIONS);
+
+ useFetchRuleSources = (lessonId?: string): ReplicaSyncResult =>
+ this.#ruleSources.useSync(lessonId, SYNC_OPTIONS);
+
+ useFetchRuleRevisions = (lessonId?: string): ReplicaSyncResult =>
+ this.#ruleRevisions.useSync(lessonId, SYNC_OPTIONS);
+
+ /**
+ * One agent's portrait. `refreshInterval` is only set while a history
+ * warm-up is running so newly learned habits stream in without a reload.
+ */
+ useFetchOverview = (agentId?: string, refreshInterval?: number): ReplicaSyncResult =>
+ this.#overview.useSync(agentId, { ...SYNC_OPTIONS, refreshInterval });
+
+ useFetchDomain = (domainId?: string): ReplicaSyncResult =>
+ this.#domain.useSync(domainId, SYNC_OPTIONS);
+
+ useFetchLesson = (lessonId?: string): ReplicaSyncResult =>
+ this.#lesson.useSync(lessonId, SYNC_OPTIONS);
+
+ useFetchHistoryCount = (agentId?: string): ReplicaSyncResult =>
+ this.#historyCount.useSync(agentId, SYNC_OPTIONS);
+
+ refreshRules = async (): Promise<void> => {
+ await this.#rules.fetch(RULES_KEY, { fresh: true });
+ };
+
+ refreshRuleRevisions = async (lessonId: string): Promise<void> => {
+ await this.#ruleRevisions.fetch(lessonId, { fresh: true });
+ };
+
+ refreshOverview = async (agentId: string): Promise<void> => {
+ await this.#overview.fetch(agentId, { fresh: true });
+ };
+
+ // โ”€โ”€โ”€ writes โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
+
+ /**
+ * Apply `apply` to the rule sheet at once and run `serverCall`; a failed call
+ * rolls the sheet back to the last confirmed value and rethrows. The sheet is
+ * re-read afterwards either way, by the caller.
+ */
+ patchRules = <T>(
+ apply: (data: RulesOverview) => RulesOverview,
+ serverCall: () => Promise<T>,
+ ): Promise<T> => {
+ // Nothing on screen yet: there is no sheet to patch, only the call to make.
+ if (!this.#get().rulesMap[RULES_KEY]) return serverCall();
+ return this.#rules.optimistic(RULES_KEY, apply, serverCall);
+ };
+
+ /** Teach, revise or any portrait write that the server reshapes: re-read the portrait. */
+ afterLessonWrite = async (agentId: string, lessonId?: string): Promise<void> => {
+ await Promise.all([
+ this.refreshOverview(agentId),
+ lessonId && this.#get().lessonMap[lessonId]
+ ? this.#lesson.fetch(lessonId, { fresh: true })
+ : undefined,
+ ]);
+ };
+
+ /** The habit drops from the portrait at once (and from its persisted copy); it returns on failure. */
+ retireLesson = async (agentId: string, lessonId: string): Promise<void> => {
+ await this.#optimisticOverview(
+ agentId,
+ (data) => ({
+ ...data,
+ domains: data.domains.map((d) => ({
+ ...d,
+ lessons: d.lessons.filter((l) => l.id !== lessonId),
+ })),
+ }),
+ () => expertiseService.retireLesson(lessonId),
+ );
+ await this.afterLessonWrite(agentId, lessonId);
+ };
+
+ /** The direction drops from the portrait and its detail entry is removed with its persisted row. */
+ deleteDomain = async (agentId: string, domainId: string): Promise<void> => {
+ await this.#optimisticOverview(
+ agentId,
+ (data) => ({ ...data, domains: data.domains.filter((d) => d.id !== domainId) }),
+ () => expertiseService.deleteDomain(domainId),
+ );
+ this.#domain.remove(domainId);
+ await this.refreshOverview(agentId);
+ };
+
+ // โ”€โ”€โ”€ cold start โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
+
+ /**
+ * Seed the persisted rule sheet before the route commits (see the My rules
+ * route loader): `useSync` only hydrates after mount, which would leave the
+ * page on its loader for the IndexedDB read.
+ */
+ preHydrateRules = (): Promise<boolean> => {
+ const scope = cacheScope.get();
+ // The slot may still hold the previous identity's rows; drop them before seeding.
+ this.#rules.ensureScope(scope);
+ return this.#rules.hydrate(RULES_KEY, scope);
+ };
+
+ /** Same as `preHydrateRules`, for an agent's Self-evolving portrait. */
+ preHydrateOverview = (agentId: string): Promise<boolean> => {
+ const scope = cacheScope.get();
+ this.#overview.ensureScope(scope);
+ return this.#overview.hydrate(agentId, scope);
+ };
+
+ /** A lesson deep link (`โ€ฆ/experience/:lessonId`) paints its last copy before the route commits. */
+ preHydrateLesson = (lessonId: string): Promise<boolean> => {
+ const scope = cacheScope.get();
+ this.#lesson.ensureScope(scope);
+ return this.#lesson.hydrate(lessonId, scope);
+ };
+
+ reset = (): void => {
+ // `clear()` drops in-flight reads of the previous data context and this
+ // scope's persisted rows, so a new identity never paints the old sheet.
+ for (const slice of [
+ this.#domain,
+ this.#historyCount,
+ this.#lesson,
+ this.#overview,
+ this.#ruleRevisions,
+ this.#ruleSources,
+ this.#rules,
+ ]) {
+ void slice.clear();
+ }
+ this.#set(initialState, false, n('reset'));
+ };
+
+ #optimisticOverview = <T>(
+ agentId: string,
+ apply: (data: ExpertiseOverview) => ExpertiseOverview,
+ serverCall: () => Promise<T>,
+ ): Promise<T> => {
+ if (!this.#get().overviewMap[agentId]) return serverCall();
+ return this.#overview.optimistic(agentId, apply, serverCall);
+ };
+
+ #setLessonNotFound = (lessonId: string, notFound: boolean): void => {
+ const current = this.#get().lessonNotFoundMap;
+ if (notFound === !!current[lessonId]) return;
+ this.#set(
+ {
+ lessonNotFoundMap: notFound
+ ? { ...current, [lessonId]: true }
+ : withoutKey(current, lessonId),
+ },
+ false,
+ n('setLessonNotFound'),
+ );
+ };
+
+ #forgetNotFoundOnScopeChange = (): void => {
+ if (Object.keys(this.#get().lessonNotFoundMap).length === 0) return;
+ this.#set({ lessonNotFoundMap: {} }, false, n('scopeChanged'));
+ };
+}
+
+const { getState, setState } = useExpertiseStore;
+
+export const expertiseActions = new ExpertiseActionImpl(setState, getState);
diff --git a/src/store/expertise/index.ts b/src/store/expertise/index.ts
new file mode 100644
index 00000000000..da7c7c99e30
--- /dev/null
+++ b/src/store/expertise/index.ts
@@ -0,0 +1,3 @@
+export { expertiseActions } from './action';
+export { expertiseSelectors } from './selectors';
+export { useExpertiseStore } from './store';
diff --git a/src/store/expertise/initialState.ts b/src/store/expertise/initialState.ts
new file mode 100644
index 00000000000..188af117479
--- /dev/null
+++ b/src/store/expertise/initialState.ts
@@ -0,0 +1,55 @@
+import { createReplicaState, type ReplicaState } from '@/libs/replica';
+import type {
+ ExpertiseDomainDetail,
+ ExpertiseLessonDetail,
+ ExpertiseOverview,
+ RuleRevision,
+ RuleSource,
+ RulesOverview,
+} from '@/services/expertise';
+
+import type { ExpertiseHistoryCount } from './projection';
+
+export interface ExpertiseState {
+ /** One direction per domain id (replica view). */
+ domainMap: Record<string, ExpertiseDomainDetail>;
+ domainReplica: ReplicaState<ExpertiseDomainDetail>;
+ /** Warm-up candidate count per agent id (replica view). */
+ historyCountMap: Record<string, ExpertiseHistoryCount>;
+ historyCountReplica: ReplicaState<ExpertiseHistoryCount>;
+ /** One lesson with its hits per lesson id (replica view). */
+ lessonMap: Record<string, ExpertiseLessonDetail>;
+ /** Lesson ids the server confirmed are gone, in the active scope. */
+ lessonNotFoundMap: Record<string, true>;
+ lessonReplica: ReplicaState<ExpertiseLessonDetail>;
+ /** One agent's portrait per agent id (replica view). */
+ overviewMap: Record<string, ExpertiseOverview>;
+ overviewReplica: ReplicaState<ExpertiseOverview>;
+ /** A rule's edits per lesson id (replica view). */
+ ruleRevisionsMap: Record<string, RuleRevision[]>;
+ ruleRevisionsReplica: ReplicaState<RuleRevision[]>;
+ /** The reviewer's rule sheet under `RULES_KEY` (replica view). */
+ rulesMap: Record<string, RulesOverview>;
+ /** A rule's evidence per lesson id (replica view). */
+ ruleSourcesMap: Record<string, RuleSource[]>;
+ ruleSourcesReplica: ReplicaState<RuleSource[]>;
+ rulesReplica: ReplicaState<RulesOverview>;
+}
+
+export const initialState: ExpertiseState = {
+ domainMap: {},
+ domainReplica: createReplicaState(),
+ historyCountMap: {},
+ historyCountReplica: createReplicaState(),
+ lessonMap: {},
+ lessonNotFoundMap: {},
+ lessonReplica: createReplicaState(),
+ overviewMap: {},
+ overviewReplica: createReplicaState(),
+ ruleRevisionsMap: {},
+ ruleRevisionsReplica: createReplicaState(),
+ ruleSourcesMap: {},
+ ruleSourcesReplica: createReplicaState(),
+ rulesMap: {},
+ rulesReplica: createReplicaState(),
+};
diff --git a/src/store/expertise/projection.ts b/src/store/expertise/projection.ts
new file mode 100644
index 00000000000..d40f109ea06
--- /dev/null
+++ b/src/store/expertise/projection.ts
@@ -0,0 +1,96 @@
+import { defineReplica } from '@/libs/replica';
+import type {
+ ExpertiseDomainDetail,
+ ExpertiseLessonDetail,
+ ExpertiseOverview,
+ expertiseService,
+ RuleRevision,
+ RuleSource,
+ RulesOverview,
+} from '@/services/expertise';
+
+/** The only entry of the reviewer's rule sheet: one query, no parameters. */
+export const RULES_KEY = 'self';
+
+/** The candidate count the history warm-up card shows. */
+export type ExpertiseHistoryCount = Awaited<ReturnType<typeof expertiseService.countHistory>>;
+
+/**
+ * Every expertise read is persisted to IndexedDB under the replica's user +
+ * workspace scope, so My rules and an agent's Self-evolving pages paint the last
+ * sheet on reload and revalidate in the background. Resource names stay clear
+ * of the legacy SWR `expertise:` keys so nothing is stored twice.
+ */
+export const expertiseRulesResource = defineReplica<typeof RULES_KEY, RulesOverview>({
+ key: () => RULES_KEY,
+ name: 'expertiseRules',
+ storage: 'indexedDB',
+ version: 1,
+});
+
+/** The evidence a rule grew from, per lesson id (the rule document's sources section). */
+export const expertiseRuleSourcesResource = defineReplica<string, RuleSource[]>({
+ key: (lessonId) => lessonId,
+ name: 'expertiseRuleSources',
+ persist: { maxEntries: 30 },
+ storage: 'indexedDB',
+ version: 1,
+});
+
+/** The edits a rule has been through, per lesson id. */
+export const expertiseRuleRevisionsResource = defineReplica<string, RuleRevision[]>({
+ key: (lessonId) => lessonId,
+ name: 'expertiseRuleRevisions',
+ persist: { maxEntries: 30 },
+ storage: 'indexedDB',
+ version: 1,
+});
+
+/** One agent's portrait: its directions and their lessons, per agent id. */
+export const expertiseOverviewResource = defineReplica<string, ExpertiseOverview>({
+ key: (agentId) => agentId,
+ name: 'expertiseOverview',
+ persist: { maxEntries: 20 },
+ storage: 'indexedDB',
+ version: 1,
+});
+
+/**
+ * One direction, per domain id. The server answers `null` for a direction that
+ * is gone; the slice keeps that as a missing entry.
+ */
+export const expertiseDomainResource = defineReplica<
+ string,
+ ExpertiseDomainDetail,
+ ExpertiseDomainDetail | null
+>({
+ key: (domainId) => domainId,
+ name: 'expertiseDomain',
+ persist: { maxEntries: 30 },
+ storage: 'indexedDB',
+ version: 1,
+});
+
+/**
+ * One lesson with its hits, per lesson id. Hovering a habit row prefetches it,
+ * so only the most recent ones survive a reload.
+ */
+export const expertiseLessonResource = defineReplica<
+ string,
+ ExpertiseLessonDetail,
+ ExpertiseLessonDetail | null
+>({
+ key: (lessonId) => lessonId,
+ name: 'expertiseLesson',
+ persist: { maxEntries: 50 },
+ storage: 'indexedDB',
+ version: 1,
+});
+
+export const expertiseHistoryCountResource = defineReplica<string, ExpertiseHistoryCount>({
+ key: (agentId) => agentId,
+ name: 'expertiseHistoryCount',
+ persist: { maxEntries: 20 },
+ storage: 'indexedDB',
+ version: 1,
+});
diff --git a/src/store/expertise/selectors.ts b/src/store/expertise/selectors.ts
new file mode 100644
index 00000000000..8003b3cc446
--- /dev/null
+++ b/src/store/expertise/selectors.ts
@@ -0,0 +1,87 @@
+import type { ReplicaSource } from '@/libs/replica';
+import type {
+ ExpertiseDomainDetail,
+ ExpertiseLessonDetail,
+ ExpertiseOverview,
+ RuleRevision,
+ RuleSource,
+ RulesOverview,
+} from '@/services/expertise';
+
+import type { ExpertiseState } from './initialState';
+import { type ExpertiseHistoryCount, RULES_KEY } from './projection';
+
+/**
+ * A value painted from IndexedDB (`storage`) is last session's answer, not the
+ * server's: it may be an empty or outdated snapshot. Only a server response or
+ * a write made on top of one counts as confirmed, so "nothing here" / "not
+ * found" is said only then.
+ */
+const isConfirmedSource = (source: ReplicaSource | undefined) =>
+ source === 'server' || source === 'local';
+
+/** Each read is `undefined` until the local copy or the server fills it. */
+const rules = (s: ExpertiseState): RulesOverview | undefined => s.rulesMap[RULES_KEY];
+
+const isRulesConfirmed = (s: ExpertiseState): boolean =>
+ isConfirmedSource(s.rulesReplica.entries[RULES_KEY]?.source);
+
+const ruleSources =
+ (lessonId?: string) =>
+ (s: ExpertiseState): RuleSource[] | undefined =>
+ lessonId ? s.ruleSourcesMap[lessonId] : undefined;
+
+const isRuleSourcesConfirmed =
+ (lessonId?: string) =>
+ (s: ExpertiseState): boolean =>
+ !!lessonId && isConfirmedSource(s.ruleSourcesReplica.entries[lessonId]?.source);
+
+const ruleRevisions =
+ (lessonId?: string) =>
+ (s: ExpertiseState): RuleRevision[] | undefined =>
+ lessonId ? s.ruleRevisionsMap[lessonId] : undefined;
+
+const overview =
+ (agentId?: string) =>
+ (s: ExpertiseState): ExpertiseOverview | undefined =>
+ agentId ? s.overviewMap[agentId] : undefined;
+
+const isOverviewConfirmed =
+ (agentId?: string) =>
+ (s: ExpertiseState): boolean =>
+ !!agentId && isConfirmedSource(s.overviewReplica.entries[agentId]?.source);
+
+const domain =
+ (domainId?: string) =>
+ (s: ExpertiseState): ExpertiseDomainDetail | undefined =>
+ domainId ? s.domainMap[domainId] : undefined;
+
+const lesson =
+ (lessonId?: string) =>
+ (s: ExpertiseState): ExpertiseLessonDetail | undefined =>
+ lessonId ? s.lessonMap[lessonId] : undefined;
+
+/** The server answered that this lesson no longer exists (not merely "not loaded yet"). */
+const isLessonNotFound =
+ (lessonId?: string) =>
+ (s: ExpertiseState): boolean =>
+ !!lessonId && !!s.lessonNotFoundMap[lessonId];
+
+const historyCount =
+ (agentId?: string) =>
+ (s: ExpertiseState): ExpertiseHistoryCount | undefined =>
+ agentId ? s.historyCountMap[agentId] : undefined;
+
+export const expertiseSelectors = {
+ domain,
+ historyCount,
+ isLessonNotFound,
+ isOverviewConfirmed,
+ isRuleSourcesConfirmed,
+ isRulesConfirmed,
+ lesson,
+ overview,
+ ruleRevisions,
+ ruleSources,
+ rules,
+};
diff --git a/src/store/expertise/store.ts b/src/store/expertise/store.ts
new file mode 100644
index 00000000000..0e121cc092f
--- /dev/null
+++ b/src/store/expertise/store.ts
@@ -0,0 +1,15 @@
+import { shallow } from 'zustand/shallow';
+import { createWithEqualityFn } from 'zustand/traditional';
+
+import { createDevtools } from '../middleware/createDevtools';
+import { expose } from '../middleware/expose';
+import { type ExpertiseState, initialState } from './initialState';
+
+const devtools = createDevtools('expertise');
+
+export const useExpertiseStore = createWithEqualityFn<ExpertiseState>()(
+ devtools(() => initialState),
+ shallow,
+);
+
+expose('expertise', useExpertiseStore);
diff --git a/src/store/utils/userDataStores.test.ts b/src/store/utils/userDataStores.test.ts
index 3bacdecb742..02761f05a5d 100644
--- a/src/store/utils/userDataStores.test.ts
+++ b/src/store/utils/userDataStores.test.ts
@@ -2,6 +2,7 @@ import { beforeEach, describe, expect, it, vi } from 'vitest';
const resetGatewayMuxRegistry = vi.hoisted(() => vi.fn());
const storeResets = vi.hoisted(() => [] as Array<() => void>);
+const expertiseReset = vi.hoisted(() => vi.fn());
const pageReset = vi.hoisted(() => vi.fn());
const resourcePermissionReset = vi.hoisted(() => vi.fn());
const sandboxReset = vi.hoisted(() => vi.fn());
@@ -25,6 +26,7 @@ vi.mock('@/store/chat', () => ({ useChatStore: fakeStore() }));
vi.mock('@/store/discover', () => ({ useDiscoverStore: fakeStore() }));
vi.mock('@/store/document', () => ({ useDocumentStore: fakeStore() }));
vi.mock('@/store/eval', () => ({ useEvalStore: fakeStore() }));
+vi.mock('@/store/expertise', () => ({ expertiseActions: { reset: expertiseReset } }));
vi.mock('@/store/file', () => ({ useFileStore: fakeStore() }));
vi.mock('@/store/home', () => ({ useHomeStore: fakeStore() }));
vi.mock('@/store/image', () => ({ useImageStore: fakeStore() }));
@@ -48,6 +50,7 @@ describe('stores.reset', () => {
beforeEach(() => {
resetGatewayMuxRegistry.mockClear();
storeResets.length = 0;
+ expertiseReset.mockClear();
pageReset.mockClear();
resourcePermissionReset.mockClear();
sandboxReset.mockClear();
@@ -64,6 +67,8 @@ describe('stores.reset', () => {
expect(resetGatewayMuxRegistry).toHaveBeenCalledTimes(1);
expect(storeResets).toHaveLength(19);
expect(pageReset).toHaveBeenCalledTimes(1);
+ // The rule sheet and agent portraits must not leak into the next identity.
+ expect(expertiseReset).toHaveBeenCalledTimes(1);
// Confirmed manage grants and the memory-only collaborator roster must not
// outlive the data context, even when the next one reuses the scope string.
expect(resourcePermissionReset).toHaveBeenCalledTimes(1);
diff --git a/src/store/utils/userDataStores.ts b/src/store/utils/userDataStores.ts
index 408e0e07baf..4ebad196631 100644
--- a/src/store/utils/userDataStores.ts
+++ b/src/store/utils/userDataStores.ts
@@ -10,6 +10,7 @@ import { resetGatewayMuxRegistry } from '@/store/chat/slices/agentRun/actions/tr
import { useDiscoverStore } from '@/store/discover';
import { useDocumentStore } from '@/store/document';
import { useEvalStore } from '@/store/eval';
+import { expertiseActions } from '@/store/expertise';
import { useFileStore } from '@/store/file';
import { useHomeStore } from '@/store/home';
import { useImageStore } from '@/store/image';
@@ -58,6 +59,7 @@ const resetableStores: ResetableStoreApi[] = [
const resetableActions: ResetableStore[] = [
channelActions,
agentDocumentActions,
+ expertiseActions,
pageActions,
projectFileActions,
resourcePermissionActions,