🤯 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): continue a goal past its creation limits and render goal links as goals (#19967)
Arvin Xuaa0f67c818c6
diff --git a/apps/cli/src/commands/goal.test.ts b/apps/cli/src/commands/goal.test.tsindex 76be51a8353..216d8919e7c 100644--- a/apps/cli/src/commands/goal.test.ts+++ b/apps/cli/src/commands/goal.test.ts@@ -11,6 +11,7 @@ const { mockClient } = vi.hoisted(() => ({submitPlan: { mutate: vi.fn() },submitOperationPlan: { mutate: vi.fn() },graph: { query: vi.fn() },+ setBudget: { mutate: vi.fn() },supervision: { query: vi.fn() },tick: { mutate: vi.fn() },},@@ -489,3 +490,40 @@ describe('goal supervision command', () => {expect(mockClient.goal.tick.mutate).not.toHaveBeenCalled();});});++describe('goal set-budget command', () => {+ beforeEach(() => {+ vi.clearAllMocks();+ vi.spyOn(log, 'info').mockImplementation(() => {});+ });++ it('edits the limits a goal was created with, so it can continue instead of being copied', async () => {+ mockClient.goal.setBudget.mutate.mockResolvedValue({ message: 'Goal budget updated' });++ await createProgram().parseAsync([+ 'node',+ 'test',+ 'goal',+ 'set-budget',+ 'goal-1',+ '--max-manager-turns',+ '60',+ '--max-concurrent-tasks',+ '1',+ '--max-attempts-per-task',+ '5',+ '--max-steps-per-run',+ 'none',+ ]);++ expect(mockClient.goal.setBudget.mutate).toHaveBeenCalledWith(+ expect.objectContaining({+ id: 'goal-1',+ maxAttemptsPerTask: 5,+ maxConcurrentTasks: 1,+ maxManagerTurns: 60,+ maxStepsPerRun: null,+ }),+ );+ });+});diff --git a/apps/cli/src/commands/goal.ts b/apps/cli/src/commands/goal.tsindex 0fa6b1c8568..52019b00fcd 100644--- a/apps/cli/src/commands/goal.ts+++ b/apps/cli/src/commands/goal.ts@@ -533,10 +533,28 @@ export function registerGoalCommand(program: Command) {.option('--max-rounds <n>').option('--max-cost <usd>').option('--max-experiments <n>', 'Exploration experiment cap (1–200)')+ .option(+ '--max-manager-turns <n>',+ 'Main Agent turn cap (1–100); raising it resumes a goal it paused',+ )+ .option(+ '--max-concurrent-tasks <n>',+ 'Tasks allowed to run at once (1–10; "none" restores the default)',+ )+ .option('--max-attempts-per-task <n>', 'Attempts per Task before opening a decision gate')+ .option('--max-steps-per-run <n>', 'Agent step cap per Task run ("none" removes it)').action(async (id: string,- options: { maxCost?: string; maxRounds?: string; maxExperiments?: string },+ options: {+ maxAttemptsPerTask?: string;+ maxConcurrentTasks?: string;+ maxCost?: string;+ maxExperiments?: string;+ maxManagerTurns?: string;+ maxRounds?: string;+ maxStepsPerRun?: string;+ },) => {const parseLimit = (value: string | undefined, integer = false) =>value === undefined@@ -550,9 +568,19 @@ export function registerGoalCommand(program: Command) {await getTrpcClient()).goal.setBudget.mutate({id,+ maxAttemptsPerTask:+ options.maxAttemptsPerTask === undefined+ ? undefined+ : Number.parseInt(options.maxAttemptsPerTask, 10),+ maxConcurrentTasks: parseLimit(options.maxConcurrentTasks, true),maxExperiments:options.maxExperiments === undefined ? undefined : Number(options.maxExperiments),+ maxManagerTurns:+ options.maxManagerTurns === undefined+ ? undefined+ : Number.parseInt(options.maxManagerTurns, 10),maxRounds: parseLimit(options.maxRounds, true),+ maxStepsPerRun: parseLimit(options.maxStepsPerRun, true),maxTotalCost: parseLimit(options.maxCost),});log.info(result.message);diff --git a/apps/server/src/routers/lambda/goal.ts b/apps/server/src/routers/lambda/goal.tsindex bd171216c1a..0bc5c45f82e 100644--- a/apps/server/src/routers/lambda/goal.ts+++ b/apps/server/src/routers/lambda/goal.ts@@ -11,6 +11,10 @@ import { serverDatabase } from '@/libs/trpc/lambda/middleware';import { GoalService } from '@/server/services/goal';import { advanceGoal } from '@/server/services/goal/advanceGoal';import { GoalManagerService, goalPlanSchema } from '@/server/services/goal/manager';+import {+ DEFAULT_MANAGER_MAX_TURNS,+ managerTurnsSpent,+} from '@/server/services/goal/recoveryPolicy';import { scheduleGoalAdvance } from '@/server/services/goal/scheduler';import {HeteroOperationPrincipalError,@@ -560,7 +564,13 @@ export const goalRouter = router({userId: ctx.userId,workspaceId: ctx.workspaceId ?? undefined,});- return { data, message: 'Goal resumed', success: true };+ // Resuming does not give the main Agent more turns, so a goal it paused+ // for running out would stop again on the next tick. Say how to continue+ // it instead of leaving the caller to replace it with a new goal.+ const message = managerTurnsSpent(data.config)+ ? `Goal resumed, but its main Agent has used all ${data.config?.manager?.maxTurns ?? DEFAULT_MANAGER_MAX_TURNS} turns and it will pause again. Raise the cap with: lh goal set-budget ${input.id} --max-manager-turns <n>`+ : 'Goal resumed';+ return { data, message, success: true };} catch (error) {mapGoalError(error, 'resume');}@@ -673,8 +683,15 @@ export const goalRouter = router({idInput.extend({/** ISO-8601 calendar-time budget; null clears the deadline. */deadline: z.string().datetime().nullable().optional(),+ maxAttemptsPerTask: z.number().int().positive().optional(),+ /** null restores the default concurrency. */+ maxConcurrentTasks: z.number().int().min(1).max(10).nullable().optional(),maxExperiments: z.number().int().min(1).max(200).optional(),+ /** Main Agent turn cap; only for a goal that has a main Agent. */+ maxManagerTurns: z.number().int().min(1).max(100).optional(),maxRounds: z.number().int().positive().nullable().optional(),+ /** null removes the per-run step cap. */+ maxStepsPerRun: z.number().int().positive().nullable().optional(),maxTotalCost: z.number().positive().nullable().optional(),}),)diff --git a/apps/server/src/services/goal/index.test.ts b/apps/server/src/services/goal/index.test.tsindex ae5a14a9117..f5a906f2bf9 100644--- a/apps/server/src/services/goal/index.test.ts+++ b/apps/server/src/services/goal/index.test.ts@@ -718,6 +718,77 @@ describe('GoalService', () => {expect(raised?.status).not.toBe('paused');});+ describe('limits a goal was created with', () => {+ // A goal its main Agent paused for running out of turns: resuming it alone+ // pauses it again, which is what pushed agents into creating a copy of it.+ const turnSpentGoal = async (service: GoalService) => {+ const graph = await service.create({+ tasks: ['Keep working'],+ title: 'Out of main Agent turns',+ });+ const current = (await service.graph(graph.goal.id)).goal;+ await serverDB+ .update(goals)+ .set({+ config: {+ ...current.config,+ manager: { maxTurns: 2 },+ managerState: { turns: 2 } as never,+ },+ status: 'paused',+ })+ .where(eq(goals.id, graph.goal.id));+ return graph.goal.id;+ };++ it('resumes a goal its main Agent paused once the turn cap is raised', async () => {+ const service = new GoalService(serverDB, userId);+ const goalId = await turnSpentGoal(service);++ const raised = await service.setBudget(goalId, { maxManagerTurns: 20 });++ expect(raised.config?.manager?.maxTurns).toBe(20);+ expect(raised.status).not.toBe('paused');+ });++ it('keeps a goal paused when the raised cap is still spent', async () => {+ const service = new GoalService(serverDB, userId);+ const goalId = await turnSpentGoal(service);++ expect((await service.setBudget(goalId, { maxManagerTurns: 2 })).status).toBe('paused');+ });++ it('edits the execution limits without dropping the rest of the config', async () => {+ const service = new GoalService(serverDB, userId);+ const graph = await service.create({+ config: { recovery: { maxAttemptsPerTask: 3, maxStepsPerRun: 200 } },+ tasks: ['Run'],+ title: 'Editable limits',+ });++ const updated = await service.setBudget(graph.goal.id, {+ maxAttemptsPerTask: 5,+ maxConcurrentTasks: 1,+ maxStepsPerRun: null,+ });++ expect(updated.config?.maxConcurrentTasks).toBe(1);+ expect(updated.config?.recovery).toMatchObject({+ maxAttemptsPerTask: 5,+ maxStepsPerRun: null,+ });+ });++ it('rejects a turn cap for a goal without a main Agent', async () => {+ const service = new GoalService(serverDB, userId);+ const graph = await service.create({ tasks: ['Run'], title: 'No main Agent' });++ await expect(service.setBudget(graph.goal.id, { maxManagerTurns: 20 })).rejects.toThrow(+ 'Only a Goal with a main Agent has a turn budget',+ );+ });+ });+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'sdiff --git a/apps/server/src/services/goal/index.ts b/apps/server/src/services/goal/index.tsindex a04d49ea8f9..1186cf99ed2 100644--- a/apps/server/src/services/goal/index.ts+++ b/apps/server/src/services/goal/index.ts@@ -60,8 +60,10 @@ import {import { experimentResults, exploreGraph } from './exploreGraph';import { answeredProblem, GoalManagerService, problemKey } from './manager';import {+ DEFAULT_MANAGER_MAX_TURNS,DEVICE_RECONNECT_WAIT_MS,isDeviceUnavailableFailure,+ managerTurnsSpent,resolveMaxConcurrentTasks,resolveOperationLeaseTimeout,resolveTaskMaxSteps,@@ -317,7 +319,7 @@ export class GoalService {message: 'A main Agent requires the goal agent',});}- const turns = managerOptions?.maxTurns ?? 12;+ const turns = managerOptions?.maxTurns ?? DEFAULT_MANAGER_MAX_TURNS;if (!Number.isInteger(turns) || turns < 1 || turns > 100)throw new TRPCError({code: 'BAD_REQUEST',@@ -1277,13 +1279,18 @@ export class GoalService {goalId: string,budget: {deadline?: string | null;+ maxAttemptsPerTask?: number;+ maxConcurrentTasks?: number | null;maxExperiments?: number;+ maxManagerTurns?: number;maxRounds?: number | null;+ maxStepsPerRun?: number | null;maxTotalCost?: number | null;},) => {const before = await this.requireGraph(goalId);const wasBinding = await this.evaluateBudget(before.goal, before);+ const managerTurnsWereSpent = managerTurnsSpent(before.goal.config);// Deadline joins the two execution budgets on the goal row's config; null// clears it, and omitting it leaves it alone — the cost/round editor sends@@ -1307,6 +1314,29 @@ export class GoalService {if (budget.deadline !== undefined) {config.schedule = { ...config.schedule, deadline: budget.deadline };}+ // The limits a goal is created with stay editable: a goal that ran into one+ // must be continued with a higher one, not replaced by a copy of itself.+ if (budget.maxManagerTurns !== undefined) {+ if (!config.manager) {+ throw new TRPCError({+ code: 'BAD_REQUEST',+ message: 'Only a Goal with a main Agent has a turn budget',+ });+ }+ config.manager = { ...config.manager, maxTurns: budget.maxManagerTurns };+ }+ if (budget.maxConcurrentTasks !== undefined) {+ config.maxConcurrentTasks = budget.maxConcurrentTasks;+ }+ if (budget.maxAttemptsPerTask !== undefined || budget.maxStepsPerRun !== undefined) {+ config.recovery = {+ ...config.recovery,+ ...(budget.maxAttemptsPerTask !== undefined && {+ maxAttemptsPerTask: budget.maxAttemptsPerTask,+ }),+ ...(budget.maxStepsPerRun !== undefined && { maxStepsPerRun: budget.maxStepsPerRun }),+ };+ }const goal = await this.goalModel.update(goalId, {config,@@ -1324,10 +1354,13 @@ export class GoalService {const stoppedByBudget =wasBinding.costLimitReached || wasBinding.roundLimitReached || wasBinding.deadlinePassed;const stoppedByExploration = before.goal.config?.pausedBy === 'exploration_limit';+ // The main Agent pauses its goal when its turns run out, and resuming alone+ // pauses it again on the next tick. Raising the cap is what lets it continue.+ const stoppedByManagerTurns = managerTurnsWereSpent && !managerTurnsSpent(goal.config);if (goal.status !== 'paused' ||goal.config?.pausedBy === 'user' ||- (!stoppedByBudget && !stoppedByExploration)+ (!stoppedByBudget && !stoppedByExploration && !stoppedByManagerTurns))return goal;if (diff --git a/apps/server/src/services/goal/manager.ts b/apps/server/src/services/goal/manager.tsindex 70d08fe0d87..91f905aed5e 100644--- a/apps/server/src/services/goal/manager.ts+++ b/apps/server/src/services/goal/manager.ts@@ -23,6 +23,7 @@ import { goals } from '@/database/schemas/goal';import type { LobeChatDatabase } from '@/database/type';import { AiAgentService } from '@/server/services/aiAgent';+import { DEFAULT_MANAGER_MAX_TURNS } from './recoveryPolicy';import { scheduleGoalAdvance } from './scheduler';import { recoveryEligibility } from './supervisor/policy';@@ -479,7 +480,10 @@ export class GoalManagerService {const blocked = await this.uninvitedTurnBlocked(graph, unfinished, tasks);if (blocked) return null;}- if ((state?.turns ?? 0) >= (policy.maxTurns ?? 12) || (await this.budgetBlocked(graph))) {+ if (+ (state?.turns ?? 0) >= (policy.maxTurns ?? DEFAULT_MANAGER_MAX_TURNS) ||+ (await this.budgetBlocked(graph))+ ) {// An invited turn declines instead of pausing. The caller was about to open// a gate carrying the actual problem; pausing here would replace that// question with "the main Agent is out of turns" and lose it.@@ -504,7 +508,8 @@ export class GoalManagerService {const current = await this.graph(db).getGraph(goal.id);if (!current || managerSnapshot(current) !== managerSnapshot(graph)) return;if (- (fresh.config?.managerState?.turns ?? 0) >= (fresh.config?.manager?.maxTurns ?? 12) ||+ (fresh.config?.managerState?.turns ?? 0) >=+ (fresh.config?.manager?.maxTurns ?? DEFAULT_MANAGER_MAX_TURNS) ||(await this.budgetBlocked(current, db)))return;diff --git a/apps/server/src/services/goal/recoveryPolicy.ts b/apps/server/src/services/goal/recoveryPolicy.tsindex a48a7bff8ce..ff36dfe359d 100644--- a/apps/server/src/services/goal/recoveryPolicy.ts+++ b/apps/server/src/services/goal/recoveryPolicy.ts@@ -20,6 +20,8 @@ const DEFAULT_MAX_ATTEMPTS_PER_TASK = 8;* anyone sees a result.*/const DEFAULT_MAX_CONCURRENT_TASKS = 3;+/** Turns a goal's main Agent gets when its manager policy does not set its own. */+export const DEFAULT_MANAGER_MAX_TURNS = 12;const MAX_CONCURRENT_TASKS_CEILING = 10;const DEFAULT_OPERATION_LEASE_TIMEOUT_MS = 5 * 60 * 1000;// Agent runtime refreshes the durable operation lease every third 30-second@@ -90,3 +92,8 @@ export const isDeviceUnavailableFailure = (error?: string | null): boolean =>DEVICE_UNAVAILABLE_CODES.some((code) => error.includes(code) || error.includes(HETERO_DISPATCH_ERROR_HEADLINES[code]),);++/** Whether a goal's main Agent has used every turn its policy allows. */+export const managerTurnsSpent = (config: GoalItem['config']): boolean =>+ !!config?.manager &&+ (config.managerState?.turns ?? 0) >= (config.manager.maxTurns ?? DEFAULT_MANAGER_MAX_TURNS);diff --git a/locales/en-US/chat.json b/locales/en-US/chat.jsonindex 9b3a37f80d0..33fd1b781e7 100644--- a/locales/en-US/chat.json+++ b/locales/en-US/chat.json@@ -1128,6 +1128,7 @@"internalLink.preview.acceptanceRounds_other": "{{count}} verification rounds","internalLink.preview.agent": "Agent","internalLink.preview.document": "Page",+ "internalLink.preview.goal": "Goal","internalLink.preview.task": "Task","internalLink.preview.verify": "Verification report","internalLink.preview.verifyCounts": "{{passed}} passed · {{failed}} failed · {{uncertain}} uncertain",diff --git a/locales/zh-CN/chat.json b/locales/zh-CN/chat.jsonindex fc1cb981d76..918cd85f568 100644--- a/locales/zh-CN/chat.json+++ b/locales/zh-CN/chat.json@@ -1128,6 +1128,7 @@"internalLink.preview.acceptanceRounds_other": "{{count}} 轮验证","internalLink.preview.agent": "Agent","internalLink.preview.document": "页面",+ "internalLink.preview.goal": "目标","internalLink.preview.task": "任务","internalLink.preview.verify": "验证报告","internalLink.preview.verifyCounts": "已通过 {{passed}} · 未通过 {{failed}} · 不确定 {{uncertain}}",diff --git a/packages/locales/src/default/chat.ts b/packages/locales/src/default/chat.tsindex 4ccd25a7e9b..d54511b5148 100644--- a/packages/locales/src/default/chat.ts+++ b/packages/locales/src/default/chat.ts@@ -3146,6 +3146,7 @@ export default {'internalLink.preview.acceptanceRounds_other': '{{count}} verification rounds','internalLink.preview.agent': 'Agent','internalLink.preview.document': 'Page',+ 'internalLink.preview.goal': 'Goal','internalLink.preview.task': 'Task','internalLink.preview.verify': 'Verification report','internalLink.preview.verifyCounts':diff --git a/src/features/Conversation/Markdown/plugins/Link/Render/InternalEntityLink.tsx b/src/features/Conversation/Markdown/plugins/Link/Render/InternalEntityLink.tsxindex 81b58e7e3b1..3e4bc0980dc 100644--- a/src/features/Conversation/Markdown/plugins/Link/Render/InternalEntityLink.tsx+++ b/src/features/Conversation/Markdown/plugins/Link/Render/InternalEntityLink.tsx@@ -10,6 +10,7 @@ import {CheckCircleIcon,CheckSquareIcon,FileTextIcon,+ TargetIcon,} from 'lucide-react';import type { MouseEvent } from 'react';import { memo, useCallback } from 'react';@@ -22,7 +23,7 @@ import { agentDocumentService, agentDocumentSWRKeys } from '@/services/agentDocuimport { useAgentStore } from '@/store/agent';import { useChatStore } from '@/store/chat';-import { type InternalLinkReference, isBareLinkLabel } from '../internalLink';+import { type InternalLinkReference, isBareLinkLabel, isEntityIdLabel } from '../internalLink';import {getPreviewData,InternalEntityPreview,@@ -70,6 +71,7 @@ const ENTITY_ICONS = {acceptance: BadgeCheckIcon,agent: BotIcon,document: FileTextIcon,+ goal: TargetIcon,task: CheckSquareIcon,verify: CheckCircleIcon,} as const;@@ -84,14 +86,21 @@ export const InternalEntityLink = memo<InternalEntityLinkProps>(({ href, label,const { t } = useTranslation('chat');const navigate = useWorkspaceAwareNavigate();const activeAgentId = useAgentStore((s) => s.activeAgentId);- const [openAcceptance, openAgentDetail, openDocument, openTaskDetail, openVerifyReport] =- useChatStore((s) => [- s.openAcceptance,- s.openAgentDetail,- s.openDocument,- s.openTaskDetail,- s.openVerifyReport,- ]);+ const [+ openAcceptance,+ openAgentDetail,+ openDocument,+ openGoal,+ openTaskDetail,+ openVerifyReport,+ ] = useChatStore((s) => [+ s.openAcceptance,+ s.openAgentDetail,+ s.openDocument,+ s.openGoal,+ s.openTaskDetail,+ s.openVerifyReport,+ ]);// A pasted URL says nothing about what it points to, so resolve the entity's// own title and show that instead — the same read the hover preview makes,// under the same key, so the eager fetch also makes the hover card instant.@@ -101,7 +110,9 @@ export const InternalEntityLink = memo<InternalEntityLinkProps>(({ href, label,// workspace-unique id like T-198 can name a different entity entirely.// Authored link text is never replaced; a failed read just leaves the URL.const shouldResolveTitle =- reference.type !== 'route' && !reference.workspaceSlug && isBareLinkLabel(label, href);+ reference.type !== 'route' &&+ !reference.workspaceSlug &&+ (isBareLinkLabel(label, href) || isEntityIdLabel(label, reference));const { data: entity } = useClientDataSWR(shouldResolveTitle ? internalEntityPreviewKey(reference) : null,() => getPreviewData(reference, t),@@ -171,6 +182,10 @@ export const InternalEntityLink = memo<InternalEntityLinkProps>(({ href, label,openAgentDetail(reference.agentId);break;}+ case 'goal': {+ openGoal(reference.goalId);+ break;+ }case 'document': {const documents = shouldResolveAgentDocument? (agentDocuments ?? (await resolveAgentDocuments().catch(() => undefined)))@@ -203,6 +218,7 @@ export const InternalEntityLink = memo<InternalEntityLinkProps>(({ href, label,openAcceptance,openAgentDetail,openDocument,+ openGoal,openTaskDetail,openVerifyReport,reference,diff --git a/src/features/Conversation/Markdown/plugins/Link/Render/InternalEntityPreview.tsx b/src/features/Conversation/Markdown/plugins/Link/Render/InternalEntityPreview.tsxindex f0b9dd8d20f..5917164f0cc 100644--- a/src/features/Conversation/Markdown/plugins/Link/Render/InternalEntityPreview.tsx+++ b/src/features/Conversation/Markdown/plugins/Link/Render/InternalEntityPreview.tsx@@ -11,14 +11,17 @@ import {CheckCircleIcon,CheckSquareIcon,FileTextIcon,+ TargetIcon,} from 'lucide-react';import { memo, type PropsWithChildren, useState } from 'react';import { useTranslation } from 'react-i18next';import { ArticleSkeleton } from '@/components/Skeleton';+import { goalStatusKey } from '@/features/AgentGoals/goalPresentation';import { useClientDataSWR } from '@/libs/swr';import { agentService } from '@/services/agent';import { documentService } from '@/services/document';+import { goalService } from '@/services/goal';import { taskService } from '@/services/task';import { verifyService } from '@/services/verify';@@ -158,6 +161,23 @@ export const getPreviewData = async (}: null;}+ case 'goal': {+ const { decisions, goal, nodes } = await goalService.getGraph(reference.goalId);+ const tasks = nodes.filter((node) => node.kind === 'task');+ const done = tasks.filter((node) =>+ ['rejected', 'resolved', 'retired'].includes(node.status),+ ).length;+ const pending = decisions.filter((decision) => decision.status === 'pending').length;++ return {+ description: goal.requirement,+ meta: [+ pending > 0 ? t('goalList.needsYou', { count: pending }) : t(goalStatusKey(goal.status)),+ t('goalList.taskProgress', { done, total: tasks.length }),+ ].join(' · '),+ title: goal.title,+ };+ }case 'task': {const result = await taskService.getDetail(reference.taskId);const task = result.data;@@ -225,11 +245,13 @@ export const InternalEntityPreview = memo<InternalEntityPreviewProps>(? BadgeCheckIcon: reference.type === 'agent'? BotIcon- : reference.type === 'task'- ? CheckSquareIcon- : reference.type === 'verify'- ? CheckCircleIcon- : FileTextIcon;+ : reference.type === 'goal'+ ? TargetIcon+ : reference.type === 'task'+ ? CheckSquareIcon+ : reference.type === 'verify'+ ? CheckCircleIcon+ : FileTextIcon;const typeLabel = t(`internalLink.preview.${reference.type}`);const content = isLoading ? (diff --git a/src/features/Conversation/Markdown/plugins/Link/Render/index.test.tsx b/src/features/Conversation/Markdown/plugins/Link/Render/index.test.tsxindex 8e2526f3bbb..723c10d23ae 100644--- a/src/features/Conversation/Markdown/plugins/Link/Render/index.test.tsx+++ b/src/features/Conversation/Markdown/plugins/Link/Render/index.test.tsx@@ -46,6 +46,7 @@ const mockNavigate = vi.fn();const mockOpenAcceptance = vi.fn();const mockOpenAgentDetail = vi.fn();const mockOpenDocument = vi.fn();+const mockOpenGoal = vi.fn();const mockOpenTaskDetail = vi.fn();const mockOpenVerifyReport = vi.fn();@@ -92,6 +93,7 @@ vi.mock('@/store/chat', () => ({openAcceptance: mockOpenAcceptance,openAgentDetail: mockOpenAgentDetail,openDocument: mockOpenDocument,+ openGoal: mockOpenGoal,openTaskDetail: mockOpenTaskDetail,openVerifyReport: mockOpenVerifyReport,}),@@ -353,6 +355,39 @@ describe('Link Render — internal entities', () => {expect(mockOpenAgentDetail).toHaveBeenCalledWith('agt_1');});+ it('shows a goal the CLI printed by its title and goal icon, and opens it beside the chat', () => {+ // `lh goal create` prints the goal URL; agents paste it bare or label it with+ // the id. Either way the link should read as the goal, not its id.+ mockEntityPreview = { title: 'Vent 真信号修复' };++ const { container, getByRole } = renderLink({+ linkHref: '/goal/goal_abc',+ linkKind: 'generic',+ linkLabel: 'goal_abc',+ });++ const anchor = container.querySelector('a')!;+ expect(anchor.textContent).toBe('Vent 真信号修复');+ // The goal's own icon, not a status or progress glyph.+ expect(anchor.querySelector('svg.lucide-target')).not.toBeNull();++ fireEvent.click(getByRole('link', { name: 'Vent 真信号修复' }));+ expect(mockOpenGoal).toHaveBeenCalledWith('goal_abc');+ expect(mockNavigate).not.toHaveBeenCalled();+ });++ it('keeps authored text on a goal link', () => {+ mockEntityPreview = { title: 'Resolved goal title' };++ const { container } = renderLink({+ linkHref: '/agent/agt_1/goal/goal_abc',+ linkKind: 'generic',+ linkLabel: '接续 goal',+ });++ expect(container.querySelector('a')!.textContent).toBe('接续 goal');+ });+it('hard-navigates personal verify pages into the Workbench runtime', () => {const assign = vi.spyOn(window.location, 'assign').mockImplementation(() => undefined);diff --git a/src/features/Conversation/Markdown/plugins/Link/internalLink.test.ts b/src/features/Conversation/Markdown/plugins/Link/internalLink.test.tsindex 9f31feb97e6..4779956fc0f 100644--- a/src/features/Conversation/Markdown/plugins/Link/internalLink.test.ts+++ b/src/features/Conversation/Markdown/plugins/Link/internalLink.test.ts@@ -1,6 +1,6 @@import { describe, expect, it } from 'vitest';-import { isBareLinkLabel, parseInternalLink } from './internalLink';+import { isBareLinkLabel, isEntityIdLabel, parseInternalLink } from './internalLink';describe('parseInternalLink', () => {it('parses official agent document links', () => {@@ -89,6 +89,26 @@ describe('parseInternalLink', () => {});});+ it('parses goal links, global and agent-scoped, as dedicated entities', () => {+ expect(parseInternalLink('https://app.lobehub.com/goal/goal_JekDW3il7s4H')).toEqual({+ goalId: 'goal_JekDW3il7s4H',+ pathname: '/goal/goal_JekDW3il7s4H',+ type: 'goal',+ });+ expect(parseInternalLink('/agent/agt_1/goal/goal_abc')).toEqual({+ agentId: 'agt_1',+ goalId: 'goal_abc',+ pathname: '/agent/agt_1/goal/goal_abc',+ type: 'goal',+ });+ expect(parseInternalLink('/lobe-team/goal/goal_abc', undefined, ['lobe-team'])).toEqual({+ goalId: 'goal_abc',+ pathname: '/lobe-team/goal/goal_abc',+ type: 'goal',+ workspaceSlug: 'lobe-team',+ });+ });+it('parses workspace-prefixed entity paths', () => {expect(parseInternalLink('/lobe-team/agent/agt_agent/docs/docs_document', undefined, ['lobe-team']),@@ -183,6 +203,14 @@ describe('parseInternalLink', () => {});});+describe('isEntityIdLabel', () => {+ it('treats a goal id label as saying no more than the URL', () => {+ const reference = parseInternalLink('/goal/goal_abc')!;+ expect(isEntityIdLabel('goal_abc', reference)).toBe(true);+ expect(isEntityIdLabel('the fix goal', reference)).toBe(false);+ });+});+describe('isBareLinkLabel', () => {it('treats a label that IS the address as bare', () => {expect(isBareLinkLabel('/acceptance/acc_1', '/acceptance/acc_1')).toBe(true);diff --git a/src/features/Conversation/Markdown/plugins/Link/internalLink.ts b/src/features/Conversation/Markdown/plugins/Link/internalLink.tsindex 2dda10a7890..978a7116897 100644--- a/src/features/Conversation/Markdown/plugins/Link/internalLink.ts+++ b/src/features/Conversation/Markdown/plugins/Link/internalLink.ts@@ -3,7 +3,7 @@ import { OFFICIAL_SITE, OFFICIAL_URL } from '@lobechat/const';import { getIdFromIdentifier } from '@/utils/identifier';-const ROUTE_ROOTS = new Set(['acceptance', 'agent', 'page', 'task', 'tasks', 'verify']);+const ROUTE_ROOTS = new Set(['acceptance', 'agent', 'goal', 'page', 'task', 'tasks', 'verify']);const BUILTIN_AGENT_SLUG_SET = new Set<string>(Object.values(BUILTIN_AGENT_SLUGS));const NON_SPA_ROUTE_ROOTS = new Set(['_next', 'api', 'f', 'oidc', 'trpc', 'webapi']);const SPA_ROUTE_ROOTS = new Set([@@ -12,6 +12,7 @@ const SPA_ROUTE_ROOTS = new Set(['community','apps','eval',+ 'goal','group','image','memory',@@ -34,6 +35,7 @@ export type InternalLinkReference =type: 'document';workspaceSlug?: string;}+ | { agentId?: string; goalId: string; pathname: string; type: 'goal'; workspaceSlug?: string }| { pathname: string; type: 'route'; workspaceSlug?: string }| { pathname: string; runId: string; type: 'verify'; workspaceSlug?: string }| {@@ -86,6 +88,14 @@ const isInternalHost = (url: URL, currentOrigin?: string) => {*/export const isBareLinkLabel = (label: string, href: string) => label === href;+/**+ * Whether a link's visible text only repeats the entity's own id. Agents link+ * the goal an `lh goal create` printed as `[goal_xxx](…/goal/goal_xxx)`; the id+ * says no more than the URL does, so it is resolved to the title like one.+ */+export const isEntityIdLabel = (label: string, reference: InternalLinkReference) =>+ reference.type === 'goal' && label === reference.goalId;+/** Parse a LobeHub route into a semantic entity reference. */export const parseInternalLink = (href: string | undefined,@@ -135,6 +145,15 @@ export const parseInternalLink = (};}+ if (segments[0] === 'goal' && segments[1]) {+ return {+ goalId: segments[1],+ pathname,+ type: 'goal',+ ...(workspaceSlug ? { workspaceSlug } : {}),+ };+ }+if (segments[0] === 'page' && segments[1]) {return {documentId: getIdFromIdentifier(segments[1], 'docs'),@@ -177,6 +196,16 @@ export const parseInternalLink = (};}+ if (segments[2] === 'goal' && segments[3]) {+ return {+ agentId,+ goalId: segments[3],+ pathname,+ type: 'goal',+ ...(workspaceSlug ? { workspaceSlug } : {}),+ };+ }+if (segments[2] === 'task' && segments[3]) {return {agentId,