Skip to content

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

♻️ refactor(goal): move the topic's linked goals onto @lobechat/replica (#21302)

Arvin Xua9c0bad72f1e
diff --git a/locales/en-US/chat.json b/locales/en-US/chat.json
index ad70ee5e844..96694b7254b 100644
--- a/locales/en-US/chat.json
+++ b/locales/en-US/chat.json
@@ -966,7 +966,10 @@
"goalProcess.lifecycle.note.mainAgent": "Main Agent: {{text}}",
"goalProcess.lifecycle.note.recoveredAbandoned": "The previous run stopped responding; a new attempt started automatically",
"goalProcess.lifecycle.note.retryAfterVerification": "Verification did not pass; the next attempt started automatically",
+ "goalProcess.linked.checkFailed": "Status unconfirmed — tap to retry",
+ "goalProcess.linked.checking": "Confirming status…",
"goalProcess.linked.open": "Open goal progress",
+ "goalProcess.linked.retry": "Retry confirming the goal status",
"goalProcess.manager.pending": "Waiting for the first run",
"goalProcess.manager.title": "Main agent",
"goalProcess.manager.turns": "Planning rounds: {{count}}",
diff --git a/locales/zh-CN/chat.json b/locales/zh-CN/chat.json
index 349b80321bf..8f5d474dbc0 100644
--- a/locales/zh-CN/chat.json
+++ b/locales/zh-CN/chat.json
@@ -966,7 +966,10 @@
"goalProcess.lifecycle.note.mainAgent": "主 Agent:{{text}}",
"goalProcess.lifecycle.note.recoveredAbandoned": "上一次运行已失去响应,已自动重新开始",
"goalProcess.lifecycle.note.retryAfterVerification": "验收未通过,已自动开始下一次尝试",
+ "goalProcess.linked.checkFailed": "状态未能确认,点此重试",
+ "goalProcess.linked.checking": "正在确认状态…",
"goalProcess.linked.open": "查看目标进度",
+ "goalProcess.linked.retry": "重新确认目标状态",
"goalProcess.manager.pending": "等待首次执行",
"goalProcess.manager.title": "主 Agent",
"goalProcess.manager.turns": "已发起 {{count}} 轮规划",
diff --git a/packages/locales/src/default/chat.ts b/packages/locales/src/default/chat.ts
index 61c04c5c209..af5a6196223 100644
--- a/packages/locales/src/default/chat.ts
+++ b/packages/locales/src/default/chat.ts
@@ -2691,7 +2691,10 @@ export default {
'goalProcess.graph.exitFullscreen': 'Exit fullscreen',
'goalProcess.graph.bridgeHops_one': 'via {{count}} step not shown',
'goalProcess.graph.bridgeHops_other': 'via {{count}} steps not shown',
+ 'goalProcess.linked.checkFailed': 'Status unconfirmed — tap to retry',
+ 'goalProcess.linked.checking': 'Confirming status…',
'goalProcess.linked.open': 'Open goal progress',
+ 'goalProcess.linked.retry': 'Retry confirming the goal status',
'goalProcess.portal.openPage': 'Open goal page',
'goalProcess.portal.title': 'Goal',
'goalProcess.result.changes.comment': 'Your feedback',
diff --git a/src/features/Conversation/ChatInput/LinkedGoalTray/index.tsx b/src/features/Conversation/ChatInput/LinkedGoalTray/index.tsx
index abd68b70523..65fff5ca6bd 100644
--- a/src/features/Conversation/ChatInput/LinkedGoalTray/index.tsx
+++ b/src/features/Conversation/ChatInput/LinkedGoalTray/index.tsx
@@ -1,20 +1,20 @@
'use client';
import { createStaticStyles, cssVar, cx, Flexbox, Icon, Text } from '@lobehub/ui';
-import { ChevronRight } from 'lucide-react';
-import { memo, useMemo } from 'react';
+import { ChevronRight, CircleAlert, CircleDashed } from 'lucide-react';
+import { memo, useCallback, useMemo } from 'react';
import { useTranslation } from 'react-i18next';
import { goalStatusKey } from '@/features/AgentGoals/goalPresentation';
import GoalStatusGlyph from '@/features/AgentGoals/GoalStatusGlyph';
import type { GoalListItem } from '@/services/goal';
import { useChatStore } from '@/store/chat';
-import { useGoalStore } from '@/store/goal';
+import { goalSelectors, useGoalStore } from '@/store/goal';
import { useUserStore } from '@/store/user';
import { labPreferSelectors } from '@/store/user/selectors';
import { dataSelectors, messageStateSelectors, useConversationStore } from '../../store';
-import { isGoalRequestGenerating, selectLinkedGoals } from './linkedGoals';
+import { isGoalRequestGenerating, linkedGoalConfirmState, selectLinkedGoals } from './linkedGoals';
const styles = createStaticStyles(({ css }) => ({
container: css`
@@ -44,35 +44,54 @@ const styles = createStaticStyles(({ css }) => ({
`,
}));
-const LinkedGoalRow = memo<{ item: GoalListItem }>(({ item }) => {
+/**
+ * `confirmed` is false while the row is still the persisted copy: its status,
+ * gates and progress are whatever they were when it was stored, so the row
+ * names the goal and holds a neutral "confirming" state until the server
+ * answers rather than presenting a stale "running" as live. `failed` is that
+ * answer never arriving — the row says so and the click retries instead of
+ * opening, because a row nobody confirmed has no live status to show.
+ */
+const LinkedGoalRow = memo<{
+ confirmed: boolean;
+ failed?: boolean;
+ item: GoalListItem;
+ onRetry?: () => void;
+}>(({ confirmed, failed, item, onRetry }) => {
const { t } = useTranslation('chat');
const openGoal = useChatStore((s) => s.openGoal);
const { goal, pendingDecisions, taskDone, taskTotal } = item;
- const open = () => openGoal(goal.id);
+ const activate = failed && onRetry ? onRetry : () => openGoal(goal.id);
const planning = taskTotal === 0 && (goal.status === 'planning' || goal.status === 'running');
return (
<Flexbox
horizontal
align={'center'}
- aria-label={t('goalProcess.linked.open')}
+ aria-label={t(failed ? 'goalProcess.linked.retry' : 'goalProcess.linked.open')}
className={styles.row}
gap={8}
role={'button'}
tabIndex={0}
- onClick={open}
+ onClick={activate}
onKeyDown={(event) => {
if (event.key !== 'Enter' && event.key !== ' ') return;
event.preventDefault();
- open();
+ activate();
}}
>
- <GoalStatusGlyph size={14} status={goal.status} />
+ {confirmed ? (
+ <GoalStatusGlyph size={14} status={goal.status} />
+ ) : failed ? (
+ <Icon color={cssVar.colorWarning} icon={CircleAlert} size={14} />
+ ) : (
+ <Icon color={cssVar.colorTextQuaternary} icon={CircleDashed} size={14} />
+ )}
<Text ellipsis fontSize={12} style={{ flex: 1, minWidth: 0 }} weight={500}>
{goal.title}
</Text>
{/* Something blocked on the user outranks progress — it is the reason to click. */}
- {pendingDecisions > 0 ? (
+ {!confirmed ? null : pendingDecisions > 0 ? (
<Text fontSize={12} style={{ color: cssVar.colorWarning, flexShrink: 0 }}>
{t('goalList.needsYou', { count: pendingDecisions })}
</Text>
@@ -83,9 +102,19 @@ const LinkedGoalRow = memo<{ item: GoalListItem }>(({ item }) => {
</Text>
)
)}
- <Text fontSize={12} style={{ flexShrink: 0 }} type={'secondary'}>
+ <Text
+ fontSize={12}
+ style={{ color: failed ? cssVar.colorWarning : undefined, flexShrink: 0 }}
+ type={failed ? undefined : 'secondary'}
+ >
{/* A `/goal` run marks its goal running at creation; until the plan lands a Task it is still being planned. */}
- {planning ? t('goalTask.status.planning') : t(goalStatusKey(goal.status))}
+ {!confirmed
+ ? failed
+ ? t('goalProcess.linked.checkFailed')
+ : t('goalProcess.linked.checking')
+ : planning
+ ? t('goalTask.status.planning')
+ : t(goalStatusKey(goal.status))}
</Text>
<Icon color={cssVar.colorTextQuaternary} icon={ChevronRight} size={14} />
</Flexbox>
@@ -117,11 +146,18 @@ const LinkedGoalTray = memo<LinkedGoalTrayProps>(({ topAttached }) => {
messageStateSelectors.isAIGenerating(s),
),
);
- const { data } = useFetchTopicGoals(enabled ? topicId : undefined, goalRequestGenerating);
+ const { error, revalidate } = useFetchTopicGoals(
+ enabled ? topicId : undefined,
+ goalRequestGenerating,
+ );
+ const topicGoals = useGoalStore(goalSelectors.topicGoals(topicId));
+ const confirmed = useGoalStore(goalSelectors.topicGoalsConfirmed(topicId));
+ const confirmState = linkedGoalConfirmState(confirmed, error);
+ const retry = useCallback(() => void revalidate(), [revalidate]);
const goals = useMemo(
- () => selectLinkedGoals(data?.goals, displayMessages),
- [data, displayMessages],
+ () => selectLinkedGoals(topicGoals, displayMessages),
+ [topicGoals, displayMessages],
);
if (!enabled || !topicId || goals.length === 0) return null;
@@ -129,7 +165,13 @@ const LinkedGoalTray = memo<LinkedGoalTrayProps>(({ topAttached }) => {
return (
<Flexbox className={cx(styles.container, topAttached && styles.containerTopAttached)}>
{goals.map((item) => (
- <LinkedGoalRow item={item} key={item.goal.id} />
+ <LinkedGoalRow
+ confirmed={confirmed}
+ failed={confirmState === 'failed'}
+ item={item}
+ key={item.goal.id}
+ onRetry={confirmState === 'failed' ? retry : undefined}
+ />
))}
</Flexbox>
);
diff --git a/src/features/Conversation/ChatInput/LinkedGoalTray/linkedGoals.test.ts b/src/features/Conversation/ChatInput/LinkedGoalTray/linkedGoals.test.ts
index 2667877ccf0..3f88bb2640d 100644
--- a/src/features/Conversation/ChatInput/LinkedGoalTray/linkedGoals.test.ts
+++ b/src/features/Conversation/ChatInput/LinkedGoalTray/linkedGoals.test.ts
@@ -3,7 +3,12 @@ import { describe, expect, it } from 'vitest';
import type { GoalListItem } from '@/services/goal';
-import { isGoalRequestGenerating, MAX_LINKED_GOALS, selectLinkedGoals } from './linkedGoals';
+import {
+ isGoalRequestGenerating,
+ linkedGoalConfirmState,
+ MAX_LINKED_GOALS,
+ selectLinkedGoals,
+} from './linkedGoals';
const goal = (id: string) => ({ goal: { id } }) as unknown as GoalListItem;
@@ -105,3 +110,19 @@ describe('isGoalRequestGenerating', () => {
expect(isGoalRequestGenerating([userMessage('/goal ship the report')], false)).toBe(false);
});
});
+
+describe('linkedGoalConfirmState', () => {
+ it("reports the server answer once the rows are the server's", () => {
+ expect(linkedGoalConfirmState(true, undefined)).toBe('confirmed');
+ });
+
+ it('holds a neutral state while the first read is in flight', () => {
+ expect(linkedGoalConfirmState(false, undefined)).toBe('checking');
+ });
+
+ it('reports a failed confirmation instead of checking forever', () => {
+ // A settled goal with no run behind it stops polling, so nothing else would
+ // ever replace the "checking" state once the first read failed.
+ expect(linkedGoalConfirmState(false, new Error('offline'))).toBe('failed');
+ });
+});
diff --git a/src/features/Conversation/ChatInput/LinkedGoalTray/linkedGoals.ts b/src/features/Conversation/ChatInput/LinkedGoalTray/linkedGoals.ts
index 551d88ba7e5..37f91d6c469 100644
--- a/src/features/Conversation/ChatInput/LinkedGoalTray/linkedGoals.ts
+++ b/src/features/Conversation/ChatInput/LinkedGoalTray/linkedGoals.ts
@@ -32,6 +32,24 @@ export const selectLinkedGoals = (
return goals.filter(({ goal }) => !carded.has(goal.id)).slice(0, MAX_LINKED_GOALS);
};
+export type LinkedGoalConfirmState = 'checking' | 'confirmed' | 'failed';
+
+/**
+ * How trustworthy a tray row's status is. A row restored from storage paints
+ * before the server answers, so it holds a neutral "checking" state instead of
+ * presenting a persisted "running" as live. If that first read is the one that
+ * fails, the row has to say so: a settled goal with no run behind it stops
+ * polling, so no later request would ever replace the misleading state.
+ */
+export const linkedGoalConfirmState = (
+ confirmed: boolean,
+ syncError: unknown,
+): LinkedGoalConfirmState => {
+ if (confirmed) return 'confirmed';
+
+ return syncError ? 'failed' : 'checking';
+};
+
/**
* Whether the run in flight can be the one creating a goal: something is
* generating and the latest user message is a `/goal` request. Polling for new
diff --git a/src/features/Conversation/WorkingSidebar/GoalSection/useGoalSection.ts b/src/features/Conversation/WorkingSidebar/GoalSection/useGoalSection.ts
index 4e575489b27..5fa096a65a8 100644
--- a/src/features/Conversation/WorkingSidebar/GoalSection/useGoalSection.ts
+++ b/src/features/Conversation/WorkingSidebar/GoalSection/useGoalSection.ts
@@ -40,11 +40,12 @@ export const useTopicOperationGoals = (): OperationGoal[] => {
),
);
const useFetchTopicGoals = useGoalStore((s) => s.useFetchTopicGoals);
- const { data } = useFetchTopicGoals(context.topicId, goalRequestGenerating);
+ useFetchTopicGoals(context.topicId, goalRequestGenerating);
+ const topicGoals = useGoalStore(goalSelectors.topicGoals(context.topicId));
return useMemo(
- () => mergeTopicGoals(deriveOperationGoals(dbMessages ?? []), data?.goals),
- [dbMessages, data],
+ () => mergeTopicGoals(deriveOperationGoals(dbMessages ?? []), topicGoals),
+ [dbMessages, topicGoals],
);
};
diff --git a/src/libs/swr/keys.ts b/src/libs/swr/keys.ts
index 9f0ce752c59..aebbbaf428a 100644
--- a/src/libs/swr/keys.ts
+++ b/src/libs/swr/keys.ts
@@ -261,8 +261,6 @@ export const goalKeys = {
pendingClarifications: def('goal:pendingClarifications', () => ['goal:pendingClarifications']),
/** Gates and sign-offs waiting on the user across every goal, for the approval island. */
pendingForIsland: def('goal:pendingForIsland', () => ['goal:pendingForIsland']),
- /** Goals whose planning conversation is this topic (`subject_type = 'topic'`). */
- topicGoals: def('goal:topicGoals', (topicId: string) => ['goal:topicGoals', topicId]),
};
// ---- work ---------------------------------------------------------------
diff --git a/src/store/goal/action.test.ts b/src/store/goal/action.test.ts
index 78a3ed23332..67fcc119478 100644
--- a/src/store/goal/action.test.ts
+++ b/src/store/goal/action.test.ts
@@ -189,47 +189,53 @@ describe('GoalAction', () => {
});
describe('useFetchTopicGoals', () => {
- it('reads the goals created from the topic under a topic-scoped key', () => {
+ it('reads the goals created from the topic through the topic-keyed replica', () => {
renderHook(() => useGoalStore.getState().useFetchTopicGoals('tpc-1'));
- const [key, fetcher] = vi.mocked(useClientDataSWR).mock.calls[0];
+ const key = syncKeyFor('topicGoalList');
- expect(key).toEqual(['goal:topicGoals', 'tpc-1']);
- void (fetcher as () => unknown)();
+ expect(key?.[3]).toBe(SCOPE);
+ expect(key?.[4]).toBe('tpc-1');
+ void syncFetcherFor('topicGoalList')?.();
expect(goalService.list).toHaveBeenCalledWith({ limit: 20, topicId: 'tpc-1' });
});
it('does not fetch without a topic', () => {
renderHook(() => useGoalStore.getState().useFetchTopicGoals(undefined));
- expect(vi.mocked(useClientDataSWR).mock.calls[0][0]).toBeNull();
+ expect(syncCallFor('topicGoalList')).toBeUndefined();
});
it('polls only while one of the goals is still advancing on the server', () => {
- renderHook(() => useGoalStore.getState().useFetchTopicGoals('tpc-1'));
- const options = vi.mocked(useClientDataSWR).mock.calls[0][2] as {
- refreshInterval: (result?: { goals: Array<{ goal: { status: string } }> }) => number;
+ const withStatuses = (...statuses: string[]) => {
+ act(() =>
+ useGoalStore.setState({
+ topicGoalsByTopicId: {
+ 'tpc-1': {
+ goals: statuses.map((status) => ({ goal: { status } })) as never,
+ total: statuses.length,
+ },
+ },
+ }),
+ );
+ renderHook(() => useGoalStore.getState().useFetchTopicGoals('tpc-1'));
+ return syncConfigFor('topicGoalList')?.refreshInterval;
};
- const withStatuses = (...statuses: string[]) => ({
- goals: statuses.map((status) => ({ goal: { status } })),
- });
- expect(options.refreshInterval(withStatuses('achieved', 'running'))).toBeGreaterThan(0);
- expect(options.refreshInterval(withStatuses('review', 'paused'))).toBe(0);
- expect(options.refreshInterval(undefined)).toBe(0);
+ expect(withStatuses('achieved', 'running')).toBeGreaterThan(0);
+ expect(withStatuses('review', 'paused')).toBe(0);
// Regression: the tray read "Not started" after its agent started the draft.
- expect(options.refreshInterval(withStatuses('draft'))).toBeGreaterThan(0);
+ expect(withStatuses('draft')).toBeGreaterThan(0);
+ act(() => useGoalStore.setState({ topicGoalsByTopicId: {} }));
+ renderHook(() => useGoalStore.getState().useFetchTopicGoals('tpc-1'));
+ expect(syncConfigFor('topicGoalList')?.refreshInterval).toBe(0);
});
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.
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;
- };
- expect(options.refreshInterval(undefined)).toBeGreaterThan(0);
- expect(options.refreshInterval({ goals: [] })).toBeGreaterThan(0);
+ expect(syncConfigFor('topicGoalList')?.refreshInterval).toBeGreaterThan(0);
});
});
diff --git a/src/store/goal/action.ts b/src/store/goal/action.ts
index 69ab5689ee0..e3fbb46f6f6 100644
--- a/src/store/goal/action.ts
+++ b/src/store/goal/action.ts
@@ -28,6 +28,7 @@ import {
type GoalListValue,
goalMetricSeriesResource,
homeGoalListResource,
+ topicGoalListResource,
} from './projection';
/**
@@ -152,13 +153,21 @@ const useGoalCoordinatorAdvancing = (goalId?: string | null): boolean =>
/** A conversation rarely plans more than one goal; this only bounds a runaway topic. */
const TOPIC_GOAL_FETCH_LIMIT = 20;
-const topicGoalsRefreshInterval = (
- result: { goals: { goal: { status: GoalStatus } }[] } | undefined,
- generating?: boolean,
-) =>
- generating || result?.goals.some(({ goal }) => goalStatusPolled(goal.status))
- ? GOAL_GRAPH_POLL_INTERVAL
- : 0;
+/**
+ * The composer tray and the working sidebar both read a topic's goals on
+ * mount; this window collapses them into one request. It stays under the poll
+ * interval because SWR's poll ticks dedupe too.
+ */
+const TOPIC_GOALS_DEDUPING_INTERVAL = 4000;
+
+const useTopicGoalsAdvancing = (topicId?: string | null): boolean =>
+ useGoalStore((state) =>
+ topicId
+ ? (state.topicGoalsByTopicId[topicId]?.goals.some(({ goal }) =>
+ goalStatusPolled(goal.status),
+ ) ?? false)
+ : false,
+ );
export type GoalStore = GoalState & GoalAction;
type Setter = StoreSetter<GoalStore>;
@@ -172,6 +181,7 @@ export class GoalActionImpl {
readonly #goalMetricSeries;
readonly #homeGoalList;
readonly #set: Setter;
+ readonly #topicGoalList;
constructor(set: Setter, get: () => GoalStore, _api?: unknown) {
void _api;
@@ -205,9 +215,24 @@ export class GoalActionImpl {
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.#topicGoalList = createReplicaSlice(topicGoalListResource, {
+ actionPrefix: 'topicGoalList',
+ entity: goalListEntity,
+ fetcher: (topicId) => goalService.list({ limit: TOPIC_GOAL_FETCH_LIMIT, topicId }),
+ get,
+ set,
+ stateKey: 'topicGoalsReplica',
+ view: recordLens<GoalStore, GoalListValue>('topicGoalsByTopicId'),
+ });
+
+ // One goal row is rendered by a scope's tabs, the home rail and the
+ // conversation that created it; a change to it has to reach every list
+ // holding it, loaded or only persisted.
+ this.#goalListRows = linkReplicaEntity<GoalListItem>([
+ this.#goalList,
+ this.#homeGoalList,
+ this.#topicGoalList,
+ ]);
this.#goalGraph = createReplicaSlice(goalGraphResource, {
actionPrefix: 'goalGraph',
@@ -452,16 +477,19 @@ export class GoalActionImpl {
* while a `/goal` request is generating (`generating`, decided by the caller)
* — that run is the one that creates the goal, so nothing on screen would
* otherwise ask for it.
+ *
+ * Read the rows through `goalSelectors.topicGoals`; the persisted copy paints
+ * first, and `goalSelectors.topicGoalsConfirmed` says when its statuses are
+ * the server's current ones.
*/
- useFetchTopicGoals = (topicId?: string | null, generating?: boolean) =>
- useClientDataSWR(
- topicId ? goalKeys.topicGoals(topicId) : null,
- () => goalService.list({ limit: TOPIC_GOAL_FETCH_LIMIT, topicId: topicId! }),
- {
- refreshInterval: (result) => topicGoalsRefreshInterval(result, generating),
- revalidateOnFocus: true,
- },
- );
+ useFetchTopicGoals = (topicId?: string | null, generating?: boolean) => {
+ const advancing = useTopicGoalsAdvancing(topicId);
+ return this.#topicGoalList.useSync(topicId || null, {
+ dedupingInterval: TOPIC_GOALS_DEDUPING_INTERVAL,
+ refreshInterval: generating || advancing ? GOAL_GRAPH_POLL_INTERVAL : 0,
+ revalidateOnFocus: true,
+ });
+ };
/**
* North-star data of the goal detail header, read through
diff --git a/src/store/goal/initialState.ts b/src/store/goal/initialState.ts
index b19a24b779a..497b6f8874f 100644
--- a/src/store/goal/initialState.ts
+++ b/src/store/goal/initialState.ts
@@ -59,6 +59,10 @@ export interface GoalState {
homeGoalsByScope: Record<string, GoalListValue>;
/** Local-first bookkeeping for `homeGoalsByScope`. */
homeGoalsReplica: ReplicaState<GoalListValue>;
+ /** Goals created from one conversation, keyed by topic id. */
+ topicGoalsByTopicId: Record<string, GoalListValue>;
+ /** Local-first bookkeeping for `topicGoalsByTopicId`. */
+ topicGoalsReplica: ReplicaState<GoalListValue>;
}
export const initialState: GoalState = {
@@ -73,4 +77,6 @@ export const initialState: GoalState = {
goalViewMode: 'list',
homeGoalsByScope: {},
homeGoalsReplica: createReplicaState(),
+ topicGoalsByTopicId: {},
+ topicGoalsReplica: createReplicaState(),
};
diff --git a/src/store/goal/projection.ts b/src/store/goal/projection.ts
index a26b97ace6d..9bfd7637b0b 100644
--- a/src/store/goal/projection.ts
+++ b/src/store/goal/projection.ts
@@ -129,6 +129,18 @@ export const goalMetricSeriesResource = defineReplica<string, MetricSeriesWithPo
version: 1,
});
+/**
+ * Goals created from one conversation, keyed by topic id. Bounded: every topic
+ * the user ever opened would otherwise keep its own persisted row.
+ */
+export const topicGoalListResource = defineReplica<string, GoalListValue, GoalListResponse>({
+ key: (topicId) => topicId,
+ name: 'topicGoalList',
+ persist: { maxEntries: 50 },
+ 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
diff --git a/src/store/goal/selectors.ts b/src/store/goal/selectors.ts
index ed9a825d8f1..48d49bd9ac9 100644
--- a/src/store/goal/selectors.ts
+++ b/src/store/goal/selectors.ts
@@ -20,10 +20,23 @@ const goalList = (scope: string) => (s: GoalStore) =>
const homeGoals = (scope: string) => (s: GoalStore) =>
s.homeGoalsByScope[scope]?.goals ?? EMPTY_GOALS;
+const topicGoals = (topicId?: string | null) => (s: GoalStore) =>
+ topicId ? s.topicGoalsByTopicId[topicId]?.goals : undefined;
+
+/**
+ * Whether the topic's goal rows came from the server in this session. A row
+ * restored from storage carries the status of whenever it was persisted, so a
+ * live surface must not present it as the goal's current state until then.
+ */
+const topicGoalsConfirmed = (topicId?: string | null) => (s: GoalStore) =>
+ !!topicId && s.topicGoalsReplica.entries[topicId]?.source === 'server';
+
export const goalSelectors = {
goalGraph,
goalList,
goalListView,
goalMetricSeries,
homeGoals,
+ topicGoals,
+ topicGoalsConfirmed,
};
diff --git a/src/store/goal/topicGoals.replica.test.ts b/src/store/goal/topicGoals.replica.test.ts
new file mode 100644
index 00000000000..ee3c509b31c
--- /dev/null
+++ b/src/store/goal/topicGoals.replica.test.ts
@@ -0,0 +1,209 @@
+/**
+ * @vitest-environment happy-dom
+ *
+ * The goals a conversation created are a replica keyed by topic: a reload
+ * paints the persisted rows before the network answers, their statuses only
+ * count as current once the server confirms them, and the composer tray and
+ * the working sidebar share one request.
+ */
+import { randomUUID } from 'node:crypto';
+
+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 { useGoalStore } from './index';
+import { initialState } from './initialState';
+import { goalListResource, topicGoalListResource } from './projection';
+import { goalSelectors } from './selectors';
+
+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 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 TOPIC = 'tpc-1';
+const TOPIC_STORAGE_KEY = topicGoalListResource.storageKey(TOPIC);
+
+const topicGoalIds = () =>
+ goalSelectors
+ .topicGoals(TOPIC)(useGoalStore.getState())
+ ?.map((item) => item.goal.id);
+
+const confirmed = () => goalSelectors.topicGoalsConfirmed(TOPIC)(useGoalStore.getState());
+
+describe('topic goal replica', () => {
+ const scopes = new Set<string>();
+ const scopeRef = { current: '' };
+ const useScope = (next: string) => {
+ scopeRef.current = next;
+ scopes.add(next);
+ };
+
+ const persist = (goals: GoalListItem[], scope = scopeRef.current) =>
+ topicGoalListResource.storage!.set(
+ { queryKey: TOPIC_STORAGE_KEY, scope },
+ { data: listPage(goals), updatedAt: 1 },
+ );
+
+ const stored = async () =>
+ (
+ await topicGoalListResource.storage!.get({
+ queryKey: TOPIC_STORAGE_KEY,
+ scope: scopeRef.current,
+ })
+ )?.data;
+
+ beforeEach(() => {
+ useScope(`topic-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 scope of scopes) {
+ await topicGoalListResource.storage!.remove({ queryKey: TOPIC_STORAGE_KEY, scope });
+ await goalListResource.storage!.remove({
+ queryKey: goalListResource.storageKey({ agentId: 'agent-1', filter: 'all' }),
+ scope,
+ });
+ }
+ scopes.clear();
+ vi.restoreAllMocks();
+ vi.clearAllMocks();
+ });
+
+ it('paints the persisted rows before the network answers, then takes the server’s', async () => {
+ await persist([goal('cached')]);
+ let resolve: (value: unknown) => void = () => {};
+ vi.mocked(goalService.list).mockReturnValue(
+ new Promise((r) => {
+ resolve = r;
+ }) as never,
+ );
+
+ renderHook(() => useGoalStore((s) => s.useFetchTopicGoals)(TOPIC), { wrapper });
+
+ await waitFor(() => expect(topicGoalIds()).toEqual(['cached']));
+ expect(goalService.list).toHaveBeenCalledWith({ limit: 20, topicId: TOPIC });
+
+ await act(async () => {
+ resolve(listPage([goal('fresh', 'achieved')]));
+ });
+ await waitFor(() => expect(topicGoalIds()).toEqual(['fresh']));
+ await waitFor(async () => expect((await stored())?.goals[0].goal.id).toBe('fresh'));
+ });
+
+ it('treats the restored statuses as unconfirmed until the server answers', async () => {
+ await persist([goal('cached', 'running')]);
+ let resolve: (value: unknown) => void = () => {};
+ vi.mocked(goalService.list).mockReturnValue(
+ new Promise((r) => {
+ resolve = r;
+ }) as never,
+ );
+
+ renderHook(() => useGoalStore((s) => s.useFetchTopicGoals)(TOPIC), { wrapper });
+
+ await waitFor(() => expect(topicGoalIds()).toEqual(['cached']));
+ // A stored "running" is only what it was when persisted.
+ expect(confirmed()).toBe(false);
+
+ await act(async () => {
+ resolve(listPage([goal('cached', 'achieved')]));
+ });
+ await waitFor(() => expect(confirmed()).toBe(true));
+ });
+
+ it('keeps the last rows when a background refresh fails', async () => {
+ await persist([goal('cached')]);
+ vi.mocked(goalService.list).mockRejectedValue(new Error('network down'));
+
+ const sync = renderHook(() => useGoalStore((s) => s.useFetchTopicGoals)(TOPIC), { wrapper });
+
+ await waitFor(() => expect(sync.result.current.error).toBeDefined());
+ expect(topicGoalIds()).toEqual(['cached']);
+ });
+
+ it('sends one request for the composer tray and the sidebar together', async () => {
+ vi.mocked(goalService.list).mockResolvedValue(listPage([goal('g1')]) as never);
+
+ renderHook(
+ () => {
+ // The tray and the sidebar decide `generating` from different stores.
+ useGoalStore((s) => s.useFetchTopicGoals)(TOPIC, false);
+ useGoalStore((s) => s.useFetchTopicGoals)(TOPIC, undefined);
+ },
+ { wrapper },
+ );
+
+ await waitFor(() => expect(topicGoalIds()).toEqual(['g1']));
+ expect(goalService.list).toHaveBeenCalledTimes(1);
+ });
+
+ it('never shows the previous identity’s rows after a scope switch', async () => {
+ vi.mocked(goalService.list).mockResolvedValue(listPage([goal('mine')]) as never);
+ const sync = renderHook(() => useGoalStore((s) => s.useFetchTopicGoals)(TOPIC), { wrapper });
+ await waitFor(() => expect(topicGoalIds()).toEqual(['mine']));
+
+ vi.mocked(goalService.list).mockImplementation(pending);
+ useScope(`topic-goal-user-${randomUUID()}:personal`);
+ sync.rerender();
+
+ await waitFor(() => expect(topicGoalIds()).toBeUndefined());
+ });
+
+ it('drops a deleted goal from the topic rows and their persisted copy', async () => {
+ vi.mocked(goalService.list).mockResolvedValue(listPage([goal('g1'), goal('g2')]) as never);
+ renderHook(() => useGoalStore((s) => s.useFetchTopicGoals)(TOPIC), { wrapper });
+ await waitFor(() => expect(topicGoalIds()).toEqual(['g1', 'g2']));
+ await waitFor(async () => expect((await stored())?.goals).toHaveLength(2));
+
+ vi.mocked(goalService.delete).mockResolvedValue(undefined as never);
+ vi.mocked(goalService.list).mockImplementation(pending);
+ void useGoalStore.getState().deleteGoal('agent-1', 'g1');
+
+ await waitFor(() => expect(topicGoalIds()).toEqual(['g2']));
+ // A reload must not restore the deleted goal from storage.
+ await waitFor(async () =>
+ expect((await stored())?.goals.map((item) => item.goal.id)).toEqual(['g2']),
+ );
+ });
+});