π€― LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.
TypeScript agentagent-collaborationagent-harnessloop-engineeringmcppersonal-assistantproactive-agentskillssuper-agenttask-management
β¨ feat(goal): drive goal list & state from the goals table (#18574)
Arvin Xuac34a3e9dec2
diff --git a/apps/server/src/routers/lambda/__tests__/integration/task.integration.test.ts b/apps/server/src/routers/lambda/__tests__/integration/task.integration.test.tsindex 9a29097acb0..f68157f6445 100644--- a/apps/server/src/routers/lambda/__tests__/integration/task.integration.test.ts+++ b/apps/server/src/routers/lambda/__tests__/integration/task.integration.test.ts@@ -307,6 +307,18 @@ describe('Task Router Integration', () => {});expect(completed.data.status).toBe('completed');});++ it('updates the bound goal when addressed by task identifier', async () => {+ const task = await caller.create({+ goal: { title: 'Identifier lifecycle goal' },+ instruction: 'Test goal lifecycle',+ });++ await caller.updateStatus({ id: task.data.identifier, status: 'running' });++ const goal = await serverDB.query.goals.findFirst();+ expect(goal).toMatchObject({ status: 'running', subjectId: task.data.id });+ });});describe('comments', () => {@@ -488,6 +500,19 @@ describe('Task Router Integration', () => {});describe('run idempotency', () => {+ it('starts the bound goal when addressed by task identifier', async () => {+ const task = await caller.create({+ assigneeAgentId: testAgentId,+ goal: { title: 'Identifier run goal' },+ instruction: 'Test',+ });++ await caller.run({ id: task.data.identifier });++ const goal = await serverDB.query.goals.findFirst();+ expect(goal).toMatchObject({ status: 'running', subjectId: task.data.id });+ });+it('should reject run when a topic is already running', async () => {const task = await caller.create({assigneeAgentId: testAgentId,@@ -507,7 +532,7 @@ describe('Task Router Integration', () => {instruction: 'Test',});- const result = await caller.run({ id: task.data.id });+ await caller.run({ id: task.data.id });await expect(caller.run({ continueTopicId: 'tpc_test', id: task.data.id })).rejects.toThrow(/already running/,diff --git a/apps/server/src/routers/lambda/goal.ts b/apps/server/src/routers/lambda/goal.tsindex bb09b5e1a79..4662503094d 100644--- a/apps/server/src/routers/lambda/goal.ts+++ b/apps/server/src/routers/lambda/goal.ts@@ -1,8 +1,10 @@+import { goalStatuses } from '@lobechat/const/goal';import { TRPCError } from '@trpc/server';import { z } from 'zod';import { withScopedPermission } from '@/business/server/trpc-middlewares/rbacPermission';import { wsCompatProcedure } from '@/business/server/trpc-middlewares/workspaceAuth';+import { GoalModel } from '@/database/models/goal';import { router } from '@/libs/trpc/lambda';import { serverDatabase } from '@/libs/trpc/lambda/middleware';import { GoalService } from '@/server/services/goal';@@ -10,6 +12,11 @@ import { GoalService } from '@/server/services/goal';const goalProcedure = wsCompatProcedure.use(serverDatabase).use(async (opts) =>opts.next({ctx: {+ goalModel: new GoalModel(+ opts.ctx.serverDB,+ opts.ctx.userId,+ opts.ctx.workspaceId ?? undefined,+ ),goalService: new GoalService(opts.ctx.serverDB,opts.ctx.userId,@@ -141,6 +148,23 @@ export const goalRouter = router({}}),+ /**+ * List goals. Each item is the execution-carrier task with the goal row+ * attached (`goal`) plus subtree run statistics (`totalRunCost` /+ * `totalRunDuration`), shaped TaskItem-compatible for the existing goal UI.+ */+ list: goalProcedure+ .input(+ z.object({+ agentId: z.string().optional(),+ limit: z.number().optional(),+ offset: z.number().optional(),+ projectId: z.string().optional(),+ statuses: z.array(z.enum(goalStatuses)).optional(),+ }),+ )+ .query(async ({ input, ctx }) => ctx.goalModel.list(input)),+pause: goalWriteProcedure.input(idInput).mutation(async ({ ctx, input }) => {try {return { data: await ctx.goalService.pause(input.id), message: 'Goal paused', success: true };diff --git a/apps/server/src/routers/lambda/index.ts b/apps/server/src/routers/lambda/index.tsindex 2dc48bc18fe..56a9ff458fb 100644--- a/apps/server/src/routers/lambda/index.ts+++ b/apps/server/src/routers/lambda/index.ts@@ -108,7 +108,6 @@ export const lambdaRouter = router({agentSkills: agentSkillsRouter,expertise: expertiseRouter,agentSignal: agentSignalRouter,- task: taskRouter,changelog: changelogRouter,brief: briefRouter,aiAgent: aiAgentRouter,@@ -160,6 +159,7 @@ export const lambdaRouter = router({session: sessionRouter,sessionGroup: sessionGroupRouter,share: shareRouter,+ task: taskRouter,thread: threadRouter,topic: topicRouter,topicComment: topicCommentRouter,diff --git a/apps/server/src/routers/lambda/task.ts b/apps/server/src/routers/lambda/task.tsindex 4013bbfe514..efa4e57fe33 100644--- a/apps/server/src/routers/lambda/task.ts+++ b/apps/server/src/routers/lambda/task.ts@@ -1,4 +1,5 @@import { TASK_STATUSES } from '@lobechat/builtin-tool-task';+import type { GoalStatus } from '@lobechat/const/goal';import type { TaskListItem, TaskParticipant } from '@lobechat/types';import { TRPCError } from '@trpc/server';import { z } from 'zod';@@ -25,6 +26,17 @@ import { TransferErrorCode } from '@/types/transferError';import { assertWorkspaceRowManageable } from './_helpers/assertWorkspaceRowManageable';+/** Manual task status β bound goal lifecycle state. */+const taskStatusToGoalStatus: Record<string, GoalStatus | undefined> = {+ backlog: 'planning',+ canceled: 'canceled',+ completed: 'review',+ failed: 'failed',+ paused: 'paused',+ running: 'running',+ scheduled: 'planning',+};+const taskProcedure = wsCompatProcedure.use(serverDatabase).use(async (opts) => {const { ctx } = opts;const wsId = ctx.workspaceId ?? undefined;@@ -488,6 +500,8 @@ export const taskRouter = router({throw new TRPCError({ code: 'BAD_REQUEST', message: 'Task is not a goal root' });}assertWorkspaceRowManageable(ctx, task.createdByUserId, 'task');+ // TaskModel owns the transaction and removes goal rows for the complete+ // subtree before deleting its tasks.const count = await model.deleteSubtree(task.id);return { count, data: task, message: 'Goal deleted', success: true };} catch (error) {@@ -770,6 +784,11 @@ export const taskRouter = router({).mutation(async ({ input, ctx }) => {try {+ const task = await resolveOrThrow(ctx.taskModel, input.id);+ // A manually (re)started goal leaves its paused/review state and runs.+ const goal = await ctx.goalModel.findBySubject('task', task.id);+ if (goal) await ctx.goalModel.updateStatus(goal.id, 'running');+const runner = new TaskRunnerService(ctx.serverDB,ctx.userId,@@ -778,7 +797,7 @@ export const taskRouter = router({return await runner.runTask({continueTopicId: input.continueTopicId,extraPrompt: input.prompt,- taskId: input.id,+ taskId: task.id,});} catch (error) {if (error instanceof TRPCError) throw error;@@ -1338,6 +1357,12 @@ export const taskRouter = router({.mutation(async ({ input, ctx }) => {try {const result = await ctx.taskService.updateStatus(input);+ // Manual task status changes drive the bound goal's own state machine.+ const goal = await ctx.goalModel.findBySubject('task', result.task.id);+ if (goal) {+ const goalStatus = taskStatusToGoalStatus[input.status];+ if (goalStatus) await ctx.goalModel.updateStatus(goal.id, goalStatus);+ }const { task, unlocked, paused, checkpointTriggered, allSubtasksDone, parentTaskId } =result;return {diff --git a/packages/database/src/models/__tests__/goal.test.ts b/packages/database/src/models/__tests__/goal.test.tsindex 48bac3b3d1c..858ab4a0f2e 100644--- a/packages/database/src/models/__tests__/goal.test.ts+++ b/packages/database/src/models/__tests__/goal.test.ts@@ -3,9 +3,10 @@ import { eq } from 'drizzle-orm';import { afterEach, beforeEach, describe, expect, it } from 'vitest';import { getTestDB } from '../../core/getTestDB';-import { goals, users } from '../../schemas';+import { agents, goals, tasks, users, workspaces } from '../../schemas';import type { LobeChatDatabase } from '../../type';import { GoalModel } from '../goal';+import { TaskModel } from '../task';const serverDB: LobeChatDatabase = await getTestDB();@@ -93,6 +94,68 @@ describe('GoalModel', () => {});});+ describe('list', () => {+ it('applies the carrier task visibility boundary in a workspace', async () => {+ const workspaceId = 'goal-list-visibility-workspace';+ await serverDB.insert(workspaces).values({+ id: workspaceId,+ name: 'Goal list visibility',+ primaryOwnerId: userId,+ slug: workspaceId,+ });++ const ownerTasks = new TaskModel(serverDB, userId, workspaceId);+ const ownerGoals = new GoalModel(serverDB, userId, workspaceId);+ const privateTask = await ownerTasks.create({+ instruction: 'private',+ visibility: 'private',+ });+ const publicTask = await ownerTasks.create({ instruction: 'public', visibility: 'public' });+ await ownerGoals.create({+ subjectId: privateTask.id,+ subjectType: 'task',+ title: 'Private goal',+ });+ await ownerGoals.create({+ subjectId: publicTask.id,+ subjectType: 'task',+ title: 'Public goal',+ });++ const memberGoals = new GoalModel(serverDB, otherUserId, workspaceId);+ const result = await memberGoals.list();++ expect(result.total).toBe(1);+ expect(result.goals.map(({ id }) => id)).toEqual([publicTask.id]);+ });++ it('filters by the carrier task current assignee instead of the goal snapshot', async () => {+ const oldAgentId = 'goal-list-old-agent';+ const newAgentId = 'goal-list-new-agent';+ await serverDB.insert(agents).values([+ { id: oldAgentId, slug: oldAgentId, userId },+ { id: newAgentId, slug: newAgentId, userId },+ ]);+ const task = await new TaskModel(serverDB, userId).create({+ assigneeAgentId: oldAgentId,+ instruction: 'reassign me',+ });+ await goalModel.create({+ agentId: oldAgentId,+ subjectId: task.id,+ subjectType: 'task',+ title: 'Reassigned goal',+ });+ await serverDB+ .update(tasks)+ .set({ assigneeAgentId: newAgentId })+ .where(eq(tasks.id, task.id));++ expect((await goalModel.list({ agentId: oldAgentId })).total).toBe(0);+ expect((await goalModel.list({ agentId: newAgentId })).goals[0]?.id).toBe(task.id);+ });+ });+describe('updateStatus', () => {it('stamps startedAt on first entry into running', async () => {const { id } = await goalModel.create({diff --git a/packages/database/src/models/goal.ts b/packages/database/src/models/goal.tsindex 027a7ddb1e5..751e24f8382 100644--- a/packages/database/src/models/goal.ts+++ b/packages/database/src/models/goal.ts@@ -1,8 +1,11 @@import type { GoalStatus, GoalSubjectType } from '@lobechat/const/goal';-import { and, desc, eq, inArray } from 'drizzle-orm';+import type { TaskItem } from '@lobechat/types';+import { and, desc, eq, inArray, sql } from 'drizzle-orm';import type { GoalItem, NewGoal } from '../schemas/goal';import { goals } from '../schemas/goal';+import { tasks, taskTopics } from '../schemas/task';+import { topics } from '../schemas/topic';import type { LobeChatDatabase } from '../type';import { buildWorkspacePayload, buildWorkspaceWhere } from '../utils/workspace';@@ -31,6 +34,15 @@ export class GoalModel {private ownership = () =>buildWorkspaceWhere({ userId: this.userId, workspaceId: this.workspaceId }, goals);+ /** Visibility-aware task scope for recursive raw-SQL carrier aggregation. */+ private taskOwnershipSql = (alias?: string) => {+ const prefix = alias ? sql.raw(`${alias}.`) : sql.raw('');+ return this.workspaceId+ ? sql`${prefix}workspace_id = ${this.workspaceId}+ AND (${prefix}visibility = 'public' OR ${prefix}created_by_user_id = ${this.userId})`+ : sql`${prefix}created_by_user_id = ${this.userId} AND ${prefix}workspace_id IS NULL`;+ };+create = async (params: Omit<NewGoal, 'userId' | 'workspaceId'>): Promise<GoalItem> => {const [row] = await this.db.insert(goals)@@ -122,4 +134,131 @@ export class GoalModel {and(eq(goals.subjectType, subjectType), eq(goals.subjectId, subjectId), this.ownership()),);};++ /**+ * List goals with their execution-carrier task and subtree run statistics.+ * Each item is TaskItem-shaped with the goal row attached as `goal` and the+ * run cost / duration aggregated across the whole task subtree β mirroring+ * `TaskModel.groupList`'s `goal_tree` recursive CTE, so the goal UI reads+ * the goal's own lifecycle state the same way from either endpoint.+ */+ list = async (+ options: {+ agentId?: string;+ limit?: number;+ offset?: number;+ projectId?: string;+ statuses?: GoalStatus[];+ } = {},+ ): Promise<{ goals: GoalListItem[]; total: number }> => {+ const { agentId, limit = 50, offset = 0, projectId, statuses } = options;++ // A list item is backed by a carrier task, so task visibility is the+ // effective read boundary. Goal rows themselves intentionally have no+ // visibility column and workspace ownership alone is not sufficient.+ const taskOwnership = buildWorkspaceWhere(+ { userId: this.userId, workspaceId: this.workspaceId },+ {+ userId: tasks.createdByUserId,+ visibility: tasks.visibility,+ workspaceId: tasks.workspaceId,+ },+ );+ const conditions = [+ this.ownership(),+ eq(goals.subjectType, 'task'),+ eq(goals.subjectId, tasks.id),+ taskOwnership,+ ];+ // Scope against the current carrier instead of the goal's creation-time+ // snapshot, because tasks can be reassigned or moved between projects.+ if (agentId) conditions.push(eq(tasks.assigneeAgentId, agentId));+ if (projectId) conditions.push(eq(tasks.projectId, projectId));+ if (statuses && statuses.length > 0) conditions.push(inArray(goals.status, statuses));++ const [countRow] = await this.db+ .select({ count: sql<number>`count(*)` })+ .from(goals)+ .innerJoin(tasks, eq(goals.subjectId, tasks.id))+ .where(and(...conditions));++ const total = Number(countRow?.count ?? 0);+ if (total === 0) return { goals: [], total };++ const rows = await this.db+ .select({ goal: goals, task: tasks })+ .from(goals)+ .innerJoin(tasks, eq(goals.subjectId, tasks.id))+ .where(and(...conditions))+ .orderBy(desc(goals.createdAt))+ .limit(limit)+ .offset(offset);++ const taskIds = rows.map(({ task }) => task.id);++ const runStats =+ taskIds.length === 0+ ? []+ : (+ await this.db.execute<{+ root_id: string;+ total_run_cost: number;+ total_run_duration: number;+ }>(sql`+ WITH RECURSIVE goal_tree AS (+ SELECT ${tasks.id} AS root_id, ${tasks.id} AS task_id+ FROM ${tasks}+ WHERE ${inArray(tasks.id, taskIds)} AND ${this.taskOwnershipSql()}+ UNION ALL+ SELECT goal_tree.root_id, child.id+ FROM ${tasks} child+ JOIN goal_tree ON child.parent_task_id = goal_tree.task_id+ WHERE ${this.taskOwnershipSql('child')}+ )+ SELECT+ goal_tree.root_id,+ coalesce(sum(${topics.totalCost}), 0) AS total_run_cost,+ coalesce(+ sum(extract(epoch from (${topics.completedAt} - ${taskTopics.createdAt})) * 1000)+ filter (where ${topics.completedAt} is not null),+ 0+ ) AS total_run_duration+ FROM goal_tree+ LEFT JOIN ${taskTopics} ON ${taskTopics.taskId} = goal_tree.task_id+ LEFT JOIN ${topics} ON ${topics.id} = ${taskTopics.topicId}+ GROUP BY goal_tree.root_id+ `)+ ).rows;++ const runStatsByTaskId = new Map(+ runStats.map((s) => [+ s.root_id,+ {+ totalRunCost: Number(s.total_run_cost),+ totalRunDuration: Number(s.total_run_duration),+ },+ ]),+ );++ const items: GoalListItem[] = rows.map(({ goal, task }) => {+ const stats = runStatsByTaskId.get(task.id) ?? { totalRunCost: 0, totalRunDuration: 0 };++ return {+ ...task,+ goal,+ totalRunCost: stats.totalRunCost,+ totalRunDuration: stats.totalRunDuration,+ };+ });++ return { goals: items, total };+ };+}++/** A goal-list item: the carrier task plus the attached goal row and the+ * subtree run statistics. */+export interface GoalListItem extends TaskItem {+ goal: GoalItem | null;+ totalRunCost: number;+ totalRunDuration: number;}diff --git a/src/features/AgentGoals/AgentGoalsPage.tsx b/src/features/AgentGoals/AgentGoalsPage.tsxindex 58b09e7e442..af7328fdadf 100644--- a/src/features/AgentGoals/AgentGoalsPage.tsx+++ b/src/features/AgentGoals/AgentGoalsPage.tsx@@ -12,14 +12,12 @@ import AgentBreadcrumb from '@/features/AgentBreadcrumb';import NavHeader from '@/features/NavHeader';import WideScreenContainer from '@/features/WideScreenContainer';import { goalSelectors, useGoalStore } from '@/store/goal';-import { useVerifyStore } from '@/store/verify';import { createGoalModal } from './CreateGoalModal';import { GoalCardItem } from './GoalCardItem';import GoalEmptyState from './GoalEmptyState';import type { GoalExampleSeed } from './goalExamples';import { GoalListItem } from './GoalListItem';-import { getGoalPresentation } from './goalPresentation';import { shouldShowGoal } from './goalViewModel';const styles = createStaticStyles(({ css }) => ({@@ -82,32 +80,17 @@ const AgentGoalsPage = memo<AgentGoalsPageProps>(({ agentId, projectId }) => {const setFilter = useGoalStore((s) => s.setGoalListFilter);const setViewMode = useGoalStore((s) => s.setGoalViewMode);const loadMoreGoals = useGoalStore((s) => s.loadMoreGoals);- const acceptanceBySubjectMap = useVerifyStore((s) => s.acceptanceBySubjectMap);- const acceptanceBundleMap = useVerifyStore((s) => s.acceptanceBundleMap);const { error, isLoading } = useFetchGoals(agentId, projectId);const summary = useMemo(() => {- const delivered = goals.filter((goal) => goal.status === 'completed').length;+ const delivered = goals.filter((goal) => goal.goal?.status === 'review').length;return { delivered, pursuing: goals.length - delivered, total: goals.length };}, [goals]);const filteredGoals = useMemo(() => {if (filter === 'all') return goals;- return goals.filter((goal) => {- const acceptance = acceptanceBySubjectMap[`task:${goal.id}`];- const bundle = acceptance ? acceptanceBundleMap[acceptance.id] : undefined;- const presentation = getGoalPresentation({- acceptanceStatus: bundle?.acceptance.status,- checks: bundle?.checks,- goalStatus: goal.goal?.status,- maxRounds: goal.goal?.maxRounds,- rounds: goal.totalTopics ?? 0,- taskStatus: goal.status,- });-- return shouldShowGoal(presentation.statusKey, 'active');- });- }, [acceptanceBundleMap, acceptanceBySubjectMap, filter, goals]);+ return goals.filter((goal) => shouldShowGoal(goal.goal?.status ?? 'planning', 'active'));+ }, [filter, goals]);const visibleGoalCount = filteredGoals.length;const GoalItem = viewMode === 'list' ? GoalListItem : GoalCardItem;const openCreateGoal = (seed?: GoalExampleSeed) => {diff --git a/src/features/AgentGoals/GoalCardItem.tsx b/src/features/AgentGoals/GoalCardItem.tsxindex b6f49532b6a..8e48f8bce5c 100644--- a/src/features/AgentGoals/GoalCardItem.tsx+++ b/src/features/AgentGoals/GoalCardItem.tsx@@ -55,14 +55,15 @@ export const GoalCardItem = memo<GoalItemProps>((props) => {<GoalAcceptance taskId={task.id}>{({ bundle, error, isLoading, retry }) => {const presentation = getGoalPresentation({- acceptanceStatus: bundle?.acceptance.status,checks: bundle?.checks,- goalStatus: goal?.status,- maxRounds: goal?.maxRounds,+ goalStatus: goal?.status ?? 'planning',+ maxRounds: goal?.maxRounds ?? null,rounds: task.totalTopics ?? 0,- taskStatus: task.status,});- if (!isLoading && !shouldShowGoal(presentation.statusKey, hideAchieved ? 'active' : 'all'))+ if (+ !isLoading &&+ !shouldShowGoal(goal?.status ?? 'planning', hideAchieved ? 'active' : 'all')+ )return null;return (@@ -86,7 +87,7 @@ export const GoalCardItem = memo<GoalItemProps>((props) => {><Flexbox gap={4} style={{ minWidth: 0 }}><Flexbox horizontal align={'center'} gap={7}>- <GoalStatusGlyph size={13} statusKey={presentation.statusKey} />+ <GoalStatusGlyph size={13} status={goal?.status ?? 'planning'} /><Text ellipsis fontSize={15} weight={600}>{title}</Text>diff --git a/src/features/AgentGoals/GoalDetailPage.tsx b/src/features/AgentGoals/GoalDetailPage.tsxindex 3d1ee5b7734..d92301d6e3e 100644--- a/src/features/AgentGoals/GoalDetailPage.tsx+++ b/src/features/AgentGoals/GoalDetailPage.tsx@@ -154,13 +154,12 @@ const GoalDetailPage = memo<GoalDetailPageProps>(({ agentId, goalId }) => {const recentRuns = useMemo(() => getRecentGoalRuns(task?.activities), [task?.activities]);const runMetrics = useMemo(() => getGoalRunMetrics(task?.activities), [task?.activities]);const { text: rootUpdatedAt, title: rootUpdatedAtTitle } = useActivityTime(task?.updatedAt);+ const goalStatus = task?.goal?.status ?? 'planning';const presentation = getGoalPresentation({- acceptanceStatus: bundle?.acceptance.status,checks: bundle?.checks,- goalStatus: task?.goal?.status,- maxRounds: task?.goal?.maxRounds,+ goalStatus,+ maxRounds: task?.goal?.maxRounds ?? null,rounds: task?.topicCount ?? 0,- taskStatus: task?.status ?? 'backlog',});const title = task?.name?.trim() || task?.instruction.trim() || goalId;@@ -341,7 +340,7 @@ const GoalDetailPage = memo<GoalDetailPageProps>(({ agentId, goalId }) => {</Flexbox><Flexbox gap={4}><Flexbox horizontal align={'center'} className={styles.treeRow} gap={8}>- <GoalStatusGlyph size={14} statusKey={presentation.statusKey} />+ <GoalStatusGlyph size={14} status={goalStatus} /><Text fontSize={12} type={'secondary'}>{task.identifier}</Text>diff --git a/src/features/AgentGoals/GoalListItem.tsx b/src/features/AgentGoals/GoalListItem.tsxindex 6551679b84d..17ef56dff78 100644--- a/src/features/AgentGoals/GoalListItem.tsx+++ b/src/features/AgentGoals/GoalListItem.tsx@@ -54,14 +54,15 @@ export const GoalListItem = memo<GoalItemProps>((props) => {<GoalAcceptance taskId={task.id}>{({ bundle, error, isLoading, retry }) => {const presentation = getGoalPresentation({- acceptanceStatus: bundle?.acceptance.status,checks: bundle?.checks,- goalStatus: goal?.status,- maxRounds: goal?.maxRounds,+ goalStatus: goal?.status ?? 'planning',+ maxRounds: goal?.maxRounds ?? null,rounds: task.totalTopics ?? 0,- taskStatus: task.status,});- if (!isLoading && !shouldShowGoal(presentation.statusKey, hideAchieved ? 'active' : 'all'))+ if (+ !isLoading &&+ !shouldShowGoal(goal?.status ?? 'planning', hideAchieved ? 'active' : 'all')+ )return null;return (@@ -90,7 +91,7 @@ export const GoalListItem = memo<GoalItemProps>((props) => {><Flexbox gap={4} style={{ minWidth: 0 }}><Flexbox horizontal align={'center'} gap={7}>- <GoalStatusGlyph size={13} statusKey={presentation.statusKey} />+ <GoalStatusGlyph size={13} status={goal?.status ?? 'planning'} /><Text ellipsis fontSize={15} weight={600}>{title}</Text>diff --git a/src/features/AgentGoals/GoalStatusGlyph.tsx b/src/features/AgentGoals/GoalStatusGlyph.tsxindex f4d03e60069..76e7b6b149e 100644--- a/src/features/AgentGoals/GoalStatusGlyph.tsx+++ b/src/features/AgentGoals/GoalStatusGlyph.tsx@@ -1,3 +1,4 @@+import type { GoalStatus } from '@lobechat/const/goal';import type { TaskStatus } from '@lobechat/types';import { Icon } from '@lobehub/ui';import { memo } from 'react';@@ -13,11 +14,11 @@ import { goalStatusToTaskStatus } from './goalViewModel';* across the app β while every other state keeps its canonical static glyph* from `ExecutionStatus`.*/-const GoalStatusGlyph = memo<{ size?: number; statusKey: string }>(({ statusKey, size = 13 }) => {- if (statusKey === 'goalList.status.running') return <RunningGlyph size={size} />;+const GoalStatusGlyph = memo<{ size?: number; status: GoalStatus }>(({ status, size = 13 }) => {+ if (status === 'running') return <RunningGlyph size={size} />;const visual =- TASK_STATUS_VISUALS[goalStatusToTaskStatus(statusKey) as TaskStatus] ??+ TASK_STATUS_VISUALS[goalStatusToTaskStatus(status) as TaskStatus] ??TASK_STATUS_VISUALS.backlog;return <Icon color={visual.color} icon={visual.icon} size={size} style={{ flexShrink: 0 }} />;diff --git a/src/features/AgentGoals/goalPresentation.test.ts b/src/features/AgentGoals/goalPresentation.test.tsindex 11beeb864dd..4d3af69d05d 100644--- a/src/features/AgentGoals/goalPresentation.test.ts+++ b/src/features/AgentGoals/goalPresentation.test.ts@@ -3,13 +3,12 @@ import { describe, expect, it } from 'vitest';import { getGoalPresentation } from './goalPresentation';describe('getGoalPresentation', () => {- it('uses Acceptance as the authoritative lifecycle and progress source', () => {+ it('maps the goal lifecycle state to the goal list vocabulary', () => {expect(getGoalPresentation({- acceptanceStatus: 'verifying',checks: [{ state: 'passed' }, { state: 'failed' }, { state: 'passed' }],+ goalStatus: 'verifying',rounds: 2,- taskStatus: 'running',}),).toMatchObject({passed: 2,@@ -19,48 +18,41 @@ describe('getGoalPresentation', () => {});});- it('shows achieved only after Acceptance is accepted', () => {+ it('shows achieved only when the goal state machine reached it', () => {expect(getGoalPresentation({- acceptanceStatus: 'accepted',checks: [{ state: 'passed' }],+ goalStatus: 'achieved',rounds: 3,- taskStatus: 'completed',}).statusKey,).toBe('goalList.status.achieved');});- it('falls back to task execution and round state before Acceptance exists', () => {- expect(getGoalPresentation({ maxRounds: 5, rounds: 2, taskStatus: 'scheduled' })).toMatchObject(- {- maxRounds: 5,- passed: 0,- progress: 0,- rounds: 2,- statusKey: 'goalList.status.waiting',- total: 0,- },- );+ it('reports rounds and budget without any checks yet', () => {+ expect(getGoalPresentation({ goalStatus: 'running', maxRounds: 5, rounds: 2 })).toMatchObject({+ maxRounds: 5,+ passed: 0,+ progress: 0,+ rounds: 2,+ statusKey: 'goalList.status.running',+ total: 0,+ });});- it('keeps an executing round shown as running while the verify plan is only planned', () => {- // Regression (caught by the E2E acceptance run): the verify plan is- // confirmed at run start, so the acceptance phase reads `planned` for the- // whole executing round. That phase must fall through to the goal entity- // status (`running`) instead of rendering ιͺθ―δΈ.- expect(- getGoalPresentation({- acceptanceStatus: 'planned',- goalStatus: 'running',- rounds: 1,- taskStatus: 'running',- }).statusKey,- ).toBe('goalList.status.running');- });+ it('maps every goal status to a goal list key', () => {+ const cases: Array<[Parameters<typeof getGoalPresentation>[0]['goalStatus'], string]> = [+ ['planning', 'goalList.status.planning'],+ ['running', 'goalList.status.running'],+ ['verifying', 'goalList.status.verifying'],+ ['review', 'goalList.status.review'],+ ['paused', 'goalList.status.paused'],+ ['achieved', 'goalList.status.achieved'],+ ['failed', 'goalList.status.error'],+ ['canceled', 'goalList.status.canceled'],+ ];- it('prefers the goal entity status over the task-status heuristic', () => {- expect(- getGoalPresentation({ goalStatus: 'paused', rounds: 1, taskStatus: 'running' }).statusKey,- ).toBe('goalList.status.paused');+ for (const [goalStatus, statusKey] of cases) {+ expect(getGoalPresentation({ goalStatus, rounds: 0 }).statusKey).toBe(statusKey);+ }});});diff --git a/src/features/AgentGoals/goalPresentation.ts b/src/features/AgentGoals/goalPresentation.tsindex f6cac8c2441..e979916a23d 100644--- a/src/features/AgentGoals/goalPresentation.ts+++ b/src/features/AgentGoals/goalPresentation.ts@@ -1,91 +1,22 @@+import type { GoalStatus } from '@lobechat/const/goal';+export interface GoalPresentationInput {- acceptanceStatus?: string;checks?: Array<{ state: string }>;- /** The goal entity's own lifecycle state (`goals.status`), when loaded. */- goalStatus?: string;+ goalStatus: GoalStatus;maxRounds?: number | null;rounds: number;- taskStatus: string;}-const acceptanceStatusKey = (status?: string) => {- switch (status) {- case 'accepted': {- return 'goalList.status.achieved';- }- case 'closed':- case 'rejected': {- return 'goalList.status.paused';- }- case 'delivered': {- return 'goalList.status.review';- }- case 'errored': {- return 'goalList.status.error';- }- // `planned` deliberately falls through to the goal/task tiers: the verify- // plan is confirmed at RUN START, so this phase spans the whole executing- // round β showing ιͺθ―δΈ for it misreads an executing goal as verifying.- case 'repairing':- case 'verifying': {- return 'goalList.status.verifying';- }- default: {- return undefined;- }- }-};--/**- * `goals.status` is the server-written goal state machine β a direct 1:1 onto- * the display vocabulary (only `failed` renders through the `error` key). It- * sits between the live acceptance phase (fresher, refetched per subject) and- * the task-status heuristic (coarsest, kept as the final fallback).- */-const goalStatusKey = (status?: string) => {- switch (status) {- case 'achieved':- case 'canceled':- case 'paused':- case 'planning':- case 'review':- case 'running':- case 'verifying': {- return `goalList.status.${status}`;- }- case 'failed': {- return 'goalList.status.error';- }- default: {- return undefined;- }- }-};--const taskStatusKey = (status: string) => {- switch (status) {- case 'backlog': {- return 'goalList.status.planning';- }- case 'completed': {- return 'goalList.status.review';- }- case 'failed': {- return 'goalList.status.error';- }- case 'paused': {- return 'goalList.status.paused';- }- case 'canceled': {- return 'goalList.status.canceled';- }- case 'scheduled': {- return 'goalList.status.waiting';- }- default: {- return 'goalList.status.running';- }- }+/** Goal lifecycle state β i18n status key (goal list vocabulary). */+const goalStatusKeyMap: Record<GoalStatus, string> = {+ achieved: 'goalList.status.achieved',+ canceled: 'goalList.status.canceled',+ failed: 'goalList.status.error',+ paused: 'goalList.status.paused',+ planning: 'goalList.status.planning',+ review: 'goalList.status.review',+ running: 'goalList.status.running',+ verifying: 'goalList.status.verifying',};export const getGoalPresentation = (input: GoalPresentationInput) => {@@ -98,10 +29,7 @@ export const getGoalPresentation = (input: GoalPresentationInput) => {passed,progress: total > 0 ? Math.round((passed / total) * 100) : 0,rounds: input.rounds,- statusKey:- acceptanceStatusKey(input.acceptanceStatus) ??- goalStatusKey(input.goalStatus) ??- taskStatusKey(input.taskStatus),+ statusKey: goalStatusKeyMap[input.goalStatus],total,};};diff --git a/src/features/AgentGoals/goalViewModel.test.ts b/src/features/AgentGoals/goalViewModel.test.tsindex c7bdafeebe8..a5d618bbdce 100644--- a/src/features/AgentGoals/goalViewModel.test.ts+++ b/src/features/AgentGoals/goalViewModel.test.ts@@ -66,15 +66,15 @@ describe('goalViewModel', () => {});it('hides achieved goals from the default active filter without hiding pending acceptance', () => {- expect(shouldShowGoal('goalList.status.achieved', 'active')).toBe(false);- expect(shouldShowGoal('goalList.status.review', 'active')).toBe(true);- expect(shouldShowGoal('goalList.status.achieved', 'all')).toBe(true);+ expect(shouldShowGoal('achieved', 'active')).toBe(false);+ expect(shouldShowGoal('review', 'active')).toBe(true);+ expect(shouldShowGoal('achieved', 'all')).toBe(true);});- it('uses the Goal acceptance state for its status icon', () => {- expect(goalStatusToTaskStatus('goalList.status.review')).toBe('paused');- expect(goalStatusToTaskStatus('goalList.status.achieved')).toBe('completed');- expect(goalStatusToTaskStatus('goalList.status.verifying')).toBe('running');+ it('uses the goal lifecycle state for its status icon', () => {+ expect(goalStatusToTaskStatus('review')).toBe('paused');+ expect(goalStatusToTaskStatus('achieved')).toBe('completed');+ expect(goalStatusToTaskStatus('verifying')).toBe('running');});it('aggregates duration and cost from every topic run', () => {diff --git a/src/features/AgentGoals/goalViewModel.ts b/src/features/AgentGoals/goalViewModel.tsindex ba65f0f1c13..4b3121d7e89 100644--- a/src/features/AgentGoals/goalViewModel.ts+++ b/src/features/AgentGoals/goalViewModel.ts@@ -1,3 +1,4 @@+import type { GoalStatus } from '@lobechat/const/goal';import type { TaskDetailActivity } from '@lobechat/types';interface GoalDescriptionSource {@@ -43,29 +44,29 @@ export const getGoalRunMetrics = (activities?: TaskDetailActivity[]) =>{ cost: 0, duration: 0 },);-export const shouldShowGoal = (statusKey: string, filter: 'active' | 'all') =>- filter === 'all' || statusKey !== 'goalList.status.achieved';+export const shouldShowGoal = (goalStatus: GoalStatus, filter: 'active' | 'all') =>+ filter === 'all' || goalStatus !== 'achieved';-export const goalStatusToTaskStatus = (statusKey: string) => {- switch (statusKey) {- case 'goalList.status.achieved': {+export const goalStatusToTaskStatus = (goalStatus: GoalStatus) => {+ switch (goalStatus) {+ case 'achieved': {return 'completed';}- case 'goalList.status.error': {+ case 'failed': {return 'failed';}- case 'goalList.status.canceled': {+ case 'canceled': {return 'canceled';}- case 'goalList.status.paused':- case 'goalList.status.review': {+ case 'paused':+ case 'review': {return 'paused';}- case 'goalList.status.planning': {+ case 'planning': {return 'backlog';}- case 'goalList.status.waiting': {- return 'scheduled';+ case 'verifying': {+ return 'running';}default: {return 'running';diff --git a/src/features/HomeInbox/homeGoals.test.ts b/src/features/HomeInbox/homeGoals.test.tsindex 5a93605764f..3ccf6a172dc 100644--- a/src/features/HomeInbox/homeGoals.test.ts+++ b/src/features/HomeInbox/homeGoals.test.ts@@ -1,3 +1,4 @@+import type { GoalStatus } from '@lobechat/const/goal';import { describe, expect, it } from 'vitest';import type { GoalListItem } from '@/store/goal/initialState';@@ -9,12 +10,15 @@ import {resolveHomeGoalView,} from './homeGoals';-const goal = (overrides: Partial<GoalListItem> & Pick<GoalListItem, 'id'>): GoalListItem =>+type GoalOverrides = Omit<Partial<GoalListItem>, 'goal' | 'id'> & {+ goal?: Partial<NonNullable<GoalListItem['goal']>>;+ id: string;+};++const goal = (overrides: GoalOverrides): GoalListItem =>({assigneeAgentId: 'agt_1',- // No `status` on the entity here: these cases exercise the task-status- // fallback tier of the derivation (legacy rows before the backfill ran).- goal: { maxRounds: 3 },+ goal: { id: `g-${overrides.id}`, maxRounds: 3, status: 'running' },identifier: `T-${overrides.id}`,instruction: 'do the thing',name: `goal ${overrides.id}`,@@ -43,9 +47,9 @@ describe('indexAcceptanceStatuses', () => {describe('buildHomeGoalEntries', () => {it('puts the goals waiting on the user ahead of the ones still working', () => {const goals = [- goal({ id: 'r1', status: 'running' }),- goal({ id: 'd1', status: 'completed' }),- goal({ id: 'r2', status: 'scheduled' }),+ goal({ id: 'r1', goal: { status: 'running' } }),+ goal({ id: 'd1', goal: { status: 'review' } }),+ goal({ id: 'r2', goal: { status: 'verifying' } }),];const entries = buildHomeGoalEntries(goals);@@ -56,41 +60,44 @@ describe('buildHomeGoalEntries', () => {it('drops goals that are finished or parked', () => {const goals = [- goal({ id: 'a', status: 'canceled' }),- goal({ id: 'b', status: 'failed' }),- goal({ id: 'c', status: 'paused' }),- goal({ id: 'd', status: 'running' }),+ goal({ id: 'a', goal: { status: 'canceled' } }),+ goal({ id: 'b', goal: { status: 'failed' } }),+ goal({ id: 'c', goal: { status: 'paused' } }),+ goal({ id: 'd', goal: { status: 'achieved' } }),+ goal({ id: 'e', goal: { status: 'running' } }),];- expect(titlesOf(buildHomeGoalEntries(goals))).toEqual(['goal d']);- });-- it('lets an accepted acceptance retire a goal its task status still calls completed', () => {- const goals = [goal({ id: 'done', status: 'completed' })];-- expect(buildHomeGoalEntries(goals, { done: 'accepted' })).toEqual([]);+ expect(titlesOf(buildHomeGoalEntries(goals))).toEqual(['goal e']);});- it('reads a delivered acceptance as pending review even while the task runs on', () => {- const goals = [goal({ id: 'live', status: 'running' })];+ it('reads a review goal as pending the user even without an acceptance read', () => {+ const goals = [goal({ id: 'live', goal: { status: 'review' } })];- const [entry] = buildHomeGoalEntries(goals, { live: 'delivered' });+ const [entry] = buildHomeGoalEntries(goals);expect(entry.bucket).toBe('review');expect(entry.statusKey).toBe('goalList.status.review');});it('keeps a verifying goal in the running bucket', () => {- const goals = [goal({ id: 'v', status: 'running' })];+ const goals = [goal({ id: 'v', goal: { status: 'verifying' } })];- const [entry] = buildHomeGoalEntries(goals, { v: 'verifying' });+ const [entry] = buildHomeGoalEntries(goals);expect(entry.bucket).toBe('running');expect(entry.statusKey).toBe('goalList.status.verifying');});it('carries the round budget and falls back to the identifier for an unnamed goal', () => {- const goals = [goal({ goal: { maxRounds: 5 } as any, id: 'x', instruction: '', name: null })];+ const goals = [+ goal({+ goal: { id: 'g-x', maxRounds: 5, status: 'running' },+ id: 'x',+ instruction: '',+ name: null,+ totalTopics: 1,+ }),+ ];expect(buildHomeGoalEntries(goals)[0]).toMatchObject({agentId: 'agt_1',@@ -101,16 +108,18 @@ describe('buildHomeGoalEntries', () => {});it('reports no round budget when the goal entity carries none', () => {- const goals = [goal({ goal: { maxRounds: null } as any, id: 'x' })];+ const goals = [goal({ goal: { id: 'g-x', maxRounds: null, status: 'running' }, id: 'x' })];expect(buildHomeGoalEntries(goals)[0].maxRounds).toBeNull();});});describe('resolveHomeGoalView', () => {- const entries = (count: number, status = 'running') =>+ const entries = (count: number, status: GoalStatus = 'running') =>buildHomeGoalEntries(- Array.from({ length: count }, (_, index) => goal({ id: `g${index}`, status })),+ Array.from({ length: count }, (_, index) =>+ goal({ goal: { id: `g${index}`, status }, id: `g${index}` }),+ ),);it('names each pile and leaves an empty one out', () => {@@ -143,8 +152,10 @@ describe('resolveHomeGoalView', () => {it('cuts the least urgent rows, never the ones waiting on the user', () => {const goals = [- ...Array.from({ length: 6 }, (_, index) => goal({ id: `r${index}`, status: 'running' })),- goal({ id: 'd1', status: 'completed' }),+ ...Array.from({ length: 6 }, (_, index) =>+ goal({ goal: { id: `g-r${index}`, status: 'running' }, id: `r${index}` }),+ ),+ goal({ goal: { id: 'g-d1', status: 'review' }, id: 'd1' }),];const { buckets } = resolveHomeGoalView(buildHomeGoalEntries(goals));diff --git a/src/features/HomeInbox/homeGoals.ts b/src/features/HomeInbox/homeGoals.tsindex 43e811d3f00..12fb74e04ee 100644--- a/src/features/HomeInbox/homeGoals.ts+++ b/src/features/HomeInbox/homeGoals.ts@@ -60,19 +60,14 @@ const goalTitle = (goal: GoalListItem) =>* A goal with no acceptance row at all falls back to its task status, which is* the right reading: nothing has judged it yet.*/-export const buildHomeGoalEntries = (- goals: GoalListItem[],- acceptanceStatusByTaskId: Record<string, string> = {},-): HomeGoalEntry[] => {+export const buildHomeGoalEntries = (goals: GoalListItem[]): HomeGoalEntry[] => {const entries = goals.flatMap<HomeGoalEntry>((goal) => {const maxRounds = goal.goal?.maxRounds ?? null;const rounds = goal.totalTopics ?? 0;const { statusKey } = getGoalPresentation({- acceptanceStatus: acceptanceStatusByTaskId[goal.id],- goalStatus: goal.goal?.status,+ goalStatus: goal.goal?.status ?? 'planning',maxRounds,rounds,- taskStatus: goal.status,});if (!isOpenGoalStatus(statusKey)) return [];diff --git a/src/features/HomeInbox/index.tsx b/src/features/HomeInbox/index.tsxindex 4e704c5860d..214e7f024e9 100644--- a/src/features/HomeInbox/index.tsx+++ b/src/features/HomeInbox/index.tsx@@ -15,7 +15,6 @@ import RailCard from '@/features/Home/components/RailCard';import Recommendations, { useRecommendationsVisible } from '@/features/Recommendations';// Direct module import, not the feature barrel: home must not pull the whole// acceptance workspace into its chunk for one hook.-import { useAcceptanceStatuses } from '@/features/Verify/hooks';import { useCacheScope } from '@/libs/swr/useCacheScope';import { useBriefStore } from '@/store/brief';import { briefListSelectors } from '@/store/brief/selectors';@@ -28,7 +27,7 @@ import { authSelectors, userProfileSelectors } from '@/store/user/slices/auth/seimport GoalsRailCard from './GoalsRailCard';import { filterHiddenWidgetSections } from './hiddenWidgets';-import { buildHomeGoalEntries, indexAcceptanceStatuses } from './homeGoals';+import { buildHomeGoalEntries } from './homeGoals';import { resolveInboxBlockState } from './inboxBlockState';import InboxBriefCard from './InboxBriefCard';import MarkAllReadButton from './MarkAllReadButton';@@ -174,22 +173,11 @@ const HomeInbox = memo<HomeInboxProps>((props) => {const goalsSWR = useFetchHomeGoals(showGoals, cacheScope);const goals = useGoalStore(goalSelectors.homeGoals(cacheScope));const isGoalsInit = useGoalStore(goalSelectors.isHomeGoalsInitialized(cacheScope));- const goalIds = useMemo(() => goals.map(({ id }) => id), [goals]);- // One read for every goal's acceptance, instead of two per row β and asked- // about these goals specifically, since the recency-capped acceptance feed- // would drop an older accepted goal and resurrect it as "pending acceptance".- const acceptanceStatuses = useAcceptanceStatuses('task', goalIds, showGoals);- // Which pile a goal lands in depends on that read, so wait for it rather than- // flash an already-accepted goal into "pending acceptance" for a beat. A- // failed read still shows the card, on task status alone.- const goalsResolved =- goalIds.length === 0 || Boolean(acceptanceStatuses.data || acceptanceStatuses.error);+ // The goal rail reads the goal's own lifecycle state (`goals.status`), so it+ // no longer needs a separate acceptance read to decide each pile.const goalEntries = useMemo(- () =>- showGoals && goalsResolved- ? buildHomeGoalEntries(goals, indexAcceptanceStatuses(acceptanceStatuses.data))- : [],- [acceptanceStatuses.data, goals, goalsResolved, showGoals],+ () => (showGoals ? buildHomeGoalEntries(goals) : []),+ [goals, showGoals],);const goalsCollapsed = useGlobalStore(systemStatusSelectors.homeGoalsCollapsed);diff --git a/src/services/goal.ts b/src/services/goal.tsnew file mode 100644index 00000000000..55a4162b9bf--- /dev/null+++ b/src/services/goal.ts@@ -0,0 +1,24 @@+import type { GoalStatus } from '@lobechat/const/goal';++import { lambdaClient } from '@/libs/trpc/client';++export interface GoalListParams {+ agentId?: string;+ limit?: number;+ offset?: number;+ projectId?: string;+ statuses?: GoalStatus[];+}++class GoalService {+ /**+ * List goals. Each item is the execution-carrier task with the goal row+ * attached plus subtree run statistics β see `GoalModel.list` on the server.+ */+ list = async (params: GoalListParams) => lambdaClient.goal.list.query(params);+}++export const goalService = new GoalService();++export type GoalListResult = Awaited<ReturnType<GoalService['list']>>;+export type GoalListItem = GoalListResult['goals'][number];diff --git a/src/store/goal/action.test.ts b/src/store/goal/action.test.tsindex 469d67aaf36..2c48cdec5d7 100644--- a/src/store/goal/action.test.ts+++ b/src/store/goal/action.test.ts@@ -1,12 +1,14 @@import { beforeEach, describe, expect, it, vi } from 'vitest';import { mutate, useClientDataSWR } from '@/libs/swr';+import { goalService } from '@/services/goal';import { taskService } from '@/services/task';import { useGoalStore } from './index';vi.mock('@/libs/swr', () => ({ mutate: vi.fn(), useClientDataSWR: vi.fn() }));-vi.mock('@/services/task', () => ({ taskService: { deleteGoal: vi.fn(), groupList: vi.fn() } }));+vi.mock('@/services/goal', () => ({ goalService: { list: vi.fn() } }));+vi.mock('@/services/task', () => ({ taskService: { deleteGoal: vi.fn() } }));beforeEach(() => {vi.clearAllMocks();@@ -25,15 +27,23 @@ describe('GoalAction', () => {it('stores goal lists independently for each agent', () => {useGoalStore.getState().useFetchGoals('agent-1');const options = vi.mocked(useClientDataSWR).mock.calls[0][2] as {- onSuccess: (value: { data: Array<{ tasks: Array<{ id: string }> }> }) => void;+ onSuccess: (value: { goals: Array<{ id: string }> }) => void;};- options.onSuccess({ data: [{ tasks: [{ id: 'goal-1' }] }] });+ options.onSuccess({ goals: [{ id: 'goal-1' }] });expect(useGoalStore.getState().goalListByAgentId['agent-1']).toEqual([{ id: 'goal-1' }]);expect(useGoalStore.getState().goalListInitializedAgentIds).toContain('agent-1');});+ it('queries the goal list endpoint with an agent-scoped query and cache', () => {+ useGoalStore.getState().useFetchGoals('agent-1');+ const [, fetcher] = vi.mocked(useClientDataSWR).mock.calls[0];++ void (fetcher as () => unknown)();+ expect(goalService.list).toHaveBeenCalledWith(expect.objectContaining({ agentId: 'agent-1' }));+ });+it('uses the complete goal workspace with a project-scoped query and cache', () => {useGoalStore.getState().useFetchGoals(undefined, 'project-1');const [key, fetcher, options] = vi.mocked(useClientDataSWR).mock.calls[0];@@ -41,16 +51,16 @@ describe('GoalAction', () => {expect(key).toEqual(['task:sidebarGroups', 'project:project-1:goals-page']);expect(fetcher).toBeTypeOf('function');void (fetcher as () => unknown)();- expect(taskService.groupList).toHaveBeenCalledWith(- expect.objectContaining({ hasGoal: true, projectId: 'project-1' }),+ expect(goalService.list).toHaveBeenCalledWith(+ expect.objectContaining({ projectId: 'project-1' }),);const onSuccess = (options as {- onSuccess: (value: { data: Array<{ tasks: Array<{ id: string }> }> }) => void;+ onSuccess: (value: { goals: Array<{ id: string }> }) => void;}).onSuccess;- onSuccess({ data: [{ tasks: [{ id: 'project-goal-1' }] }] });+ onSuccess({ goals: [{ id: 'project-goal-1' }] });expect(useGoalStore.getState().goalListByAgentId['project:project-1']).toEqual([{ id: 'project-goal-1' },@@ -62,12 +72,12 @@ describe('GoalAction', () => {useGoalStore.getState().useFetchHomeGoals(true, 'user:ws-b');const optionsOf = (call: number) =>vi.mocked(useClientDataSWR).mock.calls[call][2] as {- onSuccess: (value: { data: Array<{ tasks: Array<{ id: string }> }> }) => void;+ onSuccess: (value: { goals: Array<{ id: string }> }) => void;};// ws-b lands first, then the workspace you already left answers.- optionsOf(1).onSuccess({ data: [{ tasks: [{ id: 'goal-b' }] }] });- optionsOf(0).onSuccess({ data: [{ tasks: [{ id: 'goal-a' }] }] });+ optionsOf(1).onSuccess({ goals: [{ id: 'goal-b' }] });+ optionsOf(0).onSuccess({ goals: [{ id: 'goal-a' }] });expect(useGoalStore.getState().homeGoalsByScope).toEqual({'user:ws-a': [{ id: 'goal-a' }],@@ -76,19 +86,20 @@ describe('GoalAction', () => {expect(useGoalStore.getState().homeGoalsInitializedScopes).toEqual(['user:ws-b', 'user:ws-a']);});- it('asks only for the statuses a goal can still be open in', () => {+ it('asks only for statuses rendered by the home roll-up', () => {useGoalStore.getState().useFetchHomeGoals(true, 'user:ws-a');const fetcher = vi.mocked(useClientDataSWR).mock.calls[0][1] as () => unknown;fetcher();- expect(taskService.groupList).toHaveBeenCalledWith(+ expect(goalService.list).toHaveBeenCalledWith(expect.objectContaining({- groups: [- { key: 'goals', limit: 100, statuses: ['backlog', 'running', 'scheduled', 'completed'] },- ],- hasGoal: true,- parentTaskId: null,+ statuses: ['planning', 'running', 'verifying', 'review'],+ }),+ );+ expect(goalService.list).toHaveBeenCalledWith(+ expect.not.objectContaining({+ statuses: expect.arrayContaining(['paused', 'failed', 'achieved', 'canceled']),}),);});@@ -114,18 +125,12 @@ describe('GoalAction', () => {it('deletes a goal subtree through the goal endpoint and removes it from local state', async () => {useGoalStore.getState().useFetchGoals('agent-1');const options = vi.mocked(useClientDataSWR).mock.calls[0][2] as {- onSuccess: (value: {- data: Array<{ tasks: Array<{ id: string; identifier: string }> }>;- }) => void;+ onSuccess: (value: { goals: Array<{ id: string; identifier: string }> }) => void;};options.onSuccess({- data: [- {- tasks: [- { id: 'goal-1', identifier: 'GOAL-1' },- { id: 'goal-2', identifier: 'GOAL-2' },- ],- },+ goals: [+ { id: 'goal-1', identifier: 'GOAL-1' },+ { id: 'goal-2', identifier: 'GOAL-2' },],});diff --git a/src/store/goal/action.ts b/src/store/goal/action.tsindex 4d04fcad9f2..389fc5f1eac 100644--- a/src/store/goal/action.ts+++ b/src/store/goal/action.ts@@ -1,19 +1,14 @@+import { type GoalStatus, goalStatuses } from '@lobechat/const/goal';+import { mutate, useClientDataSWR } from '@/libs/swr';import { taskKeys } from '@/libs/swr/keys';+import { goalService } from '@/services/goal';import { taskService } from '@/services/task';import type { StoreSetter } from '@/store/types';import type { GoalListFilter, GoalState, GoalViewMode } from './initialState';-const GOAL_STATUSES = [- 'backlog',- 'running',- 'scheduled',- 'paused',- 'completed',- 'failed',- 'canceled',-];+const GOAL_STATUSES: GoalStatus[] = [...goalStatuses];/*** The home roll-up only ever renders goals that are still open, so it asks for@@ -27,7 +22,10 @@ const GOAL_STATUSES = [* that for real needs an acceptance join on the server; this keeps the window* as wide as the query allows in the meantime.*/-const HOME_GOAL_STATUSES = ['backlog', 'running', 'scheduled', 'completed'];+// The home roll-up only renders goals that are still open: terminal states+// (achieved / canceled) stay on the server, `review` is included because a+// converged goal is still awaiting the user's sign-off.+const HOME_GOAL_STATUSES: GoalStatus[] = ['planning', 'running', 'verifying', 'review'];const HOME_GOAL_FETCH_LIMIT = 100;export type GoalStore = GoalState & GoalAction;@@ -89,20 +87,19 @@ export class GoalActionImpl {return useClientDataSWR(scopeId ? taskKeys.sidebarGroups(`${scopeId}:goals-page`) : null,() =>- taskService.groupList({- assigneeAgentId: agentId,- groups: [{ key: 'goals', limit: 100, statuses: GOAL_STATUSES }],- hasGoal: true,- parentTaskId: null,+ goalService.list({+ agentId,+ limit: 100,projectId,+ statuses: GOAL_STATUSES,}),{- onSuccess: ({ data }) => {+ onSuccess: ({ goals }) => {this.#set(({ goalListByAgentId, goalListInitializedAgentIds }) => ({goalListByAgentId: {...goalListByAgentId,- [scopeId!]: data[0]?.tasks ?? [],+ [scopeId!]: goals,},goalListInitializedAgentIds: goalListInitializedAgentIds.includes(scopeId!)? goalListInitializedAgentIds@@ -126,16 +123,15 @@ export class GoalActionImpl {useClientDataSWR(enabled ? taskKeys.homeGoals(scope) : null,() =>- taskService.groupList({- groups: [{ key: 'goals', limit: HOME_GOAL_FETCH_LIMIT, statuses: HOME_GOAL_STATUSES }],- hasGoal: true,- parentTaskId: null,+ goalService.list({+ limit: HOME_GOAL_FETCH_LIMIT,+ statuses: HOME_GOAL_STATUSES,}),{- onSuccess: ({ data }) => {+ onSuccess: ({ goals }) => {this.#set(({ homeGoalsByScope, homeGoalsInitializedScopes }) => ({- homeGoalsByScope: { ...homeGoalsByScope, [scope]: data[0]?.tasks ?? [] },+ homeGoalsByScope: { ...homeGoalsByScope, [scope]: goals },homeGoalsInitializedScopes: homeGoalsInitializedScopes.includes(scope)? homeGoalsInitializedScopes: [...homeGoalsInitializedScopes, scope],diff --git a/src/store/goal/initialState.ts b/src/store/goal/initialState.tsindex 320925e31e3..e2139497588 100644--- a/src/store/goal/initialState.ts+++ b/src/store/goal/initialState.ts@@ -1,6 +1,6 @@-import type { TaskGroupItem } from '@/store/task/slices/list/initialState';+import type { GoalListItem } from '@/services/goal';-export type GoalListItem = TaskGroupItem['tasks'][number];+export type { GoalListItem };export type GoalListFilter = 'active' | 'all';export type GoalViewMode = 'card' | 'list';