π€― 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(goal): move the goal lists, graph and metric series onto @lobechat/replica (#20587)
Arvin Xuc22104088fbb
diff --git a/src/features/AgentGoals/AgentGoalsPage.tsx b/src/features/AgentGoals/AgentGoalsPage.tsxindex 2fe09c7ebea..fccdca6ba12 100644--- a/src/features/AgentGoals/AgentGoalsPage.tsx+++ b/src/features/AgentGoals/AgentGoalsPage.tsx@@ -13,7 +13,8 @@ import NavHeader from '@/features/NavHeader';import WideScreenContainer from '@/features/WideScreenContainer';import { useWorkspaceAwareNavigate } from '@/features/Workspace/useWorkspaceAwareNavigate';import type { GoalListFilter } from '@/store/goal';-import { useGoalStore } from '@/store/goal';+import { goalSelectors, useGoalStore } from '@/store/goal';+import { goalListKey } from '@/store/goal/projection';import { createGoalModal } from './CreateGoalModal';import { GoalCardItem } from './GoalCardItem';@@ -102,46 +103,56 @@ const AgentGoalsPage = memo<AgentGoalsPageProps>(({ agentId, projectId }) => {const setFilter = useGoalStore((s) => s.setGoalListFilter);const setViewMode = useGoalStore((s) => s.setGoalViewMode);const loadMoreGoals = useGoalStore((s) => s.loadMoreGoals);- // Branch off the SWR response, not the store: the store sync (even via the- // sync wrapper) lands an effect after first paint, and a cache hit β which- // never fires a network callback β would render one empty-state frame in- // between. `data?.goals` keeps the settled-empty and hydrated shapes aligned.- const { data, error, isLoading } = useFetchGoals(agentId, projectId);- const goals = useMemo(() => data?.goals ?? [], [data]);+ // The rows live in the replica view; the hook only orchestrates the fetch, so+ // a revisit paints the persisted projection on the first frame instead of an+ // empty-state frame while the sync lands.+ const { error, isLoading } = useFetchGoals(agentId, projectId);// The active tab reads its own statuses from the server. `all` shares the- // window read's cache entry, so the page only pays for an extra request once- // the user opens a narrow tab.- const tabSWR = useFetchGoals(agentId, projectId, filter);+ // window read's entry, so the page only pays for an extra request once the+ // user opens a narrow tab.+ const tabSync = useFetchGoals(agentId, projectId, filter);// `delivered` is a whole-set count, not a count of the page the list happens// to hold: read the review set's own total so the header can never disagree// with what the Needs-review tab shows once a goal sits past the list's page.- const reviewSWR = useFetchGoals(agentId, projectId, 'review');+ // The read has to run whichever tab is active, since the header shows it+ // regardless β the rows themselves come from the view below.+ useFetchGoals(agentId, projectId, 'review');+ const listView = useGoalStore(goalSelectors.goalListView(scopeId));+ const tabView = useGoalStore(+ goalSelectors.goalListView(+ filter === 'all' ? scopeId : goalListKey({ agentId, filter, projectId }),+ ),+ );+ const reviewView = useGoalStore(+ goalSelectors.goalListView(goalListKey({ agentId, filter: 'review', projectId })),+ );+ const goals = useMemo(() => listView?.goals ?? [], [listView]);const summary = useMemo(() => {- const total = data?.total ?? goals.length;+ const total = listView?.total ?? goals.length;// An aggregate that has not answered is unknown, not zero. Falling back to// the review goals visible in the list's page would understate it for// exactly the accounts this page reads past one page, and present that// partial count as the delivered total.- const delivered = reviewSWR.data?.total;+ const delivered = reviewView?.total;return {delivered,pursuing: delivered === undefined ? undefined : total - delivered,total,};- }, [data, goals.length, reviewSWR.data]);+ }, [goals.length, listView?.total, reviewView?.total]);// A page of the newest goals cannot prove a tab empty, and neither can a read// that failed: hold the list's shape while the tab's own read is in flight,// and surface its failure rather than spinning on it.- const isTabUnresolved = filter !== 'all' && tabSWR.data === undefined;- const isTabPending = isTabUnresolved && !tabSWR.error;- const isTabError = isTabUnresolved && Boolean(tabSWR.error);+ const isTabUnresolved = filter !== 'all' && tabView === undefined;+ const isTabPending = isTabUnresolved && !tabSync.error;+ const isTabError = isTabUnresolved && Boolean(tabSync.error);// The rows are the tab's own read, with no client-side fallback: a page of the// newest goals cannot stand in for the tab's answer, and presenting it as if// it could is what let a tab claim an outcome it had no way to know.const filteredGoals = useMemo(- () => (filter === 'all' ? goals : (tabSWR.data?.goals ?? [])),- [filter, goals, tabSWR.data],+ () => (filter === 'all' ? goals : (tabView?.goals ?? [])),+ [filter, goals, tabView],);const isFilterEmpty = !isTabUnresolved && filteredGoals.length === 0;// The tab's count is the server's answer for that tab. Until it arrives β or@@ -190,9 +201,13 @@ const AgentGoalsPage = memo<AgentGoalsPageProps>(({ agentId, projectId }) => {paddingInline={16}wrapperStyle={{ flex: 1, overflowY: 'auto' }}>- {isLoading && data === undefined ? (+ {isLoading ? (<GoalSkeleton chrome={'body'} />- ) : error ? (+ ) : error && listView === undefined ? (+ // Only a read that left nothing to show becomes the page: a failed+ // revalidation keeps the hydrated rows on screen (the same guard the+ // home rail, the goal portal and the detail page use), so a network+ // blip no longer hides goals the user already has locally.<GoalLoadError onRetry={() => void refreshGoals(scopeId)} />) : goals.length === 0 ? (<GoalEmptyState onCreate={openCreateGoal} />diff --git a/src/features/HomeInbox/index.tsx b/src/features/HomeInbox/index.tsxindex d537787dd36..ef99bbf6a5b 100644--- a/src/features/HomeInbox/index.tsx+++ b/src/features/HomeInbox/index.tsx@@ -177,10 +177,11 @@ const HomeInbox = memo<HomeInboxProps>((props) => {const showGoals = isLogin === true && goalsEnabled && showRailSections;const useFetchHomeGoals = useGoalStore((s) => s.useFetchHomeGoals);const goalsSWR = useFetchHomeGoals(showGoals, cacheScope);- // Branch off the SWR response: a persisted-cache hit never fires a network- // callback, so the store-backed selector lags a frame and the rail would- // render nothing until the revalidate lands.- const goals = goalsSWR.data?.goals; // The goal rail reads the goal's own lifecycle state (`goals.status`), so it+ // Read the replica view, not the hook: the persisted roll-up paints the rail+ // on the first frame and the sync only confirms it, so a cache hit no longer+ // renders one empty frame before the revalidate lands.+ const goals = useGoalStore((s) => s.homeGoalsByScope[cacheScope]?.goals);+ // The goal rail reads the goal's own lifecycle state (`goals.status`), so it// no longer needs a separate acceptance read to decide each pile.const goalEntries = useMemo(() => (showGoals ? buildHomeGoalEntries(goals) : []),diff --git a/src/features/Projects/Workspace/ProjectDashboard.tsx b/src/features/Projects/Workspace/ProjectDashboard.tsxindex 0981895c30f..cdb90ac84c1 100644--- a/src/features/Projects/Workspace/ProjectDashboard.tsx+++ b/src/features/Projects/Workspace/ProjectDashboard.tsx@@ -141,6 +141,7 @@ const ProjectDashboard = memo<ProjectDashboardProps>(({ detail, projectId }) =>const workspaceId = useActiveWorkspaceId();const goalScope = `project:${projectId}`;const goals = useGoalStore(goalSelectors.goalList(goalScope));+ const goalListView = useGoalStore(goalSelectors.goalListView(goalScope));const goalSWR = useGoalStore((s) => s.useFetchGoals)(undefined, projectId);const coordinatorAgentId = detail.project.coordinatorAgentId;const projectReference = detail.project.slug ?? projectId;@@ -168,13 +169,13 @@ const ProjectDashboard = memo<ProjectDashboardProps>(({ detail, projectId }) =><Flexbox className={styles.main} gap={24}><Flexbox gap={12}><SectionTitle title={t('overview.goalProgress')} />- {goalSWR.error ? (+ {goalSWR.error && goalListView === undefined ? (<AsyncErrorerror={goalSWR.error}variant={'inline'}onRetry={() => void goalSWR.mutate()}/>- ) : goalSWR.isLoading && goalSWR.data === undefined ? (+ ) : goalSWR.isLoading ? (<ArticleSkeleton rows={4} />) : goals.length === 0 ? (<Block padding={24} variant={'outlined'}>diff --git a/src/libs/swr/keys.ts b/src/libs/swr/keys.tsindex 78f31d6cd9b..523c2bdab2d 100644--- a/src/libs/swr/keys.ts+++ b/src/libs/swr/keys.ts@@ -279,12 +279,14 @@ export const isMyTaskListKey = (key: unknown): boolean =>Array.isArray(key) && key[0] === 'task:myList';/**- * Goal Graph reads. Keyed by the `goals` row id (not the carrier task's- * identifier) because that is what every `goal.*` procedure takes.+ * Goal reads that have no local-first projection: the pending queues are live+ * "what needs you" feeds, and the topic link is a discovery poll.+ *+ * The goal list, the home roll-up, the graph snapshot and the metric series+ * used to live here β they are `@lobechat/replica` resources now (see+ * `src/store/goal/projection.ts`), so their sync keys are not SWR cache keys.*/export const goalKeys = {- graph: def('goal:graph', (goalId: string) => ['goal:graph', goalId]),- metricSeries: def('goal:metricSeries', (goalId: string) => ['goal:metricSeries', goalId]),/** Clarifications waiting on the user across every goal they own. */pendingClarifications: def('goal:pendingClarifications', () => ['goal:pendingClarifications']),/** Gates and sign-offs waiting on the user across every goal, for the approval island. */@@ -294,12 +296,6 @@ export const goalKeys = {};export const taskKeys = {- /**- * The home rail's cross-agent goal roll-up. Scoped by cache scope like the- * other home feeds β goals are workspace rows, so a list left over from the- * previous workspace holds ids this one cannot open.- */- homeGoals: def('task:homeGoals', (scope: string) => ['task:homeGoals', scope]),/*** Home's automated-task roll-up: the tasks that fire on a schedule or a* heartbeat. Kept off `list` because it is a different result set entirely βdiff --git a/src/store/brief/slices/list/action.ts b/src/store/brief/slices/list/action.tsindex 401bd5f4fc3..a870d966641 100644--- a/src/store/brief/slices/list/action.ts+++ b/src/store/brief/slices/list/action.ts@@ -6,6 +6,7 @@ import {linkReplicaEntity,recordLens,type ReplicaSyncResult,+ revalidateReplica,} from '@/libs/replica';import { mutate, useClientDataSWR } from '@/libs/swr';import { briefKeys, goalKeys } from '@/libs/swr/keys';@@ -13,6 +14,7 @@ import { briefService } from '@/services/brief';import { taskService } from '@/services/task';import { type BriefStore } from '@/store/brief/store';import { type BriefItem } from '@/store/brief/types';+import { goalGraphResource, homeGoalListResource } from '@/store/goal/projection';import { type StoreSetter } from '@/store/types';import { setNamespace } from '@/utils/storeDebug';@@ -123,13 +125,14 @@ export class BriefListActionImpl {// A goal brief answered the goal itself: the island and the goal views// asking the same question have to drop it too.if (goal)- void mutate(- (key) =>- Array.isArray(key) &&- (key[0] === goalKeys.pendingForIsland()[0] ||- key[0] === 'task:homeGoals' ||- (key[0] === 'goal:graph' && key[1] === goal.goalId)),- );+ void Promise.all([+ mutate((key) => Array.isArray(key) && key[0] === goalKeys.pendingForIsland()[0]),+ // The goal's own reads are replicas now: their sync entries live outside+ // the `goal:` / `task:` SWR cache, so they are refreshed through the+ // resource rather than a key prefix match.+ revalidateReplica(homeGoalListResource),+ revalidateReplica(goalGraphResource, goal.goalId),+ ]);};// Free-form feedback from the brief card: resolve the brief with thediff --git a/src/store/goal/action.test.ts b/src/store/goal/action.test.tsindex 942dad5e3bb..740ca69f162 100644--- a/src/store/goal/action.test.ts+++ b/src/store/goal/action.test.ts@@ -1,49 +1,84 @@import { GOAL_ACCEPTANCE_TASK_TITLE } from '@lobechat/const/goal';+import { act, renderHook } from '@testing-library/react';import { beforeEach, describe, expect, it, vi } from 'vitest';-import { mutate, useClientDataSWR, useClientDataSWRWithSync } from '@/libs/swr';+import { mutate, useClientDataSWR } from '@/libs/swr';import { goalService } from '@/services/goal';import { useGoalStore } from './index';+import { initialState } from './initialState';vi.mock('@/libs/swr', () => ({mutate: vi.fn(),useClientDataSWR: vi.fn(),- useClientDataSWRWithSync: vi.fn(),}));++vi.mock('@/libs/swr/useCacheScope', () => ({+ getCacheScope: () => 'user-1:personal',+ isScopeTrusted: () => true,+ useCacheScope: () => 'user-1:personal',+}));+vi.mock('@/services/goal', () => ({- goalService: { delete: vi.fn(), list: vi.fn() },+ goalService: { delete: vi.fn(), getGraph: vi.fn(), list: vi.fn() },}));+const SCOPE = 'user-1:personal';++/** The replica sync call of one resource β the hydrate read shares the hook. */+const syncCallFor = (name: string) =>+ vi+ .mocked(useClientDataSWR)+ .mock.calls.findLast(+ ([key]) => Array.isArray(key) && key[0] === 'replica:sync' && key[1] === name,+ );++/** The sync key of one resource: `['replica:sync', name, version, scope, entryKey, params]`. */+const syncKeyFor = (name: string) => syncCallFor(name)?.[0] as unknown[] | undefined;++const syncConfigFor = (name: string) =>+ syncCallFor(name)?.[2] as { refreshInterval?: number } | undefined;++/** The fetch thunk the driver handed to SWR for that sync. */+const syncFetcherFor = (name: string) => syncCallFor(name)?.[1] as (() => unknown) | undefined;++const graphWith = (status: string, extra: Record<string, unknown> = {}) =>+ ({+ goal: { id: 'goal-1', status, title: 'Goal' },+ nodes: [],+ ...extra,+ }) as never;+beforeEach(() => {vi.clearAllMocks();- useGoalStore.setState({- goalListByAgentId: {},- goalListFilter: 'all',- goalListInitializedAgentIds: [],- goalListVisibleLimit: 10,- goalViewMode: 'list',- homeGoalsByScope: {},- homeGoalsInitializedScopes: [],- });+ vi.mocked(useClientDataSWR).mockReturnValue({+ data: undefined,+ error: undefined,+ isValidating: false,+ mutate: vi.fn(),+ } as never);+ useGoalStore.setState(initialState);});describe('GoalAction', () => {describe('useFetchGoalGraph', () => {- const refreshIntervalFor = (status: string) => {- useGoalStore.getState().useFetchGoalGraph('goal-1');- const options = vi.mocked(useClientDataSWR).mock.calls.at(-1)?.[2] as {- refreshInterval: (graph?: { goal: { status: string } }) => number;- };- return options.refreshInterval({ goal: { status } });- };+ const renderGraph = (goalId = 'goal-1') =>+ renderHook(() => useGoalStore.getState().useFetchGoalGraph(goalId));++ const seedGraph = (graph: unknown) =>+ act(() =>+ useGoalStore.setState({ goalGraphById: graph ? { 'goal-1': graph as never } : {} }),+ );it.each(['planning', 'running', 'verifying'])('keeps re-reading a %s goal the server is still advancing',(status) => {// The goal advances from server events now; without this the page would// sit on its first snapshot until the tab lost and regained focus.- expect(refreshIntervalFor(status)).toBeGreaterThan(0);+ seedGraph(graphWith(status));+ renderGraph();++ expect(syncConfigFor('goalGraph')?.refreshInterval).toBeGreaterThan(0);},);@@ -52,34 +87,28 @@ describe('GoalAction', () => {(status) => {// Nothing on the server will move these β the next change comes from a// person, and the action that makes it refreshes the snapshot itself.- expect(refreshIntervalFor(status)).toBe(0);+ seedGraph(graphWith(status));+ renderGraph();++ expect(syncConfigFor('goalGraph')?.refreshInterval).toBe(0);},);it('keeps polling a finished goal while its wrap-up report is being written', () => {- useGoalStore.getState().useFetchGoalGraph('goal-1');- const options = vi.mocked(useClientDataSWR).mock.calls.at(-1)?.[2] as {- refreshInterval: (graph?: unknown) => number;- };-- expect(- options.refreshInterval({ goal: { status: 'achieved' }, report: { status: 'running' } }),- ).toBeGreaterThan(0);- expect(- options.refreshInterval({ goal: { status: 'achieved' }, report: { status: 'completed' } }),- ).toBe(0);- expect(- options.refreshInterval({ goal: { status: 'failed' }, report: { status: 'failed' } }),- ).toBe(0);+ seedGraph(graphWith('achieved', { report: { status: 'running' } }));+ renderGraph();+ expect(syncConfigFor('goalGraph')?.refreshInterval).toBeGreaterThan(0);++ vi.mocked(useClientDataSWR).mockClear();+ seedGraph(graphWith('achieved', { report: { status: 'completed' } }));+ renderGraph();+ expect(syncConfigFor('goalGraph')?.refreshInterval).toBe(0);});it('does not poll before the first snapshot arrives', () => {- useGoalStore.getState().useFetchGoalGraph('goal-1');- const options = vi.mocked(useClientDataSWR).mock.calls.at(-1)?.[2] as {- refreshInterval: (graph?: unknown) => number;- };+ renderGraph();- expect(options.refreshInterval(undefined)).toBe(0);+ expect(syncConfigFor('goalGraph')?.refreshInterval).toBe(0);});/**@@ -90,44 +119,60 @@ describe('GoalAction', () => {* frozen β until the page was reloaded.*/it('keeps polling a terminal Goal whose own acceptance has not settled', () => {- useGoalStore.getState().useFetchGoalGraph('goal-1');- const options = vi.mocked(useClientDataSWR).mock.calls.at(-1)?.[2] as {- refreshInterval: (graph: unknown) => number;- };- const withAcceptance = (status: string, title = GOAL_ACCEPTANCE_TASK_TITLE) => ({- acceptances: { 'node-a': { id: 'acc-1', status } },- goal: { status: 'achieved' },- nodes: [{ id: 'node-a', kind: 'task', status: 'active', taskId: 't-1', title }],- });-- expect(options.refreshInterval(withAcceptance('repairing'))).toBeGreaterThan(0);- expect(options.refreshInterval(withAcceptance('verifying'))).toBeGreaterThan(0);+ const withAcceptance = (status: string, title = GOAL_ACCEPTANCE_TASK_TITLE) =>+ graphWith('achieved', {+ acceptances: { 'node-a': { id: 'acc-1', status } },+ nodes: [{ id: 'node-a', kind: 'task', status: 'active', taskId: 't-1', title }],+ });++ for (const status of ['repairing', 'verifying']) {+ vi.mocked(useClientDataSWR).mockClear();+ seedGraph(withAcceptance(status));+ renderGraph();+ expect(syncConfigFor('goalGraph')?.refreshInterval).toBeGreaterThan(0);+ }// Settled: the page can rest on this snapshot.- expect(options.refreshInterval(withAcceptance('delivered'))).toBe(0);- expect(options.refreshInterval(withAcceptance('accepted'))).toBe(0);-- /**- * Regression: rejecting a Goal's delivery with `dispatch: false` only- * records the decision, so the acceptance stays sticky on `rejected` while- * the Goal stays `achieved`. Nothing else is coming, and polling that state- * hammered the graph endpoint every five seconds for as long as the page- * stayed open.- */- expect(options.refreshInterval(withAcceptance('rejected'))).toBe(0);+ for (const status of ['delivered', 'accepted', 'rejected']) {+ vi.mocked(useClientDataSWR).mockClear();+ seedGraph(withAcceptance(status));+ renderGraph();+ expect(syncConfigFor('goalGraph')?.refreshInterval).toBe(0);+ }+// A rejection that reopens the Goal keeps polling: the Goal is running again.- expect(- options.refreshInterval({ ...withAcceptance('rejected'), goal: { status: 'running' } }),- ).toBeGreaterThan(0);+ vi.mocked(useClientDataSWR).mockClear();+ seedGraph({+ ...(withAcceptance('rejected') as Record<string, unknown>),+ goal: { id: 'goal-1', status: 'running', title: 'Goal' },+ });+ renderGraph();+ expect(syncConfigFor('goalGraph')?.refreshInterval).toBeGreaterThan(0);// Another task's rejection never keeps a terminal Goal polling.- expect(options.refreshInterval(withAcceptance('rejected', 'Ordinary work'))).toBe(0);+ vi.mocked(useClientDataSWR).mockClear();+ seedGraph(withAcceptance('rejected', 'Ordinary work'));+ renderGraph();+ expect(syncConfigFor('goalGraph')?.refreshInterval).toBe(0);+ });+ });++ describe('useFetchGoalMetricSeries', () => {+ it('polls the series only while the coordinator is advancing', () => {+ act(() => useGoalStore.setState({ goalGraphById: { 'goal-1': graphWith('running') } }));+ renderHook(() => useGoalStore.getState().useFetchGoalMetricSeries('goal-1'));+ expect(syncConfigFor('goalMetricSeries')?.refreshInterval).toBeGreaterThan(0);++ vi.mocked(useClientDataSWR).mockClear();+ useGoalStore.setState({ goalGraphById: { 'goal-1': graphWith('review') } });+ renderHook(() => useGoalStore.getState().useFetchGoalMetricSeries('goal-1'));+ expect(syncConfigFor('goalMetricSeries')?.refreshInterval).toBe(0);});});describe('useFetchTopicGoals', () => {it('reads the goals created from the topic under a topic-scoped key', () => {- useGoalStore.getState().useFetchTopicGoals('tpc-1');+ renderHook(() => useGoalStore.getState().useFetchTopicGoals('tpc-1'));const [key, fetcher] = vi.mocked(useClientDataSWR).mock.calls[0];expect(key).toEqual(['goal:topicGoals', 'tpc-1']);@@ -136,13 +181,13 @@ describe('GoalAction', () => {});it('does not fetch without a topic', () => {- useGoalStore.getState().useFetchTopicGoals(undefined);+ renderHook(() => useGoalStore.getState().useFetchTopicGoals(undefined));expect(vi.mocked(useClientDataSWR).mock.calls[0][0]).toBeNull();});it('polls only while one of the goals is still advancing on the server', () => {- useGoalStore.getState().useFetchTopicGoals('tpc-1');+ renderHook(() => useGoalStore.getState().useFetchTopicGoals('tpc-1'));const options = vi.mocked(useClientDataSWR).mock.calls[0][2] as {refreshInterval: (result?: { goals: Array<{ goal: { status: string } }> }) => number;};@@ -158,7 +203,7 @@ describe('GoalAction', () => {it('polls while the conversation is generating, before any goal exists', () => {// A CLI agent's /goal run creates the goal mid-run: the first read finds// nothing, and without polling the tray stayed empty until a page reload.- useGoalStore.getState().useFetchTopicGoals('tpc-1', true);+ renderHook(() => useGoalStore.getState().useFetchTopicGoals('tpc-1', true));const options = vi.mocked(useClientDataSWR).mock.calls[0][2] as {refreshInterval: (result?: { goals: Array<{ goal: { status: string } }> }) => number;};@@ -168,107 +213,104 @@ describe('GoalAction', () => {});});- it('stores goal lists independently for each agent', () => {- useGoalStore.getState().useFetchGoals('agent-1');- const options = vi.mocked(useClientDataSWRWithSync).mock.calls[0][2] as {- onData: (value: { goals: Array<{ id: string }> }) => void;- };-- options.onData({ goals: [{ id: 'goal-1' }] });-- expect(useGoalStore.getState().goalListByAgentId['agent-1']).toEqual([{ id: 'goal-1' }]);- expect(useGoalStore.getState().goalListInitializedAgentIds).toContain('agent-1');- });-- it('queries the goal list endpoint with an agent-scoped query and cache', () => {- useGoalStore.getState().useFetchGoals('agent-1');- const [, fetcher] = vi.mocked(useClientDataSWRWithSync).mock.calls[0];-- void (fetcher as () => unknown)();- expect(goalService.list).toHaveBeenCalledWith(expect.objectContaining({ agentId: 'agent-1' }));- });-- it('uses the complete goal workspace with a project-scoped query and cache', () => {- useGoalStore.getState().useFetchGoals(undefined, 'project-1');- const [key, fetcher, options] = vi.mocked(useClientDataSWRWithSync).mock.calls[0];-- expect(key).toEqual(['task:sidebarGroups', 'project:project-1:goals-page']);- expect(fetcher).toBeTypeOf('function');- void (fetcher as () => unknown)();- expect(goalService.list).toHaveBeenCalledWith(- expect.objectContaining({ projectId: 'project-1' }),- );-- const onData = (- options as {- onData: (value: { goals: Array<{ id: string }> }) => void;- }- ).onData;- onData({ goals: [{ id: 'project-goal-1' }] });-- expect(useGoalStore.getState().goalListByAgentId['project:project-1']).toEqual([- { id: 'project-goal-1' },- ]);- });+ describe('useFetchGoals', () => {+ it('reads an agent scope under the scopeβs own entry, with every status', () => {+ renderHook(() => useGoalStore.getState().useFetchGoals('agent-1'));+ const key = syncKeyFor('goalList');++ expect(key?.[3]).toBe(SCOPE);+ expect(key?.[4]).toBe('agent-1');+ void syncFetcherFor('goalList')?.();+ expect(goalService.list).toHaveBeenCalledWith(+ expect.objectContaining({ agentId: 'agent-1', limit: 100 }),+ );+ });- // A persisted `task:` tier hit never fires a network callback β only the- // sync wrapper's onData runs. If that didn't fill the store, a revisit would- // render the empty state over hydrated data (the cache-flash bug).- it('initializes the store from a cache hit, whose onData fires without onSuccess', () => {- useGoalStore.getState().useFetchGoals('agent-1');- const options = vi.mocked(useClientDataSWRWithSync).mock.calls[0][2] as {- onData: (value: { goals: Array<{ id: string }> }) => void;- };+ it('uses the complete goal workspace with a project-scoped query and entry', () => {+ renderHook(() => useGoalStore.getState().useFetchGoals(undefined, 'project-1'));- expect(options.onData).toBeTypeOf('function');+ expect(syncKeyFor('goalList')?.[4]).toBe('project:project-1');+ void syncFetcherFor('goalList')?.();+ expect(goalService.list).toHaveBeenCalledWith(+ expect.objectContaining({ projectId: 'project-1' }),+ );+ });- options.onData({ goals: [{ id: 'cached-goal' }] });+ it('asks the server for the tabβs own statuses under the tabβs own entry', () => {+ // A page of the newest goals cannot answer "what is in review", so the tab+ // gets its own server read rather than a client-side filter.+ renderHook(() => useGoalStore.getState().useFetchGoals('agent-1', undefined, 'review'));- expect(useGoalStore.getState().goalListByAgentId['agent-1']).toEqual([{ id: 'cached-goal' }]);- expect(useGoalStore.getState().goalListInitializedAgentIds).toContain('agent-1');- });+ expect(syncKeyFor('goalList')?.[4]).toBe('agent-1:goals-page:review');+ void syncFetcherFor('goalList')?.();+ expect(goalService.list).toHaveBeenCalledWith(+ expect.objectContaining({ agentId: 'agent-1', statuses: ['review'] }),+ );+ });- it('keeps each workspace home roll-up apart, so a late response cannot cross scopes', () => {- useGoalStore.getState().useFetchHomeGoals(true, 'user:ws-a');- useGoalStore.getState().useFetchHomeGoals(true, 'user:ws-b');- const optionsOf = (call: number) =>- vi.mocked(useClientDataSWRWithSync).mock.calls[call][2] as {- onData: (value: { goals: Array<{ id: string }> }) => void;- };+ it('does not fetch without a scope', () => {+ const sync = renderHook(() => useGoalStore.getState().useFetchGoals());- // ws-b lands first, then the workspace you already left answers.- optionsOf(1).onData({ goals: [{ id: 'goal-b' }] });- optionsOf(0).onData({ goals: [{ id: 'goal-a' }] });+ expect(syncCallFor('goalList')).toBeUndefined();+ expect(sync.result.current.isLoading).toBe(false);+ });- expect(useGoalStore.getState().homeGoalsByScope).toEqual({- 'user:ws-a': [{ id: 'goal-a' }],- 'user:ws-b': [{ id: 'goal-b' }],+ it('reports loading only while nothing is on screen for the entry', () => {+ vi.mocked(useClientDataSWR).mockReturnValue({+ data: undefined,+ error: undefined,+ isValidating: true,+ mutate: vi.fn(),+ } as never);++ const sync = renderHook(() => useGoalStore.getState().useFetchGoals('agent-1'));+ expect(sync.result.current.isLoading).toBe(true);++ // A hydrated row is on screen, so an in-flight revalidation is not a+ // reason to hide it behind a skeleton.+ act(() =>+ useGoalStore.setState({+ goalListByAgentId: { 'agent-1': { goals: [], total: 0 } },+ }),+ );+ sync.rerender();+ expect(sync.result.current.isLoading).toBe(false);});- expect(useGoalStore.getState().homeGoalsInitializedScopes).toEqual(['user:ws-b', 'user:ws-a']);});- it('asks only for statuses rendered by the home roll-up', () => {- useGoalStore.getState().useFetchHomeGoals(true, 'user:ws-a');- const fetcher = vi.mocked(useClientDataSWRWithSync).mock.calls[0][1] as () => unknown;-- fetcher();-- expect(goalService.list).toHaveBeenCalledWith(- expect.objectContaining({- statuses: ['planning', 'running', 'verifying', 'review'],- }),- );- expect(goalService.list).toHaveBeenCalledWith(- expect.not.objectContaining({- statuses: expect.arrayContaining(['paused', 'failed', 'achieved', 'canceled']),- }),- );+ describe('useFetchHomeGoals', () => {+ it('keys the roll-up by cache scope and asks only for the open statuses', () => {+ renderHook(() => useGoalStore.getState().useFetchHomeGoals(true, 'user:ws-a'));++ expect(syncKeyFor('homeGoalList')?.[4]).toBe('user:ws-a');+ void syncFetcherFor('homeGoalList')?.();+ expect(goalService.list).toHaveBeenCalledWith(+ expect.objectContaining({ statuses: ['planning', 'running', 'verifying', 'review'] }),+ );+ expect(goalService.list).toHaveBeenCalledWith(+ expect.not.objectContaining({+ statuses: expect.arrayContaining(['paused', 'failed', 'achieved', 'canceled']),+ }),+ );+ });});- it('refreshes only the requested agent goal cache', async () => {+ it('revalidates every tab of the requested scope, and no other scope', async () => {await useGoalStore.getState().refreshGoals('agent-1');- expect(mutate).toHaveBeenCalledWith(['task:sidebarGroups', 'agent-1:goals-page']);+ const matches = vi+ .mocked(mutate)+ .mock.calls.map(([match]) => match as (key: unknown) => boolean);+ const isMatched = (entryKey: string) =>+ matches.some((match) =>+ match(['replica:sync', 'goalList', 1, SCOPE, entryKey, {}] as unknown),+ );++ expect(isMatched('agent-1')).toBe(true);+ expect(isMatched('agent-1:goals-page:review')).toBe(true);+ expect(isMatched('agent-1:goals-page:running')).toBe(true);+ expect(isMatched('agent-1:goals-page:achieved')).toBe(true);+ expect(isMatched('agent-2')).toBe(false);});it('owns list display state', () => {@@ -283,18 +325,21 @@ describe('GoalAction', () => {});});- it('deletes a goal through the goal endpoint and removes it from local state', async () => {- useGoalStore.getState().useFetchGoals('agent-1');- const options = vi.mocked(useClientDataSWRWithSync).mock.calls[0][2] as {- onData: (value: { goals: Array<{ goal: { id: string } }> }) => void;- };- options.onData({ goals: [{ goal: { id: 'goal-1' } }, { goal: { id: 'goal-2' } }] });+ it('deletes a goal through the goal endpoint and drops it from the loaded list', async () => {+ useGoalStore.setState({+ goalListByAgentId: {+ 'agent-1': {+ goals: [{ goal: { id: 'goal-1' } }, { goal: { id: 'goal-2' } }] as never,+ total: 2,+ },+ },+ });await useGoalStore.getState().deleteGoal('agent-1', 'goal-1');expect(goalService.delete).toHaveBeenCalledWith('goal-1');- expect(useGoalStore.getState().goalListByAgentId['agent-1']).toEqual([- { goal: { id: 'goal-2' } },- ]);+ const list = useGoalStore.getState().goalListByAgentId['agent-1'];+ expect(list?.goals.map((item) => item.goal.id)).toEqual(['goal-2']);+ expect(list?.total).toBe(1);});});diff --git a/src/store/goal/action.ts b/src/store/goal/action.tsindex abf1e6426e1..edd9945620f 100644--- a/src/store/goal/action.ts+++ b/src/store/goal/action.ts@@ -1,25 +1,40 @@import { GOAL_ACCEPTANCE_TASK_TITLE, type GoalStatus } from '@lobechat/const/goal';-import type { GoalMetricCriterion, GoalTickResult } from '@lobechat/types';--import { mutate, useClientDataSWR, useClientDataSWRWithSync } from '@/libs/swr';-import { goalKeys, taskKeys } from '@/libs/swr/keys';-import { goalService } from '@/services/goal';-import { metricService } from '@/services/metric';+import type { GoalGraphSnapshot, GoalMetricCriterion, GoalTickResult } from '@lobechat/types';++import {+ createReplicaSlice,+ linkReplicaEntity,+ recordLens,+ revalidateReplica,+} from '@/libs/replica';+import { mutate, useClientDataSWR } from '@/libs/swr';+import { goalKeys } from '@/libs/swr/keys';+import { type GoalListItem, goalService } from '@/services/goal';+import { type MetricSeriesWithPoints, metricService } from '@/services/metric';import type { StoreSetter } from '@/store/types';+import { isTrpcErrorCode } from '@/utils/trpcError';import { goalStatusesForFilter } from './goalListFilter';+import { useGoalStore } from './index';import type { GoalListFilter, GoalState, GoalViewMode } from './initialState';--/** The list page's tabs, in render order. `refreshGoals` revalidates every one. */-const GOAL_LIST_FILTERS: GoalListFilter[] = ['all', 'review', 'running', 'achieved'];+import {+ GOAL_LIST_FILTERS,+ goalGraphResource,+ goalListEntity,+ goalListKey,+ type GoalListParams,+ goalListResource,+ goalListScopeParams,+ type GoalListValue,+ goalMetricSeriesResource,+ homeGoalListResource,+} from './projection';/**- * Cache scope of one tab's list. `all` keeps the scope's own entry β it is the- * page-level window the project dashboard and the overview metrics read β while- * a narrow tab gets its own entry, so each tab caches its own server answer.+ * The goals page reads one wide page and reveals more of it client-side, so the+ * server read is a single window rather than a paged walk.*/-const goalListCacheScope = (scopeId: string, filter: GoalListFilter): string =>- filter === 'all' ? `${scopeId}:goals-page` : `${scopeId}:goals-page:${filter}`;+const GOAL_LIST_FETCH_LIMIT = 100;/*** The home roll-up only ever renders goals that are still open, so it asks for@@ -85,10 +100,7 @@ const SETTLED_ACCEPTANCE_STATUSES = new Set([* reloaded. Keep reading until the acceptance settles; the settled snapshot is* the one the page can rest on.*/-const goalAcceptanceUnsettled = (graph: {- acceptances?: Record<string, { status: string }>;- nodes?: { id: string; kind: string; title: string }[];-}): boolean => {+const goalAcceptanceUnsettled = (graph: GoalGraphSnapshot): boolean => {const terminal = graph.nodes?.find((node) => node.kind === 'task' && node.title === GOAL_ACCEPTANCE_TASK_TITLE,);@@ -96,6 +108,39 @@ const goalAcceptanceUnsettled = (graph: {return !!acceptance && !SETTLED_ACCEPTANCE_STATUSES.has(acceptance.status);};+/**+ * Whether an open graph still has a server-side write coming β the poll driver+ * for the graph snapshot itself.+ */+const goalGraphShouldPoll = (graph: GoalGraphSnapshot): boolean =>+ SERVER_ADVANCING_STATUSES.has(graph.goal.status) ||+ graph.report?.status === 'running' ||+ (graph.goal.status === 'achieved' && goalAcceptanceUnsettled(graph));++/**+ * Whether the *coordinator* is still moving β the poll driver for the north-star+ * series, which is only re-sampled while the goal is advancing.+ */+const goalCoordinatorAdvancing = (graph: GoalGraphSnapshot | undefined): boolean =>+ !!graph && SERVER_ADVANCING_STATUSES.has(graph.goal.status);++/**+ * Polling is driven from the store view, not from SWR's function-form+ * `refreshInterval`: a replica's sync hook is a plain number, and the goal+ * graph lands in the view after the first response, which re-renders this+ * subscription and arms the timer.+ */+const useGoalGraphAdvancing = (goalId?: string | null): boolean =>+ useGoalStore((state) => {+ const graph = goalId ? state.goalGraphById[goalId] : undefined;+ return graph ? goalGraphShouldPoll(graph) : false;+ });++const useGoalCoordinatorAdvancing = (goalId?: string | null): boolean =>+ useGoalStore((state) =>+ goalCoordinatorAdvancing(goalId ? state.goalGraphById[goalId] : undefined),+ );+/** A conversation rarely plans more than one goal; this only bounds a runaway topic. */const TOPIC_GOAL_FETCH_LIMIT = 20;@@ -112,12 +157,79 @@ type Setter = StoreSetter<GoalStore>;export class GoalActionImpl {readonly #get: () => GoalStore;+ readonly #goalGraph;+ readonly #goalList;+ /** The list rows wherever they are held: the scope's tabs and the home rail. */+ readonly #goalListRows;+ readonly #goalMetricSeries;+ readonly #homeGoalList;readonly #set: Setter;constructor(set: Setter, get: () => GoalStore, _api?: unknown) {void _api;this.#get = get;this.#set = set;++ this.#goalList = createReplicaSlice(goalListResource, {+ actionPrefix: 'goalList',+ entity: goalListEntity,+ fetcher: ({ agentId, filter, projectId }) =>+ goalService.list({+ agentId,+ limit: GOAL_LIST_FETCH_LIMIT,+ projectId,+ statuses: goalStatusesForFilter(filter),+ }),+ get,+ set,+ stateKey: 'goalListReplica',+ view: recordLens<GoalStore, GoalListValue>('goalListByAgentId'),+ });++ this.#homeGoalList = createReplicaSlice(homeGoalListResource, {+ actionPrefix: 'homeGoalList',+ entity: goalListEntity,+ fetcher: () =>+ goalService.list({ limit: HOME_GOAL_FETCH_LIMIT, statuses: HOME_GOAL_STATUSES }),+ get,+ set,+ stateKey: 'homeGoalsReplica',+ view: recordLens<GoalStore, GoalListValue>('homeGoalsByScope'),+ });++ // One goal row is rendered by a scope's tabs and by the home rail; a change+ // to it has to reach every list holding it, loaded or only persisted.+ this.#goalListRows = linkReplicaEntity<GoalListItem>([this.#goalList, this.#homeGoalList]);++ this.#goalGraph = createReplicaSlice(goalGraphResource, {+ actionPrefix: 'goalGraph',+ fetcher: (goalId) => goalService.getGraph(goalId),+ get,+ set,+ stateKey: 'goalGraphReplica',+ view: recordLens<GoalStore, GoalGraphSnapshot>('goalGraphById'),+ });++ this.#goalMetricSeries = createReplicaSlice(goalMetricSeriesResource, {+ actionPrefix: 'goalMetricSeries',+ // Only the declared keys are fetched β the same goal can accumulate any+ // number of other sampled series, and none of them can affect this view.+ // Keys are read at fetch time; the declare path revalidates this cache+ // key right after refreshing the graph, so a newly declared clause is+ // fetched against fresh criteria.+ fetcher: (goalId) =>+ metricService.listSeriesWithPoints(+ 'goal',+ goalId,+ (this.#get().goalGraphById[goalId]?.goal.config?.acceptance?.metrics ?? []).map(+ (criterion) => criterion.key,+ ),+ ),+ get,+ set,+ stateKey: 'goalMetricSeriesReplica',+ view: recordLens<GoalStore, MetricSeriesWithPoints[]>('goalMetricSeriesById'),+ });}/**@@ -132,19 +244,15 @@ export class GoalActionImpl {scopeId?: string,): Promise<void> => {await goalService.delete(goalId);- if (agentId) {- const current = this.#get().goalListByAgentId[agentId] ?? [];- this.#set(- ({ goalListByAgentId }) => ({- goalListByAgentId: {- ...goalListByAgentId,- [agentId]: current.filter(({ goal }) => goal.id !== goalId),- },- }),- false,- 'deleteGoal/success',- );- }+ // Fan out across every list that holds the row β every tab of the scope the+ // caller was rendering, the home rail, and persisted rows of lists that are+ // not loaded: a list the user navigated away from must not repaint it.+ this.#goalListRows.remove(goalId);+ // The graph and the metric series are their own per-goal replicas: the+ // deleted id is never fetched again, so a persisted row left behind is an+ // orphan that only consumes local storage. Drop both with the lists.+ this.#goalGraph.remove(goalId);+ this.#goalMetricSeries.remove(goalId);const scope = scopeId ?? agentId;if (scope) await this.refreshGoals(scope);};@@ -165,9 +273,8 @@ export class GoalActionImpl {await Promise.all([this.refreshGoalGraph(goalId),mutate(goalKeys.pendingForIsland()),- mutate(- (key) => Array.isArray(key) && (key[0] === 'brief:list' || key[0] === 'task:homeGoals'),- ),+ revalidateReplica(homeGoalListResource),+ mutate((key) => Array.isArray(key) && key[0] === 'brief:list'),]);};@@ -191,7 +298,7 @@ export class GoalActionImpl {};refreshGoalGraph = async (goalId: string): Promise<void> => {- await mutate(goalKeys.graph(goalId));+ await this.#goalGraph.revalidate(goalId);};resumeGoal = async (goalId: string): Promise<void> => {@@ -257,29 +364,32 @@ export class GoalActionImpl {{ refreshInterval: PENDING_CLARIFICATIONS_POLL_INTERVAL, revalidateOnFocus: true },);- /** The Goal Graph snapshot behind the process-control surface. */- useFetchGoalGraph = (goalId?: string | null) =>- useClientDataSWR(goalId ? goalKeys.graph(goalId) : null, () => goalService.getGraph(goalId!), {- onSuccess: (graph) => {- this.#set(- ({ goalGraphById }) => ({ goalGraphById: { ...goalGraphById, [goalId!]: graph } }),- false,- 'useFetchGoalGraph/success',- );+ /**+ * The Goal Graph snapshot behind the process-control surface. Read it through+ * `goalSelectors.goalGraph`, never from this hook β the replica owns the+ * value, the hook only orchestrates the fetch.+ */+ useFetchGoalGraph = (goalId?: string | null) => {+ const shouldPoll = useGoalGraphAdvancing(goalId);+ // Freshness while a graph is polling is the point; the first frame paints+ // the persisted snapshot, so nothing has to wait for the network.+ const sync = this.#goalGraph.useSync(goalId || null, {+ // A goal deleted by another client answers NOT_FOUND on every read, and a+ // cached snapshot is enough for the page to keep painting the gone goal β+ // and, while it still reads as advancing, to keep polling the missing+ // endpoint. NOT_FOUND is definitive, so drop the goal's cached rows (the+ // snapshot and its metric series) and let the page settle on its 404; any+ // transient failure keeps the persisted snapshot on screen.+ onError: (error) => {+ if (!goalId || !isTrpcErrorCode(error, 'NOT_FOUND')) return;+ this.#goalGraph.remove(goalId);+ this.#goalMetricSeries.remove(goalId);},- // The wrap-up report is written after the Goal settles, so a finished- // Goal keeps polling until its report run ends and the storyline lands.- // A Goal that already reads terminal while its own acceptance has not- // settled is mid-transition too β the verdict is still coming.- refreshInterval: (graph) =>- graph &&- (SERVER_ADVANCING_STATUSES.has(graph.goal.status) ||- graph.report?.status === 'running' ||- (graph.goal.status === 'achieved' && goalAcceptanceUnsettled(graph)))- ? GOAL_GRAPH_POLL_INTERVAL- : 0,+ refreshInterval: shouldPoll ? GOAL_GRAPH_POLL_INTERVAL : 0,revalidateOnFocus: true,});+ return { ...sync, isLoading: sync.isValidating, mutate: sync.revalidate };+ };/*** Goals created from one conversation. A goal a CLI agent creates through@@ -301,48 +411,22 @@ export class GoalActionImpl {);/**- * North-star data of the goal detail header. Polls on the same cadence logic- * as the graph: while the server is advancing, a probe Work or an agent+ * North-star data of the goal detail header, read through+ * `goalSelectors.goalMetricSeries`. Polls on the same cadence logic as the+ * graph: while the server is advancing, a probe Work or an agent* `recordObservation` can land a fresh point at any time.*/- useFetchGoalMetricSeries = (goalId?: string | null) =>- useClientDataSWR(- goalId ? goalKeys.metricSeries(goalId) : null,- // Only the declared keys are fetched β the same goal can accumulate any- // number of other sampled series, and none of them can affect this view.- // Keys are read at fetch time; the declare path revalidates this cache- // key right after refreshing the graph, so a newly declared clause is- // fetched against fresh criteria.- () =>- metricService.listSeriesWithPoints(- 'goal',- goalId!,- (this.#get().goalGraphById[goalId!]?.goal.config?.acceptance?.metrics ?? []).map(- (criterion) => criterion.key,- ),- ),- {- onSuccess: (series) => {- this.#set(- ({ goalMetricSeriesById }) => ({- goalMetricSeriesById: { ...goalMetricSeriesById, [goalId!]: series },- }),- false,- 'useFetchGoalMetricSeries/success',- );- },- refreshInterval: () => {- const graph = this.#get().goalGraphById[goalId!];- return graph && SERVER_ADVANCING_STATUSES.has(graph.goal.status)- ? GOAL_GRAPH_POLL_INTERVAL- : 0;- },- revalidateOnFocus: true,- },- );+ useFetchGoalMetricSeries = (goalId?: string | null) => {+ const shouldPoll = useGoalCoordinatorAdvancing(goalId);+ const sync = this.#goalMetricSeries.useSync(goalId || null, {+ refreshInterval: shouldPoll ? GOAL_GRAPH_POLL_INTERVAL : 0,+ revalidateOnFocus: true,+ });+ return { ...sync, isLoading: sync.isValidating, mutate: sync.revalidate };+ };refreshGoalMetricSeries = async (goalId: string): Promise<void> => {- await mutate(goalKeys.metricSeries(goalId));+ await this.#goalMetricSeries.revalidate(goalId);};/** Append one clause to the goal's measured acceptance and refresh both reads. */@@ -377,16 +461,17 @@ export class GoalActionImpl {);};+ /** Re-read every tab of one scope's list (a create / delete moves any of them). */refreshGoals = async (scopeId: string): Promise<void> => {await Promise.all(GOAL_LIST_FILTERS.map((filter) =>- mutate(taskKeys.sidebarGroups(goalListCacheScope(scopeId, filter))),+ this.#goalList.revalidate(goalListKey(goalListScopeParams(scopeId, filter))),),);};refreshHomeGoals = async (scope: string): Promise<void> => {- await mutate(taskKeys.homeGoals(scope));+ await this.#homeGoalList.revalidate(scope);};setGoalListFilter = (filter: GoalListFilter): void => {@@ -398,88 +483,47 @@ export class GoalActionImpl {};/**- * The goal list page's read, one entry per tab.+ * The goal list page's read, one entry per tab β read the rows through+ * `goalSelectors.goalListView` (`all`) or the tab's own entry key.** A narrow tab asks the server for its own statuses rather than filtering the* `all` page on the client: the read only loads the newest `limit` goals, so a* client-side filter would let a busy agent's older matching goal fall past* the page and the tab would report itself empty while the goal exists.*- * The sync wrapper matters here: this list is persisted in the `task:`- * IndexedDB tier, and a cache hit never fires `onSuccess` β without `onData`- * the store would stay uninitialized on a revisit and the page would flash its- * empty state over hydrated data.+ * The persisted projection is what makes a revisit paint the rows before the+ * network answers, so the page never flashes its empty state over hydrated+ * data.*/useFetchGoals = (agentId?: string, projectId?: string, filter: GoalListFilter = 'all') => {- const scopeId = projectId ? `project:${projectId}` : agentId;-- return useClientDataSWRWithSync(- scopeId ? taskKeys.sidebarGroups(goalListCacheScope(scopeId, filter)) : null,- () =>- goalService.list({- agentId,- limit: 100,- projectId,- statuses: goalStatusesForFilter(filter),- }),- {- onData: ({ goals }) => {- // Only `all` feeds the shared slice: it is the page-level window the- // project dashboard reads, and a filtered list stored under the plain- // scope would make that reader render a subset as if it were the list.- if (filter !== 'all') return;-- this.#set(- ({ goalListByAgentId, goalListInitializedAgentIds }) => ({- goalListByAgentId: {- ...goalListByAgentId,- [scopeId!]: goals,- },- goalListInitializedAgentIds: goalListInitializedAgentIds.includes(scopeId!)- ? goalListInitializedAgentIds- : [...goalListInitializedAgentIds, scopeId!],- }),- false,- 'useFetchGoals/success',- );- },- revalidateOnFocus: true,- },- );+ const params: GoalListParams | undefined =+ agentId || projectId ? { agentId, filter, projectId } : undefined;+ const key = params ? goalListKey(params) : undefined;+ const sync = this.#goalList.useSync(params ?? null, { revalidateOnFocus: true });++ return {+ ...sync,+ // A request in flight with nothing to show for this key yet β the store+ // view, not the network, decides whether there is something on screen.+ isLoading: sync.isValidating && !(key && this.#get().goalListByAgentId[key]),+ mutate: sync.revalidate,+ };};/*** Every agent's goals in one read β the home rail is a cross-agent roll-up,* so it cannot go through the per-agent list. Same server query minus the- * assignee filter; the rail buckets and truncates client-side.- *- * Sync-wrapper for the same reason as `useFetchGoals`: this roll-up is- * persisted under the `task:` tier and must initialize from a cache hit.+ * assignee filter; the rail buckets and truncates client-side. Read the rows+ * through `goalSelectors.homeGoals(scope)`.*/- useFetchHomeGoals = (enabled: boolean, scope: string) =>- useClientDataSWRWithSync(- enabled ? taskKeys.homeGoals(scope) : null,- () =>- goalService.list({- limit: HOME_GOAL_FETCH_LIMIT,- statuses: HOME_GOAL_STATUSES,- }),- {- onData: ({ goals }) => {- this.#set(- ({ homeGoalsByScope, homeGoalsInitializedScopes }) => ({- homeGoalsByScope: { ...homeGoalsByScope, [scope]: goals },- homeGoalsInitializedScopes: homeGoalsInitializedScopes.includes(scope)- ? homeGoalsInitializedScopes- : [...homeGoalsInitializedScopes, scope],- }),- false,- 'useFetchHomeGoals/success',- );- },- revalidateOnFocus: true,- },- );+ useFetchHomeGoals = (enabled: boolean, scope: string) => {+ const sync = this.#homeGoalList.useSync({ scope }, { enabled, revalidateOnFocus: true });+ return {+ ...sync,+ isLoading: sync.isValidating && !this.#get().homeGoalsByScope[scope],+ mutate: sync.revalidate,+ };+ };}export type GoalAction = Pick<GoalActionImpl, keyof GoalActionImpl>;diff --git a/src/store/goal/index.ts b/src/store/goal/index.tsindex d67f580e9f0..50303a75dca 100644--- a/src/store/goal/index.ts+++ b/src/store/goal/index.ts@@ -4,6 +4,7 @@ import { shallow } from 'zustand/shallow';import { createWithEqualityFn } from 'zustand/traditional';import { createDevtools } from '@/store/middleware/createDevtools';+import { expose } from '@/store/middleware/expose';import { flattenActions } from '@/store/utils/flattenActions';import { type GoalAction, GoalActionImpl, type GoalStore } from './action';@@ -19,6 +20,8 @@ export const useGoalStore = createWithEqualityFn<GoalStore>()(shallow,);+expose('goal', useGoalStore);+export const getGoalStoreState = () => useGoalStore.getState();export { goalStatusesForFilter } from './goalListFilter';diff --git a/src/store/goal/initialState.ts b/src/store/goal/initialState.tsindex 3b407f934ad..4ae8bf6e3ba 100644--- a/src/store/goal/initialState.ts+++ b/src/store/goal/initialState.ts@@ -1,8 +1,11 @@import type { GoalGraphSnapshot } from '@lobechat/types';+import { createReplicaState, type ReplicaState } from '@/libs/replica';import type { GoalListItem } from '@/services/goal';import type { MetricSeriesWithPoints } from '@/services/metric';+import type { GoalListValue } from './projection';+export type { GoalListItem };/*** List tab. Each option names the lifecycle states it keeps: `all` is the@@ -16,11 +19,22 @@ export type GoalListFilter = 'all' | 'review' | 'running' | 'achieved';export type GoalViewMode = 'card' | 'list';export interface GoalState {- /** Goal Graph snapshots keyed by `goals.id` β the process-control surface's read model. */+ /**+ * Goal Graph snapshots keyed by `goals.id` β the process-control surface's+ * read model.+ */goalGraphById: Record<string, GoalGraphSnapshot>;- goalListByAgentId: Record<string, GoalListItem[]>;+ /** Local-first bookkeeping for `goalGraphById`. */+ goalGraphReplica: ReplicaState<GoalGraphSnapshot>;+ /**+ * Goal lists keyed by the tab's entry key: the scope's own entry for `all`+ * (what the project dashboard and the route meta read) and one sibling entry+ * per narrow tab (`goalListKey`).+ */+ goalListByAgentId: Record<string, GoalListValue>;goalListFilter: GoalListFilter;- goalListInitializedAgentIds: string[];+ /** Local-first bookkeeping for `goalListByAgentId`. */+ goalListReplica: ReplicaState<GoalListValue>;goalListVisibleLimit: number;/*** North-star series of a goal (subjectType 'goal'), points included. Keyed@@ -28,6 +42,8 @@ export interface GoalState {* same row and refresh together.*/goalMetricSeriesById: Record<string, MetricSeriesWithPoints[]>;+ /** Local-first bookkeeping for `goalMetricSeriesById`. */+ goalMetricSeriesReplica: ReplicaState<MetricSeriesWithPoints[]>;goalViewMode: GoalViewMode;/*** Every agent's goals, for the home rail's cross-agent roll-up β keyed by@@ -35,18 +51,21 @@ export interface GoalState {* slower response from the workspace you just left overwrite this one's, and* render titles and links that cannot resolve here.*/- homeGoalsByScope: Record<string, GoalListItem[]>;- homeGoalsInitializedScopes: string[];+ homeGoalsByScope: Record<string, GoalListValue>;+ /** Local-first bookkeeping for `homeGoalsByScope`. */+ homeGoalsReplica: ReplicaState<GoalListValue>;}export const initialState: GoalState = {- goalMetricSeriesById: {},goalGraphById: {},+ goalGraphReplica: createReplicaState(),goalListByAgentId: {},goalListFilter: 'all',- goalListInitializedAgentIds: [],+ goalListReplica: createReplicaState(),goalListVisibleLimit: 10,+ goalMetricSeriesById: {},+ goalMetricSeriesReplica: createReplicaState(),goalViewMode: 'list',homeGoalsByScope: {},- homeGoalsInitializedScopes: [],+ homeGoalsReplica: createReplicaState(),};diff --git a/src/store/goal/projection.ts b/src/store/goal/projection.tsnew file mode 100644index 00000000000..5b0bd14e1f2--- /dev/null+++ b/src/store/goal/projection.ts@@ -0,0 +1,136 @@+import type { GoalGraphSnapshot } from '@lobechat/types';++import { defineReplica, type ReplicaEntityAdapter } from '@/libs/replica';+import type { GoalListItem, goalService } from '@/services/goal';+import type { MetricSeriesWithPoints } from '@/services/metric';++import type { GoalListFilter } from './initialState';++type GoalListResponse = Awaited<ReturnType<typeof goalService.list>>;++/**+ * The list read's value: the page of goals plus the server's own total. The+ * total is the whole set, not the page β the header counts a scope whose goal+ * history is longer than one `limit` correctly, and the project dashboard+ * reports real progress rather than the slice it happens to hold.+ */+export interface GoalListValue {+ goals: GoalListItem[];+ total: number;+}++/**+ * Which list a goals page is showing. `all` is the scope's own entry β the+ * page-level window the project dashboard and the route meta read β while each+ * narrow tab keeps its own entry: the read only loads the newest page, so a+ * client-side filter would let a busy scope's older matching goal fall past the+ * page and the tab would report itself empty while the goal exists.+ */+export interface GoalListParams {+ agentId?: string;+ filter: GoalListFilter;+ projectId?: string;+}++/** The home rail's cross-agent roll-up, scoped like the other home feeds. */+export interface HomeGoalListParams {+ /** Cache scope (`userId:workspaceId`), so a workspace you left cannot answer here. */+ scope: string;+}++/**+ * Scope id of a goals page: an agent's page, or a project's. Also the entry key+ * of that scope's `all` list β the key `goalListByAgentId` has always used.+ */+export const goalListScopeId = ({+ agentId,+ projectId,+}: Pick<GoalListParams, 'agentId' | 'projectId'>): string =>+ projectId ? `project:${projectId}` : agentId!;++/** Rebuild the list params of one scope id (the inverse of `goalListScopeId`). */+export const goalListScopeParams = (scopeId: string, filter: GoalListFilter): GoalListParams =>+ scopeId.startsWith('project:')+ ? { filter, projectId: scopeId.slice('project:'.length) }+ : { agentId: scopeId, filter };++/**+ * Entry key of one tab's list. `all` keys the scope itself; a narrow tab keys a+ * sibling entry so switching tabs never resets the page-level window.+ */+export const goalListKey = (params: GoalListParams): string => {+ const scopeId = goalListScopeId(params);+ return params.filter === 'all' ? scopeId : `${scopeId}:goals-page:${params.filter}`;+};++/** Every tab of one scope, for a refresh that has to cover them all. */+export const GOAL_LIST_FILTERS: GoalListFilter[] = ['all', 'review', 'running', 'achieved'];++/** One scope's goal list, one entry per tab (`goalListByAgentId`). */+export const goalListResource = defineReplica<GoalListParams, GoalListValue, GoalListResponse>({+ key: goalListKey,+ name: 'goalList',+ storage: 'indexedDB',+ version: 1,+});++/** The home rail's cross-agent goal roll-up, one entry per cache scope. */+export const homeGoalListResource = defineReplica<+ HomeGoalListParams,+ GoalListValue,+ GoalListResponse+>({+ key: ({ scope }) => scope,+ name: 'homeGoalList',+ storage: 'indexedDB',+ version: 1,+});++/**+ * The Goal Graph snapshot behind the process-control surface, keyed by the+ * `goals` row id β the id every `goal.*` procedure takes (not the carrier+ * task's identifier).+ */+export const goalGraphResource = defineReplica<string, GoalGraphSnapshot>({+ key: (goalId) => goalId,+ name: 'goalGraph',+ storage: 'indexedDB',+ version: 1,+});++/**+ * North-star series of a goal (subjectType 'goal'), points included, keyed by+ * goal id like the graph snapshot β the strip and the graph describe the same+ * row and refresh together.+ */+export const goalMetricSeriesResource = defineReplica<string, MetricSeriesWithPoints[]>({+ key: (goalId) => goalId,+ name: 'goalMetricSeries',+ storage: 'indexedDB',+ version: 1,+});++/**+ * Goals are addressed by `goal.id` across the goal store, and a list row+ * carries the row plus its graph roll-up. Deleting one drops the row and the+ * total it was counted in, in every list that holds it β loaded or only+ * persisted, since the replica patches both.+ */+export const goalListEntity: ReplicaEntityAdapter<GoalListValue, GoalListItem> = {+ has: (data, id) => data.goals.some((item) => item.goal.id === id),+ map: (data, id, fn) => {+ const index = data.goals.findIndex((item) => item.goal.id === id);+ if (index === -1) return data;+ const current = data.goals[index];+ const next = fn(current);+ if (next === current) return data;+ if (next === undefined)+ return {+ goals: data.goals.filter((_, i) => i !== index),+ total: Math.max(0, data.total - 1),+ };+ const goals = [...data.goals];+ goals[index] = next;+ return { ...data, goals };+ },+};diff --git a/src/store/goal/replica.test.ts b/src/store/goal/replica.test.tsnew file mode 100644index 00000000000..6563affe33c--- /dev/null+++ b/src/store/goal/replica.test.ts@@ -0,0 +1,377 @@+/**+ * @vitest-environment happy-dom+ *+ * The goal domain is a set of replicas now: the lists, the graph snapshot and+ * the metric series paint from their persisted copy on the first frame, the+ * network only confirms, deleting a goal fans out across every list that holds+ * it, and a scope switch never shows the previous identity's rows.+ */+import { randomUUID } from 'node:crypto';++import type { GoalGraphSnapshot } from '@lobechat/types';+import { act, 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 { type GoalListItem, goalService } from '@/services/goal';+import { metricService } from '@/services/metric';++import { useGoalStore } from './index';+import { initialState } from './initialState';+import {+ goalGraphResource,+ goalListResource,+ goalMetricSeriesResource,+ homeGoalListResource,+} from './projection';++vi.mock('@/services/goal', () => ({+ goalService: {+ delete: vi.fn(),+ getGraph: vi.fn(),+ list: vi.fn(),+ },+}));++vi.mock('@/services/metric', () => ({+ metricService: { listSeriesWithPoints: 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,+ );++const goal = (id: string, status = 'running'): GoalListItem =>+ ({ goal: { id, status, title: id }, pendingDecisions: 0 }) as unknown as GoalListItem;++const graph = (id: string, status = 'running'): GoalGraphSnapshot =>+ ({ goal: { id, status, title: id }, nodes: [] }) as unknown as GoalGraphSnapshot;++const listPage = (goals: GoalListItem[], total = goals.length) => ({ goals, total });++/** Never-resolving fetch: the first frame can only come from storage. */+const pending = () => new Promise<never>(() => {});++const AGENT_KEY = 'agent-1';+const REVIEW_KEY = `${AGENT_KEY}:goals-page:review`;+const ALL_STORAGE_KEY = goalListResource.storageKey({ agentId: AGENT_KEY, filter: 'all' });+const REVIEW_STORAGE_KEY = goalListResource.storageKey({ agentId: AGENT_KEY, filter: 'review' });+const GRAPH_STORAGE_KEY = goalGraphResource.storageKey('goal-1');+const SERIES_STORAGE_KEY = goalMetricSeriesResource.storageKey('goal-1');+const GRAPH_G1_STORAGE_KEY = goalGraphResource.storageKey('g1');+const SERIES_G1_STORAGE_KEY = goalMetricSeriesResource.storageKey('g1');+const HOME_SCOPE = 'home-scope';+const HOME_STORAGE_KEY = homeGoalListResource.storageKey({ scope: HOME_SCOPE });++const ALL_QUERY_KEYS = [+ ALL_STORAGE_KEY,+ REVIEW_STORAGE_KEY,+ GRAPH_STORAGE_KEY,+ SERIES_STORAGE_KEY,+ GRAPH_G1_STORAGE_KEY,+ SERIES_G1_STORAGE_KEY,+ HOME_STORAGE_KEY,+];++describe('goal store replicas', () => {+ const scopes = new Set<string>();+ const scopeRef = { current: '' };+ const useScope = (next: string) => {+ scopeRef.current = next;+ scopes.add(next);+ };++ beforeEach(() => {+ useScope(`goal-user-${randomUUID()}:personal`);+ vi.spyOn(cacheScope, 'get').mockImplementation(() => scopeRef.current);+ vi.spyOn(cacheScope, 'use').mockImplementation(() => scopeRef.current);+ vi.spyOn(cacheScope, 'canPersist').mockReturnValue(true);+ act(() => useGoalStore.setState(initialState));+ });++ afterEach(async () => {+ for (const value of scopes) {+ for (const queryKey of ALL_QUERY_KEYS) {+ for (const resource of [+ goalListResource,+ goalGraphResource,+ goalMetricSeriesResource,+ homeGoalListResource,+ ]) {+ await resource.storage!.remove({ queryKey, scope: value });+ }+ }+ }+ scopes.clear();+ vi.restoreAllMocks();+ vi.clearAllMocks();+ });++ it('paints the persisted list before the network answers', async () => {+ await goalListResource.storage!.set(+ { queryKey: ALL_STORAGE_KEY, scope: scopeRef.current },+ { data: listPage([goal('cached')], 7), updatedAt: 1 },+ );+ vi.mocked(goalService.list).mockImplementation(pending);++ const sync = renderHook(() => useGoalStore((s) => s.useFetchGoals)(AGENT_KEY), { wrapper });+ const list = renderHook(() => useGoalStore((s) => s.goalListByAgentId[AGENT_KEY]));++ await waitFor(() => expect(list.result.current?.goals[0].goal.id).toBe('cached'));+ // The total is the server's whole-set count, restored with the page.+ expect(list.result.current?.total).toBe(7);+ expect(sync.result.current.isHydrated).toBe(true);+ expect(sync.result.current.isValidating).toBe(true);+ });++ it('replaces the list with the server response and persists it', async () => {+ vi.mocked(goalService.list).mockResolvedValue(listPage([goal('server')], 1) as never);++ renderHook(() => useGoalStore((s) => s.useFetchGoals)(AGENT_KEY), { wrapper });++ await waitFor(() =>+ expect(useGoalStore.getState().goalListByAgentId[AGENT_KEY]?.goals[0].goal.id).toBe('server'),+ );+ await waitFor(async () =>+ expect(+ (+ await goalListResource.storage!.get({+ queryKey: ALL_STORAGE_KEY,+ scope: scopeRef.current,+ })+ )?.data,+ ).toEqual(listPage([goal('server')], 1)),+ );+ });++ it('keeps each tab its own entry, so a narrow tab never resets the window', async () => {+ vi.mocked(goalService.list).mockImplementation((async (params: { statuses?: string[] }) =>+ listPage([goal(params.statuses?.length === 1 ? 'review-only' : 'window')], 1)) as never);++ renderHook(+ () => {+ useGoalStore((s) => s.useFetchGoals)(AGENT_KEY);+ useGoalStore((s) => s.useFetchGoals)(AGENT_KEY, undefined, 'review');+ },+ { wrapper },+ );++ await waitFor(() =>+ expect(useGoalStore.getState().goalListByAgentId[AGENT_KEY]?.goals[0].goal.id).toBe('window'),+ );+ await waitFor(() =>+ expect(useGoalStore.getState().goalListByAgentId[REVIEW_KEY]?.goals[0].goal.id).toBe(+ 'review-only',+ ),+ );+ });++ it('paints the persisted graph snapshot before the network answers', async () => {+ await goalGraphResource.storage!.set(+ { queryKey: GRAPH_STORAGE_KEY, scope: scopeRef.current },+ { data: graph('goal-1'), updatedAt: 1 },+ );+ vi.mocked(goalService.getGraph).mockImplementation(pending);++ const sync = renderHook(() => useGoalStore((s) => s.useFetchGoalGraph)('goal-1'), { wrapper });+ const snapshot = renderHook(() => useGoalStore((s) => s.goalGraphById['goal-1']));++ await waitFor(() => expect(snapshot.result.current?.goal.id).toBe('goal-1'));+ expect(sync.result.current.isHydrated).toBe(true);+ });++ it('paints the persisted metric series before the network answers', async () => {+ const series = [{ key: 'stars', points: [{ value: 1 }] }];+ await goalMetricSeriesResource.storage!.set(+ { queryKey: SERIES_STORAGE_KEY, scope: scopeRef.current },+ { data: series as never, updatedAt: 1 },+ );+ vi.mocked(metricService.listSeriesWithPoints).mockImplementation(pending);++ renderHook(() => useGoalStore((s) => s.useFetchGoalMetricSeries)('goal-1'), { wrapper });+ const view = renderHook(() => useGoalStore((s) => s.goalMetricSeriesById['goal-1']));++ await waitFor(() => expect(view.result.current).toEqual(series));+ });++ it('evicts a goal deleted elsewhere: a NOT_FOUND graph read drops the snapshot and its series', async () => {+ let rejectGraph: (error: unknown) => void = () => {};+ vi.mocked(goalService.getGraph).mockReturnValue(+ new Promise((_resolve, reject) => {+ rejectGraph = reject;+ }) as never,+ );+ vi.mocked(metricService.listSeriesWithPoints).mockImplementation(pending);++ await goalGraphResource.storage!.set(+ { queryKey: GRAPH_G1_STORAGE_KEY, scope: scopeRef.current },+ { data: graph('g1'), updatedAt: 1 },+ );+ await goalMetricSeriesResource.storage!.set(+ { queryKey: SERIES_G1_STORAGE_KEY, scope: scopeRef.current },+ { data: [{ key: 'stars', points: [{ value: 1 }] }] as never, updatedAt: 1 },+ );++ renderHook(() => useGoalStore((s) => s.useFetchGoalGraph)('g1'), { wrapper });+ const view = renderHook(() => useGoalStore((s) => s.goalGraphById.g1));++ // The first frame is the persisted snapshot of the now-deleted goal...+ await waitFor(() => expect(view.result.current?.goal.id).toBe('g1'));++ // ...and the deleted-elsewhere answer is definitive, so it is evicted.+ await act(async () => {+ rejectGraph({ data: { code: 'NOT_FOUND' } });+ });++ await waitFor(() => expect(useGoalStore.getState().goalGraphById.g1).toBeUndefined());+ await waitFor(() => expect(useGoalStore.getState().goalMetricSeriesById.g1).toBeUndefined());+ await waitFor(async () =>+ expect(+ await goalGraphResource.storage!.get({+ queryKey: GRAPH_G1_STORAGE_KEY,+ scope: scopeRef.current,+ }),+ ).toBeUndefined(),+ );+ });++ it('keeps the persisted snapshot when the graph read fails transiently', async () => {+ let rejectGraph: (error: unknown) => void = () => {};+ vi.mocked(goalService.getGraph).mockReturnValue(+ new Promise((_resolve, reject) => {+ rejectGraph = reject;+ }) as never,+ );+ vi.mocked(metricService.listSeriesWithPoints).mockImplementation(pending);++ await goalGraphResource.storage!.set(+ { queryKey: GRAPH_G1_STORAGE_KEY, scope: scopeRef.current },+ { data: graph('g1'), updatedAt: 1 },+ );++ renderHook(() => useGoalStore((s) => s.useFetchGoalGraph)('g1'), { wrapper });+ const view = renderHook(() => useGoalStore((s) => s.goalGraphById.g1));+ await waitFor(() => expect(view.result.current?.goal.id).toBe('g1'));++ await act(async () => {+ rejectGraph(new Error('network down'));+ });+ // A transient failure is not a delete: the persisted snapshot stays.+ await new Promise((resolve) => setTimeout(resolve, 0));+ expect(useGoalStore.getState().goalGraphById.g1).toBeDefined();+ });++ it('paints the home roll-up from storage, scoped to the workspace it belongs to', async () => {+ await homeGoalListResource.storage!.set(+ { queryKey: HOME_STORAGE_KEY, scope: scopeRef.current },+ { data: listPage([goal('home-goal')], 1), updatedAt: 1 },+ );+ vi.mocked(goalService.list).mockImplementation(pending);++ renderHook(() => useGoalStore((s) => s.useFetchHomeGoals)(true, HOME_SCOPE), { wrapper });+ const view = renderHook(() => useGoalStore((s) => s.homeGoalsByScope[HOME_SCOPE]));++ await waitFor(() => expect(view.result.current?.goals[0].goal.id).toBe('home-goal'));+ });++ it('drops the previous identityβs rows before the next one paints', async () => {+ vi.mocked(goalService.list).mockResolvedValue(listPage([goal('mine')], 1) as never);+ const sync = renderHook(() => useGoalStore((s) => s.useFetchGoals)(AGENT_KEY), { wrapper });+ await waitFor(() => expect(useGoalStore.getState().goalListByAgentId[AGENT_KEY]).toBeDefined());++ vi.mocked(goalService.list).mockImplementation(pending);+ useScope(`goal-user-${randomUUID()}:personal`);+ sync.rerender();++ // Nothing from the previous identity stays on screen while the new scope's+ // (empty) storage read is still in flight.+ await waitFor(() =>+ expect(useGoalStore.getState().goalListByAgentId[AGENT_KEY]).toBeUndefined(),+ );+ });++ describe('deleteGoal', () => {+ const seed = async () => {+ vi.mocked(goalService.list).mockResolvedValue(listPage([goal('g1'), goal('g2')], 2) as never);+ vi.mocked(goalService.getGraph).mockResolvedValue(graph('g1') as never);+ vi.mocked(metricService.listSeriesWithPoints).mockResolvedValue([+ { key: 'stars', points: [{ value: 1 }] },+ ] as never);+ renderHook(+ () => {+ useGoalStore((s) => s.useFetchGoals)(AGENT_KEY);+ useGoalStore((s) => s.useFetchGoals)(AGENT_KEY, undefined, 'review');+ useGoalStore((s) => s.useFetchHomeGoals)(true, HOME_SCOPE);+ useGoalStore((s) => s.useFetchGoalGraph)('g1');+ useGoalStore((s) => s.useFetchGoalMetricSeries)('g1');+ },+ { wrapper },+ );+ await waitFor(() => {+ expect(useGoalStore.getState().goalListByAgentId[AGENT_KEY]?.goals).toHaveLength(2);+ expect(useGoalStore.getState().homeGoalsByScope[HOME_SCOPE]?.goals).toHaveLength(2);+ expect(useGoalStore.getState().goalGraphById.g1).toBeDefined();+ expect(useGoalStore.getState().goalMetricSeriesById.g1).toBeDefined();+ });+ };++ it('removes the goal from every loaded list, the home roll-up, its graph and its metric series', async () => {+ await seed();+ vi.mocked(goalService.delete).mockResolvedValue(undefined as never);+ // Keep the follow-up list refresh in flight: the fan-out has to stand on+ // its own, and a landed refresh would answer for it instead.+ vi.mocked(goalService.list).mockImplementation(pending);++ const deletion = useGoalStore.getState().deleteGoal(AGENT_KEY, 'g1');++ await waitFor(() => {+ expect(useGoalStore.getState().goalGraphById.g1).toBeUndefined();+ expect(useGoalStore.getState().goalMetricSeriesById.g1).toBeUndefined();+ expect(+ useGoalStore.getState().homeGoalsByScope[HOME_SCOPE]?.goals.map((item) => item.goal.id),+ ).toEqual(['g2']);+ });++ const all = useGoalStore.getState().goalListByAgentId[AGENT_KEY];+ expect(all?.goals.map((item) => item.goal.id)).toEqual(['g2']);+ expect(all?.total).toBe(1);+ expect(+ useGoalStore.getState().goalListByAgentId[REVIEW_KEY]?.goals.map((item) => item.goal.id),+ ).toEqual(['g2']);+ // The deleted id is never fetched again, so its persisted per-goal rows+ // must not be left orphaned in IndexedDB.+ await waitFor(async () =>+ expect(+ await goalMetricSeriesResource.storage!.get({+ queryKey: SERIES_G1_STORAGE_KEY,+ scope: scopeRef.current,+ }),+ ).toBeUndefined(),+ );+ await waitFor(async () =>+ expect(+ await goalGraphResource.storage!.get({+ queryKey: GRAPH_G1_STORAGE_KEY,+ scope: scopeRef.current,+ }),+ ).toBeUndefined(),+ );+ expect(goalService.delete).toHaveBeenCalledWith('g1');+ void deletion;+ });+ });+});diff --git a/src/store/goal/selectors.ts b/src/store/goal/selectors.tsindex 3bbf746d585..ed9a825d8f1 100644--- a/src/store/goal/selectors.ts+++ b/src/store/goal/selectors.ts@@ -1,6 +1,8 @@+import type { GoalListItem } from '@/services/goal';+import type { GoalStore } from './action';-const EMPTY_GOALS: GoalStore['goalListByAgentId'][string] = [];+const EMPTY_GOALS: GoalListItem[] = [];const goalGraph = (goalId?: string | null) => (s: GoalStore) =>goalId ? s.goalGraphById[goalId] : undefined;@@ -8,21 +10,20 @@ const goalGraph = (goalId?: string | null) => (s: GoalStore) =>const goalMetricSeries = (goalId?: string | null) => (s: GoalStore) =>goalId ? s.goalMetricSeriesById[goalId] : undefined;-const goalList = (agentId: string) => (s: GoalStore) => s.goalListByAgentId[agentId] ?? EMPTY_GOALS;--const isGoalListInitialized = (agentId: string) => (s: GoalStore) =>- s.goalListInitializedAgentIds.includes(agentId);+/** One list entry by its replica key β the scope itself for `all`, a tab's own key otherwise. */+const goalListView = (entryKey: string) => (s: GoalStore) => s.goalListByAgentId[entryKey];-const homeGoals = (scope: string) => (s: GoalStore) => s.homeGoalsByScope[scope] ?? EMPTY_GOALS;+/** The `all` rows of one scope; the narrow tabs read their own entry through `goalListView`. */+const goalList = (scope: string) => (s: GoalStore) =>+ s.goalListByAgentId[scope]?.goals ?? EMPTY_GOALS;-const isHomeGoalsInitialized = (scope: string) => (s: GoalStore) =>- s.homeGoalsInitializedScopes.includes(scope);+const homeGoals = (scope: string) => (s: GoalStore) =>+ s.homeGoalsByScope[scope]?.goals ?? EMPTY_GOALS;export const goalSelectors = {- goalMetricSeries,goalGraph,goalList,+ goalListView,+ goalMetricSeries,homeGoals,- isGoalListInitialized,- isHomeGoalsInitialized,};diff --git a/src/store/task/slices/detail/action.test.ts b/src/store/task/slices/detail/action.test.tsindex 6a87b79391c..c43234ecab0 100644--- a/src/store/task/slices/detail/action.test.ts+++ b/src/store/task/slices/detail/action.test.ts@@ -11,6 +11,7 @@ import { cacheScope, createReplicaState } from '@/libs/replica';import { useClientDataSWR } from '@/libs/swr';import { taskService } from '@/services/task';import { workService } from '@/services/work';+import { goalGraphResource } from '@/store/goal/projection';import { taskDetailSelectors } from '@/store/task/selectors';import { useUserStore } from '@/store/user';@@ -18,6 +19,16 @@ import { useTaskStore } from '../../store';import { taskDetailResource } from './projection';import { taskDetailRefreshes } from './testUtils';+/** A goal graph's replica sync key, as the refresh matcher has to recognise it. */+const goalGraphSyncKey = (goalId: string) => [+ 'replica:sync',+ goalGraphResource.name,+ goalGraphResource.version,+ goalGraphResource.scope.get(),+ goalId,+ {},+];+vi.mock('@/services/task', () => ({taskService: {addComment: vi.fn(),@@ -500,8 +511,10 @@ describe('TaskDetailSliceAction', () => {.mock.calls.map(([key]) => key).filter((key): key is (key: unknown) => boolean => typeof key === 'function');const matchesGoalGraph = (key: unknown) => matchers.some((match) => match(key));- expect(matchesGoalGraph(['goal:graph', 'goal-1'])).toBe(true);- expect(matchesGoalGraph(['goal:graph', 'goal-1', 'ws-1'])).toBe(true);+ // The goal graph is a replica: its sync keys live outside the SWR `goal:`+ // cache, so the refresh matches through the resource.+ expect(matchesGoalGraph(goalGraphSyncKey('goal-1'))).toBe(true);+ expect(matchesGoalGraph(['goal:graph', 'goal-1'])).toBe(false);expect(matchesGoalGraph(['task:detail', 'T-1'])).toBe(false);});@@ -518,7 +531,7 @@ describe('TaskDetailSliceAction', () => {.mocked(mutate).mock.calls.map(([key]) => key).filter((key): key is (key: unknown) => boolean => typeof key === 'function');- expect(matchers.some((match) => match(['goal:graph', 'goal-1']))).toBe(false);+ expect(matchers.some((match) => match(goalGraphSyncKey('goal-1')))).toBe(false);});it('should clear stale editorData for instruction-only optimistic updates', async () => {diff --git a/src/store/task/slices/detail/action.ts b/src/store/task/slices/detail/action.tsindex ea177f002bb..cab9876aee6 100644--- a/src/store/task/slices/detail/action.ts+++ b/src/store/task/slices/detail/action.ts@@ -8,11 +8,10 @@ import { toast } from '@lobehub/ui/base-ui';import isEqual from 'fast-deep-equal';import { t } from 'i18next';-import { createReplicaSlice, recordLens } from '@/libs/replica';-import { mutate } from '@/libs/swr';-import { goalKeys } from '@/libs/swr/keys';+import { createReplicaSlice, recordLens, revalidateReplica } from '@/libs/replica';import { taskService } from '@/services/task';import { workService } from '@/services/work';+import { goalGraphResource } from '@/store/goal/projection';import type { StoreSetter } from '@/store/types';import { useUserStore } from '@/store/user';import { userProfileSelectors } from '@/store/user/selectors';@@ -611,9 +610,7 @@ export class TaskDetailSliceActionImpl {// and only polls while the goal is advancing β a paused or finished// goal would keep showing the old assignee. The task does not know its// goal, so revalidate every goal graph; only mounted ones refetch.- assigneeAgentId !== undefined- ? mutate((key) => Array.isArray(key) && key[0] === goalKeys.graph.root)- : undefined,+ assigneeAgentId !== undefined ? revalidateReplica(goalGraphResource) : undefined,]).catch(() => {});}};