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.

🐛 fix(goal): unstick three panels that could not scroll, and merge spend into the budget metric (#19157)

Arvin Xuf20ea9602b6e
diff --git a/apps/server/src/services/goal/index.test.ts b/apps/server/src/services/goal/index.test.ts
index ef0960ae620..f659a91a458 100644
--- a/apps/server/src/services/goal/index.test.ts
+++ b/apps/server/src/services/goal/index.test.ts
@@ -463,6 +463,71 @@ describe('GoalService', () => {
expect(raised?.status).not.toBe('paused');
});
+ it('ships the spend the budget is enforced against with the graph', async () => {
+ // The header renders `spent / cap` as one fraction, so the number it shows
+ // has to be the number the coordinator will stop on — not the goal list's
+ // subtree roll-up, which counts Tasks the graph's Tasks spawned.
+ const service = new GoalService(serverDB, userId);
+ const graph = await service.create({
+ maxTotalCost: 10,
+ tasks: ['Costs money'],
+ title: 'Spend',
+ });
+ const created = await service.tick(graph.goal.id);
+
+ await serverDB
+ .insert(topics)
+ .values({ id: 'tpc_spend_1', totalCost: 6.4, totalTokens: 1200, userId });
+ await serverDB
+ .insert(taskTopics)
+ .values({ seq: 1, taskId: created.taskId!, topicId: 'tpc_spend_1', userId });
+ // A run that has not settled is a round with no cost yet.
+ await serverDB.insert(topics).values({ id: 'tpc_spend_2', userId });
+ await serverDB
+ .insert(taskTopics)
+ .values({ seq: 2, taskId: created.taskId!, topicId: 'tpc_spend_2', userId });
+
+ const { spend } = await service.graph(graph.goal.id);
+
+ expect(spend).toMatchObject({ runs: 2, totalCost: 6.4, totalTokens: 1200 });
+ // The cost panel lists WHERE the money went, so the same read carries the
+ // per-Task split rather than only the total the budget is checked against.
+ expect(spend?.byTask).toEqual([
+ { runs: 2, taskId: created.taskId!, totalCost: 6.4, totalTokens: 1200 },
+ ]);
+ });
+
+ it('keeps an existing deadline when only the cost cap is edited', async () => {
+ // The budget panel sends one dimension at a time; an omitted deadline used
+ // to be written back as null, silently dropping a calendar budget someone
+ // set from a click that only meant to raise the dollars.
+ const service = new GoalService(serverDB, userId);
+ const deadline = new Date(Date.now() + 3_600_000).toISOString();
+ const graph = await service.create({
+ config: { schedule: { deadline } },
+ tasks: ['Bounded'],
+ title: 'Deadline keeper',
+ });
+
+ const updated = await service.setBudget(graph.goal.id, { maxTotalCost: 25 });
+
+ expect(updated?.config?.schedule?.deadline).toBe(deadline);
+ expect(Number(updated?.maxTotalCost)).toBe(25);
+ });
+
+ it('leaves the round cap alone when only the cost cap is edited', async () => {
+ const service = new GoalService(serverDB, userId);
+ const graph = await service.create({
+ maxRounds: 7,
+ tasks: ['Bounded'],
+ title: 'Round keeper',
+ });
+
+ const updated = await service.setBudget(graph.goal.id, { maxTotalCost: 25 });
+
+ expect(updated?.maxRounds).toBe(7);
+ });
+
it('edits the standing requirement in place', async () => {
const service = new GoalService(serverDB, userId);
const graph = await service.create({
diff --git a/apps/server/src/services/goal/index.ts b/apps/server/src/services/goal/index.ts
index 9c52baff55e..136e5ace50d 100644
--- a/apps/server/src/services/goal/index.ts
+++ b/apps/server/src/services/goal/index.ts
@@ -472,7 +472,11 @@ export class GoalService {
graph = async (goalId: string) => {
const graph = await this.requireGraph(goalId);
- return { ...graph, runHeartbeats: await this.collectRunHeartbeats(graph) };
+ const [runHeartbeats, spend] = await Promise.all([
+ this.collectRunHeartbeats(graph),
+ this.resolveSpend(graph),
+ ]);
+ return { ...graph, runHeartbeats, spend };
};
/**
@@ -684,20 +688,32 @@ export class GoalService {
};
private evaluateBudget = async (goal: GoalItem, graph: GoalGraphSnapshot) => {
- const taskIds = graph.nodes.flatMap((node) => (node.taskId ? [node.taskId] : []));
- const runs = await this.taskTopicModel.findWithHandoffByTaskIds(taskIds, 10_000);
- const totalCost = runs.reduce((sum, run) => sum + Number(run.totalCost ?? 0), 0);
+ const { runs, totalCost } = await this.resolveSpend(graph);
const deadline = goal.config?.schedule?.deadline ?? null;
return {
costLimitReached: goal.maxTotalCost !== null && totalCost >= Number(goal.maxTotalCost),
deadline,
deadlinePassed: deadline !== null && Date.now() >= new Date(deadline).getTime(),
- roundLimitReached: goal.maxRounds !== null && runs.length >= goal.maxRounds,
+ roundLimitReached: goal.maxRounds !== null && runs >= goal.maxRounds,
runs,
totalCost,
};
};
+ /**
+ * Rounds run and dollars spent, by the definition the budget is enforced
+ * against: the runs of the graph's own Task nodes.
+ *
+ * `graph()` ships this to the client so the page's spend reads the same
+ * number the coordinator will stop on. Note it is deliberately NOT the goal
+ * list's `totalRunCost`, which walks the whole `parent_task_id` subtree —
+ * that number is larger for a goal whose Tasks spawned Tasks.
+ */
+ private resolveSpend = async (graph: GoalGraphSnapshot) =>
+ this.taskTopicModel.sumRunCostByTaskIds(
+ graph.nodes.flatMap((node) => (node.taskId ? [node.taskId] : [])),
+ );
+
/**
* Edit the goal's standing acceptance requirement in place. The next
* coordinator move and every later dispatched Task read the updated text;
@@ -721,10 +737,12 @@ export class GoalService {
const wasBinding = await this.evaluateBudget(before.goal, before);
// Deadline joins the two execution budgets on the goal row's config; null
- // clears it. The merge keeps an untouched recovery/schedule block intact.
+ // clears it, and omitting it leaves it alone — the cost/round editor sends
+ // only what it owns, and must not silently drop a deadline someone set.
+ // The merge keeps an untouched recovery/schedule block intact.
const config = { ...before.goal.config };
- if (budget.deadline !== undefined || config.schedule) {
- config.schedule = { ...config.schedule, deadline: budget.deadline ?? null };
+ if (budget.deadline !== undefined) {
+ config.schedule = { ...config.schedule, deadline: budget.deadline };
}
const goal = await this.goalModel.update(goalId, {
diff --git a/apps/server/src/services/goal/traceObservation.ts b/apps/server/src/services/goal/traceObservation.ts
index fe51bc1241d..78cc574c50c 100644
--- a/apps/server/src/services/goal/traceObservation.ts
+++ b/apps/server/src/services/goal/traceObservation.ts
@@ -94,7 +94,8 @@ export interface BudgetEvaluation {
deadline: string | null;
deadlinePassed: boolean;
roundLimitReached: boolean;
- runs: { length: number };
+ /** Runs the graph's Task nodes produced — the round count. */
+ runs: number;
totalCost: number;
}
@@ -104,6 +105,6 @@ export const toBudgetState = (goal: GoalItem, budget: BudgetEvaluation): GoalBud
maxRounds: goal.maxRounds,
maxTotalCost: goal.maxTotalCost === null ? null : Number(goal.maxTotalCost),
roundLimitReached: budget.roundLimitReached,
- runs: budget.runs.length,
+ runs: budget.runs,
totalCost: budget.totalCost,
});
diff --git a/locales/en-US/chat.json b/locales/en-US/chat.json
index c5b3326710f..0b312503eb2 100644
--- a/locales/en-US/chat.json
+++ b/locales/en-US/chat.json
@@ -581,10 +581,16 @@
"goalProcess.kind.finding": "Finding",
"goalProcess.kind.problem": "Question",
"goalProcess.kind.task": "Task",
- "goalProcess.metricDetail.budget.rounds": "Round cap",
- "goalProcess.metricDetail.budget.spendNote": "Per-run spend is recorded on each dispatched task — open a task to see what its runs actually cost.",
- "goalProcess.metricDetail.budget.title": "Budget",
- "goalProcess.metricDetail.budget.totalCost": "Total cost cap",
+ "goalProcess.metricDetail.budget.controlTitle": "Budget control",
+ "goalProcess.metricDetail.budget.perTaskEmpty": "No run has been billed yet.",
+ "goalProcess.metricDetail.budget.perTaskTitle": "Where it went",
+ "goalProcess.metricDetail.budget.raiseNote": "Raising a cap is what restarts a goal the coordinator parked on its budget — it starts moving again on its own, no Resume needed. Leave a field empty to run uncapped.",
+ "goalProcess.metricDetail.budget.rounds": "Rounds",
+ "goalProcess.metricDetail.budget.runsValue": "{{count}} runs",
+ "goalProcess.metricDetail.budget.saveFailed": "Could not update the budget",
+ "goalProcess.metricDetail.budget.title": "Cost",
+ "goalProcess.metricDetail.budget.tokensValue": "{{value}} tokens",
+ "goalProcess.metricDetail.budget.totalCost": "Spend",
"goalProcess.metricDetail.budget.uncapped": "Uncapped",
"goalProcess.metricDetail.duration.now": "now",
"goalProcess.metricDetail.duration.taskSpans": "Task spans",
@@ -598,11 +604,12 @@
"goalProcess.metricDetail.liveness.running": "Running now",
"goalProcess.metricDetail.liveness.title": "Liveness",
"goalProcess.metricDetail.tasks.title": "All tasks",
- "goalProcess.metrics.budget": "Budget",
"goalProcess.metrics.duration": "Runtime",
"goalProcess.metrics.findings": "Findings",
"goalProcess.metrics.liveness": "Last activity",
+ "goalProcess.metrics.rounds": "Rounds",
"goalProcess.metrics.roundsValue": "{{count}} rounds",
+ "goalProcess.metrics.spend": "Spend",
"goalProcess.metrics.status": "Status",
"goalProcess.metrics.tasks": "Tasks",
"goalProcess.metrics.uncapped": "Uncapped",
diff --git a/locales/zh-CN/chat.json b/locales/zh-CN/chat.json
index b58f941e512..3ad191b05c8 100644
--- a/locales/zh-CN/chat.json
+++ b/locales/zh-CN/chat.json
@@ -581,10 +581,16 @@
"goalProcess.kind.finding": "结论",
"goalProcess.kind.problem": "问题",
"goalProcess.kind.task": "任务",
- "goalProcess.metricDetail.budget.rounds": "轮次上限",
- "goalProcess.metricDetail.budget.spendNote": "实际消耗记录在派发出去的各个任务上——打开任务详情即可查看每次运行花了多少。",
- "goalProcess.metricDetail.budget.title": "预算",
- "goalProcess.metricDetail.budget.totalCost": "总成本上限",
+ "goalProcess.metricDetail.budget.controlTitle": "预算控制",
+ "goalProcess.metricDetail.budget.perTaskEmpty": "还没有产生任何计费运行。",
+ "goalProcess.metricDetail.budget.perTaskTitle": "花在哪了",
+ "goalProcess.metricDetail.budget.raiseNote": "目标因预算被暂停时,提高上限就是让它继续跑的方式——它会自己重新推进,不需要再点一次「继续」。留空表示不限。",
+ "goalProcess.metricDetail.budget.rounds": "轮次",
+ "goalProcess.metricDetail.budget.runsValue": "{{count}} 次运行",
+ "goalProcess.metricDetail.budget.saveFailed": "预算更新失败",
+ "goalProcess.metricDetail.budget.title": "成本统计",
+ "goalProcess.metricDetail.budget.tokensValue": "{{value}} tokens",
+ "goalProcess.metricDetail.budget.totalCost": "开销",
"goalProcess.metricDetail.budget.uncapped": "未设限",
"goalProcess.metricDetail.duration.now": "现在",
"goalProcess.metricDetail.duration.taskSpans": "各任务起止",
@@ -598,11 +604,12 @@
"goalProcess.metricDetail.liveness.running": "正在执行",
"goalProcess.metricDetail.liveness.title": "活性",
"goalProcess.metricDetail.tasks.title": "全部任务",
- "goalProcess.metrics.budget": "预算",
"goalProcess.metrics.duration": "运行时长",
"goalProcess.metrics.findings": "结论",
"goalProcess.metrics.liveness": "最近活动",
+ "goalProcess.metrics.rounds": "轮次",
"goalProcess.metrics.roundsValue": "{{count}} 轮",
+ "goalProcess.metrics.spend": "开销",
"goalProcess.metrics.status": "状态",
"goalProcess.metrics.tasks": "任务",
"goalProcess.metrics.uncapped": "未设限",
diff --git a/packages/database/src/models/taskTopic.ts b/packages/database/src/models/taskTopic.ts
index c6e18dc5f4d..3ecc41aee1f 100644
--- a/packages/database/src/models/taskTopic.ts
+++ b/packages/database/src/models/taskTopic.ts
@@ -314,6 +314,55 @@ export class TaskTopicModel {
.limit(limit);
}
+ /**
+ * A goal's spend and round count in one aggregate: how many runs those tasks
+ * produced and what they cost.
+ *
+ * The Goal page renders these numbers and the coordinator enforces the budget
+ * against them, so both read them from here — a second definition of "what
+ * this goal has spent" would let the header disagree with the move that
+ * parks the goal on `budget_exhausted`.
+ *
+ * `topics.totalCost` is NULL for a run that has not settled yet; those count
+ * as a round but contribute nothing to the sum.
+ */
+ async sumRunCostByTaskIds(taskIds: string[]): Promise<{
+ byTask: { runs: number; taskId: string; totalCost: number; totalTokens: number }[];
+ runs: number;
+ totalCost: number;
+ totalTokens: number;
+ }> {
+ if (taskIds.length === 0) return { byTask: [], runs: 0, totalCost: 0, totalTokens: 0 };
+
+ // Grouped once, then folded — one round trip serves both the enforced
+ // total and the per-Task breakdown the cost panel lists.
+ const rows = await this.db
+ .select({
+ runs: count(),
+ taskId: taskTopics.taskId,
+ totalCost: sql<string>`coalesce(sum(${topics.totalCost}), 0)`,
+ totalTokens: sql<string>`coalesce(sum(${topics.totalTokens}), 0)`,
+ })
+ .from(taskTopics)
+ .leftJoin(topics, eq(taskTopics.topicId, topics.id))
+ .where(and(inArray(taskTopics.taskId, taskIds), this.ownership()))
+ .groupBy(taskTopics.taskId);
+
+ const byTask = rows.map((row) => ({
+ runs: row.runs,
+ taskId: row.taskId,
+ totalCost: Number(row.totalCost ?? 0),
+ totalTokens: Number(row.totalTokens ?? 0),
+ }));
+
+ return {
+ byTask,
+ runs: byTask.reduce((sum, row) => sum + row.runs, 0),
+ totalCost: byTask.reduce((sum, row) => sum + row.totalCost, 0),
+ totalTokens: byTask.reduce((sum, row) => sum + row.totalTokens, 0),
+ };
+ }
+
async findWithHandoffByTaskIds(taskIds: string[], limit: number) {
if (taskIds.length === 0) return [];
diff --git a/packages/locales/src/default/chat.ts b/packages/locales/src/default/chat.ts
index 4798f6ec967..f3aef846349 100644
--- a/packages/locales/src/default/chat.ts
+++ b/packages/locales/src/default/chat.ts
@@ -1943,11 +1943,17 @@ export default {
'goalProcess.eventType.retired': 'Retired',
'goalProcess.eventType.unlinked': 'Unlinked',
'goalProcess.eventType.updated': 'Updated',
- 'goalProcess.metricDetail.budget.rounds': 'Round cap',
- 'goalProcess.metricDetail.budget.spendNote':
- 'Per-run spend is recorded on each dispatched task \u2014 open a task to see what its runs actually cost.',
- 'goalProcess.metricDetail.budget.title': 'Budget',
- 'goalProcess.metricDetail.budget.totalCost': 'Total cost cap',
+ 'goalProcess.metricDetail.budget.controlTitle': 'Budget control',
+ 'goalProcess.metricDetail.budget.perTaskEmpty': 'No run has been billed yet.',
+ 'goalProcess.metricDetail.budget.perTaskTitle': 'Where it went',
+ 'goalProcess.metricDetail.budget.runsValue': '{{count}} runs',
+ 'goalProcess.metricDetail.budget.tokensValue': '{{value}} tokens',
+ 'goalProcess.metricDetail.budget.raiseNote':
+ 'Raising a cap is what restarts a goal the coordinator parked on its budget \u2014 it starts moving again on its own, no Resume needed. Leave a field empty to run uncapped.',
+ 'goalProcess.metricDetail.budget.rounds': 'Rounds',
+ 'goalProcess.metricDetail.budget.saveFailed': 'Could not update the budget',
+ 'goalProcess.metricDetail.budget.title': 'Cost',
+ 'goalProcess.metricDetail.budget.totalCost': 'Spend',
'goalProcess.metricDetail.budget.uncapped': 'Uncapped',
'goalProcess.metricDetail.duration.now': 'now',
'goalProcess.metricDetail.duration.taskSpans': 'Task spans',
@@ -1962,10 +1968,11 @@ export default {
'goalProcess.metricDetail.liveness.running': 'Running now',
'goalProcess.metricDetail.liveness.title': 'Liveness',
'goalProcess.metricDetail.tasks.title': 'All tasks',
- 'goalProcess.metrics.budget': 'Budget',
'goalProcess.metrics.duration': 'Runtime',
'goalProcess.metrics.liveness': 'Last activity',
+ 'goalProcess.metrics.rounds': 'Rounds',
'goalProcess.metrics.roundsValue': '{{count}} rounds',
+ 'goalProcess.metrics.spend': 'Spend',
'goalProcess.metrics.uncapped': 'Uncapped',
'goalProcess.node.blockers': 'Blocked by',
'goalProcess.node.description': 'Description',
diff --git a/packages/types/src/goal.ts b/packages/types/src/goal.ts
index bb1d9a9a3b7..7af64735156 100644
--- a/packages/types/src/goal.ts
+++ b/packages/types/src/goal.ts
@@ -309,9 +309,38 @@ export interface GoalGraphSnapshot {
* liveness judgements must use whichever of the two is newer.
*/
runHeartbeats?: Record<string, Date>;
+ /**
+ * Rounds run and dollars spent so far, by the definition the coordinator
+ * enforces the budget against. Present on a fetched graph; absent on the
+ * snapshots the write paths return.
+ */
+ spend?: GoalSpend;
workVersions: GoalGraphWorkVersionLink[];
}
+/** What a goal has spent against what it is allowed to spend. */
+export interface GoalSpend {
+ /**
+ * The same spend split per Task node, so the cost panel can say WHERE the
+ * money went rather than only how much is left.
+ */
+ byTask: GoalTaskSpend[];
+ /** Runs the graph's Task nodes produced — what `maxRounds` is counted in. */
+ runs: number;
+ /** USD across those runs; a run that has not settled contributes 0. */
+ totalCost: number;
+ /** Tokens across those runs; a run that has not settled contributes 0. */
+ totalTokens: number;
+}
+
+/** One Task's share of a goal's spend. */
+export interface GoalTaskSpend {
+ runs: number;
+ taskId: string;
+ totalCost: number;
+ totalTokens: number;
+}
+
/**
* Distill a graph snapshot into the structured goal overview that rides
* `RuntimeInitialContext.goalOverview`. Shared by every transport (client
diff --git a/src/features/Acceptance/Report/MarkdownEvidence.tsx b/src/features/Acceptance/Report/MarkdownEvidence.tsx
index d5b8a6f3af6..3e5ffedb5f4 100644
--- a/src/features/Acceptance/Report/MarkdownEvidence.tsx
+++ b/src/features/Acceptance/Report/MarkdownEvidence.tsx
@@ -77,6 +77,10 @@ const styles = createStaticStyles(({ css }) => ({
transition: color 120ms ease;
`,
+ /* A plain block, deliberately not a Flexbox: `Markdown`'s root is
+ `overflow: hidden`, so as a flex item its automatic minimum size collapses
+ to 0 and a long document gets squeezed to the viewer's height and clipped
+ instead of overflowing it — leaving this box scrollable in name only. */
docViewer: css`
overflow: auto;
flex: 1;
@@ -275,7 +279,7 @@ export const DocumentViewer = memo<{ fileName?: string | null; markdown?: boolea
);
return (
- <Flexbox className={styles.docViewer}>
+ <div className={styles.docViewer}>
{markdown ? (
<Markdown fontSize={13} variant={'chat'}>
{fileData}
@@ -290,7 +294,7 @@ export const DocumentViewer = memo<{ fileName?: string | null; markdown?: boolea
{fileData}
</Highlighter>
)}
- </Flexbox>
+ </div>
);
},
);
diff --git a/src/features/AgentBreadcrumb/index.tsx b/src/features/AgentBreadcrumb/index.tsx
index f7ad23088f1..08c3785963b 100644
--- a/src/features/AgentBreadcrumb/index.tsx
+++ b/src/features/AgentBreadcrumb/index.tsx
@@ -6,20 +6,15 @@ import { Text } from '@lobehub/ui/base-ui';
import { Breadcrumb as AntBreadcrumb } from 'antd';
import { createStaticStyles } from 'antd-style';
import { ChevronRight } from 'lucide-react';
-import { memo, type ReactNode, useMemo } from 'react';
+import { memo, type ReactNode } from 'react';
import { useTranslation } from 'react-i18next';
-import { Link, useLocation } from 'react-router';
-import urlJoin from 'url-join';
+import { Link } from 'react-router';
-import { useActiveWorkspaceSlug } from '@/business/client/hooks/useActiveWorkspaceSlug';
-import {
- buildPrefixedAgentRoutePath,
- parseAgentPathname,
-} from '@/features/AgentSidebar/utils/agentPathname';
-import { buildWorkspaceAwarePath } from '@/features/Workspace/workspaceAwarePath';
import { useAgentStore } from '@/store/agent';
import { agentSelectors, builtinAgentSelectors } from '@/store/agent/selectors';
+import { useAgentRoutePath } from './useAgentRoutePath';
+
const styles = createStaticStyles(({ css }) => ({
breadcrumb: css`
ol {
@@ -54,8 +49,7 @@ interface AgentBreadcrumbProps {
*/
const AgentBreadcrumb = memo<AgentBreadcrumbProps>(({ agentId, extraItems, title }) => {
const { t } = useTranslation(['chat', 'common']);
- const { pathname } = useLocation();
- const activeWorkspaceSlug = useActiveWorkspaceSlug();
+ const buildAgentPath = useAgentRoutePath(agentId);
const agentTitle = useAgentStore((s) =>
agentDisplayName(agentSelectors.getAgentMetaById(agentId)(s)),
);
@@ -64,11 +58,7 @@ const AgentBreadcrumb = memo<AgentBreadcrumbProps>(({ agentId, extraItems, title
const displayTitle = isInbox
? agentTitle || t('inbox.title', { ns: 'chat' })
: agentTitle || t('defaultSession', { ns: 'common' });
- const agentRoute = useMemo(() => parseAgentPathname(pathname), [pathname]);
- const agentHomePath = useMemo(() => {
- const targetPath = buildWorkspaceAwarePath(urlJoin('/agent', agentId), activeWorkspaceSlug);
- return buildPrefixedAgentRoutePath(targetPath, agentRoute, activeWorkspaceSlug);
- }, [activeWorkspaceSlug, agentId, agentRoute]);
+ const agentHomePath = buildAgentPath();
return (
<AntBreadcrumb
diff --git a/src/features/AgentBreadcrumb/useAgentRoutePath.test.ts b/src/features/AgentBreadcrumb/useAgentRoutePath.test.ts
new file mode 100644
index 00000000000..0a82fffb609
--- /dev/null
+++ b/src/features/AgentBreadcrumb/useAgentRoutePath.test.ts
@@ -0,0 +1,57 @@
+import { renderHook } from '@testing-library/react';
+import { createElement, type ReactNode } from 'react';
+import { MemoryRouter } from 'react-router';
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { useAgentRoutePath } from './useAgentRoutePath';
+
+const mocks = vi.hoisted(() => ({ activeWorkspaceSlug: null as string | null }));
+
+vi.mock('@/business/client/hooks/useActiveWorkspaceSlug', () => ({
+ useActiveWorkspaceSlug: () => mocks.activeWorkspaceSlug,
+}));
+
+const wrapperAt = (pathname: string, basename?: string) =>
+ function Wrapper({ children }: { children: ReactNode }) {
+ return createElement(MemoryRouter, { basename, initialEntries: [pathname] }, children);
+ };
+
+describe('useAgentRoutePath', () => {
+ beforeEach(() => {
+ mocks.activeWorkspaceSlug = null;
+ });
+
+ it('returns the agent home when no segment is given', () => {
+ const { result } = renderHook(() => useAgentRoutePath('agent-1'), {
+ wrapper: wrapperAt('/agent/agent-1/goal/goal-1'),
+ });
+
+ expect(result.current()).toBe('/agent/agent-1');
+ });
+
+ it('builds a sub-page path under the agent', () => {
+ const { result } = renderHook(() => useAgentRoutePath('agent-1'), {
+ wrapper: wrapperAt('/agent/agent-1/goal/goal-1'),
+ });
+
+ expect(result.current('goals')).toBe('/agent/agent-1/goals');
+ });
+
+ it('keeps the active workspace prefix on a sub-page path', () => {
+ mocks.activeWorkspaceSlug = 'team';
+
+ const { result } = renderHook(() => useAgentRoutePath('agent-1'), {
+ wrapper: wrapperAt('/team/agent/agent-1/goal/goal-1'),
+ });
+
+ expect(result.current('goals')).toBe('/team/agent/agent-1/goals');
+ });
+
+ it('keeps a non-workspace route prefix on a sub-page path', () => {
+ const { result } = renderHook(() => useAgentRoutePath('agent-1'), {
+ wrapper: wrapperAt('/chat/agent/agent-1/goal/goal-1'),
+ });
+
+ expect(result.current('goals')).toBe('/chat/agent/agent-1/goals');
+ });
+});
diff --git a/src/features/AgentBreadcrumb/useAgentRoutePath.ts b/src/features/AgentBreadcrumb/useAgentRoutePath.ts
new file mode 100644
index 00000000000..e66fd909c71
--- /dev/null
+++ b/src/features/AgentBreadcrumb/useAgentRoutePath.ts
@@ -0,0 +1,33 @@
+import { useCallback, useMemo } from 'react';
+import { useLocation } from 'react-router';
+import urlJoin from 'url-join';
+
+import { useActiveWorkspaceSlug } from '@/business/client/hooks/useActiveWorkspaceSlug';
+import {
+ buildPrefixedAgentRoutePath,
+ parseAgentPathname,
+} from '@/features/AgentSidebar/utils/agentPathname';
+import { buildWorkspaceAwarePath } from '@/features/Workspace/workspaceAwarePath';
+
+/**
+ * Builds links that stay inside the current agent's route family, keeping the
+ * workspace slug and whatever prefix the current pathname already carries.
+ * Calling the returned builder with no segment yields the agent home; pass
+ * segments for a sub-page, e.g. `buildAgentPath('goals')`.
+ */
+export const useAgentRoutePath = (agentId: string) => {
+ const { pathname } = useLocation();
+ const activeWorkspaceSlug = useActiveWorkspaceSlug();
+ const agentRoute = useMemo(() => parseAgentPathname(pathname), [pathname]);
+
+ return useCallback(
+ (...segments: string[]) => {
+ const targetPath = buildWorkspaceAwarePath(
+ urlJoin('/agent', agentId, ...segments),
+ activeWorkspaceSlug,
+ );
+ return buildPrefixedAgentRoutePath(targetPath, agentRoute, activeWorkspaceSlug);
+ },
+ [activeWorkspaceSlug, agentId, agentRoute],
+ );
+};
diff --git a/src/features/AgentBuilder/TopicSelector.tsx b/src/features/AgentBuilder/TopicSelector.tsx
index 861c77228c5..9d6b45fb000 100644
--- a/src/features/AgentBuilder/TopicSelector.tsx
+++ b/src/features/AgentBuilder/TopicSelector.tsx
@@ -9,6 +9,7 @@ import { useTranslation } from 'react-i18next';
import { DESKTOP_HEADER_ICON_SMALL_SIZE } from '@/const/layoutTokens';
import NavHeader from '@/features/NavHeader';
+import { useFetchAgentChatTopics } from '@/hooks/useFetchChatTopics';
import { useChatStore } from '@/store/chat';
import { topicSelectors } from '@/store/chat/slices/topic/selectors';
@@ -37,9 +38,7 @@ const TopicSelector = memo<TopicSelectorProps>(({ agentId, disabled }) => {
const { t } = useTranslation('topic');
// Fetch topics for the agent builder
- const useFetchTopics = useChatStore((s) => s.useFetchTopics);
-
- useFetchTopics(true, { agentId });
+ useFetchAgentChatTopics(agentId);
const [activeTopicId, switchTopic, topics] = useChatStore((s) => [
s.activeTopicId,
diff --git a/src/features/AgentGoals/GoalChat/Toolbar.tsx b/src/features/AgentGoals/GoalChat/Toolbar.tsx
index 97aaeb49693..eaccad26cb7 100644
--- a/src/features/AgentGoals/GoalChat/Toolbar.tsx
+++ b/src/features/AgentGoals/GoalChat/Toolbar.tsx
@@ -8,6 +8,7 @@ import { DESKTOP_HEADER_ICON_SMALL_SIZE } from '@/const/layoutTokens';
import { conversationSelectors, useConversationStore } from '@/features/Conversation';
import NavHeader from '@/features/NavHeader';
import TopicItem from '@/features/PageEditor/Copilot/TopicSelector/TopicItem';
+import { useFetchAgentChatTopics } from '@/hooks/useFetchChatTopics';
import { useChatStore } from '@/store/chat';
import { topicSelectors } from '@/store/chat/slices/topic/selectors';
@@ -21,7 +22,7 @@ const Toolbar = memo<ToolbarProps>(({ onCollapse }) => {
const [topicPopoverOpen, setTopicPopoverOpen] = useState(false);
const agentId = useConversationStore(conversationSelectors.agentId);
- useChatStore((s) => s.useFetchTopics)(true, { agentId });
+ useFetchAgentChatTopics(agentId);
const [activeTopicId, switchTopic, topics] = useChatStore((s) => [
s.activeTopicId,
diff --git a/src/features/AgentGoals/GoalDetailPage.tsx b/src/features/AgentGoals/GoalDetailPage.tsx
index 0da2d6b09f1..126beef08ea 100644
--- a/src/features/AgentGoals/GoalDetailPage.tsx
+++ b/src/features/AgentGoals/GoalDetailPage.tsx
@@ -6,11 +6,13 @@ import { createStaticStyles, cssVar } from 'antd-style';
import { PauseIcon, PlayIcon } from 'lucide-react';
import { memo, type ReactNode, useEffect, useMemo, useState } from 'react';
import { useTranslation } from 'react-i18next';
+import { Link } from 'react-router';
import NotFound from '@/components/404';
import AsyncError from '@/components/AsyncError';
import GoalDetailSkeleton from '@/components/Skeleton/GoalDetail';
import AgentBreadcrumb from '@/features/AgentBreadcrumb';
+import { useAgentRoutePath } from '@/features/AgentBreadcrumb/useAgentRoutePath';
import NavHeader from '@/features/NavHeader';
import { PortalContent } from '@/features/Portal/router';
import { usePortalPanelWidth } from '@/features/Portal/usePortalPanelWidth';
@@ -26,7 +28,7 @@ import { goalSelectors, useGoalStore } from '@/store/goal';
import GoalChat from './GoalChat';
import GoalDetailActions from './GoalDetailActions';
-import { formatSpan, goalStatusKey } from './goalPresentation';
+import { formatSpan, formatUsd, goalStatusKey, summarizeGoalBudget } from './goalPresentation';
import GoalRequirement from './GoalRequirement';
import GoalStatusGlyph from './GoalStatusGlyph';
import ProcessControl from './ProcessControl';
@@ -112,6 +114,8 @@ const GoalDetailPage = memo<GoalDetailPageProps>(({ agentId, goalId }) => {
const pauseGoal = useGoalStore((s) => s.pauseGoal);
const resumeGoal = useGoalStore((s) => s.resumeGoal);
+ const buildAgentPath = useAgentRoutePath(agentId ?? '');
+
const showPortal = useChatStore(chatPortalSelectors.showPortal);
const currentViewType = useChatStore(chatPortalSelectors.currentViewType);
const [chatOpen, setChatOpen] = useState(true);
@@ -169,12 +173,25 @@ const GoalDetailPage = memo<GoalDetailPageProps>(({ agentId, goalId }) => {
const durationText = goal.startedAt
? formatSpan((goal.completedAt ?? new Date()).getTime() - goal.startedAt.getTime())
: '—';
- const budgetText =
- goal.maxTotalCost === null
- ? goal.maxRounds === null
- ? t('goalProcess.metrics.uncapped')
- : t('goalProcess.metrics.roundsValue', { count: goal.maxRounds })
- : `$${goal.maxTotalCost}`;
+ // Spend is the metric; the cap is the context it is read against — see
+ // `summarizeGoalBudget`. The label names only the number in the lead, and the
+ // cap trails it at secondary weight rather than sharing top billing.
+ const budget = summarizeGoalBudget(goal, snapshot.spend);
+ const budgetLabel = t(
+ budget.kind === 'rounds' ? 'goalProcess.metrics.rounds' : 'goalProcess.metrics.spend',
+ );
+ const budgetLead =
+ budget.kind === 'cost'
+ ? formatUsd(budget.spent)
+ : budget.kind === 'rounds'
+ ? String(budget.runs)
+ : formatUsd(budget.spent);
+ const budgetTrail =
+ budget.kind === 'cost'
+ ? `/ ${formatUsd(budget.cap)}`
+ : budget.kind === 'rounds'
+ ? `/ ${t('goalProcess.metrics.roundsValue', { count: budget.cap })}`
+ : t('goalProcess.metrics.uncapped');
return (
<Flexbox horizontal flex={1} height={'100%'} style={{ overflow: 'hidden' }}>
@@ -186,7 +203,9 @@ const GoalDetailPage = memo<GoalDetailPageProps>(({ agentId, goalId }) => {
<AgentBreadcrumb
agentId={agentId}
extraItems={[goal.title]}
- title={t('goalList.title')}
+ // The goal title owns the last crumb, so this one is a way back
+ // to the agent's goal list rather than a label for this page.
+ title={<Link to={buildAgentPath('goals')}>{t('goalList.title')}</Link>}
/>
) : (
<Text fontSize={14} weight={500}>
@@ -257,11 +276,16 @@ const GoalDetailPage = memo<GoalDetailPageProps>(({ agentId, goalId }) => {
onClick={open('findings')}
/>
<Metric
- label={t('goalProcess.metrics.budget')}
+ label={budgetLabel}
value={
- <Text fontSize={16} weight={600}>
- {budgetText}
- </Text>
+ <>
+ <Text fontSize={16} weight={600}>
+ {budgetLead}
+ </Text>
+ <Text fontSize={12} type={'secondary'}>
+ {budgetTrail}
+ </Text>
+ </>
}
onClick={open('budget')}
/>
diff --git a/src/features/AgentGoals/ProcessControl/Frontier.tsx b/src/features/AgentGoals/ProcessControl/Frontier.tsx
index d2e656e0445..c23975184b8 100644
--- a/src/features/AgentGoals/ProcessControl/Frontier.tsx
+++ b/src/features/AgentGoals/ProcessControl/Frontier.tsx
@@ -353,7 +353,14 @@ const FrontierRow = memo<{
</Flexbox>
{item.rank === 0 && (
- <Flexbox className={styles.body} gap={14} onClick={stop}>
+ // The expanded body is READ-ONLY content — why it stopped and what each
+ // attempt did — so it must stay part of the row's click target. It used
+ // to stop propagation wholesale for the gate form's sake, which made a
+ // lost/gate row unopenable in practice: the body is most of the row's
+ // height, so a click aimed anywhere natural landed in dead space while
+ // the pointer cursor still promised otherwise. Only the form below opts
+ // out.
+ <Flexbox className={styles.body} gap={14}>
{item.kind === 'gate' && view.decision && (
// State the problem itself, in the user's language when the
// coordinator's vocabulary is recognized — the buttons below
@@ -365,7 +372,9 @@ const FrontierRow = memo<{
{item.kind === 'stale' && <StaleBody view={view} />}
<AttemptLedger view={subject ?? view} />
{item.kind === 'gate' && canEdit && (
- <>
+ // A click here is aimed at the note field or a decision button —
+ // never at "open this node".
+ <Flexbox gap={14} onClick={stop}>
<Flexbox gap={4}>
<span className={styles.label}>{t('goalProcess.gate.noteLabel')}</span>
<TextArea
@@ -393,7 +402,7 @@ const FrontierRow = memo<{
</Tooltip>
))}
</Flexbox>
- </>
+ </Flexbox>
)}
</Flexbox>
)}
diff --git a/src/features/AgentGoals/ProcessControl/goalGraphViewModel.test.ts b/src/features/AgentGoals/ProcessControl/goalGraphViewModel.test.ts
index 9aafc331b9d..1f91cb5d4e0 100644
--- a/src/features/AgentGoals/ProcessControl/goalGraphViewModel.test.ts
+++ b/src/features/AgentGoals/ProcessControl/goalGraphViewModel.test.ts
@@ -8,7 +8,7 @@ import type {
} from '@lobechat/types';
import { describe, expect, it } from 'vitest';
-import { buildGoalGraphView } from './goalGraphViewModel';
+import { buildGoalGraphView, isTroubledTaskNode } from './goalGraphViewModel';
const T0 = new Date('2026-08-01T00:00:00Z');
const at = (minutes: number) => new Date(T0.getTime() + minutes * 60_000);
@@ -453,3 +453,63 @@ describe('buildGoalGraphView', () => {
expect(view.artifacts).toEqual([]);
});
});
+
+describe('isTroubledTaskNode', () => {
+ // A healthy Task opens on its result surface; a broken one has no result
+ // worth reviewing, so the drill-down goes to the original Task instead.
+ it('flags a task that lost its heartbeat', () => {
+ const view = buildGoalGraphView(
+ snapshot({ nodes: [node('w1', { status: 'active', updatedAt: at(0) })] }),
+ NOW,
+ );
+
+ expect(view.byId.w1.isStale).toBe(true);
+ expect(isTroubledTaskNode(view.byId.w1)).toBe(true);
+ });
+
+ it('flags a task whose latest attempt failed', () => {
+ const view = buildGoalGraphView(
+ snapshot({
+ events: [event('w1', 'activated', 100), event('w1', 'rejected', 110)],
+ nodes: [node('w1', { status: 'rejected', updatedAt: at(110) })],
+ }),
+ NOW,
+ );
+
+ expect(isTroubledTaskNode(view.byId.w1)).toBe(true);
+ });
+
+ it('leaves a healthy running task alone', () => {
+ const view = buildGoalGraphView(
+ snapshot({
+ events: [event('w1', 'activated', 110)],
+ nodes: [node('w1', { status: 'active', updatedAt: at(115) })],
+ }),
+ NOW,
+ );
+
+ expect(view.byId.w1.isStale).toBe(false);
+ expect(isTroubledTaskNode(view.byId.w1)).toBe(false);
+ });
+
+ it('leaves a finished task alone — its result is the thing to read', () => {
+ const view = buildGoalGraphView(
+ snapshot({
+ events: [event('w1', 'activated', 100), event('w1', 'resolved', 110)],
+ nodes: [node('w1', { resolvedAt: at(110), status: 'resolved', updatedAt: at(110) })],
+ }),
+ NOW,
+ );
+
+ expect(isTroubledTaskNode(view.byId.w1)).toBe(false);
+ });
+
+ it('is not a judgement about non-task nodes', () => {
+ const view = buildGoalGraphView(
+ snapshot({ nodes: [node('p1', { kind: 'problem', status: 'active', updatedAt: at(0) })] }),
+ NOW,
+ );
+
+ expect(isTroubledTaskNode(view.byId.p1)).toBe(false);
+ });
+});
diff --git a/src/features/AgentGoals/ProcessControl/goalGraphViewModel.ts b/src/features/AgentGoals/ProcessControl/goalGraphViewModel.ts
index 0d0451b6a25..068dab78ea7 100644
--- a/src/features/AgentGoals/ProcessControl/goalGraphViewModel.ts
+++ b/src/features/AgentGoals/ProcessControl/goalGraphViewModel.ts
@@ -94,6 +94,22 @@ export interface GoalNodeView {
startedAt?: Date;
}
+/**
+ * Whether a Task node is in trouble — lost its heartbeat, or its latest attempt
+ * failed / was rejected.
+ *
+ * A healthy Task opens on its result surface: the delivery is the thing to read
+ * and the implementation metadata stays one step deeper. A broken one inverts
+ * that — there is no result worth reviewing, and the question is what the run
+ * actually did — so it opens the original Task instead.
+ */
+export const isTroubledTaskNode = (view: GoalNodeView): boolean => {
+ if (view.node.kind !== 'task') return false;
+ if (view.isStale) return true;
+ if (view.node.status === 'rejected') return true;
+ return view.attempts.at(-1)?.outcome === 'failed';
+};
+
export type FrontierItemKind = 'gate' | 'stale' | 'running' | 'ready' | 'done';
export interface FrontierItem {
diff --git a/src/features/AgentGoals/ProcessControl/index.tsx b/src/features/AgentGoals/ProcessControl/index.tsx
index ff2d3d9b2d9..6cac88ab876 100644
--- a/src/features/AgentGoals/ProcessControl/index.tsx
+++ b/src/features/AgentGoals/ProcessControl/index.tsx
@@ -16,7 +16,7 @@ import Activity from './Activity';
import Deliverables from './Deliverables';
import Findings from './Findings';
import Frontier, { type FrontierActions } from './Frontier';
-import { buildGoalGraphView } from './goalGraphViewModel';
+import { buildGoalGraphView, isTroubledTaskNode } from './goalGraphViewModel';
import Graph from './Graph';
/**
@@ -50,6 +50,7 @@ const ProcessControl = memo<ProcessControlProps>(
const decideGoal = useGoalStore((s) => s.decideGoal);
const refreshGoalGraph = useGoalStore((s) => s.refreshGoalGraph);
const openTaskResult = useChatStore((s) => s.openTaskResult);
+ const openTaskDetail = useChatStore((s) => s.openTaskDetail);
const openGoalNode = useChatStore((s) => s.openGoalNode);
useFetchGoalGraph(goalId);
const snapshot = useGoalStore(goalSelectors.goalGraph(goalId));
@@ -72,14 +73,22 @@ const ProcessControl = memo<ProcessControlProps>(
// open the drill-down — a dispatched Task lands on its result-focused
// review surface. The original editable Task remains one explicit step
// deeper, so Goal inspection does not begin with implementation metadata.
+ //
+ // A lost or failed Task inverts that: it has no result worth reviewing, and
+ // the question is what the run did, so it opens the original Task directly.
const select = useCallback(
(nodeId: string) => {
setSelectedId(nodeId);
- const taskId = graph?.byId[nodeId]?.node.taskId;
- if (taskId) openTaskResult(taskId);
- else openGoalNode(goalId, nodeId);
+ const view = graph?.byId[nodeId];
+ const taskId = view?.node.taskId;
+ if (!taskId) {
+ openGoalNode(goalId, nodeId);
+ return;
+ }
+ if (view && isTroubledTaskNode(view)) openTaskDetail(taskId);
+ else openTaskResult(taskId);
},
- [goalId, graph, openGoalNode, openTaskResult],
+ [goalId, graph, openGoalNode, openTaskDetail, openTaskResult],
);
// Task-carried goals share the `goals` table but never grow a graph. Nothing
diff --git a/src/features/AgentGoals/goalPresentation.test.ts b/src/features/AgentGoals/goalPresentation.test.ts
index e4bae48fb1b..9e327d0da7e 100644
--- a/src/features/AgentGoals/goalPresentation.test.ts
+++ b/src/features/AgentGoals/goalPresentation.test.ts
@@ -1,6 +1,6 @@
import { describe, expect, it } from 'vitest';
-import { formatSpan, goalStatusKey } from './goalPresentation';
+import { formatSpan, formatUsd, goalStatusKey, summarizeGoalBudget } from './goalPresentation';
describe('goalStatusKey', () => {
it('maps every lifecycle state to a list-vocabulary key', () => {
@@ -25,3 +25,44 @@ describe('formatSpan', () => {
expect(formatSpan(71 * 60_000)).toBe('1h 11m');
});
});
+
+describe('formatUsd', () => {
+ it('reads a budget as money without trailing noise', () => {
+ expect(formatUsd(10)).toBe('$10');
+ expect(formatUsd(6.4)).toBe('$6.4');
+ expect(formatUsd(0)).toBe('$0');
+ });
+
+ it('rounds a long-tailed accumulation to cents', () => {
+ expect(formatUsd(6.437_912)).toBe('$6.44');
+ });
+});
+
+describe('summarizeGoalBudget', () => {
+ it('pairs spend with the cost cap so the header can state one fraction', () => {
+ expect(
+ summarizeGoalBudget({ maxRounds: 5, maxTotalCost: 10 }, { runs: 3, totalCost: 6.4 }),
+ ).toEqual({ cap: 10, kind: 'cost', spent: 6.4 });
+ });
+
+ it('switches to rounds when that is the unit the goal is actually capped in', () => {
+ // "$6.4 / 5 rounds" is two units pretending to be a ratio.
+ expect(
+ summarizeGoalBudget({ maxRounds: 5, maxTotalCost: null }, { runs: 3, totalCost: 6.4 }),
+ ).toEqual({ cap: 5, kind: 'rounds', runs: 3 });
+ });
+
+ it('states spend alone when nothing caps the goal', () => {
+ expect(
+ summarizeGoalBudget({ maxRounds: null, maxTotalCost: null }, { runs: 3, totalCost: 6.4 }),
+ ).toEqual({ kind: 'uncapped', spent: 6.4 });
+ });
+
+ it('reads an absent spend as zero rather than blanking the metric', () => {
+ expect(summarizeGoalBudget({ maxRounds: null, maxTotalCost: 10 })).toEqual({
+ cap: 10,
+ kind: 'cost',
+ spent: 0,
+ });
+ });
+});
diff --git a/src/features/AgentGoals/goalPresentation.ts b/src/features/AgentGoals/goalPresentation.ts
index 133c13930de..ec6fc49733b 100644
--- a/src/features/AgentGoals/goalPresentation.ts
+++ b/src/features/AgentGoals/goalPresentation.ts
@@ -1,5 +1,5 @@
import type { GoalStatus } from '@lobechat/const/goal';
-import type { TaskStatus } from '@lobechat/types';
+import type { GoalSpend, TaskStatus } from '@lobechat/types';
/** Goal lifecycle state → i18n status key (goal list vocabulary). */
const goalStatusKeyMap = {
@@ -49,3 +49,33 @@ export const goalStatusToTaskStatus = (goalStatus: GoalStatus): TaskStatus => {
}
}
};
+
+/** `$6.4` — a budget read as money, at the precision a budget is set in. */
+export const formatUsd = (amount: number): string => `$${Math.round(amount * 100) / 100}`;
+
+/**
+ * Spend and budget as ONE metric — they are a fraction, and two neighbouring
+ * cards made the reader do the division.
+ *
+ * The fraction is always stated in the unit the budget is actually capped in.
+ * A goal capped in rounds would otherwise read "$6.4 / 5 rounds", which is two
+ * units wearing the costume of a ratio; there the rounds are the meaningful
+ * numerator and the dollars move into the drill-down.
+ */
+export type GoalBudgetSummary =
+ | { cap: number; kind: 'cost'; spent: number }
+ | { cap: number; kind: 'rounds'; runs: number }
+ | { kind: 'uncapped'; spent: number };
+
+export const summarizeGoalBudget = (
+ goal: { maxRounds: number | null; maxTotalCost: number | null },
+ spend?: Pick<GoalSpend, 'runs' | 'totalCost'>,
+): GoalBudgetSummary => {
+ // An unfetched spend is 0 rather than unknown: the graph read that carries
+ // the budget carries the spend with it, so the pair is never half-loaded.
+ const { runs = 0, totalCost = 0 } = spend ?? {};
+
+ if (goal.maxTotalCost !== null) return { cap: goal.maxTotalCost, kind: 'cost', spent: totalCost };
+ if (goal.maxRounds !== null) return { cap: goal.maxRounds, kind: 'rounds', runs };
+ return { kind: 'uncapped', spent: totalCost };
+};
diff --git a/src/features/AgentTaskManager/Toolbar.tsx b/src/features/AgentTaskManager/Toolbar.tsx
index 850dcb876af..6b17dfad180 100644
--- a/src/features/AgentTaskManager/Toolbar.tsx
+++ b/src/features/AgentTaskManager/Toolbar.tsx
@@ -8,6 +8,7 @@ import { DESKTOP_HEADER_ICON_SMALL_SIZE } from '@/const/layoutTokens';
import { conversationSelectors, useConversationStore } from '@/features/Conversation';
import NavHeader from '@/features/NavHeader';
import TopicItem from '@/features/PageEditor/Copilot/TopicSelector/TopicItem';
+import { useFetchAgentChatTopics } from '@/hooks/useFetchChatTopics';
import { useChatStore } from '@/store/chat';
import { topicSelectors } from '@/store/chat/slices/topic/selectors';
import { useGlobalStore } from '@/store/global';
@@ -17,7 +18,7 @@ const Toolbar = memo(() => {
const [topicPopoverOpen, setTopicPopoverOpen] = useState(false);
const agentId = useConversationStore(conversationSelectors.agentId);
- useChatStore((s) => s.useFetchTopics)(true, { agentId });
+ useFetchAgentChatTopics(agentId);
const [activeTopicId, switchTopic, topics] = useChatStore((s) => [
s.activeTopicId,
diff --git a/src/features/PageEditor/Copilot/Toolbar.tsx b/src/features/PageEditor/Copilot/Toolbar.tsx
index fd96b12852b..dfe5c08143f 100644
--- a/src/features/PageEditor/Copilot/Toolbar.tsx
+++ b/src/features/PageEditor/Copilot/Toolbar.tsx
@@ -7,6 +7,7 @@ import { useTranslation } from 'react-i18next';
import { DESKTOP_HEADER_ICON_SMALL_SIZE } from '@/const/layoutTokens';
import { conversationSelectors, useConversationStore } from '@/features/Conversation';
import NavHeader from '@/features/NavHeader';
+import { useFetchAgentChatTopics } from '@/hooks/useFetchChatTopics';
import { useChatStore } from '@/store/chat';
import { topicSelectors } from '@/store/chat/slices/topic/selectors';
@@ -23,7 +24,7 @@ const CopilotToolbar = memo<CopilotToolbarProps>(({ onTopicChange, topicId }) =>
const [topicPopoverOpen, setTopicPopoverOpen] = useState(false);
const agentId = useConversationStore(conversationSelectors.agentId);
- useChatStore((s) => s.useFetchTopics)(true, { agentId });
+ useFetchAgentChatTopics(agentId);
const [globalActiveTopicId, switchTopic, topics] = useChatStore((s) => [
s.activeTopicId,
diff --git a/src/features/Portal/GoalMetric/Body.tsx b/src/features/Portal/GoalMetric/Body.tsx
index aba936408de..e45386ef390 100644
--- a/src/features/Portal/GoalMetric/Body.tsx
+++ b/src/features/Portal/GoalMetric/Body.tsx
@@ -1,16 +1,19 @@
+import type { GoalSpend } from '@lobechat/types';
import { Flexbox } from '@lobehub/ui';
-import { Tag, Text } from '@lobehub/ui/base-ui';
+import { Tag, Text, toast } from '@lobehub/ui/base-ui';
+import { InputNumber } from 'antd';
import { createStaticStyles, cssVar } from 'antd-style';
import dayjs from 'dayjs';
-import { memo, type ReactNode, useMemo } from 'react';
+import { memo, type ReactNode, useMemo, useState } from 'react';
import { useTranslation } from 'react-i18next';
-import { formatSpan } from '@/features/AgentGoals/goalPresentation';
+import { formatSpan, formatUsd } from '@/features/AgentGoals/goalPresentation';
import {
buildGoalGraphView,
type GoalGraphView,
} from '@/features/AgentGoals/ProcessControl/goalGraphViewModel';
import { KindDot } from '@/features/AgentGoals/ProcessControl/shared';
+import { usePermission } from '@/hooks/usePermission';
import { useChatStore } from '@/store/chat';
import { chatPortalSelectors } from '@/store/chat/selectors';
import { goalSelectors, useGoalStore } from '@/store/goal';
@@ -190,31 +193,224 @@ const Findings = memo<{ goalId: string; graph: GoalGraphView }>(({ goalId, graph
Findings.displayName = 'GoalMetricFindings';
-const Budget = memo<{ graph: GoalGraphView }>(({ graph }) => {
+/**
+ * One budget dimension as `spent / cap`, where the cap IS the input — the
+ * number you read and the number you change are the same number, so raising a
+ * budget needs no separate edit mode.
+ *
+ * The draft is local and commits on blur / Enter: the goal graph polls while
+ * the goal runs, and binding the field straight to the snapshot would wipe
+ * half-typed digits on every refresh.
+ */
+const BudgetField = memo<{
+ cap: number | null;
+ goalId: string;
+ label: string;
+ /** `maxTotalCost` is money and takes a `$`; `maxRounds` is a plain count. */
+ money?: boolean;
+ used: number;
+}>(({ cap, goalId, label, money, used }) => {
const { t } = useTranslation('chat');
- const { maxRounds, maxTotalCost } = graph.goal;
+ const { allowed: canEdit } = usePermission('create_content');
+ const setGoalBudget = useGoalStore((s) => s.setGoalBudget);
+ const [draft, setDraft] = useState<number | null>(cap);
+ const [saving, setSaving] = useState(false);
+
+ // Re-seed from the server whenever it disagrees and the user is not mid-edit.
+ const [committed, setCommitted] = useState(cap);
+ if (committed !== cap && !saving) {
+ setCommitted(cap);
+ setDraft(cap);
+ }
+
+ const commit = async () => {
+ if (!canEdit || draft === cap) return;
+ // A cap below what the goal already spent would park it immediately; that
+ // is a legitimate way to stop a goal, so it is allowed — only nonsense
+ // (negative, zero) is refused, matching the router's `positive()`.
+ if (draft !== null && draft <= 0) {
+ setDraft(cap);
+ return;
+ }
+
+ try {
+ setSaving(true);
+ // Only the field that changed is sent: `setBudget` treats an omitted
+ // dimension as untouched, so editing the cost cap keeps the round cap.
+ await setGoalBudget(goalId, money ? { maxTotalCost: draft } : { maxRounds: draft });
+ } catch (error) {
+ console.error('[GoalMetricBudget] Failed to save:', error);
+ toast.error(t('goalProcess.metricDetail.budget.saveFailed'));
+ setDraft(cap);
+ } finally {
+ setSaving(false);
+ }
+ };
return (
- <Flexbox gap={14}>
- <Flexbox gap={2}>
- <span className={styles.label}>{t('goalProcess.metricDetail.budget.totalCost')}</span>
+ <Flexbox gap={2}>
+ <span className={styles.label}>{label}</span>
+ <Flexbox horizontal align={'center'} gap={8}>
<Text className={styles.mono} style={{ fontSize: 20 }} weight={600}>
- {maxTotalCost === null
- ? t('goalProcess.metricDetail.budget.uncapped')
- : `$${maxTotalCost}`}
+ {money ? formatUsd(used) : used}
+ </Text>
+ <Text className={styles.mono} style={{ fontSize: 20 }} type={'secondary'}>
+ /
</Text>
+ <InputNumber
+ className={styles.mono}
+ controls={false}
+ disabled={!canEdit || saving}
+ min={0}
+ placeholder={t('goalProcess.metricDetail.budget.uncapped')}
+ size={'small'}
+ style={{ width: 120 }}
+ value={draft}
+ variant={'filled'}
+ prefix={
+ money ? (
+ <Text fontSize={12} type={'secondary'}>
+ $
+ </Text>
+ ) : undefined
+ }
+ onBlur={() => void commit()}
+ onChange={setDraft}
+ onPressEnter={() => void commit()}
+ />
</Flexbox>
- <Flexbox gap={2}>
- <span className={styles.label}>{t('goalProcess.metricDetail.budget.rounds')}</span>
- <Text className={styles.mono} style={{ fontSize: 20 }} weight={600}>
- {maxRounds === null ? t('goalProcess.metricDetail.budget.uncapped') : maxRounds}
+ </Flexbox>
+ );
+});
+
+BudgetField.displayName = 'GoalMetricBudgetField';
+
+/** `12.4k` — token counts are read for magnitude, not audited digit by digit. */
+const formatTokens = (value: number): string =>
+ value >= 1000 ? `${Math.round(value / 100) / 10}k` : String(value);
+
+/**
+ * Where the money went, one row per dispatched Task. The caps above answer
+ * "how much is left"; without this the panel could not answer the question a
+ * user actually arrives with — which Task is eating the budget.
+ *
+ * Rows are ordered by spend, and a Task whose runs have not settled shows $0
+ * rather than being dropped: it is still consuming rounds.
+ */
+const CostBreakdown = memo<{ goalId: string; graph: GoalGraphView; spend?: GoalSpend }>(
+ ({ goalId, graph, spend }) => {
+ const { t } = useTranslation('chat');
+ const openGoalNode = useChatStore((s) => s.openGoalNode);
+
+ const rows = useMemo(() => {
+ const nodeByTaskId = new Map(
+ graph.nodes
+ .filter((view) => view.node.taskId)
+ .map((view) => [view.node.taskId!, view] as const),
+ );
+ return (spend?.byTask ?? [])
+ .map((row) => ({ ...row, view: nodeByTaskId.get(row.taskId) }))
+ .sort((a, b) => b.totalCost - a.totalCost || b.totalTokens - a.totalTokens);
+ }, [graph, spend]);
+
+ if (rows.length === 0)
+ return (
+ <Text fontSize={13} type={'secondary'}>
+ {t('goalProcess.metricDetail.budget.perTaskEmpty')}
+ </Text>
+ );
+
+ return (
+ <Flexbox gap={4}>
+ <span className={styles.label}>{t('goalProcess.metricDetail.budget.perTaskTitle')}</span>
+ <Flexbox gap={0}>
+ {rows.map((row) => {
+ const body = (
+ <Flexbox horizontal align={'center'} gap={8} key={row.taskId}>
+ {row.view?.seq !== undefined && (
+ <Text
+ className={styles.mono}
+ fontSize={12}
+ style={{ flex: 'none' }}
+ type={'secondary'}
+ >
+ #{row.view.seq}
+ </Text>
+ )}
+ <Text ellipsis style={{ flex: 1, minWidth: 0 }}>
+ {row.view?.node.title ?? row.taskId}
+ </Text>
+ <Text
+ className={styles.mono}
+ fontSize={12}
+ style={{ flex: 'none' }}
+ type={'secondary'}
+ >
+ {t('goalProcess.metricDetail.budget.tokensValue', {
+ value: formatTokens(row.totalTokens),
+ })}
+ </Text>
+ <Text className={styles.mono} style={{ flex: 'none' }} weight={500}>
+ {formatUsd(row.totalCost)}
+ </Text>
+ </Flexbox>
+ );
+
+ // A row without a graph node is a Task the snapshot no longer
+ // carries — still billed, but nothing to open.
+ return row.view ? (
+ <Flexbox
+ className={styles.row}
+ key={row.taskId}
+ onClick={() => openGoalNode(goalId, row.view!.node.id)}
+ >
+ {body}
+ </Flexbox>
+ ) : (
+ <Flexbox className={styles.staticRow} key={row.taskId}>
+ {body}
+ </Flexbox>
+ );
+ })}
+ </Flexbox>
+ </Flexbox>
+ );
+ },
+);
+
+CostBreakdown.displayName = 'GoalMetricCostBreakdown';
+
+const Budget = memo<{ goalId: string; graph: GoalGraphView }>(({ goalId, graph }) => {
+ const { t } = useTranslation('chat');
+ const { maxRounds, maxTotalCost } = graph.goal;
+ const snapshot = useGoalStore(goalSelectors.goalGraph(goalId));
+ const spend = snapshot?.spend;
+
+ return (
+ <Flexbox gap={20}>
+ <Flexbox gap={14}>
+ <span className={styles.label}>{t('goalProcess.metricDetail.budget.controlTitle')}</span>
+ <BudgetField
+ money
+ cap={maxTotalCost}
+ goalId={goalId}
+ label={t('goalProcess.metricDetail.budget.totalCost')}
+ used={spend?.totalCost ?? 0}
+ />
+ <BudgetField
+ cap={maxRounds}
+ goalId={goalId}
+ label={t('goalProcess.metricDetail.budget.rounds')}
+ used={spend?.runs ?? 0}
+ />
+ {/* Raising a cap is how a user restarts a goal the coordinator parked on
+ one — say so, because the alternative gesture (Resume) looks like the
+ obvious one and does nothing while the budget is still binding. */}
+ <Text fontSize={12} style={{ lineHeight: 1.7 }} type={'secondary'}>
+ {t('goalProcess.metricDetail.budget.raiseNote')}
</Text>
</Flexbox>
- {/* Per-round spend is recorded on each dispatched Task, not on the goal
- row — say so instead of rendering a fabricated total. */}
- <Text fontSize={12} type={'secondary'}>
- {t('goalProcess.metricDetail.budget.spendNote')}
- </Text>
+ <CostBreakdown goalId={goalId} graph={graph} spend={spend} />
</Flexbox>
);
});
@@ -335,7 +531,7 @@ const Body = memo(() => {
{metric === 'lifecycle' && <Lifecycle goalId={goalId} graph={graph} />}
{metric === 'tasks' && <Tasks goalId={goalId} graph={graph} />}
{metric === 'findings' && <Findings goalId={goalId} graph={graph} />}
- {metric === 'budget' && <Budget graph={graph} />}
+ {metric === 'budget' && <Budget goalId={goalId} graph={graph} />}
{metric === 'duration' && <Duration goalId={goalId} graph={graph} />}
{metric === 'liveness' && <Liveness goalId={goalId} graph={graph} />}
</Flexbox>
diff --git a/src/features/Portal/GoalNode/Body.tsx b/src/features/Portal/GoalNode/Body.tsx
index 0a053d1af9d..4224d0293ac 100644
--- a/src/features/Portal/GoalNode/Body.tsx
+++ b/src/features/Portal/GoalNode/Body.tsx
@@ -167,8 +167,11 @@ const Body = memo(() => {
{node.description &&
(isFinding ? (
// A finding's description is the run's handoff — real Markdown, so
- // render it as such instead of pre-wrapped source text.
- <Markdown fontSize={13} variant={'chat'}>
+ // render it as such instead of pre-wrapped source text. `flex-shrink: 0`
+ // is load-bearing: Markdown's root is `overflow: hidden`, so as a flex
+ // item its automatic minimum size collapses to 0 and a long handoff
+ // would be squeezed (and clipped) to fit instead of scrolling the panel.
+ <Markdown fontSize={13} style={{ flexShrink: 0 }} variant={'chat'}>
{node.description}
</Markdown>
) : (
diff --git a/src/hooks/useFetchChatTopics.test.ts b/src/hooks/useFetchChatTopics.test.ts
new file mode 100644
index 00000000000..97e6d4bd366
--- /dev/null
+++ b/src/hooks/useFetchChatTopics.test.ts
@@ -0,0 +1,99 @@
+import { renderHook } from '@testing-library/react';
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { MAIN_SIDEBAR_EXCLUDE_TRIGGERS } from '@/const/topic';
+
+import { useFetchAgentChatTopics, useFetchChatTopics } from './useFetchChatTopics';
+
+const mocks = vi.hoisted(() => ({
+ activeAgentId: 'agent-1' as string | undefined,
+ activeGroupId: undefined as string | undefined,
+ inboxAgentId: 'inbox' as string | undefined,
+ storeFetchTopics: vi.fn(
+ (_enable: boolean, _args: Record<string, unknown> = {}) =>
+ ({ data: undefined, isValidating: false }) as never,
+ ),
+ topicGroupMode: 'byStatus' as string,
+ topicIncludeCompleted: false,
+ topicPageSize: 20,
+}));
+
+vi.mock('@/features/AgentSidebar/Topic/hooks/useAgentTopicGroupMode', () => ({
+ useAgentTopicGroupMode: () => ({ topicGroupMode: mocks.topicGroupMode }),
+}));
+
+vi.mock('@/store/agent', () => ({
+ useAgentStore: (selector: (state: unknown) => unknown) => selector({}),
+}));
+
+vi.mock('@/store/agent/selectors', () => ({
+ builtinAgentSelectors: {
+ inboxAgentId: () => mocks.inboxAgentId,
+ isInboxAgent: () => mocks.activeAgentId === mocks.inboxAgentId,
+ },
+}));
+
+vi.mock('@/store/chat', () => ({
+ useChatStore: (selector: (state: unknown) => unknown) =>
+ selector({
+ activeAgentId: mocks.activeAgentId,
+ activeGroupId: mocks.activeGroupId,
+ useFetchTopics: mocks.storeFetchTopics,
+ }),
+}));
+
+vi.mock('@/store/global', () => ({
+ useGlobalStore: (selector: (state: unknown) => unknown) => selector({}),
+}));
+
+vi.mock('@/store/global/selectors', () => ({
+ systemStatusSelectors: { topicPageSize: () => mocks.topicPageSize },
+}));
+
+vi.mock('@/store/user', () => ({
+ useUserStore: (selector: (state: unknown) => unknown) => selector({}),
+}));
+
+vi.mock('@/store/user/selectors', () => ({
+ preferenceSelectors: { topicIncludeCompleted: () => mocks.topicIncludeCompleted },
+}));
+
+describe('chat topic list fetches', () => {
+ beforeEach(() => {
+ mocks.storeFetchTopics.mockClear();
+ });
+
+ it('asks the same query for a named agent as the sidebar does for the active one', () => {
+ // Both write into `topicDataMap[agent_<id>]`, which is keyed by container
+ // and not by filters — a looser query here overwrites the sidebar's list
+ // with task-run / cron / doc / eval topics the moment the panel mounts.
+ renderHook(() => useFetchChatTopics());
+ const sidebarCall = mocks.storeFetchTopics.mock.calls.at(-1)!;
+
+ renderHook(() => useFetchAgentChatTopics('agent-1'));
+ const panelCall = mocks.storeFetchTopics.mock.calls.at(-1)!;
+
+ const [sidebarEnabled, sidebarArgs = {}] = sidebarCall;
+ const [panelEnabled, panelArgs = {}] = panelCall;
+
+ expect(sidebarEnabled).toBe(true);
+ expect(panelEnabled).toBe(true);
+ expect(panelArgs).toMatchObject({
+ agentId: 'agent-1',
+ excludeStatuses: sidebarArgs.excludeStatuses,
+ excludeTriggers: sidebarArgs.excludeTriggers,
+ isInbox: sidebarArgs.isInbox,
+ pageSize: sidebarArgs.pageSize,
+ sortBy: sidebarArgs.sortBy,
+ });
+ expect(panelArgs.excludeTriggers).toEqual(MAIN_SIDEBAR_EXCLUDE_TRIGGERS);
+ });
+
+ it('stays disabled until the panel knows its agent', () => {
+ renderHook(() => useFetchAgentChatTopics(undefined));
+
+ const [enabled] = mocks.storeFetchTopics.mock.calls.at(-1)!;
+
+ expect(enabled).toBe(false);
+ });
+});
diff --git a/src/hooks/useFetchChatTopics.ts b/src/hooks/useFetchChatTopics.ts
index 82d9a5ebf3a..45985eb2756 100644
--- a/src/hooks/useFetchChatTopics.ts
+++ b/src/hooks/useFetchChatTopics.ts
@@ -1,24 +1,29 @@
+import type { TopicQuerySortBy } from '@lobechat/types';
+
import { MAIN_SIDEBAR_EXCLUDE_TRIGGERS } from '@/const/topic';
import { useAgentTopicGroupMode } from '@/features/AgentSidebar/Topic/hooks/useAgentTopicGroupMode';
import { useFetchTopics } from '@/hooks/useFetchTopics';
+import { useAgentStore } from '@/store/agent';
+import { builtinAgentSelectors } from '@/store/agent/selectors';
import { useChatStore } from '@/store/chat';
+import { useGlobalStore } from '@/store/global';
+import { systemStatusSelectors } from '@/store/global/selectors';
import { useUserStore } from '@/store/user';
import { preferenceSelectors } from '@/store/user/selectors';
const EXCLUDE_STATUSES_COMPLETED = ['completed'];
/**
- * Canonical topic fetch for chat sidebars (agent + group). Reads every
- * filter from a single source so all call sites in the same route mount
- * the same SWR key — otherwise two sibling `useFetchTopics()` calls with
- * different args both write to `topicDataMap[containerKey]` and whichever
- * response lands last wins, which is how completed topics used to leak
- * into the list despite the `excludeStatuses` filter.
+ * The one query shape a `topicDataMap` bucket is allowed to hold. The bucket is
+ * keyed by container (`agent_<id>`) only — not by filters — so every fetch that
+ * targets a container overwrites whatever the previous one put there. Two
+ * mounted fetches with different filters therefore fight, and the looser one
+ * wins whenever it lands last.
*
- * Extend this hook when adding more preference-driven topic params; don't
- * spread them across individual components.
+ * Keep all filter derivation here so no call site can drift: same args means
+ * the same SWR key, which means SWR dedupes them into a single request.
*/
-export const useFetchChatTopics = () => {
+const useChatTopicListQuery = () => {
const includeCompleted = useUserStore(preferenceSelectors.topicIncludeCompleted);
const activeGroupId = useChatStore((s) => s.activeGroupId);
const { topicGroupMode } = useAgentTopicGroupMode();
@@ -28,11 +33,44 @@ export const useFetchChatTopics = () => {
// the list is paginated — client-side grouping over a partial page is exactly
// what made the previous approach flaky. Only the agent sidebar supports it;
// group sessions keep the default updatedAt ordering.
- const sortBy = !activeGroupId && topicGroupMode === 'byStatus' ? 'status' : undefined;
+ const sortBy: TopicQuerySortBy | undefined =
+ !activeGroupId && topicGroupMode === 'byStatus' ? 'status' : undefined;
- return useFetchTopics({
+ return {
excludeStatuses: includeCompleted ? undefined : EXCLUDE_STATUSES_COMPLETED,
excludeTriggers: MAIN_SIDEBAR_EXCLUDE_TRIGGERS,
sortBy,
+ };
+};
+
+/**
+ * Canonical topic fetch for chat sidebars (agent + group), driven by the active
+ * session. Use {@link useFetchAgentChatTopics} for a panel that names its agent
+ * explicitly.
+ *
+ * Extend {@link useChatTopicListQuery} when adding more preference-driven topic
+ * params; don't spread them across individual components.
+ */
+export const useFetchChatTopics = () => useFetchTopics(useChatTopicListQuery());
+
+/**
+ * Same canonical list, for the secondary conversation panels that carry their
+ * own topic picker (goal chat, task manager, page copilot, agent builder).
+ *
+ * These share `topicDataMap[agent_<id>]` with the sidebar, so they must ask for
+ * exactly the same list: fetching unfiltered here used to overwrite the
+ * sidebar's bucket with system-owned topics (task runs, cron, docs, evals) the
+ * moment such a panel mounted next to it.
+ */
+export const useFetchAgentChatTopics = (agentId?: string) => {
+ const query = useChatTopicListQuery();
+ const inboxAgentId = useAgentStore(builtinAgentSelectors.inboxAgentId);
+ const pageSize = useGlobalStore(systemStatusSelectors.topicPageSize);
+
+ return useChatStore((s) => s.useFetchTopics)(!!agentId, {
+ agentId,
+ ...query,
+ isInbox: !!inboxAgentId && agentId === inboxAgentId,
+ pageSize,
});
};
diff --git a/src/routes/(main)/group/profile/features/AgentBuilder/TopicSelector.tsx b/src/routes/(main)/group/profile/features/AgentBuilder/TopicSelector.tsx
index 7ed8c278c1f..efc817dfaec 100644
--- a/src/routes/(main)/group/profile/features/AgentBuilder/TopicSelector.tsx
+++ b/src/routes/(main)/group/profile/features/AgentBuilder/TopicSelector.tsx
@@ -8,6 +8,7 @@ import { useTranslation } from 'react-i18next';
import { DESKTOP_HEADER_ICON_SMALL_SIZE } from '@/const/layoutTokens';
import NavHeader from '@/features/NavHeader';
+import { useFetchAgentChatTopics } from '@/hooks/useFetchChatTopics';
import { useQueryState } from '@/hooks/useQueryParam';
import { useChatStore } from '@/store/chat';
import { topicSelectors } from '@/store/chat/slices/topic/selectors';
@@ -35,7 +36,7 @@ const TopicSelector = memo<TopicSelectorProps>(({ agentId, disabled }) => {
const { t } = useTranslation('topic');
// Fetch topics for the group agent builder
- useChatStore((s) => s.useFetchTopics)(true, { agentId });
+ useFetchAgentChatTopics(agentId);
// Use activeTopicId from chatStore (synced from URL query 'bt' via ProfileHydration)
const activeTopicId = useChatStore((s) => s.activeTopicId);
diff --git a/src/store/chat/slices/topic/selectors.test.ts b/src/store/chat/slices/topic/selectors.test.ts
index 18403660b03..6981acfa74d 100644
--- a/src/store/chat/slices/topic/selectors.test.ts
+++ b/src/store/chat/slices/topic/selectors.test.ts
@@ -237,6 +237,34 @@ describe('topicSelectors', () => {
const topics = topicSelectors.displayTopics(state);
expect(topics).toEqual(topicItems);
});
+
+ it('should hide every system-owned trigger, not just cron', () => {
+ // A panel fetching the same agent with looser filters (goal chat, task
+ // manager, page copilot) overwrites this bucket, so the list surfaces
+ // must not render whatever lands in it.
+ const polluted = [
+ ...topicItems,
+ { id: 'cron1', name: 'Cron', trigger: 'cron' },
+ { id: 'task1', name: 'Task run', trigger: 'task' },
+ { id: 'doc1', name: 'Doc chat', trigger: 'document' },
+ { id: 'eval1', name: 'Eval', trigger: 'eval' },
+ ];
+ const state = merge(initialStore, {
+ activeAgentId: 'test',
+ topicDataMap: {
+ [topicMapKey({ agentId: 'test' })]: {
+ currentPage: 0,
+ hasMore: false,
+ items: polluted,
+ pageSize: 20,
+ total: polluted.length,
+ },
+ },
+ });
+
+ expect(topicSelectors.displayTopics(state)).toEqual(topicItems);
+ expect(topicSelectors.currentTopicLength(state)).toBe(topicItems.length);
+ });
});
describe('searchTopics', () => {
diff --git a/src/store/chat/slices/topic/selectors.ts b/src/store/chat/slices/topic/selectors.ts
index ad4a4ca53a9..b8b13cba649 100644
--- a/src/store/chat/slices/topic/selectors.ts
+++ b/src/store/chat/slices/topic/selectors.ts
@@ -2,6 +2,7 @@ import { isDesktop } from '@lobechat/const';
import { getWorkingDirEffectivePath } from '@lobechat/types';
import { t } from 'i18next';
+import { MAIN_SIDEBAR_EXCLUDE_TRIGGERS } from '@/const/topic';
import {
type ChatTopic,
type ChatTopicSummary,
@@ -33,11 +34,21 @@ const currentTopicData = (s: ChatStoreState): TopicData | undefined => {
const currentTopics = (s: ChatStoreState): ChatTopic[] | undefined => currentTopicData(s)?.items;
-// Get topics without cron-triggered ones
-const currentTopicsWithoutCron = (s: ChatStoreState): ChatTopic[] | undefined => {
+/**
+ * Every list surface reads through here, so system-owned topics (cron, task
+ * runs, doc chats, evals) stay out of the user's chat history.
+ *
+ * The sidebar fetch already excludes them server-side; this repeats the filter
+ * because `topicDataMap` is keyed by container and not by query, so any panel
+ * fetching the same agent with looser filters overwrites the bucket. Belt and
+ * braces — the fetch decides the page and the total, this decides what renders.
+ */
+const currentTopicsWithoutSystemTriggers = (s: ChatStoreState): ChatTopic[] | undefined => {
const topics = currentTopics(s);
if (!topics) return undefined;
- return topics.filter((topic) => topic.trigger !== 'cron');
+ return topics.filter(
+ (topic) => !topic.trigger || !MAIN_SIDEBAR_EXCLUDE_TRIGGERS.includes(topic.trigger),
+ );
};
const currentActiveTopic = (s: ChatStoreState): ChatTopic | undefined => {
@@ -50,12 +61,14 @@ const currentActiveTopic = (s: ChatStoreState): ChatTopic | undefined => {
};
const searchTopics = (s: ChatStoreState): ChatTopic[] => s.searchTopics;
-const displayTopics = (s: ChatStoreState): ChatTopic[] | undefined => currentTopicsWithoutCron(s);
+const displayTopics = (s: ChatStoreState): ChatTopic[] | undefined =>
+ currentTopicsWithoutSystemTriggers(s);
const currentUnFavTopics = (s: ChatStoreState): ChatTopic[] =>
- currentTopicsWithoutCron(s)?.filter((s) => !s.favorite) || [];
+ currentTopicsWithoutSystemTriggers(s)?.filter((s) => !s.favorite) || [];
-const currentTopicLength = (s: ChatStoreState): number => currentTopicsWithoutCron(s)?.length || 0;
+const currentTopicLength = (s: ChatStoreState): number =>
+ currentTopicsWithoutSystemTriggers(s)?.length || 0;
const currentTopicCount = (s: ChatStoreState): number => currentTopicData(s)?.total || 0;
@@ -221,7 +234,7 @@ const sortTopics = (topics: ChatTopic[], sortBy: TopicSortBy): ChatTopic[] => {
const displayTopicsForSidebar =
(pageSize: number, sortBy: TopicSortBy = 'updatedAt', includeCompleted = true) =>
(s: ChatStoreState): ChatTopic[] | undefined => {
- const topics = currentTopicsWithoutCron(s);
+ const topics = currentTopicsWithoutSystemTriggers(s);
if (!topics) return undefined;
const visibleTopics = includeCompleted
@@ -391,7 +404,7 @@ export const topicSelectors = {
currentTopicMetadata,
currentTopicWorkingDirectory,
currentTopics,
- currentTopicsWithoutCron,
+ currentTopicsWithoutSystemTriggers,
currentUnFavTopics,
displayTopics,
displayTopicsForSidebar,