🤯 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(task): show the goal a task belongs to on task detail (#20403)
Arvin Xu3f9e0eb1cda9
diff --git a/apps/server/src/services/task/index.test.ts b/apps/server/src/services/task/index.test.tsindex 48a66d4f207..ec98ac168bc 100644--- a/apps/server/src/services/task/index.test.ts+++ b/apps/server/src/services/task/index.test.ts@@ -30,6 +30,15 @@ vi.mock('@/database/models/task', () => ({}),}));+const { findGoalByTaskId } = vi.hoisted(() => ({+ findGoalByTaskId: vi.fn().mockResolvedValue(undefined),+}));+vi.mock('@/database/models/goalGraph', () => ({+ GoalGraphModel: vi.fn().mockImplementation(function () {+ return { findGoalByTaskId };+ }),+}));+vi.mock('@/database/models/taskTopic', () => ({TaskTopicModel: vi.fn(),}));@@ -259,6 +268,12 @@ describe('TaskService', () => {expect(result?.activities).toBeUndefined();expect(result?.workspace).toBeUndefined();expect(result?.parent).toBeNull();+ expect(result?.goal).toBeNull();+ expect(findGoalByTaskId).toHaveBeenCalledWith('task_001');++ findGoalByTaskId.mockResolvedValueOnce({ id: 'goal_1', title: 'G' });+ const withGoal = await service.getTaskDetail('TASK-1');+ expect(withGoal?.goal).toEqual({ id: 'goal_1', title: 'G' });});it('surfaces the effective inherited Acceptance policy', async () => {diff --git a/apps/server/src/services/task/index.ts b/apps/server/src/services/task/index.tsindex cdb4a6ccc12..e55c1151129 100644--- a/apps/server/src/services/task/index.ts+++ b/apps/server/src/services/task/index.ts@@ -20,6 +20,7 @@ import type {import { TRPCError } from '@trpc/server';import { AgentModel } from '@/database/models/agent';+import { GoalGraphModel } from '@/database/models/goalGraph';import { ProjectModel } from '@/database/models/project';import { RbacModel } from '@/database/models/rbac';import {@@ -982,6 +983,7 @@ export class TaskService {activityLogs,workspace,acceptance,+ goal,] = await Promise.all([this.taskModel.findAllDescendants(task.id),this.taskModel.getDependencies(task.id),@@ -990,6 +992,10 @@ export class TaskService {this.taskModel.getActivities(task.id, TASK_DETAIL_ACTIVITY_LIMIT).catch(() => []),this.taskModel.getTreePinnedDocuments(task.id).catch(() => emptyWorkspace),resolveTaskAcceptance(this.db, this.userId, task.id, this.workspaceId).catch(() => undefined),+ // The goal this task belongs to, so the page can link back to it+ new GoalGraphModel(this.db, this.userId, this.workspaceId)+ .findGoalByTaskId(task.id)+ .catch(() => undefined),]);// What the reader is shown, not what was written: a burst of edits to one@@ -1378,6 +1384,7 @@ export class TaskService {description: task.description,editorData: task.editorData ?? undefined,error: task.error,+ goal: goal ?? null,files: taskFiles.length > 0 ? taskFiles : undefined,heartbeat:task.heartbeatInterval || task.heartbeatTimeout || task.lastHeartbeatAtdiff --git a/locales/en-US/chat.json b/locales/en-US/chat.jsonindex a7d9bbe9391..3eaa9fe5417 100644--- a/locales/en-US/chat.json+++ b/locales/en-US/chat.json@@ -1974,6 +1974,7 @@"taskDetail.notFound.title": "Task not found","taskDetail.openDetail": "Open detail","taskDetail.openRunChat": "Open this run’s conversation",+ "taskDetail.partOfGoal": "Part of goal","taskDetail.pauseTask": "Pause task","taskDetail.priority.high": "High","taskDetail.priority.low": "Low",diff --git a/locales/zh-CN/chat.json b/locales/zh-CN/chat.jsonindex 9cd0985c4f8..4159fb642bb 100644--- a/locales/zh-CN/chat.json+++ b/locales/zh-CN/chat.json@@ -1974,6 +1974,7 @@"taskDetail.notFound.title": "找不到该任务","taskDetail.openDetail": "展开详情","taskDetail.openRunChat": "打开这次运行的对话",+ "taskDetail.partOfGoal": "隶属于目标","taskDetail.pauseTask": "暂停任务","taskDetail.priority.high": "高","taskDetail.priority.low": "低",diff --git a/packages/database/src/models/__tests__/goalGraph.test.ts b/packages/database/src/models/__tests__/goalGraph.test.tsindex d77f16e39a2..06ac3b4d76c 100644--- a/packages/database/src/models/__tests__/goalGraph.test.ts+++ b/packages/database/src/models/__tests__/goalGraph.test.ts@@ -4,7 +4,7 @@ import { eq } from 'drizzle-orm';import { afterEach, beforeEach, describe, expect, it } from 'vitest';import { getTestDB } from '../../core/getTestDB';-import { agents, goalNodes, goals, topics, users, workspaces } from '../../schemas';+import { agents, goalNodes, goals, tasks, topics, users, workspaces } from '../../schemas';import type { LobeChatDatabase } from '../../type';import { GoalModel } from '../goal';import { GoalGraphModel } from '../goalGraph';@@ -178,6 +178,71 @@ describe('GoalGraphModel', () => {expect(graph?.events.filter((event) => event.entityType === 'task')).toHaveLength(1);});+ it('finds the goal a task belongs to, as a node task, the carrier, or via an ancestor', async () => {+ const taskModel = new TaskModel(serverDB, userId);+ const [nodeTask, carrierTask, looseTask] = await Promise.all([+ taskModel.create({ instruction: 'Node task' }),+ taskModel.create({ instruction: 'Carrier task' }),+ taskModel.create({ instruction: 'Loose task' }),+ ]);+ const goal = await goalModel.create({ subjectType: 'standalone', title: 'Owning goal' });+ const node = await graphModel.createNode(goal.id, { kind: 'task', title: 'Do it' });+ await graphModel.claimTaskNode(goal.id, node!.id, new Date(0));+ await graphModel.bindTask(goal.id, node!.id, nodeTask.id);+ const carrierGoal = await goalModel.create({+ subjectId: carrierTask.id,+ subjectType: 'task',+ title: 'Carrier goal',+ });++ const child = await taskModel.create({ instruction: 'Child', parentTaskId: nodeTask.id });+ const grandchild = await taskModel.create({+ instruction: 'Grandchild',+ parentTaskId: child.id,+ });++ expect(await graphModel.findGoalByTaskId(nodeTask.id)).toEqual({+ id: goal.id,+ title: 'Owning goal',+ });+ // Subtasks a goal task spawns belong to the same goal.+ expect((await graphModel.findGoalByTaskId(grandchild.id))?.id).toBe(goal.id);+ expect((await graphModel.findGoalByTaskId(carrierTask.id))?.id).toBe(carrierGoal.id);+ // The nearest goal wins: a subtask carrying its own goal links to that one.+ const nested = await taskModel.create({ instruction: 'Nested', parentTaskId: nodeTask.id });+ const nestedGoal = await goalModel.create({+ subjectId: nested.id,+ subjectType: 'task',+ title: 'Nested goal',+ });+ expect((await graphModel.findGoalByTaskId(nested.id))?.id).toBe(nestedGoal.id);+ expect(await graphModel.findGoalByTaskId(looseTask.id)).toBeUndefined();+ expect(+ await new GoalGraphModel(serverDB, otherUserId).findGoalByTaskId(nodeTask.id),+ ).toBeUndefined();+ });++ it('finds the goal through a task chain deeper than 32 levels and stops on a cycle', async () => {+ const taskModel = new TaskModel(serverDB, userId);+ const root = await taskModel.create({ instruction: 'Root' });+ const goal = await goalModel.create({+ subjectId: root.id,+ subjectType: 'task',+ title: 'Deep goal',+ });+ let leaf = root;+ for (let i = 0; i < 40; i++) {+ leaf = await taskModel.create({ instruction: `Level ${i}`, parentTaskId: leaf.id });+ }+ expect((await graphModel.findGoalByTaskId(leaf.id))?.id).toBe(goal.id);++ // A corrupt cycle (a -> b -> a) must terminate instead of recursing forever.+ const a = await taskModel.create({ instruction: 'Cycle A' });+ const b = await taskModel.create({ instruction: 'Cycle B', parentTaskId: a.id });+ await serverDB.update(tasks).set({ parentTaskId: b.id }).where(eq(tasks.id, a.id));+ expect(await graphModel.findGoalByTaskId(b.id)).toBeUndefined();+ });+it('refuses to bind a task to a node retired while the task was being created', async () => {// Retirement fences the node before it looks for bound Tasks; a Task a// concurrent coordinator finishes creating afterwards must not flip thediff --git a/packages/database/src/models/goalGraph.ts b/packages/database/src/models/goalGraph.tsindex 7a5ff9eb0a5..b45b3458ae8 100644--- a/packages/database/src/models/goalGraph.ts+++ b/packages/database/src/models/goalGraph.ts@@ -385,6 +385,67 @@ export class GoalGraphModel {return row?.count ?? 0;};+ /**+ * The goal a task belongs to — as the responsible Task of one of its nodes,+ * as the goal's own execution carrier, or through the nearest ancestor that is+ * either (goal Tasks spawn their own subtasks). Lets a Task page link back to+ * the goal that owns it.+ */+ findGoalByTaskId = async (taskId: string): Promise<{ id: string; title: string } | undefined> => {+ // Walk up `parent_task_id`, nearest first. The task tree has no depth limit,+ // so stop on a revisited id instead of a fixed depth: a corrupt cycle ends+ // without truncating a valid deep chain.+ const chain = await this.db.execute<{ depth: number; id: string }>(sql`+ WITH RECURSIVE chain(id, depth, visited) AS (+ SELECT ${tasks.id}, 0, ARRAY[${tasks.id}] FROM ${tasks} WHERE ${tasks.id} = ${taskId}+ UNION ALL+ SELECT ${tasks.parentTaskId}, chain.depth + 1, chain.visited || ${tasks.parentTaskId}+ FROM ${tasks} JOIN chain ON ${tasks.id} = chain.id+ WHERE ${tasks.parentTaskId} IS NOT NULL+ AND NOT (${tasks.parentTaskId} = ANY(chain.visited))+ )+ SELECT id, depth FROM chain+ `);+ const depthOf = new Map(chain.rows.map((row) => [row.id, Number(row.depth)]));+ if (depthOf.size === 0) return undefined;+ const taskIds = [...depthOf.keys()];++ const rows = await this.db+ .select({+ carrierTaskId: goals.subjectId,+ createdAt: goals.createdAt,+ id: goals.id,+ nodeTaskId: goalNodes.taskId,+ subjectType: goals.subjectType,+ title: goals.title,+ })+ .from(goals)+ .leftJoin(goalNodes, and(eq(goalNodes.goalId, goals.id), inArray(goalNodes.taskId, taskIds)))+ .where(+ and(+ this.ownership(),+ or(+ inArray(goalNodes.taskId, taskIds),+ and(eq(goals.subjectType, 'task'), inArray(goals.subjectId, taskIds)),+ ),+ ),+ );++ const depthOfRow = (row: (typeof rows)[number]) =>+ Math.min(+ row.nodeTaskId ? (depthOf.get(row.nodeTaskId) ?? Infinity) : Infinity,+ row.subjectType === 'task' && row.carrierTaskId+ ? (depthOf.get(row.carrierTaskId) ?? Infinity)+ : Infinity,+ );+ const [nearest] = rows.sort(+ (a, b) =>+ depthOfRow(a) - depthOfRow(b) ||+ new Date(b.createdAt).getTime() - new Date(a.createdAt).getTime(),+ );+ return nearest ? { id: nearest.id, title: nearest.title } : undefined;+ };+createNode = async (goalId: string, input: CreateNodeInput) =>this.db.transaction(async (tx) => {if (!(await this.ownedGoal(goalId, tx))) return undefined;diff --git a/packages/locales/src/default/chat.ts b/packages/locales/src/default/chat.tsindex 1d086e34a6d..e00c696e6a8 100644--- a/packages/locales/src/default/chat.ts+++ b/packages/locales/src/default/chat.ts@@ -1746,6 +1746,7 @@ export default {'taskDetail.cancelSchedule': 'Cancel schedule','taskDetail.nextRunCountdown': 'Next run in {{countdown}}','taskDetail.nextRunCountdownDays': 'Next run in {{days}}d {{hours}}h',+ 'taskDetail.partOfGoal': 'Part of goal','taskDetail.pauseTask': 'Pause task','taskDetail.rerunTask': 'Re-run task','taskDetail.runNow': 'Run now',diff --git a/packages/types/src/task/index.ts b/packages/types/src/task/index.tsindex e5dcf5d2dfa..8bf0b1aac25 100644--- a/packages/types/src/task/index.ts+++ b/packages/types/src/task/index.ts@@ -610,6 +610,8 @@ export interface TaskDetailData {error?: string | null;/** Files attached to the task instruction (persistent context for every run). */files?: ChatFileItem[];+ /** The goal this task (or its nearest goal-bound ancestor) belongs to; null when none. */+ goal?: { id: string; title: string } | null;// heartbeat.interval: periodic execution interval | heartbeat.timeout+lastAt: watchdog monitoring (detects stuck tasks)heartbeat?: {interval?: number | null;diff --git a/src/features/AgentTasks/AgentTaskDetail/TaskDetailSections.tsx b/src/features/AgentTasks/AgentTaskDetail/TaskDetailSections.tsxindex 97ec6cb7a31..f1ea24026ff 100644--- a/src/features/AgentTasks/AgentTaskDetail/TaskDetailSections.tsx+++ b/src/features/AgentTasks/AgentTaskDetail/TaskDetailSections.tsx@@ -9,6 +9,7 @@ import { taskDetailLayoutStyles as styles } from './taskDetailLayoutStyles';import TaskDetailRunPauseAction from './TaskDetailRunPauseAction';import TaskDetailTitleInput from './TaskDetailTitleInput';import TaskExecutionConfig from './TaskExecutionConfig';+import TaskGoalBar from './TaskGoalBar';import TaskInstruction from './TaskInstruction';import TaskModelConfig from './TaskModelConfig';import TaskParentBar from './TaskParentBar';@@ -26,6 +27,7 @@ const TaskDetailSections = memo(() => {<div className={styles.root}><div className={styles.header}><Flexbox className={styles.main} gap={12}>+ <TaskGoalBar /><TaskParentBar /><TaskDetailTitleInput /><Flexbox horizontal align={'center'} gap={8} style={{ maxWidth: '100%' }} wrap={'wrap'}>diff --git a/src/features/AgentTasks/AgentTaskDetail/TaskGoalBar.tsx b/src/features/AgentTasks/AgentTaskDetail/TaskGoalBar.tsxnew file mode 100644index 00000000000..6173d09ee7d--- /dev/null+++ b/src/features/AgentTasks/AgentTaskDetail/TaskGoalBar.tsx@@ -0,0 +1,53 @@+import { Flexbox, Icon } from '@lobehub/ui';+import { Button, Text } from '@lobehub/ui/base-ui';+import { TargetIcon } from 'lucide-react';+import { memo } from 'react';+import { useTranslation } from 'react-i18next';++import { useWorkspaceAwareNavigate } from '@/features/Workspace/useWorkspaceAwareNavigate';+import { useTaskStore } from '@/store/task';+import { taskDetailSelectors } from '@/store/task/selectors';++import { hasGoalPage } from './goalPageLink';++/** "Part of goal" link back to the goal that drives this task, mirroring the parent-task bar. */+const TaskGoalBar = memo(() => {+ const { t } = useTranslation('chat');+ const navigate = useWorkspaceAwareNavigate();+ const goal = useTaskStore(taskDetailSelectors.activeTaskGoal);++ if (!goal) return null;++ return (+ <Flexbox horizontal align="center" gap={8} style={{ maxWidth: '100%', minWidth: 0 }}>+ <Text fontSize={12} style={{ flex: 'none' }} type={'secondary'}>+ {t('taskDetail.partOfGoal')}+ </Text>+ {!hasGoalPage() ? (+ // The mobile router has no goal page, so name the goal without linking it.+ <Flexbox horizontal align="center" gap={6} style={{ minWidth: 0 }}>+ <Icon icon={TargetIcon} size={16} style={{ flex: 'none' }} />+ <Text ellipsis style={{ minWidth: 0 }} weight={500}>+ {goal.title}+ </Text>+ </Flexbox>+ ) : (+ <Button+ icon={<Icon icon={TargetIcon} size={16} />}+ size={'small'}+ style={{ maxWidth: '100%', minWidth: 0 }}+ type={'text'}+ // The agent-less route: the goal's supervising agent may be private to its+ // creator or gated by Agent Lab, while the goal itself stays readable.+ onClick={() => navigate(`/goal/${goal.id}`)}+ >+ <Text ellipsis style={{ minWidth: 0 }} weight={500}>+ {goal.title}+ </Text>+ </Button>+ )}+ </Flexbox>+ );+});++export default TaskGoalBar;diff --git a/src/features/AgentTasks/AgentTaskDetail/goalPageLink.test.ts b/src/features/AgentTasks/AgentTaskDetail/goalPageLink.test.tsnew file mode 100644index 00000000000..fd0a0db6cdb--- /dev/null+++ b/src/features/AgentTasks/AgentTaskDetail/goalPageLink.test.ts@@ -0,0 +1,19 @@+import { afterEach, describe, expect, it, vi } from 'vitest';++import { hasGoalPage } from './goalPageLink';++describe('hasGoalPage', () => {+ afterEach(() => {+ vi.unstubAllGlobals();+ });++ it('is true on the desktop/web bundle', () => {+ vi.stubGlobal('__MOBILE__', false);+ expect(hasGoalPage()).toBe(true);+ });++ it('is false on the mobile bundle regardless of viewport width', () => {+ vi.stubGlobal('__MOBILE__', true);+ expect(hasGoalPage()).toBe(false);+ });+});diff --git a/src/features/AgentTasks/AgentTaskDetail/goalPageLink.ts b/src/features/AgentTasks/AgentTaskDetail/goalPageLink.tsnew file mode 100644index 00000000000..0640cb9fbe2--- /dev/null+++ b/src/features/AgentTasks/AgentTaskDetail/goalPageLink.ts@@ -0,0 +1,7 @@+/**+ * Whether this bundle registers the agent-less `/goal/:goalId` page. The mobile+ * router does not, and it is chosen by the bundle (`entry.mobile.tsx`), not by the+ * viewport — a landscape phone above the mobile breakpoint is still the mobile+ * router. Read per call so a test can stub `__MOBILE__`.+ */+export const hasGoalPage = () => !(typeof __MOBILE__ !== 'undefined' && __MOBILE__);diff --git a/src/store/task/selectors/detailSelectors.ts b/src/store/task/selectors/detailSelectors.tsindex 30c8e8e9dc2..81215035d60 100644--- a/src/store/task/selectors/detailSelectors.ts+++ b/src/store/task/selectors/detailSelectors.ts@@ -57,6 +57,8 @@ const activeTaskDependencies = (s: TaskStoreState) => activeTaskDetail(s)?.depenconst activeTaskParent = (s: TaskStoreState) => activeTaskDetail(s)?.parent;+const activeTaskGoal = (s: TaskStoreState) => activeTaskDetail(s)?.goal;+// Periodic execution interval (seconds); 0 or undefined means not configuredconst activeTaskPeriodicInterval = (s: TaskStoreState) =>activeTaskDetail(s)?.heartbeat?.interval ?? 0;@@ -144,6 +146,7 @@ export const taskDetailSelectors = {activeTaskInstruction,activeTaskInstructionRevision,activeTaskName,+ activeTaskGoal,activeTaskParent,activeTaskPeriodicInterval,activeTaskPriority,