π€― LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.
TypeScript agentagent-collaborationagent-harnessloop-engineeringmcppersonal-assistantproactive-agentskillssuper-agenttask-management
π fix(goals): hold the goal skeleton instead of blanking, bouncing or flashing the empty state (#20024)
Arvin Xu51a80460f5a8
diff --git a/src/features/AgentGoals/AgentGoalsPage.tsx b/src/features/AgentGoals/AgentGoalsPage.tsxindex 63c03cceac0..1f43cd41d15 100644--- a/src/features/AgentGoals/AgentGoalsPage.tsx+++ b/src/features/AgentGoals/AgentGoalsPage.tsx@@ -13,7 +13,7 @@ import AgentBreadcrumb from '@/features/AgentBreadcrumb';import NavHeader from '@/features/NavHeader';import WideScreenContainer from '@/features/WideScreenContainer';import { useWorkspaceAwareNavigate } from '@/features/Workspace/useWorkspaceAwareNavigate';-import { goalSelectors, useGoalStore } from '@/store/goal';+import { useGoalStore } from '@/store/goal';import { createGoalModal } from './CreateGoalModal';import { GoalCardItem } from './GoalCardItem';@@ -77,15 +77,18 @@ const AgentGoalsPage = memo<AgentGoalsPageProps>(({ agentId, projectId }) => {const scopeId = projectId ? `project:${projectId}` : agentId!;const useFetchGoals = useGoalStore((s) => s.useFetchGoals);const refreshGoals = useGoalStore((s) => s.refreshGoals);- const goals = useGoalStore(goalSelectors.goalList(scopeId));- const isInitialized = useGoalStore(goalSelectors.isGoalListInitialized(scopeId));const filter = useGoalStore((s) => s.goalListFilter);const viewMode = useGoalStore((s) => s.goalViewMode);const visibleLimit = useGoalStore((s) => s.goalListVisibleLimit);const setFilter = useGoalStore((s) => s.setGoalListFilter);const setViewMode = useGoalStore((s) => s.setGoalViewMode);const loadMoreGoals = useGoalStore((s) => s.loadMoreGoals);- const { error, isLoading } = useFetchGoals(agentId, projectId);+ // 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]);const summary = useMemo(() => {const delivered = goals.filter(({ goal }) => goal.status === 'review').length;@@ -138,7 +141,7 @@ const AgentGoalsPage = memo<AgentGoalsPageProps>(({ agentId, projectId }) => {paddingBlock={16}wrapperStyle={{ flex: 1, overflowY: 'auto' }}>- {isLoading && !isInitialized ? (+ {isLoading && data === undefined ? (<GoalSkeleton chrome={'body'} />) : error ? (<Block padding={32} variant={'outlined'}>diff --git a/src/features/AgentGoals/useAgentLabGate.test.ts b/src/features/AgentGoals/useAgentLabGate.test.tsnew file mode 100644index 00000000000..a1c237ca453--- /dev/null+++ b/src/features/AgentGoals/useAgentLabGate.test.ts@@ -0,0 +1,89 @@+import { renderHook } from '@testing-library/react';+import { beforeEach, describe, expect, it, vi } from 'vitest';++import { useAgentLabGate } from './useAgentLabGate';++/**+ * The lab gate reads `preference.lab.enableTopicAcceptance`, which is `false`+ * until `useInitUserState` resolves. Before the gate split "still loading"+ * from "settled off" via `isPreferenceInit`, the initial `false` rendered+ * `null` (a white flash inside the agent layout) and the redirect effect+ * kicked cold-boot visitors back to chat before their preference ever arrived.+ */+const userStateMock: {+ initError?: unknown;+ isUserStateInit?: boolean;+ preference: { lab?: { enableTopicAcceptance?: boolean } };+} = { preference: {} };++vi.mock('@/store/user', () => ({+ useUserStore: (selector: (state: Record<string, unknown>) => unknown) =>+ selector({+ isUserStateInit: userStateMock.isUserStateInit,+ isUserStateInitError: userStateMock.initError,+ preference: userStateMock.preference,+ }),+}));++beforeEach(() => {+ userStateMock.initError = undefined;+ userStateMock.isUserStateInit = true;+ userStateMock.preference = {};+});++describe('useAgentLabGate', () => {+ it('reports the gate as unjudged while preference is still initializing', () => {+ userStateMock.isUserStateInit = false;++ const { result } = renderHook(() => useAgentLabGate());++ expect(result.current.isPreferenceInit).toBe(false);+ expect(result.current.shouldRedirect).toBe(false);+ });++ it('opens the gate once preference settles with the lab enabled', () => {+ userStateMock.preference = { lab: { enableTopicAcceptance: true } };++ const { result } = renderHook(() => useAgentLabGate());++ expect(result.current).toEqual({+ enabled: true,+ initFailed: false,+ isPreferenceInit: true,+ shouldRedirect: false,+ });+ });++ it('redirects only after preference confirms the lab is off', () => {+ userStateMock.preference = { lab: { enableTopicAcceptance: false } };++ const { result } = renderHook(() => useAgentLabGate());++ expect(result.current.shouldRedirect).toBe(true);+ });++ it('redirects even when user state failed to initialize, so the page is not a dead end', () => {+ userStateMock.initError = new Error('offline');+ userStateMock.isUserStateInit = false;++ const { result } = renderHook(() => useAgentLabGate());++ // The gate itself stays unjudged β the route reads `isUserStateInitError`+ // separately, skips the skeleton, and this redirect is what actually gets+ // the visitor off the page instead of an empty pane with no exit.+ expect(result.current).toMatchObject({+ initFailed: true,+ isPreferenceInit: false,+ shouldRedirect: true,+ });+ });++ it('treats a falsy init error as no failure', () => {+ userStateMock.initError = null;+ userStateMock.isUserStateInit = false;++ const { result } = renderHook(() => useAgentLabGate());++ expect(result.current).toMatchObject({ initFailed: false, shouldRedirect: false });+ });+});diff --git a/src/features/AgentGoals/useAgentLabGate.ts b/src/features/AgentGoals/useAgentLabGate.tsnew file mode 100644index 00000000000..237ee6464e5--- /dev/null+++ b/src/features/AgentGoals/useAgentLabGate.ts@@ -0,0 +1,40 @@+'use client';++import { useMemo } from 'react';++import { useUserStore } from '@/store/user';+import { labPreferSelectors, preferenceSelectors } from '@/store/user/selectors';++/**+ * The lab gate every `/agent/:aid/goal*` route sits behind.+ *+ * `enableTopicAcceptance` reads `preference.lab`, which is `false` until+ * `useInitUserState` resolves. Judging the gate before that settles renders a+ * white flash (`null` for the whole pane) and the redirect effect kicks+ * cold-boot visitors back to chat before their preference ever arrived.+ * `isPreferenceInit` splits "still loading" from "settled off", and a failed+ * user-state init keeps the legacy escape instead of an endless skeleton.+ */+export const useAgentLabGate = () => {+ const initError = useUserStore((s) => s.isUserStateInitError);+ const isPreferenceInit = useUserStore(preferenceSelectors.isPreferenceInit);+ const enabled = useUserStore(labPreferSelectors.enableTopicAcceptance);++ const initFailed = !!initError;++ return useMemo(+ () => ({+ enabled,+ // A failed user-state init keeps the legacy escape: the route falls+ // through to its redirect instead of an endless skeleton.+ initFailed,+ isPreferenceInit,+ // A failed init never settles the preference, so the gate stays+ // unjudgeable forever. `shouldRedirect` is what actually gets the+ // visitor out, so it must fire here too β without it the route skips the+ // skeleton and then renders `null`, leaving an empty pane with no exit.+ shouldRedirect: (isPreferenceInit || initFailed) && !enabled,+ }),+ [enabled, initFailed, isPreferenceInit],+ );+};diff --git a/src/features/HomeInbox/homeGoals.ts b/src/features/HomeInbox/homeGoals.tsindex 8981cfcf35d..70352720c6b 100644--- a/src/features/HomeInbox/homeGoals.ts+++ b/src/features/HomeInbox/homeGoals.ts@@ -43,9 +43,9 @@ const isOpenGoalStatus = (statusKey: string): statusKey is GoalStatusKey =>/** Actionable first: a delivered goal is blocked on the user, a running one isn't. */const BUCKET_ORDER: HomeGoalBucket[] = ['review', 'running'];-/** The rail's goal rows, bucketed and ordered. */-export const buildHomeGoalEntries = (goals: GoalListItem[]): HomeGoalEntry[] => {- const entries = goals.flatMap<HomeGoalEntry>((item) => {+/** The rail's goal rows, bucketed and ordered. `undefined` (still loading) folds to none. */+export const buildHomeGoalEntries = (goals?: GoalListItem[]): HomeGoalEntry[] => {+ const entries = (goals ?? []).flatMap<HomeGoalEntry>((item) => {const statusKey = goalStatusKey(item.goal.status);if (!isOpenGoalStatus(statusKey)) return [];diff --git a/src/features/HomeInbox/index.tsx b/src/features/HomeInbox/index.tsxindex 4bb72af147b..30e608cb27c 100644--- a/src/features/HomeInbox/index.tsx+++ b/src/features/HomeInbox/index.tsx@@ -24,7 +24,7 @@ import { useBriefStore } from '@/store/brief';import { briefListSelectors } from '@/store/brief/selectors';import { useGlobalStore } from '@/store/global';import { systemStatusSelectors } from '@/store/global/selectors';-import { goalSelectors, useGoalStore } from '@/store/goal';+import { useGoalStore } from '@/store/goal';import { useUserStore } from '@/store/user';import { labPreferSelectors } from '@/store/user/selectors';import { authSelectors, userProfileSelectors } from '@/store/user/slices/auth/selectors';@@ -175,9 +175,10 @@ const HomeInbox = memo<HomeInboxProps>((props) => {const showGoals = isLogin === true && goalsEnabled && showRailSections;const useFetchHomeGoals = useGoalStore((s) => s.useFetchHomeGoals);const goalsSWR = useFetchHomeGoals(showGoals, cacheScope);- const goals = useGoalStore(goalSelectors.homeGoals(cacheScope));- const isGoalsInit = useGoalStore(goalSelectors.isHomeGoalsInitialized(cacheScope));- // The goal rail reads the goal's own lifecycle state (`goals.status`), so it+ // 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// no longer needs a separate acceptance read to decide each pile.const goalEntries = useMemo(() => (showGoals ? buildHomeGoalEntries(goals) : []),@@ -292,7 +293,7 @@ const HomeInbox = memo<HomeInboxProps>((props) => {// A goal feed failure must not be silent: without this the card just vanishes,// which is indistinguishable from having no open goals β the one reading a// long-running goal surface can least afford.- if (showGoals && goalsSWR.error && !isGoalsInit)+ if (showGoals && goalsSWR.error && goals === undefined)sections.push({key: 'goals-error',label: t('inbox.goals.title'),diff --git a/src/features/Projects/Workspace/ProjectDashboard.tsx b/src/features/Projects/Workspace/ProjectDashboard.tsxindex 70774bb2920..0981895c30f 100644--- a/src/features/Projects/Workspace/ProjectDashboard.tsx+++ b/src/features/Projects/Workspace/ProjectDashboard.tsx@@ -174,7 +174,7 @@ const ProjectDashboard = memo<ProjectDashboardProps>(({ detail, projectId }) =>variant={'inline'}onRetry={() => void goalSWR.mutate()}/>- ) : goalSWR.isLoading && goals.length === 0 ? (+ ) : goalSWR.isLoading && goalSWR.data === undefined ? (<ArticleSkeleton rows={4} />) : goals.length === 0 ? (<Block padding={24} variant={'outlined'}>diff --git a/src/libs/swr/useClientDataSWRWithSync.test.ts b/src/libs/swr/useClientDataSWRWithSync.test.tsnew file mode 100644index 00000000000..7665d034a40--- /dev/null+++ b/src/libs/swr/useClientDataSWRWithSync.test.ts@@ -0,0 +1,132 @@+/**+ * @vitest-environment happy-dom+ *+ * Regression: a persisted-cache hit for the NEXT key must reach onData.+ *+ * `hasSyncedRef` guards against double-syncing one key's data. It used to be+ * reset in a plain useEffect, which runs AFTER the data-effect in the same+ * commit β so when the key changed and SWR already held cached data for the+ * new key, the data-effect fired first, saw the stale guard, and swallowed+ * the sync. In the goal store this meant switching agents kept rendering the+ * previous agent's list until the network resolved.+ *+ * The discriminating leg (third test) switches the key with the row already+ * in the cache and a fetcher that can never resolve β no network callback can+ * fire, so onData running at all proves the cache-hit effect beat the guard.+ */+import { act, renderHook, waitFor } from '@testing-library/react';+import { createElement, type ReactNode } from 'react';+import type { Cache } from 'swr';+import { SWRConfig } from 'swr';+import { describe, expect, it, vi } from 'vitest';++import { useClientDataSWRWithSync } from './useClientDataSWRWithSync';++const makeWrapper =+ (cache: Map<string, unknown>) =>+ ({ children }: { children: ReactNode }) =>+ createElement(SWRConfig, { value: { provider: () => cache as unknown as Cache } }, children);++type Leg = { key: string; fetcher: () => Promise<{ id: string }> };++const never = () => new Promise<{ id: string }>(() => {});++describe('useClientDataSWRWithSync', () => {+ it('calls onData when data arrives, and again for a different key', async () => {+ const seen: string[] = [];++ const { rerender } = renderHook(+ ({ key }: { key: string }) =>+ useClientDataSWRWithSync(key, () => Promise.resolve({ id: key }), {+ onData: (data: { id: string }) => {+ seen.push(data.id);+ },+ }),+ {+ initialProps: { key: 'a' },+ wrapper: makeWrapper(new Map()),+ },+ );++ await waitFor(() => expect(seen).toEqual(['a']));++ // Switch to a key whose fetcher resolves instantly: onData must fire for+ // the new key β a stale guard must not swallow it.+ rerender({ key: 'b' });++ await waitFor(() => expect(seen).toEqual(['a', 'b']));+ });++ it('syncs a cache hit for a new key in the same commit as the switch', async () => {+ const seen: string[] = [];+ const onData = (data: { id: string }) => {+ seen.push(data.id);+ };+ const cache = new Map();+ const wrapper = makeWrapper(cache);++ const { rerender } = renderHook(+ ({ key, fetcher }: Leg) => useClientDataSWRWithSync(key, fetcher, { onData }),+ { initialProps: { key: 'b', fetcher: () => Promise.resolve({ id: 'b' }) }, wrapper },+ );+ await waitFor(() => expect(seen).toEqual(['b']));++ // Switch to key 'a' and let it resolve β the guard is now set by 'a'.+ rerender({ key: 'a', fetcher: () => Promise.resolve({ id: 'a' }) });+ await waitFor(() => expect(seen).toEqual(['b', 'a']));++ // Switch back to 'b': the row is already in the cache, and this leg's+ // fetcher never resolves, so no network callback can deliver 'b'. onData+ // firing proves the cache-hit effect ran β which requires the guard to+ // have been reset before the data-effect, i.e. the useLayoutEffect fix.+ rerender({ key: 'b', fetcher: never });++ await waitFor(() => expect(seen).toEqual(['b', 'a', 'b']), { timeout: 2000 });+ });++ it('serves a persisted-cache hit through onData without any network', async () => {+ const cache = new Map();+ const wrapper = makeWrapper(cache);+ const onData = vi.fn();++ // Warm the cache through a normal hook lifecycle first.+ const warm = renderHook(+ ({ key }: { key: string }) =>+ useClientDataSWRWithSync(key, () => Promise.resolve({ id: key }), { onData }),+ { initialProps: { key: 'warm' }, wrapper },+ );+ await waitFor(() => expect(onData).toHaveBeenCalledWith({ id: 'warm' }));+ warm.unmount();++ // A fresh consumer of the same key with the network unavailable still+ // syncs β this is the revisit path that used to render an empty state.+ const fresh = renderHook(+ () =>+ useClientDataSWRWithSync('warm', never, {+ onData,+ revalidateIfStale: false,+ revalidateOnFocus: false,+ revalidateOnReconnect: false,+ }),+ { wrapper },+ );++ await waitFor(() => expect(onData).toHaveBeenCalledTimes(2));+ expect(fresh.result.current.data).toEqual({ id: 'warm' });+ });++ it('does not call onData twice for the same key', async () => {+ const onData = vi.fn();++ renderHook(+ () => useClientDataSWRWithSync('same', () => Promise.resolve({ id: 'a' }), { onData }),+ { wrapper: makeWrapper(new Map()) },+ );++ await waitFor(() => expect(onData).toHaveBeenCalledTimes(1));+ await act(async () => {+ await Promise.resolve();+ });+ expect(onData).toHaveBeenCalledTimes(1);+ });+});diff --git a/src/libs/swr/useClientDataSWRWithSync.ts b/src/libs/swr/useClientDataSWRWithSync.tsindex fc3257bec9f..07749b3d699 100644--- a/src/libs/swr/useClientDataSWRWithSync.ts+++ b/src/libs/swr/useClientDataSWRWithSync.ts@@ -9,7 +9,7 @@* SWR key β consumers never need to opt in per call.*/-import { useEffect, useRef } from 'react';+import { useEffect, useLayoutEffect, useRef } from 'react';import { type SWRConfiguration, type SWRResponse } from 'swr';import { useClientDataSWR } from './index';@@ -81,8 +81,11 @@ export function useClientDataSWRWithSync<T>(}}, [data, onData, skipSync]);- // Reset sync state when key changes- useEffect(() => {+ // Reset sync state when the key changes. useLayoutEffect on purpose: this+ // must run before the data-effect above, or a data arrival for the new key+ // in the same commit is swallowed by the stale `hasSyncedRef` β e.g.+ // switching agents would keep rendering the previous agent's data.+ useLayoutEffect(() => {hasSyncedRef.current = false;}, [key?.toString()]);diff --git a/src/routes/(main)/agent/goal/[goalId]/index.tsx b/src/routes/(main)/agent/goal/[goalId]/index.tsxindex 449e5bba94c..83db47b869c 100644--- a/src/routes/(main)/agent/goal/[goalId]/index.tsx+++ b/src/routes/(main)/agent/goal/[goalId]/index.tsx@@ -3,21 +3,26 @@import { memo, useEffect } from 'react';import { useParams } from 'react-router';+import GoalDetailSkeleton from '@/components/Skeleton/GoalDetail';import { GoalDetailPage } from '@/features/AgentGoals';+import { useAgentLabGate } from '@/features/AgentGoals/useAgentLabGate';import { useWorkspaceAwareNavigate } from '@/features/Workspace/useWorkspaceAwareNavigate';-import { useUserStore } from '@/store/user';-import { labPreferSelectors } from '@/store/user/selectors';const GoalDetailRoute = memo(() => {const { aid, goalId } = useParams<{ aid?: string; goalId?: string }>();const navigate = useWorkspaceAwareNavigate();- const enabled = useUserStore(labPreferSelectors.enableTopicAcceptance);+ const { enabled, initFailed, isPreferenceInit, shouldRedirect } = useAgentLabGate();useEffect(() => {- if (aid && !enabled) navigate(`/agent/${aid}`, { replace: true });- }, [aid, enabled, navigate]);+ if (aid && shouldRedirect) navigate(`/agent/${aid}`, { replace: true });+ }, [aid, navigate, shouldRedirect]);if (!aid || !goalId) return null;+ // Preference still loading: the gate cannot be judged yet, so hold the page+ // skeleton instead of painting nothing (the white flash) or redirecting.+ // A failed user-state init keeps the legacy escape: fall through to the+ // redirect below rather than an endless skeleton.+ if (!isPreferenceInit && !initFailed) return <GoalDetailSkeleton />;if (!enabled) return null;return <GoalDetailPage agentId={aid} goalId={goalId} />;diff --git a/src/routes/(main)/agent/goals/index.tsx b/src/routes/(main)/agent/goals/index.tsxindex 636917400fd..65467977bbb 100644--- a/src/routes/(main)/agent/goals/index.tsx+++ b/src/routes/(main)/agent/goals/index.tsx@@ -3,21 +3,26 @@import { memo, useEffect } from 'react';import { useParams } from 'react-router';+import GoalSkeleton from '@/components/Skeleton/Goal';import { AgentGoalsPage } from '@/features/AgentGoals';+import { useAgentLabGate } from '@/features/AgentGoals/useAgentLabGate';import { useWorkspaceAwareNavigate } from '@/features/Workspace/useWorkspaceAwareNavigate';-import { useUserStore } from '@/store/user';-import { labPreferSelectors } from '@/store/user/selectors';const AgentGoalsRoute = memo(() => {const { aid } = useParams<{ aid?: string }>();const navigate = useWorkspaceAwareNavigate();- const enabled = useUserStore(labPreferSelectors.enableTopicAcceptance);+ const { enabled, initFailed, isPreferenceInit, shouldRedirect } = useAgentLabGate();useEffect(() => {- if (aid && !enabled) navigate(`/agent/${aid}`, { replace: true });- }, [aid, enabled, navigate]);+ if (aid && shouldRedirect) navigate(`/agent/${aid}`, { replace: true });+ }, [aid, navigate, shouldRedirect]);if (!aid) return null;+ // Preference still loading: the gate cannot be judged yet, so hold the page+ // skeleton instead of painting nothing (the white flash) or redirecting.+ // A failed user-state init keeps the legacy escape: fall through to the+ // redirect below rather than an endless skeleton.+ if (!isPreferenceInit && !initFailed) return <GoalSkeleton />;if (!enabled) return null;return <AgentGoalsPage agentId={aid} />;diff --git a/src/store/goal/action.test.ts b/src/store/goal/action.test.tsindex 1d2ee3edc46..56d852b172e 100644--- a/src/store/goal/action.test.ts+++ b/src/store/goal/action.test.ts@@ -1,11 +1,15 @@import { beforeEach, describe, expect, it, vi } from 'vitest';-import { mutate, useClientDataSWR } from '@/libs/swr';+import { mutate, useClientDataSWR, useClientDataSWRWithSync } from '@/libs/swr';import { goalService } from '@/services/goal';import { useGoalStore } from './index';-vi.mock('@/libs/swr', () => ({ mutate: vi.fn(), useClientDataSWR: vi.fn() }));+vi.mock('@/libs/swr', () => ({+ mutate: vi.fn(),+ useClientDataSWR: vi.fn(),+ useClientDataSWRWithSync: vi.fn(),+}));vi.mock('@/services/goal', () => ({goalService: { delete: vi.fn(), list: vi.fn() },}));@@ -106,11 +110,11 @@ describe('GoalAction', () => {it('stores goal lists independently for each agent', () => {useGoalStore.getState().useFetchGoals('agent-1');- const options = vi.mocked(useClientDataSWR).mock.calls[0][2] as {- onSuccess: (value: { goals: Array<{ id: string }> }) => void;+ const options = vi.mocked(useClientDataSWRWithSync).mock.calls[0][2] as {+ onData: (value: { goals: Array<{ id: string }> }) => void;};- options.onSuccess({ goals: [{ id: 'goal-1' }] });+ options.onData({ goals: [{ id: 'goal-1' }] });expect(useGoalStore.getState().goalListByAgentId['agent-1']).toEqual([{ id: 'goal-1' }]);expect(useGoalStore.getState().goalListInitializedAgentIds).toContain('agent-1');@@ -118,7 +122,7 @@ describe('GoalAction', () => {it('queries the goal list endpoint with an agent-scoped query and cache', () => {useGoalStore.getState().useFetchGoals('agent-1');- const [, fetcher] = vi.mocked(useClientDataSWR).mock.calls[0];+ const [, fetcher] = vi.mocked(useClientDataSWRWithSync).mock.calls[0];void (fetcher as () => unknown)();expect(goalService.list).toHaveBeenCalledWith(expect.objectContaining({ agentId: 'agent-1' }));@@ -126,7 +130,7 @@ describe('GoalAction', () => {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(useClientDataSWR).mock.calls[0];+ const [key, fetcher, options] = vi.mocked(useClientDataSWRWithSync).mock.calls[0];expect(key).toEqual(['task:sidebarGroups', 'project:project-1:goals-page']);expect(fetcher).toBeTypeOf('function');@@ -135,29 +139,46 @@ describe('GoalAction', () => {expect.objectContaining({ projectId: 'project-1' }),);- const onSuccess = (+ const onData = (options as {- onSuccess: (value: { goals: Array<{ id: string }> }) => void;+ onData: (value: { goals: Array<{ id: string }> }) => void;}- ).onSuccess;- onSuccess({ goals: [{ id: 'project-goal-1' }] });+ ).onData;+ onData({ goals: [{ id: 'project-goal-1' }] });expect(useGoalStore.getState().goalListByAgentId['project:project-1']).toEqual([{ id: 'project-goal-1' },]);});+ // 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;+ };++ expect(options.onData).toBeTypeOf('function');++ options.onData({ goals: [{ id: 'cached-goal' }] });++ expect(useGoalStore.getState().goalListByAgentId['agent-1']).toEqual([{ id: 'cached-goal' }]);+ expect(useGoalStore.getState().goalListInitializedAgentIds).toContain('agent-1');+ });+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(useClientDataSWR).mock.calls[call][2] as {- onSuccess: (value: { goals: Array<{ id: string }> }) => void;+ vi.mocked(useClientDataSWRWithSync).mock.calls[call][2] as {+ onData: (value: { goals: Array<{ id: string }> }) => void;};// ws-b lands first, then the workspace you already left answers.- optionsOf(1).onSuccess({ goals: [{ id: 'goal-b' }] });- optionsOf(0).onSuccess({ goals: [{ id: 'goal-a' }] });+ optionsOf(1).onData({ goals: [{ id: 'goal-b' }] });+ optionsOf(0).onData({ goals: [{ id: 'goal-a' }] });expect(useGoalStore.getState().homeGoalsByScope).toEqual({'user:ws-a': [{ id: 'goal-a' }],@@ -168,7 +189,7 @@ describe('GoalAction', () => {it('asks only for statuses rendered by the home roll-up', () => {useGoalStore.getState().useFetchHomeGoals(true, 'user:ws-a');- const fetcher = vi.mocked(useClientDataSWR).mock.calls[0][1] as () => unknown;+ const fetcher = vi.mocked(useClientDataSWRWithSync).mock.calls[0][1] as () => unknown;fetcher();@@ -204,10 +225,10 @@ 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(useClientDataSWR).mock.calls[0][2] as {- onSuccess: (value: { goals: Array<{ goal: { id: string } }> }) => void;+ const options = vi.mocked(useClientDataSWRWithSync).mock.calls[0][2] as {+ onData: (value: { goals: Array<{ goal: { id: string } }> }) => void;};- options.onSuccess({ goals: [{ goal: { id: 'goal-1' } }, { goal: { id: 'goal-2' } }] });+ options.onData({ goals: [{ goal: { id: 'goal-1' } }, { goal: { id: 'goal-2' } }] });await useGoalStore.getState().deleteGoal('agent-1', 'goal-1');diff --git a/src/store/goal/action.ts b/src/store/goal/action.tsindex f972e6ba470..029c0355c9b 100644--- a/src/store/goal/action.ts+++ b/src/store/goal/action.ts@@ -1,7 +1,7 @@import { type GoalStatus, goalStatuses } from '@lobechat/const/goal';import type { GoalMetricCriterion, GoalTickResult } from '@lobechat/types';-import { mutate, useClientDataSWR } from '@/libs/swr';+import { mutate, useClientDataSWR, useClientDataSWRWithSync } from '@/libs/swr';import { goalKeys, taskKeys } from '@/libs/swr/keys';import { goalService } from '@/services/goal';import { metricService } from '@/services/metric';@@ -286,10 +286,16 @@ export class GoalActionImpl {this.#set({ goalViewMode: mode }, false, 'setGoalViewMode');};+ /**+ * The goal list page's read. 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.+ */useFetchGoals = (agentId?: string, projectId?: string) => {const scopeId = projectId ? `project:${projectId}` : agentId;- return useClientDataSWR(+ return useClientDataSWRWithSync(scopeId ? taskKeys.sidebarGroups(`${scopeId}:goals-page`) : null,() =>goalService.list({@@ -299,7 +305,7 @@ export class GoalActionImpl {statuses: GOAL_STATUSES,}),{- onSuccess: ({ goals }) => {+ onData: ({ goals }) => {this.#set(({ goalListByAgentId, goalListInitializedAgentIds }) => ({goalListByAgentId: {@@ -323,9 +329,12 @@ export class GoalActionImpl {* 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.*/useFetchHomeGoals = (enabled: boolean, scope: string) =>- useClientDataSWR(+ useClientDataSWRWithSync(enabled ? taskKeys.homeGoals(scope) : null,() =>goalService.list({@@ -333,7 +342,7 @@ export class GoalActionImpl {statuses: HOME_GOAL_STATUSES,}),{- onSuccess: ({ goals }) => {+ onData: ({ goals }) => {this.#set(({ homeGoalsByScope, homeGoalsInitializedScopes }) => ({homeGoalsByScope: { ...homeGoalsByScope, [scope]: goals },