Skip to content

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

✨ feat(goal): add process control UI and server-driven execution (#18762)

Arvin Xu4dc26d48ef7b
diff --git a/apps/cli/src/commands/goal.ts b/apps/cli/src/commands/goal.ts
index 58c3b9e3ccb..217c041391f 100644
--- a/apps/cli/src/commands/goal.ts
+++ b/apps/cli/src/commands/goal.ts
@@ -111,6 +111,39 @@ export function registerGoalCommand(program: Command) {
printGraph(result.data);
});
+ goal
+ .command('list')
+ .description('List goals with their graph roll-up')
+ .option('--agent <id>', 'Filter by responsible agent')
+ .option('--project <id>', 'Filter by project')
+ .option('--status <status...>', 'Filter by lifecycle status')
+ .option('--limit <n>', 'Maximum rows', '50')
+ .option('--json [fields]', 'Output JSON')
+ .action(async (options) => {
+ const result = await (
+ await getTrpcClient()
+ ).goal.list.query({
+ agentId: options.agent,
+ limit: Number.parseInt(options.limit, 10),
+ projectId: options.project,
+ statuses: options.status,
+ });
+ if (options.json !== undefined) return outputJson(result.goals, options.json);
+ if (result.goals.length === 0) return log.info('No goals yet.');
+ printTable(
+ result.goals.map((item) => [
+ item.goal.status,
+ truncate(item.goal.title, 44),
+ `${item.workDone}/${item.workTotal}`,
+ String(item.findingCount),
+ item.pendingDecisions > 0 ? pc.yellow(String(item.pendingDecisions)) : '-',
+ `$${item.totalRunCost.toFixed(2)}`,
+ item.goal.id,
+ ]),
+ ['STATUS', 'TITLE', 'WORK', 'FINDINGS', 'NEEDS YOU', 'COST', 'GOAL ID'],
+ );
+ });
+
const show = async (id: string, options: { json?: boolean | string }) => {
const result = await (await getTrpcClient()).goal.graph.query({ id });
if (options.json !== undefined) return outputJson(result.data, options.json);
diff --git a/apps/server/src/router-hono/workflows/goal/handlers/advance.ts b/apps/server/src/router-hono/workflows/goal/handlers/advance.ts
new file mode 100644
index 00000000000..594a40d6176
--- /dev/null
+++ b/apps/server/src/router-hono/workflows/goal/handlers/advance.ts
@@ -0,0 +1,47 @@
+import debug from 'debug';
+import type { Context } from 'hono';
+
+import { advanceGoal } from '@/server/services/goal/advanceGoal';
+
+const log = debug('lobe-server:workflows:goal:advance');
+
+export interface GoalAdvancePayload {
+ goalId?: string;
+ userId?: string;
+ workspaceId?: string;
+}
+
+/**
+ * Advance one goal. Queued whenever something may have unblocked it — it was
+ * created, a decision gate was resolved, a budget was raised, or one of its
+ * Work Tasks settled.
+ *
+ * No per-user authentication: the payload carries the goal's own owner, and the
+ * route is signature-verified by the `qstashAuth` middleware. The handler
+ * re-reads the goal, so a message that lands after the user paused it, or after
+ * it finished, is a no-op.
+ */
+export async function advance(c: Context) {
+ try {
+ const body = (await c.req.json().catch(() => ({}))) as GoalAdvancePayload;
+ const { goalId, userId, workspaceId } = body ?? {};
+
+ if (!goalId || !userId) {
+ return c.json({ error: 'goalId and userId are required', success: false }, 400);
+ }
+
+ const outcome = await advanceGoal({ goalId, userId, workspaceId });
+ log('goal %s advanced in %d tick(s) → %s', goalId, outcome.ticks, outcome.result.outcome);
+
+ return c.json({
+ goalId,
+ message: outcome.result.message,
+ outcome: outcome.result.outcome,
+ success: true,
+ ticks: outcome.ticks,
+ });
+ } catch (error) {
+ console.error('[goal/advance] Error:', error);
+ return c.json({ error: error instanceof Error ? error.message : 'Internal error' }, 500);
+ }
+}
diff --git a/apps/server/src/router-hono/workflows/goal/handlers/sweep.ts b/apps/server/src/router-hono/workflows/goal/handlers/sweep.ts
new file mode 100644
index 00000000000..8af174bb2c6
--- /dev/null
+++ b/apps/server/src/router-hono/workflows/goal/handlers/sweep.ts
@@ -0,0 +1,104 @@
+import debug from 'debug';
+import type { Context } from 'hono';
+
+import { GoalModel } from '@/database/models/goal';
+import { getServerDB } from '@/database/server';
+import { appEnv } from '@/envs/app';
+import { qstashClient } from '@/libs/qstash';
+import { advanceGoal } from '@/server/services/goal/advanceGoal';
+import { GOAL_ADVANCE_PATH } from '@/server/services/goal/scheduler';
+
+const log = debug('lobe-server:workflows:goal:sweep');
+
+/**
+ * How long a Work may hold its operation lease before the sweep treats the goal
+ * as stalled. Above the coordinator's own claim TTL so a healthy run is never
+ * swept while it is between heartbeats.
+ */
+const DEFAULT_STALE_AFTER_MS = 15 * 60 * 1000;
+
+export interface GoalSweepPayload {
+ /** Only report what would be advanced. */
+ dryRun?: boolean;
+ limit?: number;
+ /** Override the stale window, in milliseconds. */
+ staleAfterMs?: number;
+}
+
+/**
+ * Cron-style safety net for goal advancement.
+ *
+ * The fast path is event-driven — creating a goal, resolving a gate, or a Work
+ * Task settling all queue an advance. This sweep exists because that path can
+ * be missed: a queue message can be dropped, a runner can die between
+ * dispatching a Work and writing its outcome, and a Work can outlive its
+ * operation lease with nobody left to reclaim it. Without it, one lost message
+ * strands a long-horizon goal forever.
+ *
+ * Registered as a QStash Schedule pointing at this endpoint. Global scan, no
+ * per-user auth; the route is signature-verified by `qstashAuth`.
+ */
+export async function sweep(c: Context) {
+ try {
+ const body = (await c.req.json().catch(() => ({}))) as GoalSweepPayload;
+ const { dryRun = false, limit = 200, staleAfterMs = DEFAULT_STALE_AFTER_MS } = body ?? {};
+
+ const db = await getServerDB();
+ const stalled = await GoalModel.listStalled(db, {
+ limit,
+ staleBefore: new Date(Date.now() - staleAfterMs),
+ });
+
+ log('scan: stalled=%d dryRun=%s', stalled.length, dryRun);
+
+ if (dryRun || stalled.length === 0) {
+ return c.json({ advanced: 0, dryRun, stalled: stalled.length, success: true });
+ }
+
+ const advanced = await fanout(
+ stalled.map((goal) => ({
+ goalId: goal.id,
+ userId: goal.userId,
+ workspaceId: goal.workspaceId ?? undefined,
+ })),
+ );
+
+ return c.json({ advanced, stalled: stalled.length, success: true });
+ } catch (error) {
+ console.error('[goal/sweep] Error:', error);
+ return c.json({ error: error instanceof Error ? error.message : 'Internal error' }, 500);
+ }
+}
+
+interface StalledGoal {
+ goalId: string;
+ userId: string;
+ workspaceId?: string;
+}
+
+/**
+ * Hand each goal off individually so one that throws cannot take the sweep
+ * down with it, and so each gets its own retry budget in queue mode.
+ */
+const fanout = async (goals: StalledGoal[]): Promise<number> => {
+ const results = appEnv.enableQueueAgentRuntime
+ ? await publishAll(goals)
+ : await Promise.allSettled(goals.map((goal) => advanceGoal(goal)));
+
+ let advanced = 0;
+ for (const [index, result] of results.entries()) {
+ if (result.status === 'fulfilled') advanced += 1;
+ else
+ console.error('[goal/sweep] advance failed goal=%s: %O', goals[index].goalId, result.reason);
+ }
+ return advanced;
+};
+
+const publishAll = async (goals: StalledGoal[]) => {
+ if (!process.env.APP_URL) {
+ throw new Error('APP_URL is required to fan out goal advances via QStash');
+ }
+ const url = `${process.env.APP_URL.replace(/\/$/, '')}${GOAL_ADVANCE_PATH}`;
+
+ return Promise.allSettled(goals.map((body) => qstashClient.publishJSON({ body, url })));
+};
diff --git a/apps/server/src/router-hono/workflows/goal/index.ts b/apps/server/src/router-hono/workflows/goal/index.ts
new file mode 100644
index 00000000000..0ce50a87ca8
--- /dev/null
+++ b/apps/server/src/router-hono/workflows/goal/index.ts
@@ -0,0 +1,12 @@
+import { Hono } from 'hono';
+
+import { qstashAuth } from '../middlewares/qstashAuth';
+import { advance } from './handlers/advance';
+import { sweep } from './handlers/sweep';
+
+const app = new Hono();
+
+app.post('/advance', qstashAuth(), advance);
+app.post('/sweep', qstashAuth(), sweep);
+
+export default app;
diff --git a/apps/server/src/router-hono/workflows/index.ts b/apps/server/src/router-hono/workflows/index.ts
index 1d2bc88ac03..804a952783b 100644
--- a/apps/server/src/router-hono/workflows/index.ts
+++ b/apps/server/src/router-hono/workflows/index.ts
@@ -3,6 +3,7 @@ import { Hono } from 'hono';
import agentEvalRunApp from './agent-eval-run';
import agentSignalApp from './agent-signal';
import expertiseHistoryApp from './expertise-history';
+import goalApp from './goal';
import memoryUserMemoryApp from './memory-user-memory';
import onboardingTaskRecommendationApp from './onboarding-task-recommendation';
import onboardingUnderstandingApp from './onboarding-understanding';
@@ -15,6 +16,7 @@ const app = new Hono().basePath('/api/workflows');
app.route('/agent-eval-run', agentEvalRunApp);
app.route('/agent-signal', agentSignalApp);
app.route('/expertise-history', expertiseHistoryApp);
+app.route('/goal', goalApp);
app.route('/memory-user-memory', memoryUserMemoryApp);
app.route('/onboarding/understanding', onboardingUnderstandingApp);
app.route('/onboarding/task-recommendations', onboardingTaskRecommendationApp);
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.ts
index 01376b0a288..8df83f5a237 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
@@ -311,16 +311,15 @@ 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',
- });
+ it('resolves a task identifier to its row when changing status', async () => {
+ const task = await caller.create({ instruction: 'Test identifier resolution' });
- await caller.updateStatus({ id: task.data.identifier, status: 'running' });
+ const running = 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 });
+ expect(running.data).toMatchObject({ id: task.data.id, status: 'running' });
});
});
@@ -562,17 +561,16 @@ describe('Task Router Integration', () => {
});
describe('run idempotency', () => {
- it('starts the bound goal when addressed by task identifier', async () => {
+ it('resolves a task identifier to its row when starting a run', 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 });
+ const updated = await caller.detail({ id: task.data.id });
+ expect(updated.data?.status).toBe('running');
});
it('should reject run when a topic is already running', async () => {
diff --git a/apps/server/src/routers/lambda/goal.ts b/apps/server/src/routers/lambda/goal.ts
index be520bc3443..9f6bda4b6f9 100644
--- a/apps/server/src/routers/lambda/goal.ts
+++ b/apps/server/src/routers/lambda/goal.ts
@@ -8,6 +8,10 @@ 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';
+import { advanceGoal } from '@/server/services/goal/advanceGoal';
+import { scheduleGoalAdvance } from '@/server/services/goal/scheduler';
+
+import { assertWorkspaceRowManageable } from './_helpers/assertWorkspaceRowManageable';
const goalProcedure = wsCompatProcedure.use(serverDatabase).use(async (opts) =>
opts.next({
@@ -111,16 +115,27 @@ export const goalRouter = router({
projectId: z.string().optional(),
requirement: z.string().optional(),
title: z.string().min(1),
- work: z.array(z.string().min(1)).optional(),
+ work: z
+ .array(
+ z.union([
+ z.string().min(1),
+ z.object({ description: z.string().optional(), title: z.string().min(1) }),
+ ]),
+ )
+ .optional(),
}),
)
.mutation(async ({ ctx, input }) => {
try {
- return {
- data: await ctx.goalService.create(input),
- message: 'Goal created',
- success: true,
- };
+ const data = await ctx.goalService.create(input);
+ // A goal is not a document — creating one means starting it. The
+ // coordinator takes it from here without a client holding a loop open.
+ await scheduleGoalAdvance({
+ goalId: data.goal.id,
+ userId: ctx.userId,
+ workspaceId: ctx.workspaceId ?? undefined,
+ });
+ return { data, message: 'Goal created', success: true };
} catch (error) {
mapGoalError(error, 'create');
}
@@ -136,21 +151,65 @@ export const goalRouter = router({
)
.mutation(async ({ ctx, input }) => {
try {
- return {
- data: await ctx.goalService.decide(
- input.id,
- input.decisionId,
- input.optionId,
- input.resolution,
- ),
- message: 'Decision resolved',
- success: true,
- };
+ const data = await ctx.goalService.decide(
+ input.id,
+ input.decisionId,
+ input.optionId,
+ input.resolution,
+ );
+ // Answering the gate is what unblocks the Work; carry on from here.
+ await scheduleGoalAdvance({
+ goalId: input.id,
+ userId: ctx.userId,
+ workspaceId: ctx.workspaceId ?? undefined,
+ });
+ return { data, message: 'Decision resolved', success: true };
} catch (error) {
mapGoalError(error, 'decide');
}
}),
+ /**
+ * Run the coordinator now and report where it stopped.
+ *
+ * The goal advances on its own — this is the "don't wait for the next event"
+ * nudge, so the surface can hand off in one call instead of holding a tick
+ * loop open in the browser.
+ */
+ advance: goalWriteProcedure.input(idInput).mutation(async ({ ctx, input }) => {
+ try {
+ const { result, ticks } = await advanceGoal({
+ goalId: input.id,
+ userId: ctx.userId,
+ workspaceId: ctx.workspaceId ?? undefined,
+ });
+ return { data: { ...result, ticks }, message: result.message, success: true };
+ } catch (error) {
+ mapGoalError(error, 'advance');
+ }
+ }),
+
+ /**
+ * Delete a goal and, by FK cascade, its whole graph. Anything still running
+ * is stopped first; the Work Tasks themselves are deliberately left in place
+ * — they are ordinary tasks with their own history and acceptance.
+ */
+ delete: goalWriteProcedure.input(idInput).mutation(async ({ ctx, input }) => {
+ try {
+ // `agent:update` says the member may change goals; it does not say whose.
+ // Without this any member could delete a colleague's goal and cascade its
+ // whole graph away, which is the same rule tasks already enforce.
+ const goal = await ctx.goalModel.findById(input.id);
+ if (!goal) throw new TRPCError({ code: 'NOT_FOUND', message: 'Goal not found' });
+ assertWorkspaceRowManageable(ctx, goal.userId, 'goal');
+
+ await ctx.goalService.delete(input.id);
+ return { message: 'Goal deleted', success: true };
+ } catch (error) {
+ mapGoalError(error, 'delete');
+ }
+ }),
+
graph: goalProcedure.input(idInput).query(async ({ ctx, input }) => {
try {
return { data: await ctx.goalService.graph(input.id), success: true };
@@ -160,9 +219,8 @@ 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 goals with their graph roll-up: how much Work is done, how many
+ * decision gates wait on a human, and what the exploration has cost.
*/
list: goalProcedure
.input(
@@ -186,11 +244,13 @@ export const goalRouter = router({
resume: goalWriteProcedure.input(idInput).mutation(async ({ ctx, input }) => {
try {
- return {
- data: await ctx.goalService.resume(input.id),
- message: 'Goal resumed',
- success: true,
- };
+ const data = await ctx.goalService.resume(input.id);
+ await scheduleGoalAdvance({
+ goalId: input.id,
+ userId: ctx.userId,
+ workspaceId: ctx.workspaceId ?? undefined,
+ });
+ return { data, message: 'Goal resumed', success: true };
} catch (error) {
mapGoalError(error, 'resume');
}
@@ -205,11 +265,15 @@ export const goalRouter = router({
)
.mutation(async ({ ctx, input: { id, ...budget } }) => {
try {
- return {
- data: await ctx.goalService.setBudget(id, budget),
- message: 'Goal budget updated',
- success: true,
- };
+ const data = await ctx.goalService.setBudget(id, budget);
+ // Raising a budget is how a user un-sticks a goal that stopped on one;
+ // it should start moving again without a second gesture.
+ await scheduleGoalAdvance({
+ goalId: id,
+ userId: ctx.userId,
+ workspaceId: ctx.workspaceId ?? undefined,
+ });
+ return { data, message: 'Goal budget updated', success: true };
} catch (error) {
mapGoalError(error, 'setBudget');
}
diff --git a/apps/server/src/routers/lambda/task.ts b/apps/server/src/routers/lambda/task.ts
index dc0ddaa3d36..982aade1ef9 100644
--- a/apps/server/src/routers/lambda/task.ts
+++ b/apps/server/src/routers/lambda/task.ts
@@ -1,5 +1,4 @@
import { TASK_STATUSES } from '@lobechat/builtin-tool-task';
-import type { GoalStatus } from '@lobechat/const/goal';
import type { TaskListItem, TaskParticipant, TaskVerifyConfig } from '@lobechat/types';
import { TRPCError } from '@trpc/server';
import { z } from 'zod';
@@ -8,7 +7,6 @@ import { withScopedPermission } from '@/business/server/trpc-middlewares/rbacPer
import { wsCompatProcedure } from '@/business/server/trpc-middlewares/workspaceAuth';
import { AgentModel } from '@/database/models/agent';
import { BriefModel } from '@/database/models/brief';
-import { GoalModel } from '@/database/models/goal';
import { TaskModel } from '@/database/models/task';
import { TaskTopicModel } from '@/database/models/taskTopic';
import { TopicModel } from '@/database/models/topic';
@@ -29,17 +27,6 @@ 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;
@@ -48,7 +35,6 @@ const taskProcedure = wsCompatProcedure.use(serverDatabase).use(async (opts) =>
agentModel: new AgentModel(ctx.serverDB, ctx.userId, wsId),
briefModel: new BriefModel(ctx.serverDB, ctx.userId, wsId),
editLockService: new EditLockService(ctx.userId),
- goalModel: new GoalModel(ctx.serverDB, ctx.userId, wsId),
taskLifecycle: new TaskLifecycleService(ctx.serverDB, ctx.userId, wsId),
taskModel: new TaskModel(ctx.serverDB, ctx.userId, wsId),
taskService: new TaskService(ctx.serverDB, ctx.userId, wsId),
@@ -88,16 +74,6 @@ const createSchema = z.object({
createdByAgentId: z.string().optional(),
description: z.string().optional(),
editorData: z.unknown().optional(),
- // Bind a goal entity (`goals` row) to the created task; the task becomes the
- // goal's execution carrier and the outer verify-driven round loop applies.
- goal: z
- .object({
- maxRounds: z.number().int().nullish(),
- maxTotalCost: z.number().nullish(),
- requirement: z.string().nullish(),
- title: z.string().optional(),
- })
- .optional(),
identifierPrefix: z.string().optional(),
instruction: z.string().min(1),
name: z.string().optional(),
@@ -110,6 +86,11 @@ const createSchema = z.object({
// assignee agent's visibility (private agent → private task). UI surfaces
// such as the top-level "Tasks" create form pass it explicitly.
visibility: z.enum(['private', 'public']).optional(),
+ // Removed contract, kept so the server can recognise it. A task no longer
+ // carries a goal — the Goal Graph owns execution and dispatches its own Work
+ // Tasks — and silently dropping this field would let a released client report
+ // that a goal started when only an ordinary task exists.
+ goal: z.unknown().optional(),
});
const updateSchema = z.object({
@@ -145,7 +126,6 @@ const listSchema = z.object({
// misconfigured one cannot), false → its exact complement. Omitted leaves the
// set unnarrowed.
automated: z.boolean().optional(),
- hasGoal: z.boolean().optional(),
limit: z.number().min(1).max(100).default(50),
offset: z.number().min(0).default(0),
// Which timestamp orders the page, newest first. Defaults to creation time.
@@ -179,7 +159,6 @@ const groupListSchema = z
.min(1)
.max(10)
.optional(),
- hasGoal: z.boolean().optional(),
parentTaskId: z.string().nullish(),
projectId: z.string().optional(),
visibility: z.enum(['private', 'public']).optional(),
@@ -458,12 +437,20 @@ export const taskRouter = router({
}),
create: taskProcedureWrite.input(createSchema).mutation(async ({ input, ctx }) => {
+ const { goal: legacyGoal, ...createInput } = input;
+ if (legacyGoal !== undefined) {
+ throw new TRPCError({
+ code: 'BAD_REQUEST',
+ message:
+ 'Creating a goal through task.create is no longer supported. Reload the app, then create the goal again.',
+ });
+ }
try {
- const parsedVerify = taskVerifyConfigPatchSchema.safeParse(input.config?.verify);
- const { verify: _legacyVerify, ...taskConfig } = input.config ?? {};
+ const parsedVerify = taskVerifyConfigPatchSchema.safeParse(createInput.config?.verify);
+ const { verify: _legacyVerify, ...taskConfig } = createInput.config ?? {};
const task = await ctx.taskService.createTask({
- ...input,
- config: parsedVerify.success ? taskConfig : input.config,
+ ...createInput,
+ config: parsedVerify.success ? taskConfig : createInput.config,
});
try {
if (parsedVerify.success) {
@@ -534,30 +521,6 @@ export const taskRouter = router({
}
}),
- deleteGoal: taskProcedureWrite.input(idInput).mutation(async ({ input, ctx }) => {
- try {
- const model = ctx.taskModel;
- const task = await resolveOrThrow(model, input.id);
- const goal = await ctx.goalModel.findBySubject('task', task.id);
- if (!goal) {
- 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) {
- if (error instanceof TRPCError) throw error;
- console.error('[task:deleteGoal]', error);
- throw new TRPCError({
- cause: error,
- code: 'INTERNAL_SERVER_ERROR',
- message: 'Failed to delete goal',
- });
- }
- }),
-
detail: taskProcedure.input(idInput).query(async ({ input, ctx }) => {
try {
const detail = await ctx.taskService.getTaskDetail(input.id);
@@ -848,9 +811,6 @@ 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,
@@ -1482,12 +1442,6 @@ 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/apps/server/src/services/goal/advanceGoal.test.ts b/apps/server/src/services/goal/advanceGoal.test.ts
new file mode 100644
index 00000000000..8aa4fe39f2d
--- /dev/null
+++ b/apps/server/src/services/goal/advanceGoal.test.ts
@@ -0,0 +1,77 @@
+import type { GoalTickOutcome, GoalTickResult } from '@lobechat/types';
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+const mocks = vi.hoisted(() => ({ tick: vi.fn() }));
+
+vi.mock('@/database/server', () => ({ getServerDB: vi.fn().mockResolvedValue({}) }));
+vi.mock('./index', () => ({ GoalService: vi.fn(() => ({ tick: mocks.tick })) }));
+
+const { advanceGoal, MAX_TICKS_PER_ADVANCE } = await import('./advanceGoal');
+
+const tickResult = (outcome: GoalTickOutcome): GoalTickResult => ({
+ goalId: 'goal-1',
+ message: outcome,
+ outcome,
+});
+
+const advance = () => advanceGoal({ goalId: 'goal-1', userId: 'user-1' });
+
+describe('advanceGoal', () => {
+ beforeEach(() => mocks.tick.mockReset());
+
+ it('keeps ticking while the coordinator reports progress', async () => {
+ mocks.tick
+ .mockResolvedValueOnce(tickResult('advanced'))
+ .mockResolvedValueOnce(tickResult('advanced'))
+ .mockResolvedValueOnce(tickResult('achieved'));
+
+ const { result, ticks } = await advance();
+
+ expect(ticks).toBe(3);
+ expect(result.outcome).toBe('achieved');
+ });
+
+ it('hands off at waiting_external instead of polling a running task', async () => {
+ // The Work Task's own settle queues the next advance. Polling here would
+ // hold a worker open for the whole execution and duplicate that event.
+ mocks.tick
+ .mockResolvedValueOnce(tickResult('advanced'))
+ .mockResolvedValueOnce(tickResult('waiting_external'));
+
+ const { result, ticks } = await advance();
+
+ expect(ticks).toBe(2);
+ expect(result.outcome).toBe('waiting_external');
+ expect(mocks.tick).toHaveBeenCalledTimes(2);
+ });
+
+ it.each(['achieved', 'failed', 'no_progress', 'waiting_human'] as const)(
+ 'stops on %s without another tick',
+ async (outcome) => {
+ mocks.tick.mockResolvedValue(tickResult(outcome));
+
+ const { result } = await advance();
+
+ expect(mocks.tick).toHaveBeenCalledTimes(1);
+ expect(result.outcome).toBe(outcome);
+ },
+ );
+
+ it('gives up at the per-advance limit rather than looping forever', async () => {
+ mocks.tick.mockResolvedValue(tickResult('advanced'));
+
+ const { ticks } = await advance();
+
+ expect(ticks).toBe(MAX_TICKS_PER_ADVANCE);
+ expect(mocks.tick).toHaveBeenCalledTimes(MAX_TICKS_PER_ADVANCE);
+ });
+
+ it('runs as the goal owner, not as the caller', async () => {
+ const { GoalService } = await import('./index');
+ mocks.tick.mockResolvedValue(tickResult('no_progress'));
+
+ await advanceGoal({ goalId: 'goal-1', userId: 'owner-9', workspaceId: 'ws-3' });
+
+ expect(GoalService).toHaveBeenCalledWith(expect.anything(), 'owner-9', 'ws-3');
+ });
+});
diff --git a/apps/server/src/services/goal/advanceGoal.ts b/apps/server/src/services/goal/advanceGoal.ts
new file mode 100644
index 00000000000..34ea5b52c2d
--- /dev/null
+++ b/apps/server/src/services/goal/advanceGoal.ts
@@ -0,0 +1,68 @@
+import type { GoalTickOutcome, GoalTickResult } from '@lobechat/types';
+import debug from 'debug';
+
+import { getServerDB } from '@/database/server';
+
+import { GoalService } from './index';
+
+const log = debug('lobe-server:goal-advance');
+
+/**
+ * Outcomes the coordinator cannot get past by ticking again.
+ *
+ * `waiting_external` is one of them here, and that is the whole point of the
+ * event-driven design: it means a Work Task is now executing, so the next move
+ * belongs to that task's completion, not to a poll loop holding a worker open.
+ */
+const STOP_OUTCOMES = new Set<GoalTickOutcome>([
+ 'achieved',
+ 'failed',
+ 'no_progress',
+ 'waiting_external',
+ 'waiting_human',
+]);
+
+/**
+ * Safety limit for one advance. Dispatching a Work takes two ticks, so a
+ * healthy run is a handful; anything near this is a loop that is not
+ * converging, and the sweep will come back to it.
+ */
+export const MAX_TICKS_PER_ADVANCE = 20;
+
+export interface AdvanceGoalParams {
+ goalId: string;
+ userId: string;
+ workspaceId?: string;
+}
+
+export interface AdvanceGoalOutcome {
+ goalId: string;
+ result: GoalTickResult;
+ ticks: number;
+}
+
+/**
+ * Advance a goal until it is waiting on something that is not another tick.
+ *
+ * This is the server-side driver: a goal moves because something happened to
+ * it, not because a client is holding a loop open. Runs as the goal's own
+ * owner, so it sees exactly what that user's coordinator would see.
+ */
+export const advanceGoal = async ({
+ goalId,
+ userId,
+ workspaceId,
+}: AdvanceGoalParams): Promise<AdvanceGoalOutcome> => {
+ const db = await getServerDB();
+ const service = new GoalService(db, userId, workspaceId);
+
+ let result: GoalTickResult | undefined;
+ for (let ticks = 1; ticks <= MAX_TICKS_PER_ADVANCE; ticks++) {
+ result = await service.tick(goalId);
+ log('goal %s tick %d → %s (%s)', goalId, ticks, result.outcome, result.message);
+ if (STOP_OUTCOMES.has(result.outcome)) return { goalId, result, ticks };
+ }
+
+ log('goal %s hit the per-advance tick limit', goalId);
+ return { goalId, result: result!, ticks: MAX_TICKS_PER_ADVANCE };
+};
diff --git a/apps/server/src/services/goal/index.test.ts b/apps/server/src/services/goal/index.test.ts
index 510201f40f7..cf6db7b7e40 100644
--- a/apps/server/src/services/goal/index.test.ts
+++ b/apps/server/src/services/goal/index.test.ts
@@ -5,6 +5,7 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { getTestDB } from '@/database/core/getTestDB';
import { AcceptanceModel } from '@/database/models/acceptance';
import { AgentOperationModel } from '@/database/models/agentOperation';
+import { GoalModel } from '@/database/models/goal';
import { TaskModel } from '@/database/models/task';
import { TaskTopicModel } from '@/database/models/taskTopic';
import {
@@ -17,11 +18,14 @@ import {
goalNodes,
goals,
tasks,
+ taskTopics,
+ topics,
users,
} from '@/database/schemas';
import type { LobeChatDatabase } from '@/database/type';
import { AgentRuntimeCoordinator } from '@/server/modules/AgentRuntime/AgentRuntimeCoordinator';
+import { TaskService } from '../task';
import { TaskRunnerService } from '../taskRunner';
import { GoalService } from './index';
@@ -43,6 +47,8 @@ afterEach(async () => {
await serverDB.delete(goals);
await serverDB.delete(acceptances);
await serverDB.delete(agentOperations);
+ await serverDB.delete(taskTopics);
+ await serverDB.delete(topics);
await serverDB.delete(tasks);
await serverDB.delete(agents);
await serverDB.delete(users);
@@ -63,6 +69,165 @@ describe('GoalService', () => {
expect(current.workVersions).toHaveLength(1);
});
+ it('starts the bound Work once when advances race on dispatch', async () => {
+ // Overlapping advances (an event hook, a manual nudge, the sweep) both read
+ // the task as backlog; without an atomic claim both would call runTask and
+ // the user would pay for the same Work twice.
+ const runSpy = vi
+ .spyOn(TaskRunnerService.prototype, 'runTask')
+ .mockImplementation(async ({ taskId }) => ({ taskId }) as never);
+ const service = new GoalService(serverDB, userId);
+ const graph = await service.create({ title: 'Raced dispatch', work: ['Only run once'] });
+ await service.tick(graph.goal.id);
+
+ const results = await Promise.all([service.tick(graph.goal.id), service.tick(graph.goal.id)]);
+
+ expect(runSpy).toHaveBeenCalledTimes(1);
+ expect(results.filter((result) => result.message.startsWith('Started task'))).toHaveLength(1);
+ });
+
+ it('retries a failed verification once when advances race on recovery', async () => {
+ // The dispatch claim only covers starting a backlog Work; the automatic
+ // retry path spawns its own run, so without the same claim two overlapping
+ // advances would each pay for an attempt.
+ const runSpy = vi
+ .spyOn(TaskRunnerService.prototype, 'runTask')
+ .mockImplementation(async ({ taskId }) => ({ taskId }) as never);
+ const service = new GoalService(serverDB, userId);
+ const taskModel = new TaskModel(serverDB, userId);
+ const graph = await service.create({
+ config: { recovery: { maxAttemptsPerWork: 3 } },
+ title: 'Raced recovery',
+ work: ['Retry me once'],
+ });
+ const created = await service.tick(graph.goal.id);
+ await taskModel.update(created.taskId!, { totalTopics: 1 });
+ await taskModel.updateStatus(created.taskId!, 'paused', {
+ error: 'Delivery did not pass verification.',
+ });
+ runSpy.mockClear();
+
+ await Promise.all([service.tick(graph.goal.id), service.tick(graph.goal.id)]);
+
+ expect(runSpy).toHaveBeenCalledTimes(1);
+ });
+
+ it('hands back a dispatch claim whose worker died before the run existed', async () => {
+ // The claim is taken just before `runTask` creates the topic. If the worker
+ // dies in that sliver the task is `running` with no operation to reclaim,
+ // and every later advance would report `waiting_external` forever.
+ const runSpy = vi
+ .spyOn(TaskRunnerService.prototype, 'runTask')
+ .mockRejectedValue(new Error('worker died'));
+ const service = new GoalService(serverDB, userId);
+ const taskModel = new TaskModel(serverDB, userId);
+ const graph = await service.create({ title: 'Orphaned claim', work: ['Start me'] });
+ const created = await service.tick(graph.goal.id);
+
+ // The claim survives the crash: put the row back where a dead worker left it.
+ await expect(service.tick(graph.goal.id)).rejects.toThrow('worker died');
+ await taskModel.updateStatus(created.taskId!, 'running');
+ await serverDB
+ .update(tasks)
+ .set({ updatedAt: new Date(Date.now() - 60 * 60 * 1000) })
+ .where(eq(tasks.id, created.taskId!));
+
+ const released = await service.tick(graph.goal.id);
+
+ expect(released.outcome).toBe('advanced');
+ expect((await taskModel.findById(created.taskId!))?.status).toBe('backlog');
+ runSpy.mockRestore();
+ });
+
+ it('leaves a fresh dispatch claim alone', async () => {
+ // The same shape a moment after the claim is just a run about to start.
+ vi.spyOn(TaskRunnerService.prototype, 'runTask').mockRejectedValue(new Error('worker died'));
+ const service = new GoalService(serverDB, userId);
+ const taskModel = new TaskModel(serverDB, userId);
+ const graph = await service.create({ title: 'Fresh claim', work: ['Start me'] });
+ const created = await service.tick(graph.goal.id);
+ await expect(service.tick(graph.goal.id)).rejects.toThrow('worker died');
+ await taskModel.updateStatus(created.taskId!, 'running');
+
+ const result = await service.tick(graph.goal.id);
+
+ expect(result.outcome).toBe('waiting_external');
+ expect((await taskModel.findById(created.taskId!))?.status).toBe('running');
+ });
+
+ it('reopens a goal its round budget stopped when the budget is raised', async () => {
+ // `tick` refuses to move a paused goal, so without this the queued advance
+ // returns straight away and the user has to find Resume as a second gesture.
+ const service = new GoalService(serverDB, userId);
+ const graph = await service.create({
+ maxRounds: 1,
+ title: 'Budget stopped',
+ work: ['Costs a round'],
+ });
+ const created = await service.tick(graph.goal.id);
+ await serverDB.insert(topics).values({ id: 'tpc_budget', userId });
+ await serverDB
+ .insert(taskTopics)
+ .values({ seq: 1, taskId: created.taskId!, topicId: 'tpc_budget', userId });
+
+ const stopped = await service.tick(graph.goal.id);
+ expect(stopped.outcome).toBe('no_progress');
+ expect(stopped.message).toContain('Round budget reached');
+ expect((await service.graph(graph.goal.id)).goal.status).toBe('paused');
+
+ const raised = await service.setBudget(graph.goal.id, { maxRounds: 5 });
+
+ expect(raised?.status).not.toBe('paused');
+ });
+
+ it('leaves a deliberately paused goal paused when its budget changes', async () => {
+ // Nothing distinguishes a user pause from a budget pause on the row, so the
+ // reopen is limited to goals whose budget was actually binding.
+ const service = new GoalService(serverDB, userId);
+ const graph = await service.create({ title: 'User paused', work: ['Wait'] });
+ await service.pause(graph.goal.id);
+
+ const updated = await service.setBudget(graph.goal.id, { maxTotalCost: 50 });
+
+ expect(updated?.status).toBe('paused');
+ });
+
+ it('refuses to delete a goal whose running work cannot be stopped', async () => {
+ // Deleting anyway would remove the only surface that can stop an operation
+ // which keeps spending.
+ vi.spyOn(TaskRunnerService.prototype, 'runTask').mockResolvedValue({} as never);
+ const service = new GoalService(serverDB, userId);
+ const graph = await service.create({ title: 'Unstoppable', work: ['Runs on'] });
+ const created = await service.tick(graph.goal.id);
+ await serverDB.insert(topics).values({ id: 'tpc_stuck', userId });
+ await new TaskTopicModel(serverDB, userId).add(created.taskId!, 'tpc_stuck', { seq: 1 });
+ await new TaskTopicModel(serverDB, userId).updateStatus(
+ created.taskId!,
+ 'tpc_stuck',
+ 'running',
+ );
+ vi.spyOn(TaskService.prototype, 'cancelTopic').mockRejectedValue(new Error('gateway is down'));
+
+ await expect(service.delete(graph.goal.id)).rejects.toThrow(/not deleted/);
+ expect(await service.graph(graph.goal.id)).toBeDefined();
+ });
+
+ it('parks a goal nothing can move so the sweep stops re-picking it', async () => {
+ // A goal with no Work can only report `no_progress`. Left `running` it is
+ // selected by every newest-first scan forever, and enough of them starve
+ // every other stalled goal out of the sweep's window.
+ const service = new GoalService(serverDB, userId);
+ const graph = await service.create({ title: 'Nothing to do' });
+
+ const result = await service.tick(graph.goal.id);
+
+ expect(result.outcome).toBe('no_progress');
+ expect((await service.graph(graph.goal.id)).goal.status).toBe('paused');
+ expect(
+ await GoalModel.listStalled(serverDB, { staleBefore: new Date(Date.now() - 60_000) }),
+ ).not.toContainEqual(expect.objectContaining({ id: graph.goal.id }));
+ });
+
it('keeps the overall requirement as background while making the current work authoritative', async () => {
const service = new GoalService(serverDB, userId);
const requirement = `Generate verified training data. ${'Detailed acceptance evidence. '.repeat(20)}`;
diff --git a/apps/server/src/services/goal/index.ts b/apps/server/src/services/goal/index.ts
index 737d46635fb..ba6b1936640 100644
--- a/apps/server/src/services/goal/index.ts
+++ b/apps/server/src/services/goal/index.ts
@@ -1,9 +1,10 @@
import type {
+ GoalConfig,
GoalEdgeKind,
GoalGraphSnapshot,
+ GoalItem,
GoalNodeKind,
GoalNodeStatus,
- GoalRecoveryPolicy,
GoalTickResult,
TaskItem,
TaskTopicHandoff,
@@ -31,15 +32,21 @@ const WORK_NODE_CLAIM_TTL_MS = 5 * 60 * 1000;
const TASK_DESCRIPTION_MAX_LENGTH = 255;
const GOAL_ACCEPTANCE_WORK_TITLE = 'Complete full Goal acceptance';
+export interface CreateGoalWorkInput {
+ description?: string;
+ title: string;
+}
+
export interface CreateGoalGraphInput {
agentId?: string;
- config?: { recovery?: GoalRecoveryPolicy };
+ config?: GoalConfig;
maxRounds?: number;
maxTotalCost?: number;
projectId?: string;
requirement?: string;
title: string;
- work?: string[];
+ /** Seed Work nodes, in dependency-free order. A plain string is title-only. */
+ work?: Array<CreateGoalWorkInput | string>;
}
export interface CreateGoalNodeInput {
@@ -108,8 +115,13 @@ export class GoalService {
});
if (!problem) throw new Error('Failed to seed goal problem');
- for (const title of input.work ?? []) {
- const work = await this.graphModel.createNode(goal.id, { kind: 'work', title });
+ for (const seed of input.work ?? []) {
+ const { description, title } = typeof seed === 'string' ? { title: seed } : seed;
+ const work = await this.graphModel.createNode(goal.id, {
+ description,
+ kind: 'work',
+ title,
+ });
if (!work) throw new Error('Failed to seed goal work');
await this.graphModel.createEdge(goal.id, problem.id, work.id, 'decomposes');
}
@@ -139,19 +151,93 @@ export class GoalService {
return edge;
};
+ /**
+ * Stop everything the goal has running, then delete it and its graph.
+ *
+ * Deleting only the goal row cascades the graph away but leaves each Work
+ * Task — and the agent operation behind it — running, spending the user's
+ * budget with nothing left on screen to stop it. The tasks themselves stay:
+ * they are ordinary tasks with their own history and acceptance.
+ */
+ delete = async (goalId: string) => {
+ const graph = await this.graphModel.getGraph(goalId);
+ const taskIds = graph?.nodes.flatMap((node) => (node.taskId ? [node.taskId] : [])) ?? [];
+
+ for (const taskId of taskIds) {
+ const topics = await this.taskTopicModel.findByTaskId(taskId);
+ for (const topic of topics) {
+ if (topic.status !== 'running' || !topic.topicId) continue;
+ // Deliberately not swallowed. Interrupting can fail — the runtime or a
+ // device gateway may be unreachable — and going ahead would delete the
+ // only surface that can stop an operation which keeps spending. Better
+ // to leave the goal intact and say so.
+ try {
+ await this.taskService.cancelTopic(topic.topicId);
+ } catch (error) {
+ throw new TRPCError({
+ cause: error,
+ code: 'PRECONDITION_FAILED',
+ message:
+ 'Could not stop the work still running for this goal, so it was not deleted. Try again once the run is reachable.',
+ });
+ }
+ }
+ await this.taskModel
+ .updateStatusIfCurrent(taskId, 'running', 'paused')
+ .catch((error) => console.error('[GoalService.delete] failed to pause task:', error));
+ }
+
+ return this.goalModel.delete(goalId);
+ };
+
pause = async (goalId: string) => {
const goal = await this.goalModel.updateStatus(goalId, 'paused');
if (!goal) throw new TRPCError({ code: 'NOT_FOUND', message: 'Goal not found' });
return goal;
};
+ /**
+ * What the goal has spent against what it is allowed to spend.
+ *
+ * Rounds are counted across every Work Task in the graph, not per Work — the
+ * budget is the goal's, so `setBudget` has to read it exactly the way the
+ * coordinator does or raising a budget would not reliably unstick a goal.
+ */
+ private evaluateBudget = async (goal: GoalItem, graph: GoalGraphSnapshot) => {
+ const taskIds = graph.nodes.flatMap((node) => (node.taskId ? [node.taskId] : []));
+ const runs = await this.taskTopicModel.findWithHandoffByTaskIds(taskIds, 10_000);
+ const totalCost = runs.reduce((sum, run) => sum + Number(run.totalCost ?? 0), 0);
+ return {
+ costLimitReached: goal.maxTotalCost !== null && totalCost >= Number(goal.maxTotalCost),
+ roundLimitReached: goal.maxRounds !== null && runs.length >= goal.maxRounds,
+ runs,
+ totalCost,
+ };
+ };
+
setBudget = async (
goalId: string,
budget: { maxRounds?: number | null; maxTotalCost?: number | null },
) => {
+ const before = await this.requireGraph(goalId);
+ const wasBinding = await this.evaluateBudget(before.goal, before);
+
const goal = await this.goalModel.update(goalId, budget);
if (!goal) throw new TRPCError({ code: 'NOT_FOUND', message: 'Goal not found' });
- return goal;
+
+ // Raising a budget is how a user un-sticks a goal the coordinator parked on
+ // one, and `tick` refuses to move a paused goal — so without this the
+ // queued advance would return straight away and the user would have to find
+ // Resume as a second gesture. Only a goal the budget actually stopped is
+ // reopened: if the old budget was not binding, this pause was somebody's
+ // deliberate one and is left alone.
+ const stoppedByBudget = wasBinding.costLimitReached || wasBinding.roundLimitReached;
+ if (goal.status !== 'paused' || !stoppedByBudget) return goal;
+
+ const nowBinding = await this.evaluateBudget(goal, before);
+ if (nowBinding.costLimitReached || nowBinding.roundLimitReached) return goal;
+
+ return (await this.resume(goalId)) ?? goal;
};
resume = async (goalId: string) => {
@@ -295,6 +381,14 @@ export class GoalService {
await this.goalModel.updateStatus(goalId, 'achieved');
return { goalId, message: 'Goal-level acceptance passed', outcome: 'achieved' };
}
+ // Nothing here moves without a person: either there is no Work at all, or
+ // every remaining Work is blocked and nothing is running to unblock it.
+ // Say so on the row instead of leaving a goal that reads as `running`
+ // while it cannot run — and, just as importantly, take it out of the
+ // sweep's window. A `running` goal that always reports `no_progress` is
+ // picked by every scan forever, and enough of them starve every other
+ // stalled goal out of the newest-first limit.
+ await this.goalModel.updateStatus(goalId, 'paused');
return {
goalId,
message:
@@ -428,7 +522,7 @@ export class GoalService {
this.db,
this.userId,
this.workspaceId,
- ).recover({ goal: graph.goal, spentCost: totalCost, task, taskCarried: false });
+ ).recover({ goal: graph.goal, spentCost: totalCost, task });
if (recovery === 'continued') {
await this.graphModel.updateNodeStatus(
goalId,
@@ -483,12 +577,10 @@ export class GoalService {
};
}
- const taskIds = graph.nodes.flatMap((node) => (node.taskId ? [node.taskId] : []));
- const runs = await this.taskTopicModel.findWithHandoffByTaskIds(taskIds, 10_000);
- const totalCost = runs.reduce((sum, run) => sum + Number(run.totalCost ?? 0), 0);
- const roundLimitReached = graph.goal.maxRounds !== null && runs.length >= graph.goal.maxRounds;
- const costLimitReached =
- graph.goal.maxTotalCost !== null && totalCost >= Number(graph.goal.maxTotalCost);
+ const { costLimitReached, roundLimitReached, runs, totalCost } = await this.evaluateBudget(
+ graph.goal,
+ graph,
+ );
if (roundLimitReached || costLimitReached) {
await this.goalModel.updateStatus(goalId, 'paused');
return {
@@ -502,18 +594,49 @@ export class GoalService {
};
}
- const run = await new TaskRunnerService(this.db, this.userId, this.workspaceId).runTask({
- maxSteps: resolveWorkMaxSteps(graph.goal),
- taskId: task.id,
- trigger: 'goal',
+ // Advances arrive from independent sources — an event hook, a manual nudge,
+ // the sweep — and can overlap. `runTask` decides whether a run is already
+ // in flight by reading the task's topics and only then creating one, so two
+ // overlapping advances would both dispatch this Work and pay for it twice.
+ // Claim the task first: the transition is a single conditional UPDATE, so
+ // exactly one advance can win it.
+ const claimed = await this.taskModel.updateStatusIfCurrent(task.id, task.status, 'running', {
+ error: null,
+ startedAt: new Date(),
});
- return {
- goalId,
- message: `Started task ${task.identifier}`,
- nodeId: frontier.id,
- outcome: 'waiting_external',
- taskId: run.taskId,
- };
+ if (!claimed) {
+ return {
+ goalId,
+ message: `Task ${task.identifier} is already being started`,
+ nodeId: frontier.id,
+ outcome: 'waiting_external',
+ taskId: task.id,
+ };
+ }
+
+ try {
+ const run = await new TaskRunnerService(this.db, this.userId, this.workspaceId).runTask({
+ maxSteps: resolveWorkMaxSteps(graph.goal),
+ taskId: task.id,
+ trigger: 'goal',
+ });
+ return {
+ goalId,
+ message: `Started task ${task.identifier}`,
+ nodeId: frontier.id,
+ outcome: 'waiting_external',
+ taskId: run.taskId,
+ };
+ } catch (error) {
+ // We claimed the task, so nothing else will put it back. Release it or the
+ // Work stays 'running' with no run behind it and only the lease reclaims it.
+ await this.taskModel
+ .updateStatusIfCurrent(task.id, 'running', task.status)
+ .catch((releaseError) => {
+ console.error('[GoalService.tick] failed to release claimed task:', releaseError);
+ });
+ throw error;
+ }
};
private requireGraph = async (goalId: string) => {
@@ -544,9 +667,26 @@ export class GoalService {
const [runningTopic] = await this.taskTopicModel.findRunningByTaskIds([task.id]);
const operationId = runningTopic?.operationId;
const topicId = runningTopic?.topicId;
- if (!operationId || !topicId) return undefined;
-
const staleBefore = new Date(Date.now() - resolveOperationLeaseTimeout(graph.goal));
+
+ if (!operationId || !topicId) {
+ // A task claimed for dispatch but with no run behind it. Normally this is
+ // the sliver between the claim and `runTask` creating the topic; if the
+ // worker died in there it is permanent, and every later advance would
+ // report `waiting_external` forever because there is no operation to
+ // reclaim. Once the claim is older than the lease, hand it back.
+ if (new Date(task.updatedAt) >= staleBefore) return undefined;
+ const released = await this.taskModel.updateStatusIfCurrent(task.id, 'running', 'backlog');
+ if (!released) return undefined;
+ return {
+ goalId: graph.goal.id,
+ message: `Released the abandoned dispatch claim on task ${task.identifier}`,
+ nodeId,
+ outcome: 'advanced',
+ taskId: task.id,
+ };
+ }
+
const latestUsage = await new AgentRuntimeCoordinator().getOperationMetadata(operationId);
const reclaimed = await this.db.transaction(async (tx) => {
const settled = await new AgentOperationModel(
@@ -580,7 +720,7 @@ export class GoalService {
this.db,
this.userId,
this.workspaceId,
- ).recover({ goal: graph.goal, task, taskCarried: false });
+ ).recover({ goal: graph.goal, task });
if (recovery === 'continued') {
await this.graphModel.updateNodeStatus(
graph.goal.id,
diff --git a/apps/server/src/services/goal/recoveryPolicy.ts b/apps/server/src/services/goal/recoveryPolicy.ts
index 42254b10a7b..1a0b663e965 100644
--- a/apps/server/src/services/goal/recoveryPolicy.ts
+++ b/apps/server/src/services/goal/recoveryPolicy.ts
@@ -1,7 +1,5 @@
import type { GoalItem } from '@lobechat/types';
-import { resolveGoalRoundBudget } from '@/server/services/verify/goalBudget';
-
const DEFAULT_MAX_ATTEMPTS_PER_WORK = 3;
const DEFAULT_OPERATION_LEASE_TIMEOUT_MS = 5 * 60 * 1000;
// Agent runtime refreshes the durable operation lease every third 30-second
@@ -9,10 +7,11 @@ const DEFAULT_OPERATION_LEASE_TIMEOUT_MS = 5 * 60 * 1000;
// so a transient missed write cannot reclaim a healthy operation.
export const MIN_OPERATION_LEASE_TIMEOUT_MS = 3 * 60 * 1000;
-export const resolveWorkAttemptBudget = (goal: GoalItem, taskCarried: boolean): number => {
+/** How many attempts one Work gets before the coordinator opens a decision gate. */
+export const resolveWorkAttemptBudget = (goal: GoalItem): number => {
const configured = goal.config?.recovery?.maxAttemptsPerWork;
if (typeof configured === 'number') return Math.max(1, configured);
- return taskCarried ? resolveGoalRoundBudget(goal) : DEFAULT_MAX_ATTEMPTS_PER_WORK;
+ return DEFAULT_MAX_ATTEMPTS_PER_WORK;
};
export const resolveWorkMaxSteps = (goal: GoalItem): number | undefined => {
diff --git a/apps/server/src/services/goal/scheduler/impls/index.ts b/apps/server/src/services/goal/scheduler/impls/index.ts
new file mode 100644
index 00000000000..56ec23a251f
--- /dev/null
+++ b/apps/server/src/services/goal/scheduler/impls/index.ts
@@ -0,0 +1,36 @@
+import { appEnv } from '@/envs/app';
+import { qstashClient } from '@/libs/qstash';
+
+import { LocalGoalScheduler } from './local';
+import { QStashGoalScheduler } from './qstash';
+import type { GoalSchedulerImpl } from './type';
+
+let cached: GoalSchedulerImpl | null = null;
+
+/**
+ * The singleton goal scheduler.
+ *
+ * - `AGENT_RUNTIME_MODE=queue`: QStash (production)
+ * - otherwise: in-process timers (dev / desktop)
+ *
+ * Singleton because the local implementation holds pending timers; a
+ * per-request instance would orphan them.
+ */
+export const createGoalSchedulerModule = (): GoalSchedulerImpl => {
+ if (cached) return cached;
+
+ if (appEnv.enableQueueAgentRuntime) {
+ const baseUrl = process.env.APP_URL;
+ if (!baseUrl) throw new Error('APP_URL is required to schedule goal advances via QStash');
+ cached = new QStashGoalScheduler({ baseUrl, qstashClient });
+ return cached;
+ }
+
+ cached = new LocalGoalScheduler();
+ return cached;
+};
+
+export { LocalGoalScheduler } from './local';
+export { GOAL_ADVANCE_PATH } from './qstash';
+export { QStashGoalScheduler } from './qstash';
+export type { GoalSchedulerImpl, ScheduleGoalAdvanceParams } from './type';
diff --git a/apps/server/src/services/goal/scheduler/impls/local.ts b/apps/server/src/services/goal/scheduler/impls/local.ts
new file mode 100644
index 00000000000..8e53685832c
--- /dev/null
+++ b/apps/server/src/services/goal/scheduler/impls/local.ts
@@ -0,0 +1,34 @@
+import debug from 'debug';
+
+import { advanceGoal } from '../../advanceGoal';
+import type { GoalSchedulerImpl, ScheduleGoalAdvanceParams } from './type';
+
+const log = debug('goal-scheduler:local');
+
+/**
+ * Dev / desktop scheduler: a `setTimeout` in this process instead of a queue
+ * message. It calls the same runner the HTTP handler calls, so local runs
+ * exercise the real advance path rather than a stub.
+ */
+export class LocalGoalScheduler implements GoalSchedulerImpl {
+ private pending = new Map<string, NodeJS.Timeout>();
+
+ async scheduleAdvance(params: ScheduleGoalAdvanceParams): Promise<string> {
+ const { delay = 0, goalId, userId, workspaceId } = params;
+ const scheduleId = `local-goal-${goalId}-${Date.now()}`;
+
+ log('scheduling advance for goal %s (delay: %ds)', goalId, delay);
+ const timer = setTimeout(async () => {
+ this.pending.delete(scheduleId);
+ try {
+ await advanceGoal({ goalId, userId, workspaceId });
+ } catch (error) {
+ // Never surface: an advance is best-effort, and the sweep retries.
+ log('advance failed for goal %s: %O', goalId, error);
+ }
+ }, delay * 1000);
+
+ this.pending.set(scheduleId, timer);
+ return scheduleId;
+ }
+}
diff --git a/apps/server/src/services/goal/scheduler/impls/qstash.ts b/apps/server/src/services/goal/scheduler/impls/qstash.ts
new file mode 100644
index 00000000000..e847832be9d
--- /dev/null
+++ b/apps/server/src/services/goal/scheduler/impls/qstash.ts
@@ -0,0 +1,46 @@
+import type { Client } from '@upstash/qstash';
+import debug from 'debug';
+
+import type { GoalSchedulerImpl, ScheduleGoalAdvanceParams } from './type';
+
+const log = debug('goal-scheduler:qstash');
+
+export const GOAL_ADVANCE_PATH = '/api/workflows/goal/advance';
+
+export interface QStashGoalSchedulerConfig {
+ /** Absolute base URL (e.g. `process.env.APP_URL`) used to build the callback URL. */
+ baseUrl: string;
+ qstashClient: Client;
+}
+
+/**
+ * QStash-backed goal scheduler.
+ *
+ * Publishes a one-shot message; QStash POSTs `{ goalId, userId, workspaceId }`
+ * to `/api/workflows/goal/advance`. The handler re-reads the goal, so a message
+ * that arrives after the user paused or the goal finished is a no-op — the
+ * database is the authority, never the message.
+ */
+export class QStashGoalScheduler implements GoalSchedulerImpl {
+ private baseUrl: string;
+ private qstashClient: Client;
+
+ constructor(config: QStashGoalSchedulerConfig) {
+ this.qstashClient = config.qstashClient;
+ this.baseUrl = config.baseUrl.replace(/\/$/, '');
+ }
+
+ async scheduleAdvance(params: ScheduleGoalAdvanceParams): Promise<string> {
+ const { delay = 0, goalId, userId, workspaceId } = params;
+ const url = `${this.baseUrl}${GOAL_ADVANCE_PATH}`;
+
+ log('publishing advance: goal=%s delay=%ds url=%s', goalId, delay, url);
+ const response = await this.qstashClient.publishJSON({
+ body: { goalId, userId, workspaceId },
+ delay,
+ url,
+ });
+
+ return 'messageId' in response ? response.messageId : '';
+ }
+}
diff --git a/apps/server/src/services/goal/scheduler/impls/type.ts b/apps/server/src/services/goal/scheduler/impls/type.ts
new file mode 100644
index 00000000000..bced80dfc46
--- /dev/null
+++ b/apps/server/src/services/goal/scheduler/impls/type.ts
@@ -0,0 +1,11 @@
+export interface ScheduleGoalAdvanceParams {
+ /** Seconds to wait before advancing. Defaults to 0 (as soon as possible). */
+ delay?: number;
+ goalId: string;
+ userId: string;
+ workspaceId?: string;
+}
+
+export interface GoalSchedulerImpl {
+ scheduleAdvance: (params: ScheduleGoalAdvanceParams) => Promise<string>;
+}
diff --git a/apps/server/src/services/goal/scheduler/index.ts b/apps/server/src/services/goal/scheduler/index.ts
new file mode 100644
index 00000000000..36ea6d5d379
--- /dev/null
+++ b/apps/server/src/services/goal/scheduler/index.ts
@@ -0,0 +1,30 @@
+import debug from 'debug';
+
+import { createGoalSchedulerModule, type ScheduleGoalAdvanceParams } from './impls';
+
+const log = debug('goal-scheduler');
+
+/**
+ * Ask the coordinator to advance a goal, without waiting for it.
+ *
+ * Every caller is a place where a goal *might* now be able to move — it was
+ * created, a gate was resolved, a budget was raised, a Work Task settled. None
+ * of them should fail because the advance could not be queued, and none of them
+ * should block on it: the handler re-reads the goal, and the sweep picks up
+ * anything a lost message would have stranded.
+ */
+export const scheduleGoalAdvance = async (params: ScheduleGoalAdvanceParams): Promise<void> => {
+ try {
+ await createGoalSchedulerModule().scheduleAdvance(params);
+ log('queued advance for goal %s', params.goalId);
+ } catch (error) {
+ // Loud on purpose: this is the only thing that makes a goal move on its
+ // own, so a broken dispatch must be visible in the logs rather than left to
+ // be inferred from goals that quietly stop progressing. The sweep still
+ // covers the goal, which is why this stays non-fatal for the caller.
+ console.error('[goal/scheduler] failed to queue advance for %s:', params.goalId, error);
+ }
+};
+
+export type { GoalSchedulerImpl, ScheduleGoalAdvanceParams } from './impls';
+export { createGoalSchedulerModule, GOAL_ADVANCE_PATH } from './impls';
diff --git a/apps/server/src/services/goal/workRecoveryCoordinator.ts b/apps/server/src/services/goal/workRecoveryCoordinator.ts
index a0883b7bf6d..081526dffbc 100644
--- a/apps/server/src/services/goal/workRecoveryCoordinator.ts
+++ b/apps/server/src/services/goal/workRecoveryCoordinator.ts
@@ -2,6 +2,7 @@ import type { GoalItem, TaskItem } from '@lobechat/types';
import debug from 'debug';
import { AgentOperationModel } from '@/database/models/agentOperation';
+import { TaskModel } from '@/database/models/task';
import type { LobeChatDatabase } from '@/database/type';
import { TaskRunnerService } from '@/server/services/taskRunner';
@@ -12,7 +13,7 @@ const log = debug('lobe-server:goal-work-recovery');
export type WorkRecoveryOutcome =
'continued' | 'exhausted-cost' | 'exhausted-rounds' | 'spawn-failed';
-/** Shared retry budget and spawn boundary for task-carried goals and Goal Graph Work Tasks. */
+/** Retry budget and spawn boundary for a Goal Graph Work Task. */
export class WorkRecoveryCoordinator {
constructor(
private readonly db: LobeChatDatabase,
@@ -24,11 +25,10 @@ export class WorkRecoveryCoordinator {
goal: GoalItem;
spentCost?: number;
task: TaskItem;
- taskCarried: boolean;
}): Promise<WorkRecoveryOutcome> => {
- const { goal, task, taskCarried } = params;
+ const { goal, task } = params;
const attempts = task.totalTopics || 0;
- const attemptBudget = resolveWorkAttemptBudget(goal, taskCarried);
+ const attemptBudget = resolveWorkAttemptBudget(goal);
if (attempts >= attemptBudget) return 'exhausted-rounds';
if (typeof goal.maxTotalCost === 'number') {
@@ -40,6 +40,30 @@ export class WorkRecoveryCoordinator {
if (spent >= goal.maxTotalCost) return 'exhausted-cost';
}
+ // Both recovery paths — a failed verification and an abandoned operation —
+ // reach here from `tick`, and advances overlap: an event hook, a manual
+ // nudge, the sweep. `runTask` decides whether a run is in flight by reading
+ // the task's topics before creating one, so without this claim two
+ // coordinators would each spawn a paid retry of the same Work.
+ //
+ // Both paths hand us a task row read before they paused it, so the claim
+ // has to compare against what the row says now. A task already `running`
+ // is one another advance has claimed — leave it to that one.
+ const taskModel = new TaskModel(this.db, this.userId, this.workspaceId);
+ const current = await taskModel.findById(task.id);
+ if (!current || current.status === 'running') {
+ log('task %s recovery was already claimed by another advance', task.identifier);
+ return 'continued';
+ }
+ const claimed = await taskModel.updateStatusIfCurrent(task.id, current.status, 'running', {
+ error: null,
+ startedAt: new Date(),
+ });
+ if (!claimed) {
+ log('task %s recovery lost the claim race', task.identifier);
+ return 'continued';
+ }
+
try {
await new TaskRunnerService(this.db, this.userId, this.workspaceId).runTask({
maxSteps: resolveWorkMaxSteps(goal),
@@ -50,6 +74,12 @@ export class WorkRecoveryCoordinator {
return 'continued';
} catch (error) {
log('task %s recovery spawn failed (non-fatal): %O', task.identifier, error);
+ // We own the claim, so nothing else will put the task back.
+ await taskModel
+ .updateStatusIfCurrent(task.id, 'running', current.status, { error: current.error })
+ .catch((releaseError) => {
+ log('task %s failed to release the recovery claim: %O', task.identifier, releaseError);
+ });
return 'spawn-failed';
}
};
diff --git a/apps/server/src/services/task/index.test.ts b/apps/server/src/services/task/index.test.ts
index 183c962f817..73379809f26 100644
--- a/apps/server/src/services/task/index.test.ts
+++ b/apps/server/src/services/task/index.test.ts
@@ -45,19 +45,10 @@ vi.mock('@/database/models/user', () => ({
UserModel: { findByIds: vi.fn().mockResolvedValue([]) },
}));
-const { goalCreate, goalFindBySubject } = vi.hoisted(() => ({
- goalCreate: vi.fn(),
- goalFindBySubject: vi.fn().mockResolvedValue(undefined),
-}));
-
const { resolveTaskAcceptance } = vi.hoisted(() => ({
resolveTaskAcceptance: vi.fn(),
}));
-vi.mock('@/database/models/goal', () => ({
- GoalModel: vi.fn(() => ({ create: goalCreate, findBySubject: goalFindBySubject })),
-}));
-
vi.mock('@/server/services/verify/taskAcceptance', () => ({ resolveTaskAcceptance }));
// AiAgentService pulls in ~14 sub-dependencies in its constructor; mock it so
@@ -1680,57 +1671,6 @@ describe('TaskService', () => {
});
});
- describe('createTask goal binding', () => {
- beforeEach(() => {
- mockTaskModel.create.mockResolvedValue({
- assigneeAgentId: 'agent-1',
- id: 'task_goal_1',
- identifier: 'T-9',
- instruction: 'reach the goal',
- name: 'Goal task',
- projectId: null,
- });
- mockTaskModel.delete.mockResolvedValue(true);
- goalCreate.mockReset();
- });
-
- it('creates the bound goals row and returns it on the task', async () => {
- goalCreate.mockResolvedValue({ id: 'goal-1', status: 'planning' });
-
- const service = new TaskService(db, userId);
- const result = await service.createTask({
- goal: { maxRounds: 4, maxTotalCost: 10, requirement: 'done means done' },
- instruction: 'reach the goal',
- });
-
- expect(goalCreate).toHaveBeenCalledWith(
- expect.objectContaining({
- maxRounds: 4,
- maxTotalCost: 10,
- requirement: 'done means done',
- subjectId: 'task_goal_1',
- subjectType: 'task',
- }),
- );
- expect((result as any).goal).toEqual({ id: 'goal-1', status: 'planning' });
- expect(mockTaskModel.delete).not.toHaveBeenCalled();
- });
-
- it('compensates a failed goal insert by deleting the just-created task', async () => {
- // Regression (codex review): a task committed without its promised goal
- // is a user-visible ghost — it never lists on goal surfaces, and a retry
- // stacks another plain task.
- goalCreate.mockRejectedValue(new Error('db down'));
-
- const service = new TaskService(db, userId);
- await expect(
- service.createTask({ goal: { maxRounds: 3 }, instruction: 'reach the goal' }),
- ).rejects.toThrow('db down');
-
- expect(mockTaskModel.delete).toHaveBeenCalledWith('task_goal_1');
- });
- });
-
describe('parent ↔ child visibility compat', () => {
beforeEach(() => {
mockTaskModel.create.mockImplementation(async (data: any) => ({
diff --git a/apps/server/src/services/task/index.ts b/apps/server/src/services/task/index.ts
index 1d892f9192c..05e66922f2b 100644
--- a/apps/server/src/services/task/index.ts
+++ b/apps/server/src/services/task/index.ts
@@ -1,10 +1,7 @@
import { randomUUID } from 'node:crypto';
import { TASK_ASSIGNEE_PERMISSION_CODES } from '@lobechat/const/rbac';
-import { DEFAULT_GOAL_MAX_ROUNDS } from '@lobechat/const/verify';
import type {
- CreateTaskGoalInput,
- GoalItem,
TaskContext,
TaskDetailActivity,
TaskDetailActivityAuthor,
@@ -20,7 +17,6 @@ import type {
import { TRPCError } from '@trpc/server';
import { AgentModel } from '@/database/models/agent';
-import { GoalModel } from '@/database/models/goal';
import { ProjectModel } from '@/database/models/project';
import { RbacModel } from '@/database/models/rbac';
import { isTaskIdentifierUniqueViolation, TaskModel } from '@/database/models/task';
@@ -69,11 +65,6 @@ export interface CreateTaskInput {
description?: string;
editorData?: unknown;
fileIds?: string[];
- /**
- * Bind a goal entity (`goals` row) to the created task — the task becomes the
- * goal's execution carrier and the outer verify-driven round loop applies.
- */
- goal?: CreateTaskGoalInput;
identifierPrefix?: string;
instruction: string;
name?: string;
@@ -137,8 +128,8 @@ export class TaskService {
await this.assertAssigneeAgentBelongsToUser(input.assigneeAgentId);
this.assertAutomationAssigneeCompat(input.automationMode, input.assigneeUserId);
- const { goal, ...taskInput } = input;
- const createData: Omit<CreateTaskInput, 'goal'> & { config?: Record<string, unknown> } = {
+ const taskInput = input;
+ const createData: CreateTaskInput & { config?: Record<string, unknown> } = {
...taskInput,
};
@@ -209,39 +200,6 @@ export class TaskService {
const task = await this.createTaskWithAssigneeLock(createData);
- if (goal) {
- // Goal creation stays separate from the task write because the task's
- // membership-locked transaction has already committed. Compensate on
- // failure — a task committed without its promised goal is a ghost on
- // goal surfaces (it never lists as a goal), and a retry would stack
- // another one.
- let created: GoalItem;
- try {
- created = await new GoalModel(this.db, this.userId, this.workspaceId).create({
- agentId: task.assigneeAgentId,
- // `null` is the user's explicit "no cap"; `undefined` means they never
- // chose, which falls back to the documented default. The floor keeps a
- // degenerate 1-round loop from ever passing verify-then-stop.
- maxRounds:
- goal.maxRounds === undefined
- ? DEFAULT_GOAL_MAX_ROUNDS
- : goal.maxRounds === null
- ? null
- : Math.max(2, goal.maxRounds),
- maxTotalCost: goal.maxTotalCost ?? null,
- projectId: task.projectId,
- requirement: goal.requirement ?? null,
- subjectId: task.id,
- subjectType: 'task',
- title: goal.title?.trim() || task.name?.trim() || task.instruction,
- });
- } catch (error) {
- await this.taskModel.delete(task.id).catch(() => {});
- throw error;
- }
- return { ...task, goal: created };
- }
-
return task;
}
@@ -492,20 +450,6 @@ export class TaskService {
const task = await this.taskModel.updateStatus(resolved.id, status, extra);
if (!task) throw new TRPCError({ code: 'NOT_FOUND', message: 'Task not found' });
- // Canceling the carrier task cancels its goal: the loop has no executor
- // left, and a "running" goal over a canceled task would be a lie. The
- // user's positive sign-off (`achieved`) is never downgraded. Best-effort —
- // goal state must not block the task transition.
- if (status === 'canceled') {
- try {
- const goalModel = new GoalModel(this.db, this.userId, this.workspaceId);
- const goal = await goalModel.findBySubject('task', task.id);
- if (goal && goal.status !== 'achieved') await goalModel.updateStatus(goal.id, 'canceled');
- } catch (err) {
- console.error('[TaskService.updateStatus] goal cancel mirror failed:', err);
- }
- }
-
// Stamp the schedule run-count window each time the user (re)starts a
// scheduled task. The cron dispatcher itself flips a task running →
// scheduled on every tick, so we exclude that natural cycle by only
@@ -744,7 +688,7 @@ export class TaskService {
}
private async createTaskWithAssigneeLock(
- createData: Omit<CreateTaskInput, 'goal'> & { config?: Record<string, unknown> },
+ createData: CreateTaskInput & { config?: Record<string, unknown> },
): Promise<TaskItem> {
if (!createData.assigneeUserId || !this.workspaceId) {
await this.assertAssigneeUserAssignable(createData.assigneeUserId);
@@ -809,7 +753,7 @@ export class TaskService {
// brief-type activities — the UI converges on Task Run. Briefs are therefore
// not fetched/enriched here (see the omitted brief spread below). The brief
// lifecycle, model and data are untouched; revert this to bring them back.
- const [allDescendants, dependencies, directTopics, comments, workspace, goal, acceptance] =
+ const [allDescendants, dependencies, directTopics, comments, workspace, acceptance] =
await Promise.all([
this.taskModel.findAllDescendants(task.id),
this.taskModel.getDependencies(task.id),
@@ -818,9 +762,6 @@ export class TaskService {
.catch(() => []),
this.taskModel.getComments(task.id).catch(() => []),
this.taskModel.getTreePinnedDocuments(task.id).catch(() => emptyWorkspace),
- new GoalModel(this.db, this.userId, this.workspaceId)
- .findBySubject('task', task.id)
- .catch(() => undefined),
resolveTaskAcceptance(this.db, this.userId, task.id, this.workspaceId).catch(
() => undefined,
),
@@ -1069,7 +1010,7 @@ export class TaskService {
time: toISO(t.createdAt),
title: handoff?.title || t.title || UNTITLED_TOPIC_TITLE,
// What opened this round. Without it the feed cannot distinguish a run
- // the user started from one the goal loop / scheduler opened on its
+ // the user started from one the goal coordinator / scheduler opened on its
// own — they render identically apart from `#seq`.
trigger: t.trigger ?? null,
verify: verifyRun
@@ -1133,7 +1074,6 @@ export class TaskService {
editorData: task.editorData ?? undefined,
error: task.error,
files: taskFiles.length > 0 ? taskFiles : undefined,
- goal: goal ?? null,
heartbeat:
task.heartbeatInterval || task.heartbeatTimeout || task.lastHeartbeatAt
? {
diff --git a/apps/server/src/services/taskLifecycle/index.ts b/apps/server/src/services/taskLifecycle/index.ts
index 1d51fdc1e2c..5a6863519b3 100644
--- a/apps/server/src/services/taskLifecycle/index.ts
+++ b/apps/server/src/services/taskLifecycle/index.ts
@@ -199,15 +199,13 @@ export class TaskLifecycleService {
// The agent-driven `createBrief` tool path stays the default until
// the GrowthBook flag flips. See for the rollout plan.
//
- // Goal-loop rounds are deliberately silent. The outer loop can run many
- // rounds before it converges, and a card per round buries the one moment
- // that actually needs the user. The settle path owns those moments:
- // `driveTaskFromVerify` raises "delivery ready for sign-off" when the
- // loop succeeds and the budget-exhausted alert when it stops.
+ // Goal Work rounds are deliberately silent. The coordinator can run
+ // many attempts on one Work before it converges, and a card per round
+ // buries the one moment that actually needs the user — the decision
+ // gate the coordinator opens when the attempt budget runs out.
const isGoalLoopRound =
!!currentTask &&
- !!(await new GoalModel(this.db, this.userId, this.workspaceId).findBySubject(
- 'task',
+ !!(await new GoalModel(this.db, this.userId, this.workspaceId).findByWorkTask(
currentTask.id,
));
if (
diff --git a/apps/server/src/services/taskLifecycle/onTopicComplete.test.ts b/apps/server/src/services/taskLifecycle/onTopicComplete.test.ts
index 1caa250332d..28632ff6f16 100644
--- a/apps/server/src/services/taskLifecycle/onTopicComplete.test.ts
+++ b/apps/server/src/services/taskLifecycle/onTopicComplete.test.ts
@@ -30,9 +30,9 @@ vi.mock('@/database/models/verifyRun', () => ({
// Goal-loop rounds suppress the per-topic brief; onTopicComplete asks the
// goals table whether this task carries a goal. Default = plain task.
-const goalFindBySubject = vi.fn().mockResolvedValue(undefined);
+const goalFindByWorkTask = vi.fn().mockResolvedValue(undefined);
vi.mock('@/database/models/goal', () => ({
- GoalModel: vi.fn(() => ({ findBySubject: goalFindBySubject })),
+ GoalModel: vi.fn(() => ({ findByWorkTask: goalFindByWorkTask })),
}));
// Error-brief copy is localized at the source via the server translator; mock it
diff --git a/apps/server/src/services/taskRunner/buildTaskPrompt.ts b/apps/server/src/services/taskRunner/buildTaskPrompt.ts
index 9ee34828770..ab310e01b6f 100644
--- a/apps/server/src/services/taskRunner/buildTaskPrompt.ts
+++ b/apps/server/src/services/taskRunner/buildTaskPrompt.ts
@@ -31,12 +31,10 @@ const resolveGoalLoopContext = async (
deps: BuildTaskPromptDeps,
): Promise<TaskRunPromptGoalLoop | undefined> => {
const { db, userId, workspaceId } = deps;
- const goalModel = new GoalModel(db, userId, workspaceId);
- const taskCarriedGoal = await goalModel.findBySubject('task', task.id);
- const goal = taskCarriedGoal ?? (await goalModel.findByWorkTask(task.id));
+ const goal = await new GoalModel(db, userId, workspaceId).findByWorkTask(task.id);
if (!goal || !task.totalTopics) return undefined;
- const budget = resolveWorkAttemptBudget(goal, Boolean(taskCarriedGoal));
+ const budget = resolveWorkAttemptBudget(goal);
const context: TaskRunPromptGoalLoop = {
maxRounds: Number.isFinite(budget) ? budget : null,
round: (task.totalTopics || 0) + 1,
diff --git a/apps/server/src/services/toolExecution/serverRuntimes/__tests__/goal.test.ts b/apps/server/src/services/toolExecution/serverRuntimes/__tests__/goal.test.ts
new file mode 100644
index 00000000000..3858825435b
--- /dev/null
+++ b/apps/server/src/services/toolExecution/serverRuntimes/__tests__/goal.test.ts
@@ -0,0 +1,66 @@
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+const mocks = vi.hoisted(() => ({
+ advanceGoal: vi.fn(),
+ create: vi.fn(),
+ scheduleGoalAdvance: vi.fn(),
+}));
+
+vi.mock('@/server/services/goal', () => ({
+ GoalService: vi.fn(() => ({ create: mocks.create })),
+}));
+vi.mock('@/server/services/goal/advanceGoal', () => ({ advanceGoal: mocks.advanceGoal }));
+vi.mock('@/server/services/goal/scheduler', () => ({
+ scheduleGoalAdvance: mocks.scheduleGoalAdvance,
+}));
+
+const { goalRuntime } = await import('../goal');
+
+const runtime = () =>
+ goalRuntime.factory({
+ agentId: 'agt_1',
+ serverDB: {} as never,
+ toolManifestMap: {},
+ userId: 'user-1',
+ workspaceId: 'ws-1',
+ } as never);
+
+const args = {
+ criteria: [{ title: 'It works' }],
+ instruction: 'do the thing',
+ name: 'A goal',
+};
+
+beforeEach(() => {
+ vi.clearAllMocks();
+ mocks.create.mockResolvedValue({ goal: { id: 'goal_1', title: 'A goal' } });
+});
+
+describe('goalRuntime.createGoal', () => {
+ it('queues the advance so a failed kickoff is genuinely recoverable', async () => {
+ // This path calls GoalService directly, so nothing else schedules the goal.
+ // Without the queued advance the "the server will pick it up" message below
+ // is false and the goal sits in `planning` forever.
+ mocks.advanceGoal.mockRejectedValue(new Error('runner offline'));
+
+ const result = await runtime().createGoal(args);
+
+ expect(mocks.scheduleGoalAdvance).toHaveBeenCalledWith({
+ goalId: 'goal_1',
+ userId: 'user-1',
+ workspaceId: 'ws-1',
+ });
+ expect(result.success).toBe(true);
+ expect(result.content).toContain('Do not create it again');
+ });
+
+ it('reports the started goal when the kickoff succeeds', async () => {
+ mocks.advanceGoal.mockResolvedValue({ result: { message: 'Started task T-1', taskId: 't1' } });
+
+ const result = await runtime().createGoal(args);
+
+ expect(mocks.scheduleGoalAdvance).toHaveBeenCalledOnce();
+ expect(result.success).toBe(true);
+ expect(result.content).toContain('Started task T-1');
+ });
+});
diff --git a/apps/server/src/services/toolExecution/serverRuntimes/__tests__/task.test.ts b/apps/server/src/services/toolExecution/serverRuntimes/__tests__/task.test.ts
index b2490db80e2..25d8fea22a1 100644
--- a/apps/server/src/services/toolExecution/serverRuntimes/__tests__/task.test.ts
+++ b/apps/server/src/services/toolExecution/serverRuntimes/__tests__/task.test.ts
@@ -28,116 +28,6 @@ vi.mock('@/server/services/verify/planGenerator', () => ({
}));
describe('createTaskRuntime', () => {
- describe('createGoal', () => {
- it('leaves an omitted round budget unset so the default cap applies', async () => {
- verifyMocks.createCriteriaFromDrafts.mockResolvedValueOnce(['criterion-1']);
- const taskCaller = {
- run: vi.fn().mockResolvedValue({ operationId: 'op-1', topicId: 'topic-1' }),
- updateVerifyConfig: vi.fn().mockResolvedValue(undefined),
- };
- const taskModel = { updateTaskConfig: vi.fn().mockResolvedValue(undefined) };
- const taskService = {
- createTask: vi.fn().mockResolvedValue({
- id: 'task-db-1',
- identifier: 'T-1',
- name: 'Ship homepage',
- priority: 0,
- status: 'backlog',
- }),
- };
- const runtime = createTaskRuntime({
- agentId: 'agt-1',
- agentModel: { existsById: vi.fn().mockResolvedValue(true) } as any,
- db: {} as any,
- taskCaller: taskCaller as any,
- taskModel: taskModel as any,
- taskService: taskService as any,
- topicId: 'origin-topic',
- userId: 'user-1',
- });
-
- await runtime.createGoal({
- criteria: [{ title: 'LCP under two seconds' }],
- instruction: 'Make the homepage fast.',
- name: 'Ship homepage',
- });
-
- // `null` means "uncapped"; coercing an omitted budget into it would let a
- // failing goal spawn rounds forever. The service resolves `undefined`
- // into the documented default at write time.
- const [createInput] = taskService.createTask.mock.calls[0];
- expect(createInput.goal.maxRounds).toBeUndefined();
- });
-
- it('creates, configures, and starts one verified task', async () => {
- verifyMocks.createCriteriaFromDrafts.mockResolvedValueOnce(['criterion-1']);
- const taskCaller = {
- run: vi.fn().mockResolvedValue({ operationId: 'op-1', topicId: 'topic-1' }),
- updateVerifyConfig: vi.fn().mockResolvedValue(undefined),
- };
- const taskModel = { updateTaskConfig: vi.fn().mockResolvedValue(undefined) };
- const taskService = {
- createTask: vi.fn().mockResolvedValue({
- id: 'task-db-1',
- identifier: 'T-1',
- name: 'Ship homepage',
- priority: 0,
- status: 'backlog',
- }),
- };
- const runtime = createTaskRuntime({
- agentId: 'agt-1',
- agentModel: { existsById: vi.fn().mockResolvedValue(true) } as any,
- db: {} as any,
- taskCaller: taskCaller as any,
- taskModel: taskModel as any,
- taskService: taskService as any,
- topicId: 'origin-topic',
- userId: 'user-1',
- });
-
- const result = await runtime.createGoal({
- criteria: [{ title: 'LCP under two seconds' }],
- instruction: 'Redesign and ship the homepage',
- maxIterations: 3,
- maxTotalCost: 12,
- name: 'Ship homepage',
- });
-
- expect(result.success).toBe(true);
- expect(verifyMocks.createCriteriaFromDrafts).toHaveBeenCalledWith([
- expect.objectContaining({ onFail: 'auto_repair', required: true }),
- ]);
- expect(taskCaller.updateVerifyConfig).toHaveBeenCalledWith({
- id: 'task-db-1',
- verify: expect.objectContaining({
- enabled: true,
- maxIterations: 3,
- verifyCriteriaIds: ['criterion-1'],
- }),
- });
- // The goal entity is bound at task creation, not merged into config later.
- expect(taskService.createTask).toHaveBeenCalledWith(
- expect.objectContaining({
- goal: {
- maxRounds: 3,
- maxTotalCost: 12,
- requirement: 'Ship homepage',
- title: 'Ship homepage',
- },
- }),
- );
- expect(taskModel.updateTaskConfig).not.toHaveBeenCalled();
- expect(taskCaller.run).toHaveBeenCalledWith({ id: 'task-db-1' });
- // The success branch is the only one carrying `state`; narrow to it so
- // this asserts the shape rather than the union.
- expect(result).toHaveProperty('state');
- expect((result as { state: unknown }).state).toEqual(
- expect.objectContaining({ identifier: 'T-1', success: true, taskId: 'task-db-1' }),
- );
- });
- });
-
describe('task comments', () => {
it('adds a comment to the current task with agent attribution', async () => {
const taskCaller = {
diff --git a/apps/server/src/services/toolExecution/serverRuntimes/goal.ts b/apps/server/src/services/toolExecution/serverRuntimes/goal.ts
new file mode 100644
index 00000000000..85382355b2d
--- /dev/null
+++ b/apps/server/src/services/toolExecution/serverRuntimes/goal.ts
@@ -0,0 +1,123 @@
+import {
+ buildGoalRequirement,
+ GoalIdentifier,
+ resolveGoalAttemptBudget,
+} from '@lobechat/builtin-tool-goal';
+
+import { GoalService } from '@/server/services/goal';
+import { advanceGoal } from '@/server/services/goal/advanceGoal';
+import { scheduleGoalAdvance } from '@/server/services/goal/scheduler';
+
+import type { ServerRuntimeRegistration } from './types';
+
+/**
+ * Server-side `/goal`: create a Goal Graph and advance it once.
+ *
+ * It lives in its own runtime rather than on the task runtime because a goal is
+ * no longer a task with a `goals` row attached — the graph owns the
+ * decomposition and dispatches its own Work Tasks.
+ */
+export const goalRuntime: ServerRuntimeRegistration = {
+ factory: (context) => {
+ if (!context.userId || !context.serverDB) {
+ throw new Error('userId and serverDB are required for Goal tool execution');
+ }
+ const { agentId, serverDB, userId, workspaceId } = context;
+
+ return {
+ createGoal: async (args: {
+ criteria: Array<{ description?: string; instruction?: string; title: string }>;
+ instruction: string;
+ maxIterations?: number | null;
+ maxTotalCost?: number | null;
+ name: string;
+ }) => {
+ if (!agentId) return { content: 'A goal needs the current agent.', success: false };
+
+ const drafts = (args.criteria ?? []).filter((item) => item.title?.trim());
+ if (drafts.length === 0) {
+ return { content: 'A goal needs at least one acceptance criterion.', success: false };
+ }
+
+ try {
+ const goalService = new GoalService(serverDB, userId, workspaceId ?? undefined);
+ const graph = await goalService.create({
+ agentId,
+ config: {
+ recovery: { maxAttemptsPerWork: resolveGoalAttemptBudget(args.maxIterations) },
+ },
+ // `maxIterations` caps attempts on one Work; it is deliberately not
+ // passed as `maxRounds`, which counts runs across every Work in the
+ // graph and would strand later tasks that have not run at all.
+ maxTotalCost: args.maxTotalCost ?? undefined,
+ requirement: buildGoalRequirement(args.name, drafts, args.instruction),
+ title: args.name,
+ work: [{ description: args.instruction, title: args.name }],
+ });
+ // The TRPC `goal.create` route queues this; calling the service
+ // directly does not. Without it the "the server will pick it up"
+ // promise below is false — outside queue mode there is no local timer
+ // for the goal and no recurring sweep, so it would sit in `planning`
+ // while the agent has been told not to create it again.
+ await scheduleGoalAdvance({
+ goalId: graph.goal.id,
+ userId,
+ workspaceId: workspaceId ?? undefined,
+ });
+
+ const created = `Goal "${graph.goal.title}" created with ${drafts.length} acceptance criteria.`;
+ const tail =
+ 'Execution continues in its own task; do not perform or reproduce the work in this conversation.';
+
+ // The goal is committed. Kickoff failure must not be reported as
+ // creation failure — an agent told the goal was not created makes
+ // another one, and both then do the same paid work. `goal.create`
+ // already queued an advance, so this is only about immediate feedback.
+ try {
+ // Advance until the coordinator is waiting on something other than a
+ // tick — normally that is the first Work Task executing. From there
+ // the goal keeps itself moving through the queued advances.
+ const { result } = await advanceGoal({
+ goalId: graph.goal.id,
+ userId,
+ workspaceId: workspaceId ?? undefined,
+ });
+
+ return {
+ content: `${created} ${result.message}. ${tail}`,
+ state: {
+ goalId: graph.goal.id,
+ name: args.name,
+ startedAt: new Date().toISOString(),
+ success: true,
+ taskId: result.taskId,
+ },
+ success: true,
+ };
+ } catch (error) {
+ const message =
+ error instanceof Error ? error.message : 'Could not start it right away';
+ return {
+ content: `${created} It has not started yet (${message}); the server will pick it up. Do not create it again. ${tail}`,
+ state: {
+ goalId: graph.goal.id,
+ name: args.name,
+ startedAt: new Date().toISOString(),
+ success: true,
+ },
+ success: true,
+ };
+ }
+ } catch (error) {
+ const message = error instanceof Error ? error.message : 'Failed to create the goal';
+ return {
+ content: `Could not create the goal: ${message}`,
+ state: { name: args.name, success: false },
+ success: false,
+ };
+ }
+ },
+ };
+ },
+ identifier: GoalIdentifier,
+};
diff --git a/apps/server/src/services/toolExecution/serverRuntimes/index.ts b/apps/server/src/services/toolExecution/serverRuntimes/index.ts
index 597a54c808d..32370fe59a0 100644
--- a/apps/server/src/services/toolExecution/serverRuntimes/index.ts
+++ b/apps/server/src/services/toolExecution/serverRuntimes/index.ts
@@ -6,7 +6,6 @@
* - Pre-instantiated runtimes (e.g., WebBrowsing - no per-request context needed)
* - Per-request runtimes (e.g., CloudSandbox - needs topicId, userId)
*/
-import { GoalIdentifier } from '@lobechat/builtin-tool-goal';
import type { ToolExecutionContext } from '../types';
import { acceptanceEvidenceRuntime } from './acceptanceEvidence';
@@ -23,6 +22,7 @@ import { browserRuntime } from './browser';
import { calculatorRuntime } from './calculator';
import { cloudSandboxRuntime } from './cloudSandbox';
import { credsRuntime } from './creds';
+import { goalRuntime } from './goal';
import { groupAgentBuilderRuntime } from './groupAgentBuilder';
import { groupManagementRuntime } from './groupManagement';
import { imageGenerationRuntime } from './imageGeneration';
@@ -46,14 +46,6 @@ import { verifyResultRuntime } from './verifyResult';
import { webBrowsingRuntime } from './webBrowsing';
import { webOnboardingRuntime } from './webOnboarding';
-const goalRuntime: ServerRuntimeRegistration = {
- factory: async (context) => {
- const runtime = await taskRuntime.factory(context);
- return { createGoal: runtime.createGoal };
- },
- identifier: GoalIdentifier,
-};
-
/**
* Registry of server runtime factories by identifier
*/
diff --git a/apps/server/src/services/toolExecution/serverRuntimes/task.ts b/apps/server/src/services/toolExecution/serverRuntimes/task.ts
index 27c8094cc2e..3929ab92576 100644
--- a/apps/server/src/services/toolExecution/serverRuntimes/task.ts
+++ b/apps/server/src/services/toolExecution/serverRuntimes/task.ts
@@ -22,7 +22,6 @@ import { tasks } from '@/database/schemas';
import { appEnv } from '@/envs/app';
import { taskRouter } from '@/server/routers/lambda/task';
import { TaskService } from '@/server/services/task';
-import { VerifyPlanGeneratorService } from '@/server/services/verify/planGenerator';
import { type ServerRuntimeRegistration } from './types';
@@ -169,7 +168,6 @@ export const createTaskRuntime = (deps: TaskRuntimeDeps) => {
assigneeAgentId: args.assigneeAgentId ?? (scope === 'task' ? undefined : agentId),
context: origin ? { origin } : undefined,
createdByAgentId: agentId,
- goal: args.goal,
instruction: args.instruction,
name: args.name,
parentTaskId,
@@ -237,100 +235,6 @@ export const createTaskRuntime = (deps: TaskRuntimeDeps) => {
: rest;
},
- createGoal: async (args: {
- criteria: Array<{
- description?: string;
- instruction?: string;
- onFail?: 'auto_repair' | 'manual';
- required?: boolean;
- title: string;
- verifierConfig?: Record<string, unknown>;
- verifierType?: 'agent' | 'llm' | 'program';
- }>;
- instruction: string;
- maxIterations?: number | null;
- maxTotalCost?: number | null;
- name: string;
- }) => {
- if (!agentId) return { content: 'A goal needs the current agent.', success: false };
- if (!deps.db || !deps.userId) {
- return { content: 'Goal planning is unavailable in this runtime.', success: false };
- }
- const drafts = (args.criteria ?? []).filter((item) => item.title?.trim());
- if (drafts.length === 0) {
- return { content: 'A goal needs at least one acceptance criterion.', success: false };
- }
-
- const created = await createTaskImpl({
- assigneeAgentId: agentId,
- // The goals row is created together with the task, so the "is a goal"
- // marker can never race the verify-config write below.
- goal: {
- maxRounds: args.maxIterations,
- maxTotalCost: args.maxTotalCost ?? null,
- requirement: args.name,
- title: args.name,
- },
- instruction: args.instruction,
- name: args.name,
- });
- if (!created.success || !created.identifier || !created.taskId) return created;
-
- try {
- const verifyCriteriaIds = await new VerifyPlanGeneratorService(
- deps.db,
- deps.userId,
- deps.workspaceId,
- ).createCriteriaFromDrafts(
- drafts.map((item) => ({
- description: item.description,
- instruction: item.verifierType === 'program' ? undefined : item.instruction,
- onFail: item.onFail ?? 'auto_repair',
- required: item.required ?? true,
- title: item.title,
- verifierConfig: item.verifierConfig,
- verifierType: item.verifierType ?? 'agent',
- })),
- );
- const maxIterations = Math.min(10, Math.max(2, args.maxIterations ?? 3));
-
- await taskCaller().updateVerifyConfig({
- id: created.taskId,
- verify: {
- enabled: true,
- maxIterations,
- requirement: args.name,
- verifyCriteriaIds,
- },
- });
-
- const run = await taskCaller().run({ id: created.taskId });
- const operationId = (run as { operationId?: string }).operationId;
- const runTopicId = (run as { topicId?: string }).topicId;
-
- return {
- content: `Goal task ${created.identifier} created and started with ${drafts.length} acceptance criteria. Execution continues in its separate task topic; do not perform or reproduce the task in this conversation.`,
- state: {
- identifier: created.identifier,
- name: args.name,
- operationId,
- startedAt: new Date().toISOString(),
- success: true,
- taskId: created.taskId,
- topicId: runTopicId,
- },
- success: true,
- };
- } catch (error) {
- const message = error instanceof Error ? error.message : 'Failed to start goal';
- return {
- content: `Goal task ${created.identifier} was created but could not be started: ${message}`,
- state: { identifier: created.identifier, name: args.name, success: false },
- success: false,
- };
- }
- },
-
createTasks: async (args: { tasks: CreateTaskArgs[] }) => {
const items = Array.isArray(args.tasks) ? args.tasks : [];
if (items.length === 0) {
diff --git a/apps/server/src/services/verify/__tests__/acceptanceDecision.test.ts b/apps/server/src/services/verify/__tests__/acceptanceDecision.test.ts
index 41855cfd73c..23a2c432331 100644
--- a/apps/server/src/services/verify/__tests__/acceptanceDecision.test.ts
+++ b/apps/server/src/services/verify/__tests__/acceptanceDecision.test.ts
@@ -10,8 +10,6 @@ const mocks = vi.hoisted(() => ({
findReportByRun: vi.fn(),
findRunById: vi.fn(),
ensureForSubject: vi.fn(),
- goalFindBySubject: vi.fn(),
- goalUpdateStatus: vi.fn(),
listByAcceptance: vi.fn(),
setDecision: vi.fn(),
taskResolve: vi.fn(),
@@ -41,21 +39,11 @@ vi.mock('@/database/models/verifyEvidence', () => ({ VerifyEvidenceModel: vi.fn(
vi.mock('@/database/models/verifyReport', () => ({
VerifyReportModel: vi.fn(() => ({ findByRun: mocks.findReportByRun })),
}));
-vi.mock('@/database/models/goal', () => ({
- GoalModel: vi.fn(() => ({
- findBySubject: mocks.goalFindBySubject,
- updateStatus: mocks.goalUpdateStatus,
- })),
-}));
vi.mock('@/database/models/task', () => ({
TaskModel: vi.fn(() => ({ resolve: mocks.taskResolve })),
}));
vi.mock('@/database/models/topic', () => ({ TopicModel: vi.fn() }));
vi.mock('@/database/models/document', () => ({ DocumentModel: vi.fn() }));
-vi.mock('../goalLoop', () => ({
- maybeContinueGoalLoop: vi.fn().mockResolvedValue('spawn-failed'),
- syncGoalToolState: vi.fn(),
-}));
vi.mock('@/server/services/task', () => ({ TaskService: vi.fn() }));
const service = () => new AcceptanceService({} as any, 'user-1');
@@ -179,53 +167,3 @@ describe('AcceptanceService decision gating', () => {
expect(mocks.updateStatus).toHaveBeenCalledWith('acc-1', 'rejected');
});
});
-
-describe('AcceptanceService goal-status mirroring', () => {
- const taskAcceptance = (status: string) => ({
- id: 'acc-1',
- status,
- subjectId: 'task-1',
- subjectType: 'task',
- });
-
- beforeEach(() => {
- vi.clearAllMocks();
- mocks.findReportByRun.mockResolvedValue(null);
- mocks.goalFindBySubject.mockResolvedValue({ id: 'goal-1', status: 'running' });
- });
-
- it('does NOT flip a running goal to verifying when the round is merely planned', async () => {
- // Regression (caught by the E2E acceptance run): the verify plan is
- // instantiated and confirmed at RUN START, so the acceptance recompute goes
- // pending → planned while the round is still executing. Mirroring `planned`
- // to `verifying` showed 验证中 for the whole execution phase.
- mocks.findById.mockResolvedValue(taskAcceptance('pending'));
- mocks.listByAcceptance.mockResolvedValue([{ id: 'run-1', roundIndex: 1, status: 'planned' }]);
-
- await expect(service().recomputeStatus('acc-1')).resolves.toBe('planned');
- expect(mocks.goalUpdateStatus).not.toHaveBeenCalled();
- });
-
- it('mirrors a genuinely verifying round onto the goal', async () => {
- mocks.findById.mockResolvedValue(taskAcceptance('planned'));
- mocks.listByAcceptance.mockResolvedValue([{ id: 'run-1', roundIndex: 1, status: 'verifying' }]);
-
- await expect(service().recomputeStatus('acc-1')).resolves.toBe('verifying');
- expect(mocks.goalUpdateStatus).toHaveBeenCalledWith('goal-1', 'verifying');
- });
-
- it('mirrors a delivered round as review, but never re-opens a terminal goal', async () => {
- mocks.findById.mockResolvedValue(taskAcceptance('verifying'));
- mocks.listByAcceptance.mockResolvedValue([{ id: 'run-1', roundIndex: 1, status: 'passed' }]);
-
- await expect(service().recomputeStatus('acc-1')).resolves.toBe('delivered');
- expect(mocks.goalUpdateStatus).toHaveBeenCalledWith('goal-1', 'review');
-
- mocks.goalUpdateStatus.mockClear();
- mocks.goalFindBySubject.mockResolvedValue({ id: 'goal-1', status: 'achieved' });
- mocks.findById.mockResolvedValue(taskAcceptance('verifying'));
-
- await expect(service().recomputeStatus('acc-1')).resolves.toBe('delivered');
- expect(mocks.goalUpdateStatus).not.toHaveBeenCalled();
- });
-});
diff --git a/apps/server/src/services/verify/__tests__/acceptanceLifecycle.test.ts b/apps/server/src/services/verify/__tests__/acceptanceLifecycle.test.ts
index e715424ed98..47be517e7f5 100644
--- a/apps/server/src/services/verify/__tests__/acceptanceLifecycle.test.ts
+++ b/apps/server/src/services/verify/__tests__/acceptanceLifecycle.test.ts
@@ -20,10 +20,6 @@ const mocks = vi.hoisted(() => ({
taskAcceptanceResolve: vi.fn(),
}));
-vi.mock('../goalLoop', () => ({
- maybeContinueGoalLoop: vi.fn().mockResolvedValue('spawn-failed'),
- syncGoalToolState: vi.fn(),
-}));
vi.mock('../acceptanceService', () => ({
AcceptanceService: vi.fn(() => ({
acceptanceModel: { update: mocks.acceptanceUpdate },
diff --git a/apps/server/src/services/verify/__tests__/driveTaskFromVerify.test.ts b/apps/server/src/services/verify/__tests__/driveTaskFromVerify.test.ts
index e0c172b9380..c4c697c5d75 100644
--- a/apps/server/src/services/verify/__tests__/driveTaskFromVerify.test.ts
+++ b/apps/server/src/services/verify/__tests__/driveTaskFromVerify.test.ts
@@ -21,17 +21,9 @@ const {
serviceUpdateStatus,
statusRecompute,
deliverMock,
- goalContinueMock,
- goalSyncMock,
- goalFindBySubject,
- goalUpdateStatus,
} = vi.hoisted(() => ({
briefCreate: vi.fn(),
deliverMock: vi.fn(),
- goalContinueMock: vi.fn(),
- goalFindBySubject: vi.fn(),
- goalSyncMock: vi.fn(),
- goalUpdateStatus: vi.fn(),
opFindById: vi.fn(),
runFindByOperation: vi.fn(),
runClaimTaskDrive: vi.fn().mockResolvedValue(true),
@@ -42,31 +34,6 @@ const {
taskUpdateStatus: vi.fn(),
}));
-vi.mock('../goalLoop', () => ({
- goalExhaustedBriefCopy: (task: any, outcome: string) => ({
- summary: `budget exhausted (${outcome})`,
- title: `${task.identifier} goal paused`,
- }),
- goalReadyForReviewBriefCopy: (task: any, acceptanceId?: string) => ({
- actions: acceptanceId
- ? [
- {
- key: 'review',
- label: 'Review delivery',
- type: 'link',
- url: `/acceptance/${acceptanceId}`,
- },
- ]
- : [],
- summary: 'ready for your sign-off',
- title: `${task.identifier} goal delivered`,
- }),
- maybeContinueGoalLoop: goalContinueMock,
- resolveGoalRoundBudget: (goal: any) =>
- goal.maxRounds === null ? Number.POSITIVE_INFINITY : goal.maxRounds,
- syncGoalToolState: goalSyncMock,
-}));
-
vi.mock('../statusService', () => ({
VerifyStatusService: vi.fn(() => ({ recompute: statusRecompute })),
}));
@@ -87,12 +54,6 @@ vi.mock('@/database/models/task', () => ({
updateStatus: taskUpdateStatus,
})),
}));
-vi.mock('@/database/models/goal', () => ({
- GoalModel: vi.fn(() => ({
- findBySubject: goalFindBySubject,
- updateStatus: goalUpdateStatus,
- })),
-}));
vi.mock('@/database/models/brief', () => ({
BriefModel: vi.fn(() => ({ create: briefCreate })),
}));
@@ -120,10 +81,6 @@ describe('driveTaskFromVerify', () => {
serviceUpdateStatus,
statusRecompute,
deliverMock,
- goalContinueMock,
- goalSyncMock,
- goalFindBySubject,
- goalUpdateStatus,
].forEach((m) => m.mockReset());
// The drive is claimed before any side effect; unclaimed means "someone
// else is driving this run", which every test here is not.
@@ -135,7 +92,6 @@ describe('driveTaskFromVerify', () => {
identifier: 'T-1',
status: 'running',
});
- goalFindBySubject.mockResolvedValue(undefined);
});
afterEach(() => vi.restoreAllMocks());
@@ -280,157 +236,7 @@ describe('driveTaskFromVerify', () => {
expect(serviceUpdateStatus).not.toHaveBeenCalled();
});
- describe('goal outer loop', () => {
- const goalTask = {
- assigneeAgentId: 'a1',
- id: 'task-1',
- identifier: 'T-1',
- status: 'running',
- totalTopics: 1,
- };
- const goal = { id: 'goal-1', maxRounds: 3, maxTotalCost: null, status: 'running' };
-
- beforeEach(() => {
- taskFindById.mockResolvedValue(goalTask);
- goalFindBySubject.mockResolvedValue(goal);
- });
-
- it('failed + budget left → spawns the next round silently (no brief, no pause, no callback)', async () => {
- runFindByOperation.mockResolvedValue({
- id: 'run-1',
- metadata: { maxRepairRounds: 2 },
- status: 'failed',
- });
- goalContinueMock.mockResolvedValue('continued');
-
- await driveTaskFromVerify(db, 'u1', 'op-1');
-
- expect(goalContinueMock).toHaveBeenCalledWith(
- expect.objectContaining({ goal, task: goalTask }),
- );
- expect(briefCreate).not.toHaveBeenCalled();
- expect(taskUpdateStatus).not.toHaveBeenCalled();
- expect(deliverMock).not.toHaveBeenCalled();
- // The claim both stamps the marker and proves we own this drive.
- expect(runClaimTaskDrive).toHaveBeenCalledWith('run-1');
- expect(goalSyncMock).toHaveBeenCalledWith(
- expect.objectContaining({ state: expect.objectContaining({ phase: 'running' }) }),
- );
- });
-
- it('does nothing when another callback already claimed the drive', async () => {
- // Two verifier callbacks can settle together; only the claim winner acts.
- runClaimTaskDrive.mockResolvedValue(false);
-
- await driveTaskFromVerify({} as never, 'user-1', 'op-1');
-
- expect(goalContinueMock).not.toHaveBeenCalled();
- expect(taskUpdateStatus).not.toHaveBeenCalled();
- expect(serviceUpdateStatus).not.toHaveBeenCalled();
- expect(briefCreate).not.toHaveBeenCalled();
- });
-
- it('failed + budget exhausted → pauses with budget-specific brief copy', async () => {
- runFindByOperation.mockResolvedValue({ id: 'run-1', metadata: null, status: 'failed' });
- goalContinueMock.mockResolvedValue('exhausted-rounds');
-
- await driveTaskFromVerify(db, 'u1', 'op-1');
-
- // Reason on the row, not only in the brief — see the failed-branch test.
- expect(taskUpdateStatus).toHaveBeenCalledWith('task-1', 'paused', {
- error: 'budget exhausted (exhausted-rounds)',
- });
- const briefArg = briefCreate.mock.calls[0][0];
- expect(briefArg.summary).toContain('budget exhausted (exhausted-rounds)');
- // An exhausted budget parks the goal for the user, it does not fail it.
- expect(goalUpdateStatus).toHaveBeenCalledWith('goal-1', 'paused');
- expect(goalSyncMock).toHaveBeenCalledWith(
- expect.objectContaining({
- state: expect.objectContaining({ pausedReason: 'exhausted-rounds', phase: 'paused' }),
- }),
- );
- });
-
- it('failed + spawn failure → falls back to the regular pause + brief path', async () => {
- runFindByOperation.mockResolvedValue({ id: 'run-1', metadata: null, status: 'failed' });
- goalContinueMock.mockResolvedValue('spawn-failed');
-
- await driveTaskFromVerify(db, 'u1', 'op-1');
-
- expect(taskUpdateStatus).toHaveBeenCalledWith('task-1', 'paused', {
- error: 'Delivery did not pass verification.',
- });
- expect(briefCreate.mock.calls[0][0].summary).toContain('did not pass');
- });
-
- it('errored → never loops (verification did not run), pauses like a non-goal task', async () => {
- runFindByOperation.mockResolvedValue({ id: 'run-1', metadata: null, status: 'errored' });
-
- await driveTaskFromVerify(db, 'u1', 'op-1');
-
- expect(goalContinueMock).not.toHaveBeenCalled();
- expect(taskUpdateStatus).toHaveBeenCalledWith(
- 'task-1',
- 'paused',
- expect.objectContaining({ error: expect.stringContaining('could not run') }),
- );
- // Infra gave up without evaluating the delivery → the goal is `failed`,
- // distinct from the user-actionable `paused` of an exhausted budget.
- expect(goalUpdateStatus).toHaveBeenCalledWith('goal-1', 'failed');
- });
-
- it('passed → parks for sign-off instead of completing (the verifier only recommends)', async () => {
- runFindByOperation.mockResolvedValue({
- acceptanceId: 'acc-9',
- id: 'run-1',
- metadata: null,
- status: 'passed',
- });
-
- await driveTaskFromVerify(db, 'u1', 'op-1');
-
- // The agent saying "done" is not the business fact — the human sign-off is.
- expect(serviceUpdateStatus).not.toHaveBeenCalled();
- // A converged goal and a goal that gave up both land on `paused`; only the
- // reason on the row tells them apart in the UI.
- expect(taskUpdateStatus).toHaveBeenCalledWith('task-1', 'paused', {
- error: 'ready for your sign-off',
- });
- // The goal's own lifecycle records the sign-off wait.
- expect(goalUpdateStatus).toHaveBeenCalledWith('goal-1', 'review');
- expect(goalSyncMock).toHaveBeenCalledWith(
- expect.objectContaining({ state: expect.objectContaining({ phase: 'review' }) }),
- );
- });
-
- it('passed → raises exactly one decision brief that links to the acceptance', async () => {
- runFindByOperation.mockResolvedValue({
- acceptanceId: 'acc-9',
- id: 'run-1',
- metadata: null,
- status: 'passed',
- });
-
- await driveTaskFromVerify(db, 'u1', 'op-1');
-
- expect(briefCreate).toHaveBeenCalledTimes(1);
- const brief = briefCreate.mock.calls[0][0];
- // `result` would be filed under "news" and its approve completes the task,
- // bypassing the sign-off this branch exists to require.
- expect(brief.type).toBe('decision');
- expect(brief.actions).toEqual([
- expect.objectContaining({
- key: 'review',
- label: 'Review delivery',
- type: 'link',
- url: '/acceptance/acc-9',
- }),
- ]);
- });
- });
-
- it('non-goal task still completes on a passing verify (contract unchanged)', async () => {
- goalFindBySubject.mockResolvedValue(undefined);
+ it('completes the task on a passing verify', async () => {
runFindByOperation.mockResolvedValue({ id: 'run-1', metadata: null, status: 'passed' });
await driveTaskFromVerify(db, 'u1', 'op-1');
diff --git a/apps/server/src/services/verify/__tests__/goalLoop.test.ts b/apps/server/src/services/verify/__tests__/goalLoop.test.ts
deleted file mode 100644
index efb5b5e6af3..00000000000
--- a/apps/server/src/services/verify/__tests__/goalLoop.test.ts
+++ /dev/null
@@ -1,174 +0,0 @@
-// @vitest-environment node
-import { beforeEach, describe, expect, it, vi } from 'vitest';
-
-import { resolveGoalRoundBudget } from '../goalBudget';
-import { maybeContinueGoalLoop, syncGoalToolState } from '../goalLoop';
-
-const {
- runTaskMock,
- sumCostMock,
- findToolMessageIdMock,
- updateToolMessageMock,
- updateGoalStatusMock,
-} = vi.hoisted(() => ({
- findToolMessageIdMock: vi.fn(),
- runTaskMock: vi.fn(),
- sumCostMock: vi.fn(),
- updateGoalStatusMock: vi.fn(),
- updateToolMessageMock: vi.fn(),
-}));
-
-vi.mock('@/server/services/taskRunner', () => ({
- TaskRunnerService: vi.fn(() => ({ runTask: runTaskMock })),
-}));
-vi.mock('@/database/models/agentOperation', () => ({
- AgentOperationModel: vi.fn(() => ({ sumCostByTask: sumCostMock })),
-}));
-vi.mock('@/database/models/goal', () => ({
- GoalModel: vi.fn(() => ({ updateStatus: updateGoalStatusMock })),
-}));
-vi.mock('@/database/models/message', () => ({
- MessageModel: vi.fn(() => ({
- findToolMessageIdByToolCallId: findToolMessageIdMock,
- updateToolMessage: updateToolMessageMock,
- })),
-}));
-
-const db = {} as any;
-const baseTask = { id: 'task-1', identifier: 'T-1', totalTopics: 1 } as any;
-const goalItem = (partial: Record<string, unknown>) =>
- ({ id: 'goal-1', maxRounds: null, maxTotalCost: null, ...partial }) as any;
-
-describe('resolveGoalRoundBudget', () => {
- it('null → uncapped (write time already resolved the default)', () => {
- expect(resolveGoalRoundBudget({ maxRounds: null })).toBe(Number.POSITIVE_INFINITY);
- });
- it('numbers are floored at 2', () => {
- expect(resolveGoalRoundBudget({ maxRounds: 1 })).toBe(2);
- expect(resolveGoalRoundBudget({ maxRounds: 5 })).toBe(5);
- });
-});
-
-describe('maybeContinueGoalLoop', () => {
- beforeEach(() => {
- [runTaskMock, sumCostMock, updateGoalStatusMock].forEach((m) => m.mockReset());
- });
-
- it('spawns the next round with the goal trigger while budgets last', async () => {
- runTaskMock.mockResolvedValue({});
- const outcome = await maybeContinueGoalLoop({
- db,
- goal: goalItem({ maxRounds: 3 }),
- task: baseTask,
- userId: 'u1',
- });
- expect(outcome).toBe('continued');
- expect(runTaskMock).toHaveBeenCalledWith({ taskId: 'task-1', trigger: 'goal' });
- expect(updateGoalStatusMock).toHaveBeenCalledWith('goal-1', 'running');
- });
-
- it('stops at the round budget', async () => {
- const outcome = await maybeContinueGoalLoop({
- db,
- goal: goalItem({ maxRounds: 3 }),
- task: { ...baseTask, totalTopics: 3 },
- userId: 'u1',
- });
- expect(outcome).toBe('exhausted-rounds');
- expect(runTaskMock).not.toHaveBeenCalled();
- expect(updateGoalStatusMock).not.toHaveBeenCalled();
- });
-
- it('uncapped rounds (null) keep looping', async () => {
- runTaskMock.mockResolvedValue({});
- const outcome = await maybeContinueGoalLoop({
- db,
- goal: goalItem({ maxRounds: null }),
- task: { ...baseTask, totalTopics: 42 },
- userId: 'u1',
- });
- expect(outcome).toBe('continued');
- });
-
- it('stops when the cost budget is spent', async () => {
- sumCostMock.mockResolvedValue(21.5);
- const outcome = await maybeContinueGoalLoop({
- db,
- goal: goalItem({ maxRounds: 5, maxTotalCost: 20 }),
- task: baseTask,
- userId: 'u1',
- });
- expect(outcome).toBe('exhausted-cost');
- expect(runTaskMock).not.toHaveBeenCalled();
- });
-
- it('ignores cost when no cost budget is set', async () => {
- runTaskMock.mockResolvedValue({});
- const outcome = await maybeContinueGoalLoop({
- db,
- goal: goalItem({ maxRounds: 5, maxTotalCost: null }),
- task: baseTask,
- userId: 'u1',
- });
- expect(outcome).toBe('continued');
- expect(sumCostMock).not.toHaveBeenCalled();
- });
-
- it('degrades a spawn failure (e.g. CONFLICT: topic still running) to spawn-failed', async () => {
- runTaskMock.mockRejectedValue(new Error('CONFLICT'));
- const outcome = await maybeContinueGoalLoop({
- db,
- goal: goalItem({ maxRounds: 3 }),
- task: baseTask,
- userId: 'u1',
- });
- expect(outcome).toBe('spawn-failed');
- expect(updateGoalStatusMock).not.toHaveBeenCalled();
- });
-});
-
-describe('syncGoalToolState', () => {
- beforeEach(() => {
- [findToolMessageIdMock, updateToolMessageMock].forEach((m) => m.mockReset());
- });
-
- it('no origin toolCallId → silent no-op', async () => {
- await syncGoalToolState({
- db,
- state: { phase: 'running' },
- task: { ...baseTask, context: {} },
- userId: 'u1',
- });
- expect(findToolMessageIdMock).not.toHaveBeenCalled();
- });
-
- it('pushes phase + counters onto the origin tool card', async () => {
- findToolMessageIdMock.mockResolvedValue('msg-9');
- await syncGoalToolState({
- db,
- state: { phase: 'paused', roundsRun: 3 },
- task: { ...baseTask, context: { origin: { toolCallId: 'call-1' } } },
- userId: 'u1',
- });
- expect(findToolMessageIdMock).toHaveBeenCalledWith('call-1');
- expect(updateToolMessageMock).toHaveBeenCalledWith('msg-9', {
- pluginState: expect.objectContaining({
- goalPhase: 'paused',
- phase: 'paused',
- roundsRun: 3,
- updatedAt: expect.any(String),
- }),
- });
- });
-
- it('missing tool card → no write, no throw', async () => {
- findToolMessageIdMock.mockResolvedValue(null);
- await syncGoalToolState({
- db,
- state: { phase: 'done' },
- task: { ...baseTask, context: { origin: { toolCallId: 'call-1' } } },
- userId: 'u1',
- });
- expect(updateToolMessageMock).not.toHaveBeenCalled();
- });
-});
diff --git a/apps/server/src/services/verify/acceptanceService.ts b/apps/server/src/services/verify/acceptanceService.ts
index 43292d26a05..8ba130762ed 100644
--- a/apps/server/src/services/verify/acceptanceService.ts
+++ b/apps/server/src/services/verify/acceptanceService.ts
@@ -7,7 +7,6 @@ import type {
AcceptanceReviewAnnotation,
AcceptanceStatus,
AcceptanceSubjectType,
- GoalStatus,
ReviewProposalOutcome,
VerifyAgentPlanConfig,
VerifyCheckDecisionDetail,
@@ -20,7 +19,6 @@ import debug from 'debug';
import { AcceptanceModel } from '@/database/models/acceptance';
import { AgentModel } from '@/database/models/agent';
import { DocumentModel } from '@/database/models/document';
-import { GoalModel } from '@/database/models/goal';
import { ProjectModel } from '@/database/models/project';
import { TaskModel } from '@/database/models/task';
import { TaskTopicModel } from '@/database/models/taskTopic';
@@ -40,7 +38,6 @@ import { TaskService } from '@/server/services/task';
import { type AcceptanceMergeSummary, mergeAcceptanceRounds } from './acceptanceMerge';
import { computeFalseFlags } from './feedbackService';
-import { maybeContinueGoalLoop, syncGoalToolState } from './goalLoop';
const log = debug('lobe-server:verify-acceptance');
@@ -633,47 +630,11 @@ export class AcceptanceService {
const status = statusFromRound(current, Boolean(report));
if (status !== acceptance.status) {
await this.acceptanceModel.updatePolicyStatus(acceptanceId, status);
- await this.mirrorGoalStatus(acceptance.subjectType, acceptance.subjectId, status);
log('acceptance %s → %s (from round %d)', acceptanceId, status, current.roundIndex);
}
return status;
};
- /**
- * Keep a task-carried goal's live phase in lockstep with the acceptance
- * lifecycle. Only the in-flight phases are mirrored here — the decision
- * transitions (`achieved` / `paused` / `running` next round / `failed`) are
- * written by their owning flows (accept / reject / settle / goal loop).
- * Best-effort: goal state must never break acceptance recompute.
- */
- private mirrorGoalStatus = async (
- subjectType: string,
- subjectId: string,
- status: AcceptanceStatus,
- ): Promise<void> => {
- if (subjectType !== 'task') return;
- // `planned` is deliberately NOT mirrored: the plan being confirmed at run
- // start says nothing about verification running — the round is still
- // executing, and flipping the goal to `verifying` here would show 验证中
- // for the whole execution phase (caught by the E2E acceptance run).
- const mirrored: Partial<Record<AcceptanceStatus, GoalStatus>> = {
- delivered: 'review',
- repairing: 'verifying',
- verifying: 'verifying',
- };
- const next = mirrored[status];
- if (!next) return;
-
- try {
- const goalModel = new GoalModel(this.db, this.userId, this.workspaceId);
- const goal = await goalModel.findBySubject('task', subjectId);
- if (!goal || goal.status === 'achieved' || goal.status === 'canceled') return;
- if (goal.status !== next) await goalModel.updateStatus(goal.id, next);
- } catch (error) {
- log('mirrorGoalStatus failed (non-fatal): %O', error);
- }
- };
-
/** Latest round of an aggregate — the row `stampDecision` would write to. */
latestRound = async (acceptanceId: string) => {
const runs = await this.runModel.listByAcceptance(acceptanceId);
@@ -691,37 +652,11 @@ export class AcceptanceService {
await this.stampDecision(acceptanceId, 'accept', comment);
await this.acceptanceModel.updateStatus(acceptanceId, 'accepted');
- if (acceptance.subjectType === 'task') {
- await this.completeTaskSubject(acceptance.subjectId);
- await this.syncGoalStateOnAccept(acceptance.subjectId);
- }
+ if (acceptance.subjectType === 'task') await this.completeTaskSubject(acceptance.subjectId);
return (await this.acceptanceModel.findById(acceptanceId))!;
};
- /** Flip a goal (and its origin card) to the terminal "achieved" state. Best-effort. */
- private syncGoalStateOnAccept = async (subjectId: string): Promise<void> => {
- try {
- const taskModel = new TaskModel(this.db, this.userId, this.workspaceId);
- const task = await taskModel.findById(subjectId);
- if (!task) return;
- const goalModel = new GoalModel(this.db, this.userId, this.workspaceId);
- const goal = await goalModel.findBySubject('task', task.id);
- if (!goal) return;
-
- await goalModel.updateStatus(goal.id, 'achieved');
- await syncGoalToolState({
- db: this.db,
- state: { phase: 'done', roundsRun: task.totalTopics || 0 },
- task,
- userId: this.userId,
- workspaceId: this.workspaceId,
- });
- } catch (error) {
- log('syncGoalStateOnAccept failed (non-fatal): %O', error);
- }
- };
-
/**
* The user rejects the delivery. The comment is the re-tasking input: it is
* recorded on the round's decision detail, where the next repair/verify round
@@ -729,56 +664,19 @@ export class AcceptanceService {
* agent-bound rounds via the repair pipeline, for ingested rounds via the
* next `lh verify ingest-report`.)
*
- * Goal tasks are the exception: a reject IS the "run another round" gesture,
- * so the outer loop spawns the next task topic right here — the comment
- * reaches the new round through the prompt builder, which reads it off this
- * round's decision detail. Budgets still apply; when they ran out the reject
- * only stamps state (the UI asks the user to raise the budget first).
+ * A Goal Work Task is no exception: its next attempt is started by the Goal
+ * coordinator on the following tick, which reads the rejected round's
+ * decision detail through the prompt builder.
*/
reject = async (acceptanceId: string, comment: string): Promise<AcceptanceItem> => {
- const acceptance = await this.requireDecidableAcceptance(acceptanceId);
+ await this.requireDecidableAcceptance(acceptanceId);
await this.stampDecision(acceptanceId, 'reject', comment);
await this.acceptanceModel.updateStatus(acceptanceId, 'rejected');
- if (acceptance.subjectType === 'task') await this.spawnGoalRoundOnReject(acceptance.subjectId);
-
return (await this.acceptanceModel.findById(acceptanceId))!;
};
- /**
- * If the rejected subject is a goal task with budget left, start the next
- * round (fresh topic). Best-effort: any failure leaves the acceptance in
- * `rejected` — exactly where a non-goal reject would leave it.
- */
- private spawnGoalRoundOnReject = async (subjectId: string): Promise<void> => {
- try {
- const taskModel = new TaskModel(this.db, this.userId, this.workspaceId);
- const task = await taskModel.findById(subjectId);
- if (!task) return;
-
- const goalModel = new GoalModel(this.db, this.userId, this.workspaceId);
- const goal = await goalModel.findBySubject('task', task.id);
- if (!goal) return;
-
- const outcome = await maybeContinueGoalLoop({
- db: this.db,
- goal,
- task,
- userId: this.userId,
- workspaceId: this.workspaceId,
- });
- // `continued` already flipped the goal to `running` inside the loop; a
- // budget-blocked or failed spawn leaves the rejected goal parked on the
- // user (raise the budget / retry), which is `paused` in the goal
- // vocabulary.
- if (outcome !== 'continued') await goalModel.updateStatus(goal.id, 'paused');
- log('reject on goal task %s → loop outcome: %s', task.identifier, outcome);
- } catch (error) {
- log('spawnGoalRoundOnReject failed (non-fatal): %O', error);
- }
- };
-
/**
* Record the user's verdict on one or more union checks (a group-level
* "accept all" is just many ids). Stamps `user_decision` +
diff --git a/apps/server/src/services/verify/goalBudget.ts b/apps/server/src/services/verify/goalBudget.ts
deleted file mode 100644
index 9efb681b57a..00000000000
--- a/apps/server/src/services/verify/goalBudget.ts
+++ /dev/null
@@ -1,25 +0,0 @@
-import { DEFAULT_GOAL_MAX_ROUNDS } from '@lobechat/const/verify';
-import type { GoalItem } from '@lobechat/types';
-
-/**
- * Pure goal-budget helpers, dependency-free on purpose: both the outer loop
- * (verify/goalLoop → TaskRunnerService) and the prompt builder
- * (taskRunner/buildTaskPrompt) need them, and importing the loop service from
- * the prompt builder would create a taskRunner ⇄ verify module cycle.
- */
-
-/**
- * Applied at goal creation when the user left the round budget untouched
- * (`goals.max_rounds` is resolved at write time; `null` in the row means the
- * user explicitly opted out of a cap).
- *
- * Re-exported from `@lobechat/const/verify` so the create-goal UI and this loop
- * agree on one number; the const package is the single source of truth.
- */
-export { DEFAULT_GOAL_MAX_ROUNDS };
-
-/** Round budget: `null` = user opted out of a cap. */
-export const resolveGoalRoundBudget = (goal: Pick<GoalItem, 'maxRounds'>): number => {
- if (typeof goal.maxRounds === 'number') return Math.max(2, goal.maxRounds);
- return Number.POSITIVE_INFINITY;
-};
diff --git a/apps/server/src/services/verify/goalLoop.ts b/apps/server/src/services/verify/goalLoop.ts
deleted file mode 100644
index de89c12088a..00000000000
--- a/apps/server/src/services/verify/goalLoop.ts
+++ /dev/null
@@ -1,132 +0,0 @@
-import type { BriefAction, GoalItem, TaskContext, TaskItem } from '@lobechat/types';
-import debug from 'debug';
-
-import { GoalModel } from '@/database/models/goal';
-import { MessageModel } from '@/database/models/message';
-import type { LobeChatDatabase } from '@/database/type';
-import {
- WorkRecoveryCoordinator,
- type WorkRecoveryOutcome,
-} from '@/server/services/goal/workRecoveryCoordinator';
-
-import { resolveGoalRoundBudget } from './goalBudget';
-
-const log = debug('lobe-server:verify-goal-loop');
-
-export { DEFAULT_GOAL_MAX_ROUNDS, resolveGoalRoundBudget } from './goalBudget';
-
-export type GoalLoopOutcome = WorkRecoveryOutcome;
-
-/**
- * The goal outer loop: after a goal task's verify run settles as failed, spawn
- * the next round (a fresh task topic) unless a budget ran out. Never throws —
- * a spawn failure degrades to the caller's pause-and-notify path.
- *
- * The check-level auto-repair inner loop (same-topic re-run in repairService)
- * has already been exhausted by the time a run settles as failed, so this is
- * strictly the round-level loop.
- */
-export const maybeContinueGoalLoop = async (params: {
- db: LobeChatDatabase;
- goal: GoalItem;
- task: TaskItem;
- userId: string;
- workspaceId?: string;
-}): Promise<GoalLoopOutcome> => {
- const { db, goal, task, userId, workspaceId } = params;
-
- const outcome = await new WorkRecoveryCoordinator(db, userId, workspaceId).recover({
- goal,
- task,
- taskCarried: true,
- });
- if (outcome === 'continued') {
- // The spawned round makes the goal `running` right away, instead of
- // waiting for the runner's async start notification to flip it — the
- // UI should never show a paused/review goal that is already looping.
- await new GoalModel(db, userId, workspaceId).updateStatus(goal.id, 'running');
- log('task %s → goal round %d spawned', task.identifier, (task.totalTopics || 0) + 1);
- }
- return outcome;
-};
-
-/** User-facing copy for the pause brief when a budget ran out. */
-export const goalExhaustedBriefCopy = (
- task: TaskItem,
- outcome: Extract<GoalLoopOutcome, 'exhausted-cost' | 'exhausted-rounds'>,
- goal: GoalItem,
-): { summary: string; title: string } =>
- outcome === 'exhausted-cost'
- ? {
- summary: `The goal did not pass verification and its cost budget ($${goal.maxTotalCost}) is used up. Adjust the plan or budget to restart the loop.`,
- title: `${task.identifier} goal paused — cost budget exhausted`,
- }
- : {
- summary: `The goal did not pass verification after ${task.totalTopics || 0} rounds (budget ${resolveGoalRoundBudget(goal)}). Adjust the plan or budget to restart the loop.`,
- title: `${task.identifier} goal paused — round budget exhausted`,
- };
-
-/**
- * User-facing copy for the one brief a converged goal SHOULD raise: the loop is
- * done iterating and the delivery is waiting on the user's sign-off.
- *
- * Per-round result briefs are suppressed for goal tasks (see
- * `TaskLifecycleService.onTopicComplete`), so this is the moment the user is
- * pulled back in — not once per round.
- */
-export const goalReadyForReviewBriefCopy = (
- task: TaskItem,
- acceptanceId?: string,
-): { actions: BriefAction[]; summary: string; title: string } => ({
- // A `decision` brief, not a `result` one, for two reasons: `result` briefs are
- // filed unconditionally under "news" (nothing to do), and their approve button
- // completes the task outright — which would bypass the very sign-off this
- // change exists to require. The only action offered is a link to the
- // acceptance page, so the button promises exactly what it does.
- actions: acceptanceId
- ? [
- {
- key: 'review',
- label: 'Review delivery',
- type: 'link',
- url: `/acceptance/${acceptanceId}`,
- },
- ]
- : [],
- summary: `The goal passed verification after ${task.totalTopics || 1} round(s) and is waiting for your sign-off. Review the checks, then accept or send it back.`,
- title: `${task.identifier} goal delivered — ready for your review`,
-});
-
-/**
- * Push the goal's latest phase onto the `createGoal` tool card in the origin
- * conversation, keyed by the toolCallId recorded at creation time. Best-effort:
- * a missing origin (task created outside a conversation) or a missing card is
- * a silent no-op, and failures never propagate into the settle path.
- */
-export const syncGoalToolState = async (params: {
- db: LobeChatDatabase;
- state: {
- phase: 'done' | 'paused' | 'review' | 'running';
- roundBudget?: number | null;
- roundsRun?: number;
- } & Record<string, unknown>;
- task: TaskItem;
- userId: string;
- workspaceId?: string;
-}): Promise<void> => {
- const { db, state, task, userId, workspaceId } = params;
- const toolCallId = (task.context as TaskContext | undefined)?.origin?.toolCallId;
- if (!toolCallId) return;
-
- try {
- const messageModel = new MessageModel(db, userId, workspaceId);
- const toolMessageId = await messageModel.findToolMessageIdByToolCallId(toolCallId);
- if (!toolMessageId) return;
-
- await messageModel.updateToolMessage(toolMessageId, {
- pluginState: { goalPhase: state.phase, ...state, updatedAt: new Date().toISOString() },
- });
- } catch (error) {
- log('goal tool-state sync failed for task %s (non-fatal): %O', task.identifier, error);
- }
-};
diff --git a/apps/server/src/services/verify/index.ts b/apps/server/src/services/verify/index.ts
index f411e073904..710030bd6a5 100644
--- a/apps/server/src/services/verify/index.ts
+++ b/apps/server/src/services/verify/index.ts
@@ -25,14 +25,6 @@ export {
VerifyExecutorService,
} from './executor';
export { computeFalseFlags, VerifyFeedbackService } from './feedbackService';
-export { DEFAULT_GOAL_MAX_ROUNDS, resolveGoalRoundBudget } from './goalBudget';
-export {
- goalExhaustedBriefCopy,
- type GoalLoopOutcome,
- goalReadyForReviewBriefCopy,
- maybeContinueGoalLoop,
- syncGoalToolState,
-} from './goalLoop';
export { runVerifyOnCompletion } from './lifecycle';
export {
isHeterogeneousVerifyProvider,
diff --git a/apps/server/src/services/verify/planInstantiation.ts b/apps/server/src/services/verify/planInstantiation.ts
index edea52ba560..9cc5ee705db 100644
--- a/apps/server/src/services/verify/planInstantiation.ts
+++ b/apps/server/src/services/verify/planInstantiation.ts
@@ -1,6 +1,5 @@
import debug from 'debug';
-import { GoalModel } from '@/database/models/goal';
import { TaskModel } from '@/database/models/task';
import { VerifyRunModel } from '@/database/models/verifyRun';
import type { LobeChatDatabase } from '@/database/type';
@@ -38,25 +37,6 @@ export const instantiateVerifyPlanOnStart = async (
try {
const taskModel = new TaskModel(db, userId, workspaceId);
- // A goal task entering a run round is `running` — the single transition
- // point shared by round 1, reject-spawned rounds and manual restarts.
- // Terminal decisions stay terminal: an accepted (`achieved`) or canceled
- // goal is never silently re-opened by a stray run.
- try {
- const goalModel = new GoalModel(db, userId, workspaceId);
- const goal = await goalModel.findBySubject('task', params.taskId);
- if (
- goal &&
- goal.status !== 'running' &&
- goal.status !== 'achieved' &&
- goal.status !== 'canceled'
- ) {
- await goalModel.updateStatus(goal.id, 'running');
- }
- } catch (error) {
- log('goal running transition failed for task %s (non-fatal): %O', params.taskId, error);
- }
-
const resolvedAcceptance = await resolveTaskAcceptance(db, userId, params.taskId, workspaceId);
if (!resolvedAcceptance) return;
const { acceptance, config: verifyConfig, requirement } = resolvedAcceptance;
diff --git a/apps/server/src/services/verify/settle.ts b/apps/server/src/services/verify/settle.ts
index f4bf16699f8..840f7f9fca1 100644
--- a/apps/server/src/services/verify/settle.ts
+++ b/apps/server/src/services/verify/settle.ts
@@ -7,16 +7,10 @@ import { GoalModel } from '@/database/models/goal';
import { TaskModel } from '@/database/models/task';
import { VerifyRunModel } from '@/database/models/verifyRun';
import type { LobeChatDatabase } from '@/database/type';
+import { scheduleGoalAdvance } from '@/server/services/goal/scheduler';
import { TaskService } from '@/server/services/task';
import { TaskResultBridgeService } from '@/server/services/taskResultBridge';
-import {
- goalExhaustedBriefCopy,
- goalReadyForReviewBriefCopy,
- maybeContinueGoalLoop,
- resolveGoalRoundBudget,
- syncGoalToolState,
-} from './goalLoop';
import { maybeAutoRepair } from './repairService';
import { VerifyReporterService } from './reporter';
import { VerifyStatusService } from './statusService';
@@ -106,67 +100,23 @@ export const driveTaskFromVerify = async (
const task = await taskModel.findById(taskOperation.taskId);
if (!task || TERMINAL_TASK_STATUS.has(task.status)) return; // task already settled
- const goalModel = new GoalModel(db, userId, workspaceId);
- const goal = await goalModel.findBySubject('task', task.id);
-
if (run.status === 'passed') {
- if (goal) {
- // A goal's loop converging is NOT the same business fact as the task
- // being done: the verifier's `passed` is a recommendation, the human's
- // sign-off is the terminal event (the acceptance lifecycle already
- // models this as delivered → accepted). Completing the task here would
- // claim "done" on the agent's own say-so and leave the acceptance
- // waiting on a decision nobody is told to make.
- //
- // So: park the task for review and raise the ONE brief a goal should
- // produce. `AcceptanceService.accept` completes the task (with the same
- // cascade) once the user signs off.
- // `paused` is the only status the task vocabulary has for "stopped,
- // needs a human" — and the UI renders every paused task identically as
- // 待审阅. Without a reason on the row, a converged goal waiting for
- // sign-off and a goal that gave up look the same. Write the reason so
- // the task page can tell them apart.
- const review = goalReadyForReviewBriefCopy(task, run.acceptanceId ?? undefined);
- await taskModel.updateStatus(taskOperation.taskId, 'paused', {
- error: review.summary,
- });
- await goalModel.updateStatus(goal.id, 'review');
- await new BriefModel(db, userId, workspaceId).create({
- actions: review.actions,
- agentId: task.assigneeAgentId || undefined,
- priority: 'normal',
- summary: review.summary,
- taskId: taskOperation.taskId,
- title: review.title,
- trigger: 'task',
- type: 'decision',
- });
- await syncGoalToolState({
- db,
- state: { phase: 'review', roundsRun: task.totalTopics || 0 },
- task,
- userId,
- workspaceId,
- });
- log('verify passed → goal task %s parked for sign-off', taskOperation.taskId);
+ // Verify passing completes the task and cascades (checkpoint / sibling
+ // rollup / downstream unlock). A Goal Graph Work Task is an ordinary task
+ // here — the coordinator reads its completed status on the next tick and
+ // synthesizes the finding from it.
+ if (task.automationMode) {
+ // Recurring tasks are parked back at `scheduled` and re-armed by the
+ // task lifecycle. Verify accepts this run, not the lifetime schedule.
+ log('verify passed → recurring task %s remains scheduled', taskOperation.taskId);
} else {
- // Non-goal tasks keep the existing contract: verify passing completes
- // the task and cascades (checkpoint / sibling rollup / downstream
- // unlock). Changing that for every verify-enabled task is a separate
- // product decision, deliberately not bundled into the goal loop.
- if (task.automationMode) {
- // Recurring tasks are parked back at `scheduled` and re-armed by the
- // task lifecycle. Verify accepts this run, not the lifetime schedule.
- log('verify passed → recurring task %s remains scheduled', taskOperation.taskId);
- } else {
- // The verify → TaskService → aiAgent → agentRuntime completion → verify
- // cycle is safe statically since every use is call-time (inside this fn).
- await new TaskService(db, userId, workspaceId).updateStatus({
- id: taskOperation.taskId,
- status: 'completed',
- });
- log('verify passed → task %s completed', taskOperation.taskId);
- }
+ // The verify → TaskService → aiAgent → agentRuntime completion → verify
+ // cycle is safe statically since every use is call-time (inside this fn).
+ await new TaskService(db, userId, workspaceId).updateStatus({
+ id: taskOperation.taskId,
+ status: 'completed',
+ });
+ log('verify passed → task %s completed', taskOperation.taskId);
}
} else {
// Two non-pass outcomes, kept distinct so an infra error never reads as a
@@ -176,52 +126,21 @@ export const driveTaskFromVerify = async (
// evaluated, so we must not claim it "did not pass".
const isErrored = run.status === 'errored';
- // Goal outer loop: a *failed* (judged) run on a goal task spawns the next
- // round in a fresh topic while budgets last, instead of parking the task
- // on the user. `errored` stays on the pause path — verification never ran,
- // so looping would burn budget without new signal.
- let exhausted: 'exhausted-cost' | 'exhausted-rounds' | undefined;
- if (goal && !isErrored) {
- const outcome = await maybeContinueGoalLoop({ db, goal, task, userId, workspaceId });
- if (outcome === 'continued') {
- await syncGoalToolState({
- db,
- state: {
- phase: 'running',
- roundBudget: goal.maxRounds === null ? null : resolveGoalRoundBudget(goal),
- roundsRun: (task.totalTopics || 0) + 1,
- },
- task,
- userId,
- workspaceId,
- });
- // No brief, no pause, no creator callback — the loop continues
- // silently until it converges or a budget runs out. The drive marker
- // was already stamped by the claim above.
- return;
- }
- if (outcome === 'exhausted-cost' || outcome === 'exhausted-rounds') exhausted = outcome;
- // 'spawn-failed' falls through to the regular pause + brief path.
- }
-
- const exhaustedCopy =
- exhausted && goal ? goalExhaustedBriefCopy(task, exhausted, goal) : null;
- const pauseSummary =
- exhaustedCopy?.summary ??
- (isErrored
- ? 'Verification could not run (internal error); the delivery was not evaluated.'
- : 'Delivery did not pass verification.');
+ // `Delivery did not pass verification.` is a contract string, not just
+ // copy: the Goal coordinator matches on it to decide whether a paused
+ // Work Task should start another attempt or open a decision gate.
+ const pauseSummary = isErrored
+ ? 'Verification could not run (internal error); the delivery was not evaluated.'
+ : 'Delivery did not pass verification.';
await new BriefModel(db, userId, workspaceId).create({
actions: DEFAULT_BRIEF_ACTIONS['error'],
agentId: task.assigneeAgentId || undefined,
priority: 'urgent',
summary: pauseSummary,
taskId: taskOperation.taskId,
- title:
- exhaustedCopy?.title ??
- (isErrored
- ? `${task.identifier} verification errored`
- : `${task.identifier} failed verification`),
+ title: isErrored
+ ? `${task.identifier} verification errored`
+ : `${task.identifier} failed verification`,
trigger: 'task',
type: 'error',
});
@@ -229,23 +148,6 @@ export const driveTaskFromVerify = async (
// row, not only in a brief. The task detail feed deliberately excludes
// briefs, so a brief-only explanation is invisible from the task page.
await taskModel.updateStatus(taskOperation.taskId, 'paused', { error: pauseSummary });
- if (goal) {
- // The goal's own lifecycle: an errored run means verification never
- // evaluated the delivery — `failed` (infra gave up), while an exhausted
- // budget or spawn failure parks the goal for the user (`paused`).
- await goalModel.updateStatus(goal.id, isErrored ? 'failed' : 'paused');
- await syncGoalToolState({
- db,
- state: {
- pausedReason: exhausted ?? (isErrored ? 'verify-errored' : 'verify-failed'),
- phase: 'paused',
- roundsRun: task.totalTopics || 0,
- },
- task,
- userId,
- workspaceId,
- });
- }
log(
isErrored
? 'verify errored → task %s paused + brief'
@@ -282,6 +184,23 @@ export const driveTaskFromVerify = async (
);
}
+ // A Goal Work Task settling is the event the coordinator waits on: it
+ // decides whether to synthesize a finding, start another attempt, or open a
+ // decision gate. Queue the advance so the goal keeps moving on its own —
+ // this is the server-side driver for long-horizon goals, and without it a
+ // goal only progresses while some client keeps ticking it.
+ try {
+ const goal = await new GoalModel(db, userId, workspaceId).findByWorkTask(
+ taskOperation.taskId,
+ );
+ if (goal) {
+ await scheduleGoalAdvance({ goalId: goal.id, userId, workspaceId });
+ log('verify-settle → queued goal advance for %s', goal.id);
+ }
+ } catch (error) {
+ log('verify-settle goal advance dispatch failed (non-fatal): %O', error);
+ }
+
// The drive marker was stamped by the claim at the top of this function.
} catch (error) {
log('driveTaskFromVerify failed for op %s (non-fatal): %O', operationId, error);
diff --git a/locales/en-US/chat.json b/locales/en-US/chat.json
index bb2102a1e0b..18cd7cda929 100644
--- a/locales/en-US/chat.json
+++ b/locales/en-US/chat.json
@@ -434,8 +434,11 @@
"goalList.acceptanceProgress": "{{passed}}/{{total}} passed",
"goalList.agentRuns": "{{count}} runs",
"goalList.empty": "No goals yet",
+ "goalList.findings": "{{count}} findings",
"goalList.loadError": "Could not load goals",
"goalList.loadErrorDescription": "The service is temporarily unavailable. Your goals are not lost.",
+ "goalList.needsYou": "{{count}} need you",
+ "goalList.noWork": "No tasks yet",
"goalList.retry": "Retry",
"goalList.roundProgress": "Round {{current}}/{{total}}",
"goalList.status.achieved": "Achieved",
@@ -448,6 +451,7 @@
"goalList.status.verifying": "Verifying",
"goalList.status.waiting": "Waiting",
"goalList.title": "Goals",
+ "goalList.workProgress": "{{done}}/{{total}} tasks done",
"goalPage.activeGoals": "Open goals",
"goalPage.allGoals": "All goals",
"goalPage.create": "Create goal",
@@ -466,6 +470,88 @@
"goalPage.title": "Overview",
"goalPage.view.card": "Cards",
"goalPage.view.list": "List",
+ "goalProcess.activity.empty": "No activity yet",
+ "goalProcess.activity.finding": "Recorded finding: {{title}}",
+ "goalProcess.activity.title": "Activity",
+ "goalProcess.advance.label": "Advance",
+ "goalProcess.advance.running": "Advancing…",
+ "goalProcess.advance.tooltip": "The goal already advances on its own as its work settles. Press this to run the coordinator now — useful when you want to see where it stops without waiting.",
+ "goalProcess.attempts.failed": "Did not pass",
+ "goalProcess.attempts.nth": "Attempt {{index}}",
+ "goalProcess.attempts.passed": "Passed",
+ "goalProcess.attempts.retired": "Retired",
+ "goalProcess.attempts.running": "Running",
+ "goalProcess.attempts.title": "Previous attempts",
+ "goalProcess.edge.contradicts": "contradicts",
+ "goalProcess.edge.dependsOn": "depends on",
+ "goalProcess.edge.investigates": "investigates",
+ "goalProcess.edge.leadsTo": "leads to",
+ "goalProcess.edge.produces": "produces",
+ "goalProcess.edge.supports": "supports",
+ "goalProcess.findings.answers": "Answers “{{title}}”",
+ "goalProcess.findings.empty": "No findings yet.",
+ "goalProcess.findings.from": "From “{{title}}”",
+ "goalProcess.findings.title": "Findings",
+ "goalProcess.frontier.achievedDescription": "The findings are in the map below.",
+ "goalProcess.frontier.achievedTitle": "Nothing left to advance — this goal is achieved",
+ "goalProcess.frontier.add": "Add task",
+ "goalProcess.frontier.advanceable": "{{count}} can advance",
+ "goalProcess.frontier.blocked": "{{count}} more waiting on dependencies",
+ "goalProcess.frontier.dependsOn": "Depends on {{refs}}",
+ "goalProcess.frontier.emptyDescription": "Every task is either waiting on a dependency or already finished.",
+ "goalProcess.frontier.emptyTitle": "Nothing to advance right now",
+ "goalProcess.frontier.needsYou": "{{count}} need you",
+ "goalProcess.frontier.title": "Current tasks",
+ "goalProcess.gate.noteLabel": "Extra guidance (optional — goes into the next attempt)",
+ "goalProcess.gate.notePlaceholder": "e.g. reuse the existing checkpoint instead of retraining from scratch",
+ "goalProcess.gate.option.fail": "Fail goal",
+ "goalProcess.gate.option.retire": "Retire work",
+ "goalProcess.gate.option.retry": "Retry work",
+ "goalProcess.gate.options": "What each choice means",
+ "goalProcess.gate.recommended": "recommended",
+ "goalProcess.gate.why": "Why it stopped",
+ "goalProcess.graph.exitFullscreen": "Exit fullscreen",
+ "goalProcess.graph.fullscreen": "Fullscreen",
+ "goalProcess.graph.title": "Exploration map",
+ "goalProcess.graph.view.all": "Full map",
+ "goalProcess.graph.view.stage": "Current stage",
+ "goalProcess.kind.decision": "Decision",
+ "goalProcess.kind.finding": "Finding",
+ "goalProcess.kind.problem": "Question",
+ "goalProcess.kind.work": "Task",
+ "goalProcess.metrics.findings": "Findings",
+ "goalProcess.metrics.status": "Status",
+ "goalProcess.metrics.tasks": "Tasks",
+ "goalProcess.node.answered": "Answered by a finding",
+ "goalProcess.node.artifactsTooltip": "{{count}} work versions registered. Opening them needs a server read that does not exist yet.",
+ "goalProcess.node.attemptsTooltip": "{{count}} attempts so far",
+ "goalProcess.node.decidedByAgent": "Agent decided",
+ "goalProcess.node.decidedByYou": "You decided",
+ "goalProcess.node.done": "Done",
+ "goalProcess.node.humanTouched": "You took part in this task",
+ "goalProcess.node.running": "Running",
+ "goalProcess.node.unanswered": "Unanswered",
+ "goalProcess.node.unassigned": "Not dispatched",
+ "goalProcess.node.verifier": "verifier",
+ "goalProcess.node.verifierTooltip": "This task has its own acceptance contract — a verifier judges the delivery.",
+ "goalProcess.node.waiting": "Waiting",
+ "goalProcess.pause": "Pause",
+ "goalProcess.paused": "Paused — no new work will start",
+ "goalProcess.requirement": "What counts as done",
+ "goalProcess.resume": "Resume",
+ "goalProcess.running.elapsed": "Running {{duration}}",
+ "goalProcess.stale.description": "No heartbeat for {{duration}}. The next advance marks this attempt lost and starts a fresh one — it does not count as a failure.",
+ "goalProcess.summary.done": "Done · {{count}} attempts",
+ "goalProcess.summary.gateOpen": "Waiting for your decision",
+ "goalProcess.summary.gateResolved": "Decided: {{option}}",
+ "goalProcess.summary.notStarted": "Not started yet",
+ "goalProcess.summary.retired": "Retired · {{count}} attempts",
+ "goalProcess.summary.running": "Running · attempt {{index}}",
+ "goalProcess.summary.waiting": "{{count}} attempts did not pass — needs your decision",
+ "goalProcess.tag.done": "Done",
+ "goalProcess.tag.lost": "Lost",
+ "goalProcess.tag.needsDecision": "Needs your decision",
+ "goalProcess.tag.retired": "Retired",
"goalWork.checks": "{{passed}}/{{total}} checks passed",
"goalWork.round": "Round {{current}}",
"goalWork.roundWithBudget": "Round {{current}}/{{total}}",
@@ -478,6 +564,7 @@
"goalWork.status.running": "Executing",
"goalWork.status.verifying": "Verifying",
"goalWork.status.waiting": "Waiting",
+ "goalWork.workDone": "{{passed}}/{{total}} tasks done",
"grokBuildInstallGuide.actions.openDocs": "Open Install Guide",
"grokBuildInstallGuide.actions.openSystemTools": "Open System Tools",
"grokBuildInstallGuide.afterInstall": "After installing, run `grok login`, then retry your message or click Re-detect in System Tools.",
diff --git a/locales/zh-CN/chat.json b/locales/zh-CN/chat.json
index c66fdf8b342..aed2d25ef4d 100644
--- a/locales/zh-CN/chat.json
+++ b/locales/zh-CN/chat.json
@@ -434,8 +434,11 @@
"goalList.acceptanceProgress": "已通过 {{passed}}/{{total}}",
"goalList.agentRuns": "{{count}} 次运行",
"goalList.empty": "暂无目标",
+ "goalList.findings": "{{count}} 条结论",
"goalList.loadError": "无法加载目标",
"goalList.loadErrorDescription": "服务暂时不可用,你的目标没有丢失。",
+ "goalList.needsYou": "{{count}} 项需要你",
+ "goalList.noWork": "还没有任务",
"goalList.retry": "重试",
"goalList.roundProgress": "第 {{current}}/{{total}} 轮",
"goalList.status.achieved": "已达成",
@@ -448,6 +451,7 @@
"goalList.status.verifying": "验证中",
"goalList.status.waiting": "等待中",
"goalList.title": "目标",
+ "goalList.workProgress": "{{done}}/{{total}} 项任务完成",
"goalPage.activeGoals": "待处理目标",
"goalPage.allGoals": "全部目标",
"goalPage.create": "创建目标",
@@ -466,6 +470,88 @@
"goalPage.title": "概览",
"goalPage.view.card": "卡片",
"goalPage.view.list": "列表",
+ "goalProcess.activity.empty": "暂无活动",
+ "goalProcess.activity.finding": "沉淀结论:{{title}}",
+ "goalProcess.activity.title": "活动",
+ "goalProcess.advance.label": "推进",
+ "goalProcess.advance.running": "推进中…",
+ "goalProcess.advance.tooltip": "目标会随着任务完成自行推进。点这里立刻跑一轮协调器——想马上看到它停在哪一步时用。",
+ "goalProcess.attempts.failed": "未通过",
+ "goalProcess.attempts.nth": "第 {{index}} 次",
+ "goalProcess.attempts.passed": "通过",
+ "goalProcess.attempts.retired": "已放弃",
+ "goalProcess.attempts.running": "进行中",
+ "goalProcess.attempts.title": "之前的尝试",
+ "goalProcess.edge.contradicts": "反驳",
+ "goalProcess.edge.dependsOn": "依赖",
+ "goalProcess.edge.investigates": "调查",
+ "goalProcess.edge.leadsTo": "导向",
+ "goalProcess.edge.produces": "产出",
+ "goalProcess.edge.supports": "支持",
+ "goalProcess.findings.answers": "回答「{{title}}」",
+ "goalProcess.findings.empty": "还没有任何结论。",
+ "goalProcess.findings.from": "来自「{{title}}」",
+ "goalProcess.findings.title": "结论",
+ "goalProcess.frontier.achievedDescription": "结论都在下面的探索图里。",
+ "goalProcess.frontier.achievedTitle": "没有需要推进的了,目标已达成",
+ "goalProcess.frontier.add": "添加任务",
+ "goalProcess.frontier.advanceable": "{{count}} 项能推进",
+ "goalProcess.frontier.blocked": "还有 {{count}} 项在等依赖",
+ "goalProcess.frontier.dependsOn": "依赖 {{refs}}",
+ "goalProcess.frontier.emptyDescription": "所有任务要么在等依赖,要么已经终态。",
+ "goalProcess.frontier.emptyTitle": "当前没有可推进的任务",
+ "goalProcess.frontier.needsYou": "{{count}} 项需要你",
+ "goalProcess.frontier.title": "当前任务",
+ "goalProcess.gate.noteLabel": "补充说明(可选,会写进下一次尝试的指令)",
+ "goalProcess.gate.notePlaceholder": "例如:不要重训,基于已有 checkpoint 继续",
+ "goalProcess.gate.option.fail": "判定目标失败",
+ "goalProcess.gate.option.retire": "放弃这项任务",
+ "goalProcess.gate.option.retry": "重试这项任务",
+ "goalProcess.gate.options": "每个选择意味着什么",
+ "goalProcess.gate.recommended": "推荐",
+ "goalProcess.gate.why": "为什么停下来",
+ "goalProcess.graph.exitFullscreen": "退出全屏",
+ "goalProcess.graph.fullscreen": "全屏",
+ "goalProcess.graph.title": "探索图",
+ "goalProcess.graph.view.all": "全图",
+ "goalProcess.graph.view.stage": "当前阶段",
+ "goalProcess.kind.decision": "决策",
+ "goalProcess.kind.finding": "结论",
+ "goalProcess.kind.problem": "问题",
+ "goalProcess.kind.work": "任务",
+ "goalProcess.metrics.findings": "结论",
+ "goalProcess.metrics.status": "状态",
+ "goalProcess.metrics.tasks": "任务",
+ "goalProcess.node.answered": "已被结论回答",
+ "goalProcess.node.artifactsTooltip": "已登记 {{count}} 个产物版本;打开明细还需要服务端补读接口",
+ "goalProcess.node.attemptsTooltip": "已尝试 {{count}} 次",
+ "goalProcess.node.decidedByAgent": "Agent 决定的",
+ "goalProcess.node.decidedByYou": "你决定的",
+ "goalProcess.node.done": "完成",
+ "goalProcess.node.humanTouched": "你参与过这项任务",
+ "goalProcess.node.running": "进行中",
+ "goalProcess.node.unanswered": "待回答",
+ "goalProcess.node.unassigned": "未派发",
+ "goalProcess.node.verifier": "verifier",
+ "goalProcess.node.verifierTooltip": "这项任务有自己的验收合约,由 verifier 判定交付",
+ "goalProcess.node.waiting": "等待中",
+ "goalProcess.pause": "暂停",
+ "goalProcess.paused": "已暂停,不会再开始新的任务",
+ "goalProcess.requirement": "什么算完成",
+ "goalProcess.resume": "继续",
+ "goalProcess.running.elapsed": "已运行 {{duration}}",
+ "goalProcess.stale.description": "已 {{duration}} 没有心跳。下一次推进会把这次尝试标为失联并重开一次,不计失败次数。",
+ "goalProcess.summary.done": "完成 · {{count}} 次尝试",
+ "goalProcess.summary.gateOpen": "等你决定",
+ "goalProcess.summary.gateResolved": "已决定:{{option}}",
+ "goalProcess.summary.notStarted": "还没开始",
+ "goalProcess.summary.retired": "已放弃 · {{count}} 次尝试",
+ "goalProcess.summary.running": "进行中 · 第 {{index}} 次尝试",
+ "goalProcess.summary.waiting": "{{count}} 次尝试都没通过,等你决定",
+ "goalProcess.tag.done": "完成",
+ "goalProcess.tag.lost": "失联",
+ "goalProcess.tag.needsDecision": "等你决定",
+ "goalProcess.tag.retired": "已放弃",
"goalWork.checks": "{{passed}}/{{total}} 项通过",
"goalWork.round": "第 {{current}} 轮",
"goalWork.roundWithBudget": "第 {{current}}/{{total}} 轮",
@@ -478,6 +564,7 @@
"goalWork.status.running": "执行中",
"goalWork.status.verifying": "验证中",
"goalWork.status.waiting": "等待中",
+ "goalWork.workDone": "{{passed}}/{{total}} 项任务完成",
"grokBuildInstallGuide.actions.openDocs": "打开安装指南",
"grokBuildInstallGuide.actions.openSystemTools": "打开系统工具",
"grokBuildInstallGuide.afterInstall": "安装完成后,请运行 `grok login` 登录,然后重试刚才的消息,或在系统工具中点击“重新检测”。",
diff --git a/package.json b/package.json
index 6bb73633af1..d7d86a77edf 100644
--- a/package.json
+++ b/package.json
@@ -340,6 +340,7 @@
"@xterm/addon-web-links": "^0.12.0",
"@xterm/addon-webgl": "^0.18.0",
"@xterm/xterm": "^5.5.0",
+ "@xyflow/react": "^12.11.5",
"@zumer/snapdom": "^1.9.14",
"ahooks": "^3.9.7",
"antd": "6.3.5",
diff --git a/packages/builtin-tool-goal/src/client/executor/index.test.ts b/packages/builtin-tool-goal/src/client/executor/index.test.ts
new file mode 100644
index 00000000000..fcfd155cb30
--- /dev/null
+++ b/packages/builtin-tool-goal/src/client/executor/index.test.ts
@@ -0,0 +1,43 @@
+import { describe, expect, it, vi } from 'vitest';
+
+const mocks = vi.hoisted(() => ({ advance: vi.fn(), create: vi.fn() }));
+
+vi.mock('@/services/goal', () => ({
+ goalService: { advance: mocks.advance, create: mocks.create },
+}));
+vi.mock('@lobechat/builtin-tool-task/client/executor', () => ({
+ taskExecutor: { onAfterCall: vi.fn() },
+}));
+
+const { goalExecutor } = await import('./index');
+
+const params = {
+ criteria: [{ title: 'It works' }],
+ instruction: 'do the thing',
+ name: 'A goal',
+};
+
+describe('goalExecutor.createGoal', () => {
+ it('reports the created goal even when starting it fails', async () => {
+ // The goal is already committed. Reporting creation failure makes the agent
+ // create a second goal, and both then do the same paid work.
+ mocks.create.mockResolvedValue({ goal: { id: 'goal_1', title: 'A goal' } });
+ mocks.advance.mockRejectedValue(new Error('device runner offline'));
+
+ const result = await goalExecutor.createGoal(params, { agentId: 'agt_1' } as never);
+
+ expect(result.success).toBe(true);
+ expect((result.state as { goalId?: string }).goalId).toBe('goal_1');
+ expect(result.content).toContain('device runner offline');
+ expect(result.content).toContain('Do not create it again');
+ });
+
+ it('fails only when the goal itself was not created', async () => {
+ mocks.create.mockRejectedValue(new Error('database is down'));
+
+ const result = await goalExecutor.createGoal(params, { agentId: 'agt_1' } as never);
+
+ expect(result.success).toBe(false);
+ expect(result.error?.type).toBe('GoalCreateFailed');
+ });
+});
diff --git a/packages/builtin-tool-goal/src/client/executor/index.ts b/packages/builtin-tool-goal/src/client/executor/index.ts
index 9a642b4bcbd..1b0af463266 100644
--- a/packages/builtin-tool-goal/src/client/executor/index.ts
+++ b/packages/builtin-tool-goal/src/client/executor/index.ts
@@ -1,11 +1,26 @@
import { taskExecutor } from '@lobechat/builtin-tool-task/client/executor';
-import type { BuiltinToolContext, BuiltinToolResult, ToolAfterCallContext } from '@lobechat/types';
+import type {
+ BuiltinToolContext,
+ BuiltinToolResult,
+ GoalGraphSnapshot,
+ ToolAfterCallContext,
+} from '@lobechat/types';
import { BaseExecutor } from '@lobechat/types';
+import { goalService } from '@/services/goal';
+
+import { buildGoalRequirement, resolveGoalAttemptBudget } from '../../createGoalInput';
import { GoalIdentifier } from '../../manifest';
import type { CreateGoalParams } from '../../types';
import { GoalApiName } from '../../types';
+/**
+ * `/goal` creates a Goal Graph, not a task with a goal row attached: the graph
+ * owns the decomposition, dispatches its own Work Tasks and their acceptance
+ * contracts, and stops on a decision gate when a Work runs out of attempts.
+ * The drafted criteria become the goal's acceptance requirement, which the
+ * coordinator folds into every Work contract it writes.
+ */
class GoalExecutor extends BaseExecutor<typeof GoalApiName> {
readonly identifier = GoalIdentifier;
protected readonly apiEnum = GoalApiName;
@@ -16,8 +31,95 @@ class GoalExecutor extends BaseExecutor<typeof GoalApiName> {
createGoal = async (
params: CreateGoalParams,
- context?: BuiltinToolContext,
- ): Promise<BuiltinToolResult> => taskExecutor.createGoal(params, context);
+ ctx?: BuiltinToolContext,
+ ): Promise<BuiltinToolResult> => {
+ if (!ctx?.agentId) {
+ return {
+ content: 'A goal needs the current agent as its assignee.',
+ error: { message: 'agentId is required', type: 'MissingAgent' },
+ success: false,
+ };
+ }
+
+ const criteria = (params.criteria ?? []).filter((item) => item.title?.trim());
+ if (criteria.length === 0) {
+ return {
+ content: 'A goal needs at least one acceptance criterion.',
+ error: { message: 'criteria array is empty', type: 'EmptyCriteria' },
+ success: false,
+ };
+ }
+
+ try {
+ const graph = await goalService.create({
+ agentId: ctx.agentId,
+ config: {
+ recovery: { maxAttemptsPerWork: resolveGoalAttemptBudget(params.maxIterations) },
+ },
+ // `maxIterations` caps attempts on one Work; it is deliberately not
+ // passed as `maxRounds`, which counts runs across every Work in the
+ // graph and would strand later tasks that have not run at all.
+ maxTotalCost: params.maxTotalCost ?? undefined,
+ requirement: buildGoalRequirement(params.name, criteria, params.instruction),
+ title: params.name,
+ work: [{ description: params.instruction, title: params.name }],
+ });
+
+ return await this.reportCreatedGoal(graph, criteria.length, params.name);
+ } catch (error) {
+ const message = error instanceof Error ? error.message : 'Failed to create the goal';
+ return {
+ content: `Could not create the goal: ${message}`,
+ error: { message, type: 'GoalCreateFailed' },
+ state: { name: params.name, success: false },
+ success: false,
+ };
+ }
+ };
+
+ /**
+ * The goal is committed by the time this runs, so kickoff failure must never
+ * be reported as creation failure: an agent told the goal was not created
+ * makes another one, and both then do the same paid work. `goal.create`
+ * already queued an advance server-side, so a failure here costs nothing more
+ * than the immediate feedback.
+ */
+ private reportCreatedGoal = async (
+ graph: GoalGraphSnapshot,
+ criteriaCount: number,
+ name: string,
+ ): Promise<BuiltinToolResult> => {
+ const created = `Goal "${graph.goal.title}" created with ${criteriaCount} acceptance criteria.`;
+ const tail =
+ 'Execution continues in its own task; do not perform or reproduce the work in this conversation.';
+
+ try {
+ const advance = await goalService.advance(graph.goal.id);
+ return {
+ content: `${created} ${advance.message}. ${tail}`,
+ state: {
+ goalId: graph.goal.id,
+ name,
+ startedAt: new Date().toISOString(),
+ success: true,
+ taskId: advance.taskId,
+ },
+ success: true,
+ };
+ } catch (error) {
+ const message = error instanceof Error ? error.message : 'Could not start it right away';
+ return {
+ content: `${created} It has not started yet (${message}); the server will pick it up. Do not create it again. ${tail}`,
+ state: {
+ goalId: graph.goal.id,
+ name,
+ startedAt: new Date().toISOString(),
+ success: true,
+ },
+ success: true,
+ };
+ }
+ };
}
export const goalExecutor = new GoalExecutor();
diff --git a/packages/builtin-tool-goal/src/createGoalInput.test.ts b/packages/builtin-tool-goal/src/createGoalInput.test.ts
new file mode 100644
index 00000000000..8ed02e442e3
--- /dev/null
+++ b/packages/builtin-tool-goal/src/createGoalInput.test.ts
@@ -0,0 +1,18 @@
+import { describe, expect, it } from 'vitest';
+
+import { resolveGoalAttemptBudget } from './createGoalInput';
+
+describe('resolveGoalAttemptBudget', () => {
+ it('leaves the budget unset when the user cleared the field', () => {
+ // The manifest documents `null` as "no user-specified cap". Folding it into
+ // the default silently capped a supposedly uncapped goal at three attempts.
+ expect(resolveGoalAttemptBudget(null)).toBeUndefined();
+ expect(resolveGoalAttemptBudget(undefined)).toBeUndefined();
+ });
+
+ it('clamps a chosen value to the supported range', () => {
+ expect(resolveGoalAttemptBudget(1)).toBe(2);
+ expect(resolveGoalAttemptBudget(4)).toBe(4);
+ expect(resolveGoalAttemptBudget(99)).toBe(10);
+ });
+});
diff --git a/packages/builtin-tool-goal/src/createGoalInput.ts b/packages/builtin-tool-goal/src/createGoalInput.ts
new file mode 100644
index 00000000000..6f250870bfa
--- /dev/null
+++ b/packages/builtin-tool-goal/src/createGoalInput.ts
@@ -0,0 +1,49 @@
+/**
+ * Shared shaping for the `createGoal` tool between the client executor and the
+ * server runtime: both create the same Goal Graph, so the wording the agent and
+ * the verifier read must not drift between the two paths.
+ */
+
+export interface GoalCriterionInput {
+ description?: string;
+ instruction?: string;
+ title: string;
+}
+
+/**
+ * Attempts one Work gets before the coordinator opens a decision gate.
+ *
+ * `null` is the manifest's documented "no user-specified cap" — the cleared
+ * input field — and must stay distinct from a chosen number, or clearing the
+ * field would quietly pin the goal to three attempts. Returning `undefined`
+ * leaves `maxAttemptsPerWork` off the config so `resolveWorkAttemptBudget`
+ * applies its own default.
+ */
+export const resolveGoalAttemptBudget = (maxIterations?: number | null): number | undefined =>
+ typeof maxIterations === 'number' ? Math.min(10, Math.max(2, maxIterations)) : undefined;
+
+/**
+ * The goal's acceptance requirement. The Goal Graph models "what counts as
+ * done" as one authoritative text, which the coordinator folds into every
+ * Work's acceptance contract — so the drafted criteria are rendered into it
+ * rather than persisted as separate verify criteria rows.
+ */
+export const buildGoalRequirement = (
+ name: string,
+ criteria: GoalCriterionInput[],
+ instruction?: string,
+): string =>
+ [
+ name,
+ instruction ? `Scope: ${instruction}` : undefined,
+ 'Acceptance criteria — every one must be satisfied with concrete evidence:',
+ ...criteria.map((item, index) =>
+ [
+ `${index + 1}. ${item.title}`,
+ item.description ? ` — ${item.description}` : '',
+ item.instruction ? ` (how to judge: ${item.instruction})` : '',
+ ].join(''),
+ ),
+ ]
+ .filter(Boolean)
+ .join('\n');
diff --git a/packages/builtin-tool-goal/src/index.ts b/packages/builtin-tool-goal/src/index.ts
index 5f969bceccf..571eb13065b 100644
--- a/packages/builtin-tool-goal/src/index.ts
+++ b/packages/builtin-tool-goal/src/index.ts
@@ -1,3 +1,8 @@
+export {
+ buildGoalRequirement,
+ type GoalCriterionInput,
+ resolveGoalAttemptBudget,
+} from './createGoalInput';
export { isGoalPrompt } from './goalPrompt';
export { GoalIdentifier, GoalManifest } from './manifest';
export { systemPrompt } from './systemRole';
diff --git a/packages/builtin-tool-goal/src/manifest.ts b/packages/builtin-tool-goal/src/manifest.ts
index 2949790d144..2fa48403542 100644
--- a/packages/builtin-tool-goal/src/manifest.ts
+++ b/packages/builtin-tool-goal/src/manifest.ts
@@ -9,7 +9,7 @@ export const GoalManifest: BuiltinToolManifest = {
api: [
{
description:
- 'Create and immediately start a goal-driven task with an editable acceptance plan. Use this only when the user explicitly starts their request with /goal. The call pauses for confirmation; after approval it creates the underlying task, persists the acceptance criteria, enables bounded automatic repair, and runs the current agent in a separate task topic. Once it succeeds, do not execute or reproduce the work in the current conversation; the live result card is the progress and result entry point.',
+ 'Create and immediately start a long-horizon goal with an editable acceptance plan. Use this only when the user explicitly starts their request with /goal. The call pauses for confirmation; after approval it creates the goal, records the acceptance criteria as its requirement, and advances its coordinator once — which dispatches the first task with its own verifier. Once it succeeds, do not execute or reproduce the work in the current conversation; the live result card is the progress and result entry point.',
humanIntervention: 'always',
name: GoalApiName.createGoal,
parameters: {
@@ -40,7 +40,7 @@ export const GoalManifest: BuiltinToolManifest = {
instruction: { description: 'Detailed task direction and constraints.', type: 'string' },
maxIterations: {
description:
- 'Maximum automatic execution/repair rounds. Default 3, minimum 2. Null means no user-specified cap.',
+ 'Maximum attempts one task may take before the goal opens a decision gate. Default 3, minimum 2. Null means no user-specified cap.',
type: ['number', 'null'],
},
maxTotalCost: {
diff --git a/packages/builtin-tool-goal/src/systemRole.test.ts b/packages/builtin-tool-goal/src/systemRole.test.ts
index 6dc8f25ebb6..8a82d19b659 100644
--- a/packages/builtin-tool-goal/src/systemRole.test.ts
+++ b/packages/builtin-tool-goal/src/systemRole.test.ts
@@ -4,7 +4,7 @@ import { systemPrompt } from './systemRole';
describe('Goal systemPrompt', () => {
it('hands successful goal execution off instead of duplicating it', () => {
- expect(systemPrompt).toContain('the work has been handed off to a separate task topic');
+ expect(systemPrompt).toContain('the goal owns the work');
expect(systemPrompt).toContain(
'do not perform, reproduce, preview, or self-check the requested work in the current conversation',
);
diff --git a/packages/builtin-tool-goal/src/systemRole.ts b/packages/builtin-tool-goal/src/systemRole.ts
index 309d425c312..b4fc1fe84d6 100644
--- a/packages/builtin-tool-goal/src/systemRole.ts
+++ b/packages/builtin-tool-goal/src/systemRole.ts
@@ -1,3 +1,3 @@
export const systemPrompt = `You have access to the Goal tool.
-- **createGoal**: When — and only when — the user's message starts with \`/goal\`, turn the request into one editable goal plan and call createGoal before doing any substantive work. Use the current agent implicitly. Derive one concrete criterion per explicit requirement, default failed criteria to auto_repair, default maxIterations to 3, and omit maxTotalCost unless the user set one. The user confirms or edits the complete plan before the task starts. After createGoal succeeds, the work has been handed off to a separate task topic: do not perform, reproduce, preview, or self-check the requested work in the current conversation. End the turn with at most one brief sentence saying the goal is running and its live card shows progress.`;
+- **createGoal**: When — and only when — the user's message starts with \`/goal\`, turn the request into one editable goal plan and call createGoal before doing any substantive work. Use the current agent implicitly. Derive one concrete criterion per explicit requirement, default failed criteria to auto_repair, default maxIterations to 3, and omit maxTotalCost unless the user set one. The user confirms or edits the complete plan before the goal starts. After createGoal succeeds, the goal owns the work: its coordinator decomposes it and dispatches its own tasks, so do not perform, reproduce, preview, or self-check the requested work in the current conversation. End the turn with at most one brief sentence saying the goal is running and its live card shows progress.`;
diff --git a/packages/builtin-tool-task/src/client/Render/CreateGoal/index.tsx b/packages/builtin-tool-task/src/client/Render/CreateGoal/index.tsx
index 46f1e7bef94..c9233995d62 100644
--- a/packages/builtin-tool-task/src/client/Render/CreateGoal/index.tsx
+++ b/packages/builtin-tool-task/src/client/Render/CreateGoal/index.tsx
@@ -1,5 +1,6 @@
'use client';
+import type { GoalStatus } from '@lobechat/const/goal';
import type { BuiltinRenderProps } from '@lobechat/types';
import { Flexbox, Icon } from '@lobehub/ui';
import { Text } from '@lobehub/ui/base-ui';
@@ -19,9 +20,8 @@ import {
import { memo, useEffect, useState } from 'react';
import { useTranslation } from 'react-i18next';
-import { useAcceptanceBySubject } from '@/features/Acceptance';
-import { acceptanceOverviewPath } from '@/features/Acceptance/Viewer/routes';
import { useWorkspaceAwareNavigate } from '@/features/Workspace/useWorkspaceAwareNavigate';
+import { goalSelectors, useGoalStore } from '@/store/goal';
import type { CreateGoalParams, CreateGoalState } from '../../../types';
import { TaskResultCard } from '../shared';
@@ -87,37 +87,35 @@ const phaseLabel = (t: TFunction<'plugin'>, phase: PhaseKey): string => {
};
/**
- * The card reads the acceptance aggregate directly instead of waiting for the
- * loop to push a phase onto this tool message. A push can silently never
- * arrive (it needs the task to remember which tool call spawned it); the
- * aggregate is the same record the task page and the acceptance page read, so
- * the conversation can never disagree with them.
+ * The card reads the goal's own lifecycle state instead of waiting for the
+ * coordinator to push a phase onto this tool message. A push can silently never
+ * arrive (it needs the task to remember which tool call spawned it); the goal
+ * row is the same record the goal page reads, so the conversation can never
+ * disagree with it.
*/
-const resolvePhase = (status?: string, latestRunStatus?: string | null): PhaseKey => {
+const resolvePhase = (status: GoalStatus | undefined, pendingDecisions: number): PhaseKey => {
+ if (pendingDecisions > 0) return 'awaitingDecision';
switch (status) {
- case 'accepted': {
+ case 'achieved': {
return 'accepted';
}
- case 'closed': {
+ case 'canceled': {
return 'closed';
}
- case 'delivered': {
- return latestRunStatus === 'passed' ? 'awaitingReview' : 'awaitingDecision';
- }
- case 'errored': {
+ case 'failed': {
return 'errored';
}
- case 'rejected': {
- return 'rejected';
+ // Paused means the coordinator stopped scheduling: either the user paused
+ // it, or a budget ran out. Either way the next move is theirs.
+ case 'paused': {
+ return 'awaitingDecision';
}
- case 'repairing': {
- return 'repairing';
+ case 'review': {
+ return 'awaitingReview';
}
case 'verifying': {
return 'verifying';
}
- // No aggregate yet, or one that only holds the plan: the round is still
- // producing the delivery.
default: {
return 'running';
}
@@ -128,46 +126,45 @@ const CreateGoalRender = memo<BuiltinRenderProps<CreateGoalParams, CreateGoalSta
({ args, pluginState }) => {
const { t } = useTranslation('plugin');
const navigate = useWorkspaceAwareNavigate();
- const identifier = pluginState?.identifier;
+ const goalId = pluginState?.goalId;
const [now, setNow] = useState(() => Date.now());
- const { data: acceptance, mutate } = useAcceptanceBySubject(
- 'task',
- pluginState?.taskId ?? null,
- );
- const phase = resolvePhase(acceptance?.status, acceptance?.latestRunStatus);
+ const useFetchGoalGraph = useGoalStore((s) => s.useFetchGoalGraph);
+ useFetchGoalGraph(goalId);
+ const snapshot = useGoalStore(goalSelectors.goalGraph(goalId));
+ const pendingDecisions =
+ snapshot?.decisions.filter((decision) => decision.status === 'pending').length ?? 0;
+ const phase = resolvePhase(snapshot?.goal.status, pendingDecisions);
const meta = PHASE_META[phase];
- // The elapsed clock and the poll share one timer: both exist only while the
- // goal is still moving, and both stop the moment it settles.
+ // Ticks the elapsed clock only. Refreshing the graph is `useFetchGoalGraph`'s
+ // job and it already polls while the goal is one the server can move — doing
+ // it here too meant every mounted card pulled the whole snapshot once a
+ // second, and a card whose fetch had failed read as unsettled and never
+ // stopped asking.
useEffect(() => {
if (meta.settled) return;
- const timer = window.setInterval(() => {
- setNow(Date.now());
- void mutate();
- }, 1000);
+ const timer = window.setInterval(() => setNow(Date.now()), 1000);
return () => window.clearInterval(timer);
- }, [meta.settled, mutate]);
+ }, [meta.settled]);
- if (!pluginState?.success || !identifier) return null;
+ if (!pluginState?.success || !goalId) return null;
- const openAcceptance = acceptance
- ? () => navigate(acceptanceOverviewPath(acceptance.id))
- : undefined;
+ const agentId = snapshot?.goal.agentId;
+ const openGoal = agentId ? () => navigate(`/agent/${agentId}/goal/${goalId}`) : undefined;
return (
<TaskResultCard
icon={Target}
iconColor={cssVar.colorTextSecondary}
- identifier={identifier}
- title={pluginState.name ?? args?.name}
+ title={snapshot?.goal.title ?? pluginState.name ?? args?.name}
>
<Flexbox
horizontal
align={'center'}
gap={8}
- style={openAcceptance ? { cursor: 'pointer' } : undefined}
- onClick={openAcceptance}
+ style={openGoal ? { cursor: 'pointer' } : undefined}
+ onClick={openGoal}
>
<Icon
color={meta.color}
diff --git a/packages/builtin-tool-task/src/client/executor/index.ts b/packages/builtin-tool-task/src/client/executor/index.ts
index 5136a995343..2660ea66357 100644
--- a/packages/builtin-tool-task/src/client/executor/index.ts
+++ b/packages/builtin-tool-task/src/client/executor/index.ts
@@ -21,7 +21,6 @@ import debug from 'debug';
import { getActiveWorkspaceSlug } from '@/business/client/hooks/useActiveWorkspaceSlug';
import { taskService } from '@/services/task';
-import { verifyService } from '@/services/verify';
import { getChatStoreState } from '@/store/chat';
import { getTaskStoreState } from '@/store/task';
import { findSubtaskParentId } from '@/store/task/slices/detail/reducer';
@@ -59,7 +58,6 @@ const LIST_MUTATING_APIS = new Set<string>([
TaskApiName.runTasks,
TaskApiName.setTaskSchedule,
TaskApiName.updateTaskStatus,
- TaskApiName.createGoal,
]);
const DETAIL_MUTATING_APIS = new Set<string>([
@@ -72,7 +70,6 @@ const DETAIL_MUTATING_APIS = new Set<string>([
TaskApiName.updateTaskComment,
TaskApiName.updateTaskStatus,
TaskApiName.viewTask,
- TaskApiName.createGoal,
]);
const extractIdentifier = (params: unknown, result: BuiltinToolResult): string | undefined => {
@@ -188,12 +185,6 @@ class TaskExecutor extends BaseExecutor<typeof TaskApiName> {
instruction: string;
assigneeAgentId?: string;
// Bind a goal entity to the created task (see TaskService.createTask).
- goal?: {
- maxRounds?: number | null;
- maxTotalCost?: number | null;
- requirement?: string | null;
- title?: string;
- };
name: string;
parentIdentifier?: string;
priority?: number;
@@ -209,7 +200,6 @@ class TaskExecutor extends BaseExecutor<typeof TaskApiName> {
assigneeAgentId:
params.assigneeAgentId ?? (ctx?.scope === 'task' ? undefined : ctx?.agentId),
createdByAgentId: ctx?.agentId,
- goal: params.goal,
instruction: params.instruction,
name: params.name,
parentTaskId: parentIdentifier,
@@ -275,116 +265,6 @@ class TaskExecutor extends BaseExecutor<typeof TaskApiName> {
ctx?: BuiltinToolContext,
): Promise<BuiltinToolResult> => this.#createTask(params, ctx);
- createGoal = async (
- params: {
- criteria: Array<{
- description?: string;
- instruction?: string;
- onFail?: 'auto_repair' | 'manual';
- required?: boolean;
- title: string;
- verifierConfig?: Record<string, unknown>;
- verifierType?: 'agent' | 'llm' | 'program';
- }>;
- instruction: string;
- maxIterations?: number | null;
- maxTotalCost?: number | null;
- name: string;
- },
- ctx?: BuiltinToolContext,
- ): Promise<BuiltinToolResult> => {
- if (!ctx?.agentId) {
- return {
- content: 'A goal needs the current agent as its assignee.',
- error: { message: 'agentId is required', type: 'MissingAgent' },
- success: false,
- };
- }
-
- const criteria = (params.criteria ?? []).filter((item) => item.title?.trim());
- if (criteria.length === 0) {
- return {
- content: 'A goal needs at least one acceptance criterion.',
- error: { message: 'criteria array is empty', type: 'EmptyCriteria' },
- success: false,
- };
- }
-
- const created = await this.#createTask(
- {
- assigneeAgentId: ctx.agentId,
- // The goals row is created together with the task, so the "is a goal"
- // marker can never race the verify-config write below.
- goal: {
- maxRounds: params.maxIterations,
- maxTotalCost: params.maxTotalCost ?? null,
- requirement: params.name,
- title: params.name,
- },
- instruction: params.instruction,
- name: params.name,
- },
- ctx,
- );
- const identifier = (created.state as { identifier?: string } | undefined)?.identifier;
- const taskId = (created.state as { taskId?: string } | undefined)?.taskId;
- if (!created.success || !identifier) return created;
-
- try {
- const verifyCriteriaIds = await verifyService.createCriteria(
- criteria.map((item) => ({
- description: item.description,
- instruction: item.verifierType === 'program' ? undefined : item.instruction,
- onFail: item.onFail ?? 'auto_repair',
- required: item.required ?? true,
- title: item.title,
- verifierConfig: item.verifierConfig,
- verifierType: item.verifierType ?? 'agent',
- })),
- );
- const maxIterations = Math.min(10, Math.max(2, params.maxIterations ?? 3));
-
- await taskService.updateVerifyConfig({
- id: identifier,
- verify: {
- enabled: true,
- maxIterations,
- requirement: params.name,
- verifyCriteriaIds,
- },
- });
-
- const started = await this.runTask({ identifier }, ctx);
- if (!started.success) return started;
- const state = started.state as {
- operationId?: string;
- topicId?: string;
- };
-
- return {
- content: `Goal task ${identifier} created and started with ${criteria.length} acceptance criteria. Execution continues in its separate task topic; do not perform or reproduce the task in this conversation.`,
- state: {
- identifier,
- name: params.name,
- operationId: state.operationId,
- startedAt: new Date().toISOString(),
- success: true,
- taskId,
- topicId: state.topicId,
- },
- success: true,
- };
- } catch (error) {
- const message = error instanceof Error ? error.message : 'Failed to start goal';
- return {
- content: `Goal task ${identifier} was created but could not be started: ${message}`,
- error: { message, type: 'CreateGoalFailed' },
- state: { identifier, name: params.name, success: false },
- success: false,
- };
- }
- };
-
createTasks = async (
params: { tasks: CreateTaskParams[] },
ctx?: BuiltinToolContext,
diff --git a/packages/builtin-tool-task/src/types.ts b/packages/builtin-tool-task/src/types.ts
index a105079fbdc..534b87c092d 100644
--- a/packages/builtin-tool-task/src/types.ts
+++ b/packages/builtin-tool-task/src/types.ts
@@ -96,13 +96,13 @@ export interface CreateGoalParams {
}
export interface CreateGoalState {
- identifier?: string;
+ /** The `goals` row the Goal Graph was created as — what the card opens. */
+ goalId?: string;
name?: string;
- operationId?: string;
startedAt?: string;
success: boolean;
+ /** The responsible task the first coordinator tick dispatched, when it got that far. */
taskId?: string;
- topicId?: string;
}
// ==================== createTasks (batch) ====================
diff --git a/packages/database/src/models/__tests__/goal.test.ts b/packages/database/src/models/__tests__/goal.test.ts
index 858ab4a0f2e..fad0966129d 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 { agents, goals, tasks, users, workspaces } from '../../schemas';
+import { agents, goalEdges, goalNodeDecisions, goalNodes, users } from '../../schemas';
import type { LobeChatDatabase } from '../../type';
import { GoalModel } from '../goal';
+import { GoalGraphModel } from '../goalGraph';
import { TaskModel } from '../task';
const serverDB: LobeChatDatabase = await getTestDB();
@@ -13,6 +14,7 @@ const serverDB: LobeChatDatabase = await getTestDB();
const userId = 'goal-model-test-user-id';
const otherUserId = 'goal-model-test-user-2';
const goalModel = new GoalModel(serverDB, userId);
+const graphModel = new GoalGraphModel(serverDB, userId);
beforeEach(async () => {
await serverDB.delete(users);
@@ -27,16 +29,14 @@ describe('GoalModel', () => {
describe('create', () => {
it('creates a goal with defaults', async () => {
const result = await goalModel.create({
- subjectId: 'tsk_1',
- subjectType: 'task',
+ subjectType: 'standalone',
title: 'Ship the goals table',
});
expect(result.id).toMatch(/^goal_/);
expect(result).toMatchObject({
status: 'planning',
- subjectId: 'tsk_1',
- subjectType: 'task',
+ subjectType: 'standalone',
title: 'Ship the goals table',
userId,
});
@@ -47,8 +47,7 @@ describe('GoalModel', () => {
maxRounds: 5,
maxTotalCost: 12.5,
requirement: 'All tests pass',
- subjectId: 'tsk_2',
- subjectType: 'task',
+ subjectType: 'standalone',
title: 'Budgeted goal',
});
@@ -58,109 +57,209 @@ describe('GoalModel', () => {
});
});
- describe('findBySubject', () => {
- it('finds the goal bound to a carrier', async () => {
- const created = await goalModel.create({
- subjectId: 'tsk_3',
- subjectType: 'task',
- title: 'Carrier goal',
- });
+ describe('findByWorkTask', () => {
+ it('finds the goal whose graph owns a Work Task', async () => {
+ const task = await new TaskModel(serverDB, userId).create({ instruction: 'do the work' });
+ const goal = await goalModel.create({ subjectType: 'standalone', title: 'Owner' });
+ const node = await graphModel.createNode(goal.id, { kind: 'work', title: 'W1' });
+ await serverDB.update(goalNodes).set({ taskId: task.id }).where(eq(goalNodes.id, node!.id));
- const found = await goalModel.findBySubject('task', 'tsk_3');
- expect(found?.id).toBe(created.id);
+ expect((await goalModel.findByWorkTask(task.id))?.id).toBe(goal.id);
});
it('does not cross user boundaries', async () => {
- const otherModel = new GoalModel(serverDB, otherUserId);
- await otherModel.create({ subjectId: 'tsk_4', subjectType: 'task', title: 'Not mine' });
-
- const found = await goalModel.findBySubject('task', 'tsk_4');
- expect(found).toBeUndefined();
- });
- });
-
- describe('listBySubjects', () => {
- it('returns goals for the asked carriers only', async () => {
- await goalModel.create({ subjectId: 'tsk_a', subjectType: 'task', title: 'A' });
- await goalModel.create({ subjectId: 'tsk_b', subjectType: 'task', title: 'B' });
- await goalModel.create({ subjectId: 'tsk_c', subjectType: 'task', title: 'C' });
-
- const rows = await goalModel.listBySubjects('task', ['tsk_a', 'tsk_c']);
- expect(rows.map((r) => r.subjectId).sort()).toEqual(['tsk_a', 'tsk_c']);
- });
-
- it('returns empty for an empty id list', async () => {
- expect(await goalModel.listBySubjects('task', [])).toEqual([]);
+ const otherGoals = new GoalModel(serverDB, otherUserId);
+ const otherGraph = new GoalGraphModel(serverDB, otherUserId);
+ const task = await new TaskModel(serverDB, otherUserId).create({ instruction: 'theirs' });
+ const goal = await otherGoals.create({ subjectType: 'standalone', title: 'Theirs' });
+ const node = await otherGraph.createNode(goal.id, { kind: 'work', title: 'W1' });
+ await serverDB.update(goalNodes).set({ taskId: task.id }).where(eq(goalNodes.id, node!.id));
+
+ expect(await goalModel.findByWorkTask(task.id)).toBeUndefined();
});
});
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,
+ it('lists goals the caller owns, newest first, with the graph roll-up', async () => {
+ const goal = await goalModel.create({ subjectType: 'standalone', title: 'Reproduce it' });
+ const problem = await graphModel.createNode(goal.id, { kind: 'problem', title: 'P1' });
+ const done = await graphModel.createNode(goal.id, { kind: 'work', title: 'W1' });
+ await graphModel.createNode(goal.id, { kind: 'work', title: 'W2' });
+ await graphModel.createNode(goal.id, { kind: 'finding', title: 'F1' });
+ await graphModel.createEdge(goal.id, problem!.id, done!.id, 'decomposes');
+ await graphModel.updateNodeStatus(goal.id, done!.id, 'resolved');
+
+ const { goals, total } = await goalModel.list();
+
+ expect(total).toBe(1);
+ expect(goals[0]).toMatchObject({
+ findingCount: 1,
+ pendingDecisions: 0,
+ workDone: 1,
+ workTotal: 2,
});
+ expect(goals[0].goal.id).toBe(goal.id);
+ });
- 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',
+ it('counts only the decision gates still waiting on a human', async () => {
+ const goal = await goalModel.create({ subjectType: 'standalone', title: 'Gated' });
+ const open = await graphModel.createNode(goal.id, { kind: 'decision', title: 'D1' });
+ const closed = await graphModel.createNode(goal.id, { kind: 'decision', title: 'D2' });
+ await graphModel.createDecision(goal.id, open!.id, {
+ authority: 'user',
+ question: 'retry?',
});
- await ownerGoals.create({
- subjectId: publicTask.id,
- subjectType: 'task',
- title: 'Public goal',
+ await graphModel.createDecision(goal.id, closed!.id, {
+ authority: 'user',
+ question: 'retire?',
});
+ await serverDB
+ .update(goalNodeDecisions)
+ .set({ status: 'resolved' })
+ .where(eq(goalNodeDecisions.nodeId, closed!.id));
- const memberGoals = new GoalModel(serverDB, otherUserId, workspaceId);
- const result = await memberGoals.list();
+ expect((await goalModel.list()).goals[0].pendingDecisions).toBe(1);
+ });
+
+ it('does not leak another user’s goals', async () => {
+ await new GoalModel(serverDB, otherUserId).create({
+ subjectType: 'standalone',
+ title: 'Not mine',
+ });
- expect(result.total).toBe(1);
- expect(result.goals.map(({ id }) => id)).toEqual([publicTask.id]);
+ expect((await goalModel.list()).total).toBe(0);
});
- 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';
+ it('scopes by the goal’s responsible agent', async () => {
+ const mine = 'goal-list-agent-a';
+ const theirs = 'goal-list-agent-b';
await serverDB.insert(agents).values([
- { id: oldAgentId, slug: oldAgentId, userId },
- { id: newAgentId, slug: newAgentId, userId },
+ { id: mine, slug: mine, userId },
+ { id: theirs, slug: theirs, userId },
]);
- const task = await new TaskModel(serverDB, userId).create({
- assigneeAgentId: oldAgentId,
- instruction: 'reassign me',
+ const ours = await goalModel.create({
+ agentId: mine,
+ subjectType: 'standalone',
+ title: 'Mine',
});
- await goalModel.create({
- agentId: oldAgentId,
- subjectId: task.id,
- subjectType: 'task',
- title: 'Reassigned goal',
+ const others = await goalModel.create({
+ agentId: theirs,
+ subjectType: 'standalone',
+ title: 'Theirs',
});
+ await graphModel.createNode(ours.id, { kind: 'work', title: 'W1' });
+ await graphModel.createNode(others.id, { kind: 'work', title: 'W1' });
+
+ const scoped = await goalModel.list({ agentId: mine });
+ expect(scoped.total).toBe(1);
+ expect(scoped.goals[0].goal.title).toBe('Mine');
+ });
+
+ it('leaves out a goal that never got a graph', async () => {
+ // Rows from the earlier task-carried flow have no `goal_nodes`. Listing
+ // them renders a goal page with no work, no frontier and no way forward.
+ const legacy = await goalModel.create({ subjectType: 'task', title: 'Carrier-bound' });
+ const graphed = await goalModel.create({ subjectType: 'standalone', title: 'Has a graph' });
+ await graphModel.createNode(graphed.id, { kind: 'work', title: 'W1' });
+
+ const { goals, total } = await goalModel.list();
+
+ expect(total).toBe(1);
+ expect(goals.map(({ goal }) => goal.id)).toEqual([graphed.id]);
+ expect(goals.map(({ goal }) => goal.id)).not.toContain(legacy.id);
+ });
+
+ it('filters by lifecycle status', async () => {
+ const running = await goalModel.create({ subjectType: 'standalone', title: 'Running' });
+ const achieved = await goalModel.create({ subjectType: 'standalone', title: 'Achieved' });
+ await graphModel.createNode(running.id, { kind: 'work', title: 'W1' });
+ await graphModel.createNode(achieved.id, { kind: 'work', title: 'W1' });
+ await goalModel.updateStatus(running.id, 'running');
+ await goalModel.updateStatus(achieved.id, 'achieved');
+
+ const open = await goalModel.list({ statuses: ['running'] });
+ expect(open.goals.map(({ goal }) => goal.title)).toEqual(['Running']);
+ });
+ });
+
+ describe('listStalled', () => {
+ const staleBefore = () => new Date(Date.now() - 15 * 60 * 1000);
+
+ it('picks up an open goal with nothing running', async () => {
+ const goal = await goalModel.create({ subjectType: 'standalone', title: 'Never started' });
+ await goalModel.updateStatus(goal.id, 'running');
+ await graphModel.createNode(goal.id, { kind: 'work', title: 'W1' });
+
+ const stalled = await GoalModel.listStalled(serverDB, { staleBefore: staleBefore() });
+ expect(stalled.map(({ id }) => id)).toContain(goal.id);
+ });
+
+ it('leaves out a goal that never got a graph', async () => {
+ // No graph means no frontier, so every sweep would tick it only to hear
+ // `no_progress` back.
+ const goal = await goalModel.create({ subjectType: 'task', title: 'Carrier-bound' });
+ await goalModel.updateStatus(goal.id, 'running');
+
+ const stalled = await GoalModel.listStalled(serverDB, { staleBefore: staleBefore() });
+ expect(stalled.map(({ id }) => id)).not.toContain(goal.id);
+ });
+
+ it('leaves a goal alone while one of its Work Tasks is freshly active', async () => {
+ const goal = await goalModel.create({ subjectType: 'standalone', title: 'Working' });
+ await goalModel.updateStatus(goal.id, 'running');
+ const node = await graphModel.createNode(goal.id, { kind: 'work', title: 'W1' });
+ await graphModel.updateNodeStatus(goal.id, node!.id, 'active');
+
+ const stalled = await GoalModel.listStalled(serverDB, { staleBefore: staleBefore() });
+ expect(stalled.map(({ id }) => id)).not.toContain(goal.id);
+ });
+
+ it('reclaims a Work that outlived its operation lease', async () => {
+ const goal = await goalModel.create({ subjectType: 'standalone', title: 'Lost' });
+ await goalModel.updateStatus(goal.id, 'running');
+ const node = await graphModel.createNode(goal.id, { kind: 'work', title: 'W1' });
+ await graphModel.updateNodeStatus(goal.id, node!.id, 'active');
await serverDB
- .update(tasks)
- .set({ assigneeAgentId: newAgentId })
- .where(eq(tasks.id, task.id));
+ .update(goalNodes)
+ .set({ updatedAt: new Date(Date.now() - 60 * 60 * 1000) })
+ .where(eq(goalNodes.id, node!.id));
+
+ const stalled = await GoalModel.listStalled(serverDB, { staleBefore: staleBefore() });
+ expect(stalled.map(({ id }) => id)).toContain(goal.id);
+ });
+
+ it('skips a goal whose next move belongs to a human', async () => {
+ // Ticking a goal parked on a decision gate only re-reports `waiting_human`
+ // on every sweep; only the user can move it.
+ const goal = await goalModel.create({ subjectType: 'standalone', title: 'Gated' });
+ await goalModel.updateStatus(goal.id, 'running');
+ const gate = await graphModel.createNode(goal.id, { kind: 'decision', title: 'D1' });
+ await graphModel.createDecision(goal.id, gate!.id, {
+ authority: 'user',
+ question: 'retry?',
+ });
- expect((await goalModel.list({ agentId: oldAgentId })).total).toBe(0);
- expect((await goalModel.list({ agentId: newAgentId })).goals[0]?.id).toBe(task.id);
+ const stalled = await GoalModel.listStalled(serverDB, { staleBefore: staleBefore() });
+ expect(stalled.map(({ id }) => id)).not.toContain(goal.id);
});
+
+ it.each(['achieved', 'failed', 'canceled', 'paused'] as const)(
+ 'never sweeps a %s goal',
+ async (status) => {
+ const goal = await goalModel.create({ subjectType: 'standalone', title: status });
+ await goalModel.updateStatus(goal.id, status);
+ await graphModel.createNode(goal.id, { kind: 'work', title: 'W1' });
+
+ const stalled = await GoalModel.listStalled(serverDB, { staleBefore: staleBefore() });
+ expect(stalled.map(({ id }) => id)).not.toContain(goal.id);
+ },
+ );
});
describe('updateStatus', () => {
it('stamps startedAt on first entry into running', async () => {
const { id } = await goalModel.create({
- subjectId: 'tsk_5',
- subjectType: 'task',
+ subjectType: 'standalone',
title: 'Lifecycle goal',
});
@@ -175,8 +274,7 @@ describe('GoalModel', () => {
it('stamps completedAt on terminal states and clears it on re-open', async () => {
const { id } = await goalModel.create({
- subjectId: 'tsk_6',
- subjectType: 'task',
+ subjectType: 'standalone',
title: 'Terminal goal',
});
@@ -189,24 +287,27 @@ describe('GoalModel', () => {
it('returns undefined for a goal outside the scope', async () => {
const otherModel = new GoalModel(serverDB, otherUserId);
- const { id } = await otherModel.create({
- subjectId: 'tsk_7',
- subjectType: 'task',
- title: 'Not mine',
- });
+ const { id } = await otherModel.create({ subjectType: 'standalone', title: 'Not mine' });
expect(await goalModel.updateStatus(id, 'running')).toBeUndefined();
});
});
- describe('deleteBySubject', () => {
- it('removes the goal bound to the carrier', async () => {
- await goalModel.create({ subjectId: 'tsk_8', subjectType: 'task', title: 'Doomed' });
-
- await goalModel.deleteBySubject('task', 'tsk_8');
-
- const rows = await serverDB.query.goals.findMany({ where: eq(goals.userId, userId) });
- expect(rows).toHaveLength(0);
+ describe('delete', () => {
+ it('cascades the whole graph away with the goal', async () => {
+ const goal = await goalModel.create({ subjectType: 'standalone', title: 'Doomed' });
+ const problem = await graphModel.createNode(goal.id, { kind: 'problem', title: 'P1' });
+ const work = await graphModel.createNode(goal.id, { kind: 'work', title: 'W1' });
+ await graphModel.createEdge(goal.id, problem!.id, work!.id, 'decomposes');
+
+ await goalModel.delete(goal.id);
+
+ expect(
+ await serverDB.query.goalNodes.findMany({ where: eq(goalNodes.goalId, goal.id) }),
+ ).toHaveLength(0);
+ expect(
+ await serverDB.query.goalEdges.findMany({ where: eq(goalEdges.goalId, goal.id) }),
+ ).toHaveLength(0);
});
});
});
diff --git a/packages/database/src/models/__tests__/task.test.ts b/packages/database/src/models/__tests__/task.test.ts
index 1a3716553c0..ac2f92853cf 100644
--- a/packages/database/src/models/__tests__/task.test.ts
+++ b/packages/database/src/models/__tests__/task.test.ts
@@ -8,7 +8,6 @@ import {
agents,
briefs,
documents,
- goals,
tasks,
topics,
users,
@@ -17,7 +16,6 @@ import {
import { taskTopics } from '../../schemas/task';
import { works } from '../../schemas/work';
import type { LobeChatDatabase } from '../../type';
-import { GoalModel } from '../goal';
import { ProjectModel } from '../project';
import { TaskModel } from '../task';
import { WorkModel } from '../work';
@@ -680,36 +678,6 @@ describe('TaskModel', () => {
expect(group.total).toBe(1);
});
- it('should filter tasks by their bound goal entity', async () => {
- const model = new TaskModel(serverDB, userId);
-
- const goalTask = await model.create({ instruction: 'Persistent objective' });
- const goalRow = await new GoalModel(serverDB, userId).create({
- maxRounds: 5,
- subjectId: goalTask.id,
- subjectType: 'task',
- title: 'Persistent objective',
- });
- await model.create({ instruction: 'Ordinary task' });
-
- const goals = await model.groupList({
- groups: [{ key: 'goals', statuses: ['backlog'] }],
- hasGoal: true,
- });
- const ordinary = await model.groupList({
- groups: [{ key: 'tasks', statuses: ['backlog'] }],
- hasGoal: false,
- });
-
- expect(goals[0].tasks.map((task) => task.id)).toEqual([goalTask.id]);
- // The goal entity rides along on the returned task row.
- expect(goals[0].tasks[0].goal?.id).toBe(goalRow.id);
- expect(goals[0].tasks[0].goal?.maxRounds).toBe(5);
- expect(ordinary[0].tasks).toHaveLength(1);
- expect(ordinary[0].tasks[0].instruction).toBe('Ordinary task');
- expect(ordinary[0].tasks[0].goal).toBeNull();
- });
-
it('should group only tasks from the requested project', async () => {
const model = new TaskModel(serverDB, userId);
const project = await new ProjectModel(serverDB, userId).create({
@@ -1404,24 +1372,6 @@ describe('TaskModel', () => {
expect(total1).toBe(0);
expect(total2).toBe(1);
});
-
- it('sweeps the goals bound to bulk-deleted tasks', async () => {
- // Regression (codex review): the FK-less goals rows survived clearAll,
- // orphaning every cleared goal — only single and subtree deletion swept.
- const model = new TaskModel(serverDB, userId);
- const goalModel = new GoalModel(serverDB, userId);
- const goalTask = await model.create({ instruction: 'Goal task' });
- await goalModel.create({ subjectId: goalTask.id, subjectType: 'task', title: 'Doomed' });
- const otherUsers = new GoalModel(serverDB, userId2);
- await otherUsers.create({ subjectId: 'task_foreign', subjectType: 'task', title: 'Keep' });
-
- await model.deleteAll();
-
- const mine = await serverDB.query.goals.findMany({ where: eq(goals.userId, userId) });
- const theirs = await serverDB.query.goals.findMany({ where: eq(goals.userId, userId2) });
- expect(mine).toHaveLength(0);
- expect(theirs).toHaveLength(1);
- });
});
describe('getDependenciesByTaskIds', () => {
diff --git a/packages/database/src/models/goal.ts b/packages/database/src/models/goal.ts
index 39ff54751e2..bda0c1e3330 100644
--- a/packages/database/src/models/goal.ts
+++ b/packages/database/src/models/goal.ts
@@ -1,10 +1,10 @@
-import type { GoalStatus, GoalSubjectType } from '@lobechat/const/goal';
-import type { TaskItem } from '@lobechat/types';
+import type { GoalStatus } from '@lobechat/const/goal';
+import type { GoalNodeStatus } 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 { goalNodes } from '../schemas/goalGraph';
+import { goalNodeDecisions, goalNodes } from '../schemas/goalGraph';
import { tasks, taskTopics } from '../schemas/task';
import { topics } from '../schemas/topic';
import type { LobeChatDatabase } from '../type';
@@ -13,13 +13,16 @@ import { buildWorkspacePayload, buildWorkspaceWhere } from '../utils/workspace';
/** States after which a goal's loop no longer advances. */
const TERMINAL_GOAL_STATUSES = new Set<GoalStatus>(['achieved', 'failed', 'canceled']);
+/** Node states the coordinator will never pick up again. */
+const TERMINAL_NODE_STATUSES = new Set<GoalNodeStatus>(['resolved', 'rejected', 'retired']);
+
/**
* Owns the `goals` table: one row per goal — an independent target entity with
- * its own definition (title / requirement), budget and lifecycle state. The
- * execution carrier is a polymorphic (`subjectType`, `subjectId`) link (task /
- * topic / standalone); everything execution-specific (rounds run, cost spent,
- * acceptance checks) stays on the carrier and its tables and is derived at
- * read time, never denormalized here.
+ * its own definition (title / requirement), budget and lifecycle state.
+ *
+ * Execution lives in the goal's graph, not on the goal row: the coordinator
+ * dispatches a Task per Work node, and everything execution-specific (attempts,
+ * cost, acceptance) is derived from those tasks at read time.
*/
export class GoalModel {
private readonly db: LobeChatDatabase;
@@ -32,6 +35,15 @@ export class GoalModel {
this.workspaceId = workspaceId;
}
+ /**
+ * The goal owns a Goal Graph. `goal.create` always seeds a problem node and
+ * the opening Work, so this is exactly "not a leftover from the old
+ * task-carried flow".
+ */
+ private static hasGraphSql = sql`EXISTS (
+ SELECT 1 FROM ${goalNodes} WHERE ${goalNodes.goalId} = ${goals.id}
+ )`;
+
private ownership = () =>
buildWorkspaceWhere({ userId: this.userId, workspaceId: this.workspaceId }, goals);
@@ -56,20 +68,6 @@ export class GoalModel {
return this.db.query.goals.findFirst({ where: and(eq(goals.id, id), this.ownership()) });
};
- /** The goal bound to a carrier, or undefined when the subject carries none. */
- findBySubject = async (
- subjectType: GoalSubjectType,
- subjectId: string,
- ): Promise<GoalItem | undefined> => {
- return this.db.query.goals.findFirst({
- where: and(
- eq(goals.subjectType, subjectType),
- eq(goals.subjectId, subjectId),
- this.ownership(),
- ),
- });
- };
-
/** The Goal Graph that owns a Work Task, or undefined when the task is not graph-managed. */
findByWorkTask = async (taskId: string): Promise<GoalItem | undefined> => {
const [row] = await this.db
@@ -81,35 +79,6 @@ export class GoalModel {
return row?.goal;
};
- /**
- * The goals of many carriers in one read — for list surfaces (goal rail /
- * goals page) that already queried the carriers and need each row's goal
- * without a request per row.
- */
- listBySubjects = async (subjectType: GoalSubjectType, subjectIds: string[]) => {
- if (subjectIds.length === 0) return [];
-
- return this.db
- .select()
- .from(goals)
- .where(
- and(
- eq(goals.subjectType, subjectType),
- inArray(goals.subjectId, subjectIds),
- this.ownership(),
- ),
- );
- };
-
- /** Recent goals for the current scope, newest first. */
- query = async (limit = 50) => {
- return this.db.query.goals.findMany({
- limit,
- orderBy: [desc(goals.createdAt)],
- where: this.ownership(),
- });
- };
-
update = async (id: string, value: Partial<Omit<GoalItem, 'id' | 'userId'>>) => {
const [row] = await this.db
.update(goals)
@@ -139,20 +108,62 @@ export class GoalModel {
return this.db.delete(goals).where(and(eq(goals.id, id), this.ownership()));
};
- deleteBySubject = async (subjectType: GoalSubjectType, subjectId: string) => {
- return this.db
- .delete(goals)
+ /**
+ * Open goals that nothing is currently moving — the sweep's work list.
+ *
+ * A goal qualifies when it is still open and has no Work node that is both
+ * `active` and freshly touched: either nothing was ever dispatched, the
+ * completion event that should have re-entered the coordinator was lost, or a
+ * running Work outlived its operation lease and needs reclaiming. Goals with a
+ * decision gate open are excluded — only a human moves those, and ticking them
+ * would just report `waiting_human` on every sweep.
+ *
+ * Global by design (no ownership filter): the sweep runs as infrastructure and
+ * carries each goal's own `userId` / `workspaceId` into its advance.
+ */
+ static async listStalled(
+ db: LobeChatDatabase,
+ options: { limit?: number; staleBefore: Date },
+ ): Promise<GoalItem[]> {
+ const { limit = 200, staleBefore } = options;
+
+ return db
+ .select()
+ .from(goals)
.where(
- and(eq(goals.subjectType, subjectType), eq(goals.subjectId, subjectId), this.ownership()),
- );
- };
+ and(
+ inArray(goals.status, ['planning', 'running', 'verifying']),
+ // A graph-less legacy goal has no frontier, so every sweep would
+ // tick it only to report `no_progress`. Leave it alone.
+ GoalModel.hasGraphSql,
+ sql`NOT EXISTS (
+ SELECT 1 FROM ${goalNodes}
+ WHERE ${goalNodes.goalId} = ${goals.id}
+ AND ${goalNodes.kind} = 'work'
+ AND ${goalNodes.status} = 'active'
+ AND ${goalNodes.updatedAt} > ${staleBefore}
+ )`,
+ sql`NOT EXISTS (
+ SELECT 1 FROM ${goalNodeDecisions}
+ JOIN ${goalNodes} AS gate ON gate.id = ${goalNodeDecisions.nodeId}
+ WHERE gate.goal_id = ${goals.id}
+ AND ${goalNodeDecisions.status} = 'pending'
+ )`,
+ ),
+ )
+ .orderBy(desc(goals.updatedAt))
+ .limit(limit);
+ }
/**
- * 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 goals with the roll-up the goal surfaces render: how much of the
+ * graph is done, how many decisions are waiting on a human, and what the
+ * whole thing has cost so far.
+ *
+ * Goal-centric on purpose. Goals used to be listed through their carrier
+ * task, which made a goal without one invisible; a Goal Graph goal is
+ * `standalone`, so the list reads the `goals` table and derives execution
+ * facts from the graph's Work tasks.
*/
list = async (
options: {
@@ -165,112 +176,146 @@ export class GoalModel {
): 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));
+ // Only goals that actually have a graph. Rows created by the earlier
+ // task-carried flow have no `goal_nodes`, so they would render as a
+ // zero-work goal page that can never advance; they stay out of the list
+ // until something backfills them into graphs.
+ const conditions = [this.ownership(), GoalModel.hasGraphSql];
+ if (agentId) conditions.push(eq(goals.agentId, agentId));
+ if (projectId) conditions.push(eq(goals.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 })
+ .select()
.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 goalIds = rows.map((goal) => goal.id);
+ const [nodeRows, decisionRows, runStats] = await Promise.all([
+ this.db
+ .select({
+ goalId: goalNodes.goalId,
+ kind: goalNodes.kind,
+ status: goalNodes.status,
+ count: sql<number>`count(*)`,
+ })
+ .from(goalNodes)
+ .where(inArray(goalNodes.goalId, goalIds))
+ .groupBy(goalNodes.goalId, goalNodes.kind, goalNodes.status),
+ this.db
+ .select({ goalId: goalNodes.goalId, count: sql<number>`count(*)` })
+ .from(goalNodeDecisions)
+ .innerJoin(goalNodes, eq(goalNodeDecisions.nodeId, goalNodes.id))
+ .where(and(inArray(goalNodes.goalId, goalIds), eq(goalNodeDecisions.status, 'pending')))
+ .groupBy(goalNodes.goalId),
+ this.workTaskRunStats(goalIds),
+ ]);
- const items: GoalListItem[] = rows.map(({ goal, task }) => {
- const stats = runStatsByTaskId.get(task.id) ?? { totalRunCost: 0, totalRunDuration: 0 };
+ const stats = new Map<string, { findingCount: number; workDone: number; workTotal: number }>();
+ for (const row of nodeRows) {
+ const current = stats.get(row.goalId) ?? { findingCount: 0, workDone: 0, workTotal: 0 };
+ const count = Number(row.count);
+ if (row.kind === 'finding') current.findingCount += count;
+ if (row.kind === 'work') {
+ current.workTotal += count;
+ if (TERMINAL_NODE_STATUSES.has(row.status)) current.workDone += count;
+ }
+ stats.set(row.goalId, current);
+ }
+ const pendingByGoal = new Map(decisionRows.map((row) => [row.goalId, Number(row.count)]));
+ const items: GoalListItem[] = rows.map((goal) => {
+ const counts = stats.get(goal.id) ?? { findingCount: 0, workDone: 0, workTotal: 0 };
+ const run = runStats.get(goal.id) ?? { totalRunCost: 0, totalRunDuration: 0 };
return {
- ...task,
+ findingCount: counts.findingCount,
goal,
- totalRunCost: stats.totalRunCost,
- totalRunDuration: stats.totalRunDuration,
+ pendingDecisions: pendingByGoal.get(goal.id) ?? 0,
+ totalRunCost: run.totalRunCost,
+ totalRunDuration: run.totalRunDuration,
+ workDone: counts.workDone,
+ workTotal: counts.workTotal,
};
});
return { goals: items, total };
};
+
+ /**
+ * Cost and runtime across every task the graph dispatched, including tasks
+ * those Work tasks spawned themselves — the same subtree rule the task board
+ * uses, seeded from the Work nodes instead of one carrier root.
+ */
+ private workTaskRunStats = async (goalIds: string[]) => {
+ if (goalIds.length === 0)
+ return new Map<string, { totalRunCost: number; totalRunDuration: number }>();
+
+ const { rows } = await this.db.execute<{
+ goal_id: string;
+ total_run_cost: number;
+ total_run_duration: number;
+ }>(sql`
+ WITH RECURSIVE work_tree AS (
+ SELECT ${goalNodes.goalId} AS goal_id, ${tasks.id} AS task_id
+ FROM ${goalNodes}
+ JOIN ${tasks} ON ${tasks.id} = ${goalNodes.taskId}
+ WHERE ${inArray(goalNodes.goalId, goalIds)}
+ AND ${goalNodes.kind} = 'work'
+ AND ${this.taskOwnershipSql('tasks')}
+ UNION ALL
+ SELECT work_tree.goal_id, child.id
+ FROM ${tasks} child
+ JOIN work_tree ON child.parent_task_id = work_tree.task_id
+ WHERE ${this.taskOwnershipSql('child')}
+ )
+ SELECT
+ work_tree.goal_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 work_tree
+ LEFT JOIN ${taskTopics} ON ${taskTopics.taskId} = work_tree.task_id
+ LEFT JOIN ${topics} ON ${topics.id} = ${taskTopics.topicId}
+ GROUP BY work_tree.goal_id
+ `);
+
+ return new Map(
+ rows.map((row) => [
+ row.goal_id,
+ {
+ totalRunCost: Number(row.total_run_cost),
+ totalRunDuration: Number(row.total_run_duration),
+ },
+ ]),
+ );
+ };
}
-/** 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;
+/**
+ * A goal-list row: the goal itself plus the graph roll-up the list renders —
+ * how far the exploration got, what is blocked on a human, and what it cost.
+ */
+export interface GoalListItem {
+ findingCount: number;
+ goal: GoalItem;
+ /** Decision gates waiting on a human right now. */
+ pendingDecisions: number;
totalRunCost: number;
totalRunDuration: number;
+ workDone: number;
+ workTotal: number;
}
diff --git a/packages/database/src/models/project.ts b/packages/database/src/models/project.ts
index 2d627681f21..ac991f0f73d 100644
--- a/packages/database/src/models/project.ts
+++ b/packages/database/src/models/project.ts
@@ -4,7 +4,6 @@ import { and, asc, desc, eq, inArray, isNull, max, or, sql } from 'drizzle-orm';
import { agents } from '../schemas/agent';
import { knowledgeBases } from '../schemas/file';
-import { goals } from '../schemas/goal';
import {
projectAgents,
projectCompletionReviews,
@@ -419,25 +418,7 @@ export class ProjectModel {
)
.orderBy(asc(tasks.sortOrder), asc(tasks.seq));
- // Attach the goal entity carried by each task so project surfaces can tell
- // goal roots apart from plain tasks without re-querying per row.
- const goalRows =
- rows.length === 0
- ? []
- : await this.db
- .select()
- .from(goals)
- .where(
- and(
- eq(goals.subjectType, 'task'),
- inArray(
- goals.subjectId,
- rows.map(({ id }) => id),
- ),
- ),
- );
- const goalByTaskId = new Map(goalRows.map((row) => [row.subjectId!, row]));
- return rows.map((row) => ({ ...row, goal: goalByTaskId.get(row.id) ?? null }));
+ return rows;
}
async getEnabledKnowledgeBaseIdsForTask(taskId: string) {
diff --git a/packages/database/src/models/task.ts b/packages/database/src/models/task.ts
index ae3b2bc8eca..27b9c650a3c 100644
--- a/packages/database/src/models/task.ts
+++ b/packages/database/src/models/task.ts
@@ -28,13 +28,12 @@ import type { AnyPgColumn } from 'drizzle-orm/pg-core';
import { merge } from '@/utils/merge';
import { documents } from '../schemas/file';
-import { goals } from '../schemas/goal';
import type { NewTaskComment, TaskCommentItem } from '../schemas/task';
import { taskComments, taskDependencies, taskDocuments, tasks, taskTopics } from '../schemas/task';
import { topics } from '../schemas/topic';
import { acceptances } from '../schemas/verify';
import { works } from '../schemas/work';
-import type { LobeChatDatabase, Transaction } from '../type';
+import type { LobeChatDatabase } from '../type';
import { buildWorkspaceWhere } from '../utils/workspace';
export const isTaskIdentifierUniqueViolation = (error: unknown): boolean => {
@@ -103,20 +102,9 @@ const RUNNABLE_AUTOMATION = and(
),
)!;
-/**
- * A goal task is one carrying a `goals` row as its execution subject. Ownership
- * is not re-checked inside the EXISTS — the outer query already scopes `tasks`,
- * and a goal always belongs to its carrier's owner.
- */
-const HAS_GOAL = sql`EXISTS (
- SELECT 1 FROM ${goals}
- WHERE ${goals.subjectType} = 'task' AND ${goals.subjectId} = ${tasks.id}
-)`;
-
interface TaskListFilterOptions {
assigneeAgentId?: string;
automated?: boolean;
- hasGoal?: boolean;
parentTaskId?: string | null;
projectId?: string;
visibility?: 'private' | 'public';
@@ -206,7 +194,6 @@ export class TaskModel {
private buildListConditions = ({
assigneeAgentId,
automated,
- hasGoal,
parentTaskId,
projectId,
visibility,
@@ -218,8 +205,6 @@ export class TaskModel {
// `IS NOT TRUE`, not `NOT (…)`: nullable automation fields make the
// runnable expression NULL for manual tasks, and WHERE would drop them.
if (automated === false) conditions.push(sql`${RUNNABLE_AUTOMATION} IS NOT TRUE`);
- if (hasGoal === true) conditions.push(HAS_GOAL);
- if (hasGoal === false) conditions.push(sql`NOT ${HAS_GOAL}`);
if (projectId) conditions.push(eq(tasks.projectId, projectId));
if (visibility) conditions.push(eq(tasks.visibility, visibility));
@@ -360,39 +345,12 @@ export class TaskModel {
* to render as "resource deleted" from its version snapshot. See.
*/
async delete(id: string): Promise<boolean> {
- // The goal carried by this task has no FK on the polymorphic subject link,
- // so its row must be swept explicitly — in the same transaction, or a
- // failure between the two statements would orphan it.
- return this.db.transaction(async (tx) => {
- const deleted = await tx
- .delete(tasks)
- .where(and(eq(tasks.id, id), this.ownership()))
- .returning({ id: tasks.id });
-
- if (deleted.length > 0) await this.deleteGoalsOfTasks([id], tx);
+ const deleted = await this.db
+ .delete(tasks)
+ .where(and(eq(tasks.id, id), this.ownership()))
+ .returning({ id: tasks.id });
- return deleted.length > 0;
- });
- }
-
- /** Sweep the goals bound to the given (already deleted) tasks. */
- private async deleteGoalsOfTasks(
- taskIds: string[],
- tx: LobeChatDatabase | Transaction = this.db,
- ) {
- if (taskIds.length === 0) return;
- await tx
- .delete(goals)
- .where(
- and(
- eq(goals.subjectType, 'task'),
- inArray(goals.subjectId, taskIds),
- buildWorkspaceWhere(
- { userId: this.userId, workspaceId: this.workspaceId },
- { userId: goals.userId, workspaceId: goals.workspaceId },
- ),
- ),
- );
+ return deleted.length > 0;
}
/**
@@ -560,16 +518,8 @@ export class TaskModel {
? and(this.ownership(), eq(tasks.createdByUserId, this.userId))
: this.ownership();
- // One transaction so the FK-less goals rows can never outlive their
- // swept carriers (see deleteGoalsOfTasks).
- return this.db.transaction(async (tx) => {
- const result = await tx.delete(tasks).where(where).returning({ id: tasks.id });
- await this.deleteGoalsOfTasks(
- result.map(({ id }) => id),
- tx,
- );
- return result.length;
- });
+ const result = await this.db.delete(tasks).where(where).returning({ id: tasks.id });
+ return result.length;
}
/** Delete a task and every descendant in one transaction. */
@@ -590,7 +540,6 @@ export class TaskModel {
),
),
);
- await this.deleteGoalsOfTasks(taskIds, tx);
const result = await tx
.delete(tasks)
.where(and(inArray(tasks.id, taskIds), this.ownership()))
@@ -860,10 +809,7 @@ export class TaskModel {
const taskIds = Array.from(
new Set(results.flatMap((group) => group.tasks.map(({ id }) => id))),
);
- const [runStats, goalByTaskId] = await Promise.all([
- this.runStatsByTaskIds(taskIds),
- this.goalsByTaskIds(taskIds),
- ]);
+ const runStats = await this.runStatsByTaskIds(taskIds);
const runStatsByTaskId = new Map(
runStats.map((stats) => [
stats.root_id,
@@ -878,25 +824,12 @@ export class TaskModel {
...group,
tasks: group.tasks.map((task) => ({
...task,
- goal: goalByTaskId.get(task.id) ?? null,
totalRunCost: runStatsByTaskId.get(task.id)?.totalRunCost ?? 0,
totalRunDuration: runStatsByTaskId.get(task.id)?.totalRunDuration ?? 0,
})),
}));
}
- /** The goal entities carried by the given tasks, keyed by task id. */
- private async goalsByTaskIds(taskIds: string[]) {
- if (taskIds.length === 0) return new Map<string, typeof goals.$inferSelect>();
-
- const rows = await this.db
- .select()
- .from(goals)
- .where(and(eq(goals.subjectType, 'task'), inArray(goals.subjectId, taskIds)));
-
- return new Map(rows.map((row) => [row.subjectId!, row]));
- }
-
private async runStatsByTaskIds(taskIds: string[]): Promise<TaskRunStats[]> {
if (taskIds.length === 0) return [];
diff --git a/packages/locales/src/default/chat.ts b/packages/locales/src/default/chat.ts
index 030c444c2ab..4765106c1b3 100644
--- a/packages/locales/src/default/chat.ts
+++ b/packages/locales/src/default/chat.ts
@@ -1724,6 +1724,10 @@ export default {
'goalList.acceptanceProgress': '{{passed}}/{{total}} passed',
'goalList.agentRuns': '{{count}} runs',
'goalList.empty': 'No goals yet',
+ 'goalList.workProgress': '{{done}}/{{total}} tasks done',
+ 'goalList.findings': '{{count}} findings',
+ 'goalList.needsYou': '{{count}} need you',
+ 'goalList.noWork': 'No tasks yet',
'goalList.loadError': 'Could not load goals',
'goalList.loadErrorDescription':
'The service is temporarily unavailable. Your goals are not lost.',
@@ -1741,6 +1745,7 @@ export default {
'goalWork.checks': '{{passed}}/{{total}} checks passed',
'goalWork.round': 'Round {{current}}',
'goalWork.roundWithBudget': 'Round {{current}}/{{total}}',
+ 'goalWork.workDone': '{{passed}}/{{total}} tasks done',
'goalWork.status.achieved': 'Achieved',
'goalWork.status.canceled': 'Canceled',
'goalWork.status.error': 'Needs attention',
@@ -1786,6 +1791,94 @@ export default {
'goalDetail.taskStatus': 'Execution status',
'goalDetail.unnamedRun': 'Untitled run',
'goalDetail.viewPlan': 'View execution plan',
+ 'goalProcess.frontier.title': 'Current tasks',
+ 'goalProcess.frontier.add': 'Add task',
+ 'goalProcess.frontier.needsYou': '{{count}} need you',
+ 'goalProcess.frontier.advanceable': '{{count}} can advance',
+ 'goalProcess.frontier.blocked': '{{count}} more waiting on dependencies',
+ 'goalProcess.frontier.dependsOn': 'Depends on {{refs}}',
+ 'goalProcess.frontier.emptyTitle': 'Nothing to advance right now',
+ 'goalProcess.frontier.emptyDescription':
+ 'Every task is either waiting on a dependency or already finished.',
+ 'goalProcess.frontier.achievedTitle': 'Nothing left to advance — this goal is achieved',
+ 'goalProcess.frontier.achievedDescription': 'The findings are in the map below.',
+ 'goalProcess.tag.needsDecision': 'Needs your decision',
+ 'goalProcess.tag.lost': 'Lost',
+ 'goalProcess.tag.done': 'Done',
+ 'goalProcess.tag.retired': 'Retired',
+ 'goalProcess.gate.why': 'Why it stopped',
+ 'goalProcess.gate.options': 'What each choice means',
+ 'goalProcess.gate.recommended': 'recommended',
+ 'goalProcess.gate.noteLabel': 'Extra guidance (optional — goes into the next attempt)',
+ 'goalProcess.gate.notePlaceholder':
+ 'e.g. reuse the existing checkpoint instead of retraining from scratch',
+ 'goalProcess.gate.option.retry': 'Retry work',
+ 'goalProcess.gate.option.retire': 'Retire work',
+ 'goalProcess.gate.option.fail': 'Fail goal',
+ 'goalProcess.attempts.title': 'Previous attempts',
+ 'goalProcess.attempts.nth': 'Attempt {{index}}',
+ 'goalProcess.attempts.passed': 'Passed',
+ 'goalProcess.advance.running': 'Advancing…',
+ 'goalProcess.attempts.failed': 'Did not pass',
+ 'goalProcess.attempts.retired': 'Retired',
+ 'goalProcess.attempts.running': 'Running',
+ 'goalProcess.stale.description':
+ 'No heartbeat for {{duration}}. The next advance marks this attempt lost and starts a fresh one — it does not count as a failure.',
+ 'goalProcess.running.elapsed': 'Running {{duration}}',
+ 'goalProcess.graph.title': 'Exploration map',
+ 'goalProcess.graph.view.stage': 'Current stage',
+ 'goalProcess.graph.view.all': 'Full map',
+ 'goalProcess.graph.fullscreen': 'Fullscreen',
+ 'goalProcess.graph.exitFullscreen': 'Exit fullscreen',
+ 'goalProcess.edge.dependsOn': 'depends on',
+ 'goalProcess.edge.investigates': 'investigates',
+ 'goalProcess.edge.produces': 'produces',
+ 'goalProcess.edge.supports': 'supports',
+ 'goalProcess.edge.contradicts': 'contradicts',
+ 'goalProcess.edge.leadsTo': 'leads to',
+ 'goalProcess.kind.problem': 'Question',
+ 'goalProcess.kind.work': 'Task',
+ 'goalProcess.kind.finding': 'Finding',
+ 'goalProcess.kind.decision': 'Decision',
+ 'goalProcess.node.running': 'Running',
+ 'goalProcess.node.done': 'Done',
+ 'goalProcess.node.waiting': 'Waiting',
+ 'goalProcess.node.unanswered': 'Unanswered',
+ 'goalProcess.metrics.status': 'Status',
+ 'goalProcess.metrics.tasks': 'Tasks',
+ 'goalProcess.metrics.findings': 'Findings',
+ 'goalProcess.requirement': 'What counts as done',
+ 'goalProcess.node.answered': 'Answered by a finding',
+ 'goalProcess.node.unassigned': 'Not dispatched',
+ 'goalProcess.node.decidedByYou': 'You decided',
+ 'goalProcess.node.decidedByAgent': 'Agent decided',
+ 'goalProcess.node.attemptsTooltip': '{{count}} attempts so far',
+ 'goalProcess.node.verifier': 'verifier',
+ 'goalProcess.node.verifierTooltip':
+ 'This task has its own acceptance contract — a verifier judges the delivery.',
+ 'goalProcess.node.artifactsTooltip':
+ '{{count}} work versions registered. Opening them needs a server read that does not exist yet.',
+ 'goalProcess.node.humanTouched': 'You took part in this task',
+ 'goalProcess.findings.title': 'Findings',
+ 'goalProcess.findings.empty': 'No findings yet.',
+ 'goalProcess.findings.answers': 'Answers “{{title}}”',
+ 'goalProcess.findings.from': 'From “{{title}}”',
+ 'goalProcess.activity.title': 'Activity',
+ 'goalProcess.activity.empty': 'No activity yet',
+ 'goalProcess.activity.finding': 'Recorded finding: {{title}}',
+ 'goalProcess.summary.done': 'Done · {{count}} attempts',
+ 'goalProcess.summary.retired': 'Retired · {{count}} attempts',
+ 'goalProcess.summary.waiting': '{{count}} attempts did not pass — needs your decision',
+ 'goalProcess.summary.running': 'Running · attempt {{index}}',
+ 'goalProcess.summary.notStarted': 'Not started yet',
+ 'goalProcess.summary.gateOpen': 'Waiting for your decision',
+ 'goalProcess.summary.gateResolved': 'Decided: {{option}}',
+ 'goalProcess.advance.label': 'Advance',
+ 'goalProcess.advance.tooltip':
+ 'The goal already advances on its own as its work settles. Press this to run the coordinator now — useful when you want to see where it stops without waiting.',
+ 'goalProcess.pause': 'Pause',
+ 'goalProcess.resume': 'Resume',
+ 'goalProcess.paused': 'Paused — no new work will start',
'goalPage.allGoals': 'All goals',
'goalPage.activeGoals': 'Open goals',
'goalPage.description':
diff --git a/packages/types/src/goal.ts b/packages/types/src/goal.ts
index 2f14766a294..074e1b965e1 100644
--- a/packages/types/src/goal.ts
+++ b/packages/types/src/goal.ts
@@ -14,14 +14,14 @@ export type GoalStatus =
'planning' | 'running' | 'verifying' | 'review' | 'paused' | 'achieved' | 'failed' | 'canceled';
/**
- * The execution carrier a goal is optionally bound to:
- * - `task` — the `/goal` flow: the goal runs inside a dedicated task.
- * - `topic` — a goal declared directly in a conversation.
- * - `standalone` — a pure goal declaration with no carrier attached.
+ * The execution carrier a goal is optionally bound to. Goals are standalone
+ * today: the Goal Graph owns execution and dispatches its own Work Tasks, so
+ * nothing binds a goal to a single carrier row. The column stays because
+ * existing rows still carry the earlier `task` value.
*/
export type GoalSubjectType = 'task' | 'topic' | 'standalone';
-/** Automatic recovery policy shared by task-carried goals and Goal Graph work. */
+/** Automatic recovery policy for Goal Graph Work. */
export interface GoalRecoveryPolicy {
/** Maximum execution attempts for one Work before escalating to a decision gate. */
maxAttemptsPerWork?: number;
@@ -63,19 +63,6 @@ export interface GoalItem {
workspaceId: string | null;
}
-/**
- * Goal creation payload accepted by `TaskService.createTask` / the `task.create`
- * procedure: binds a new goals row to the created task in the same flow.
- * `maxRounds: null` is the user's explicit "no cap"; `undefined` means they
- * never chose, and the service falls back to the documented default.
- */
-export interface CreateTaskGoalInput {
- maxRounds?: number | null;
- maxTotalCost?: number | null;
- requirement?: string | null;
- title?: string;
-}
-
// ============================================
// Goal Graph — durable long-horizon reasoning structure
// ============================================
diff --git a/packages/types/src/task/index.ts b/packages/types/src/task/index.ts
index a37ee3463fc..4e920e974b7 100644
--- a/packages/types/src/task/index.ts
+++ b/packages/types/src/task/index.ts
@@ -1,5 +1,4 @@
import type { BriefArtifacts } from '../brief';
-import type { GoalItem } from '../goal';
import type { ChatFileItem } from '../message/ui/chat';
// ── Task type aliases ──
@@ -24,7 +23,7 @@ export type TaskAutomationMode = 'heartbeat' | 'schedule';
* scheduling state, nor count against the maxExecutions quota.
* - `schedule` — a cron `schedule` tick fired the run.
* - `heartbeat` — a heartbeat interval tick fired the run.
- * - `goal` — the goal outer loop spawned this round after a failed verify.
+ * - `goal` — the Goal coordinator started this Work attempt.
* Like `manual`, it never counts against automation quotas.
*/
export type TaskRunTrigger = 'manual' | 'schedule' | 'heartbeat' | 'goal';
@@ -246,12 +245,6 @@ export interface TaskItem {
description: string | null;
editorData: unknown;
error: string | null;
- /**
- * The goal entity bound to this task (`goals.subjectType='task'`), attached
- * by list/detail reads. Presence marks a goal-driven task; the goal owns its
- * budget, requirement and lifecycle status.
- */
- goal?: GoalItem | null;
heartbeatInterval: number | null;
heartbeatTimeout: number | null;
id: string;
@@ -449,7 +442,7 @@ export interface TaskDetailActivity {
time?: string;
title?: string;
topicId?: string | null;
- /** Topic-only: what opened this round — `goal` marks a loop-spawned rerun. */
+ /** Topic-only: what opened this round — `goal` marks a coordinator-started attempt. */
trigger?: TaskRunTrigger | null;
type: TaskActivityType;
userId?: string | null;
@@ -490,8 +483,6 @@ export interface TaskDetailData {
error?: string | null;
/** Files attached to the task instruction (persistent context for every run). */
files?: ChatFileItem[];
- /** The goal entity carried by this task (`goals` row); null when not a goal task. */
- goal?: GoalItem | null;
// heartbeat.interval: periodic execution interval | heartbeat.timeout+lastAt: watchdog monitoring (detects stuck tasks)
heartbeat?: {
interval?: number | null;
diff --git a/scripts/serverLauncher/startServer.js b/scripts/serverLauncher/startServer.js
index dd80221978a..e1019661a14 100644
--- a/scripts/serverLauncher/startServer.js
+++ b/scripts/serverLauncher/startServer.js
@@ -163,7 +163,25 @@ const startGateway = async () => {
console.error('❌ Gateway: Failed to start after retries.');
};
-// Function to create QStash schedule for dispatching workflow tasks every 10 minutes
+// Recurring QStash schedules this deployment needs.
+//
+// The goal sweep is not an optimization: a Goal Graph advances on events, so a
+// dropped delivery or a process that dies after dispatch would strand the goal
+// forever with nothing to notice. The sweep is what makes that recoverable.
+const QSTASH_SCHEDULES = [
+ {
+ cron: '*/10 * * * *',
+ id: 'lobe-task-schedule-dispatch',
+ path: '/api/workflows/task/schedule-dispatch',
+ },
+ {
+ cron: '*/5 * * * *',
+ id: 'lobe-goal-sweep',
+ path: '/api/workflows/goal/sweep',
+ },
+];
+
+// Function to create the recurring QStash schedules the server relies on
const createQstashSchedule = async () => {
const QSTASH_URL = process.env.QSTASH_URL || 'https://qstash-eu-central-1.upstash.io';
@@ -179,28 +197,30 @@ const createQstashSchedule = async () => {
return;
}
- const url = `${QSTASH_URL}/v2/schedules/${APP_URL}/api/workflows/task/schedule-dispatch`;
+ for (const schedule of QSTASH_SCHEDULES) {
+ const url = `${QSTASH_URL}/v2/schedules/${APP_URL}${schedule.path}`;
- try {
- const res = await fetch(url, {
- method: 'POST',
- headers: {
- 'Authorization': `Bearer ${QSTASH_TOKEN}`,
- 'Content-Type': 'application/json',
- 'Upstash-Method': 'POST',
- 'Upstash-Cron': '*/10 * * * *',
- 'Upstash-Schedule-Id': 'lobe-task-schedule-dispatch',
- },
- body: JSON.stringify({}),
- });
-
- if (res.ok) {
- console.log('✅ QStash: Schedule created successfully.');
- } else {
- console.error(`❌ QStash: Failed to create schedule. Status ${res.status}`);
+ try {
+ const res = await fetch(url, {
+ method: 'POST',
+ headers: {
+ 'Authorization': `Bearer ${QSTASH_TOKEN}`,
+ 'Content-Type': 'application/json',
+ 'Upstash-Method': 'POST',
+ 'Upstash-Cron': schedule.cron,
+ 'Upstash-Schedule-Id': schedule.id,
+ },
+ body: JSON.stringify({}),
+ });
+
+ if (res.ok) {
+ console.log(`✅ QStash: Schedule ${schedule.id} created successfully.`);
+ } else {
+ console.error(`❌ QStash: Failed to create schedule ${schedule.id}. Status ${res.status}`);
+ }
+ } catch (err) {
+ console.error(`❌ QStash: Error creating schedule ${schedule.id}:`, err);
}
- } catch (err) {
- console.error('❌ QStash: Error creating schedule:', err);
}
};
diff --git a/src/features/AgentGoals/AgentGoalsPage.tsx b/src/features/AgentGoals/AgentGoalsPage.tsx
index b01c9c30852..13dbe19a1b7 100644
--- a/src/features/AgentGoals/AgentGoalsPage.tsx
+++ b/src/features/AgentGoals/AgentGoalsPage.tsx
@@ -1,5 +1,6 @@
'use client';
+import type { GoalStatus } from '@lobechat/const/goal';
import { Block, Empty, Flexbox } from '@lobehub/ui';
import { ActionIcon, Button, Segmented, Text } from '@lobehub/ui/base-ui';
import { createStaticStyles, cssVar } from 'antd-style';
@@ -18,7 +19,6 @@ import { GoalCardItem } from './GoalCardItem';
import GoalEmptyState from './GoalEmptyState';
import type { GoalExampleSeed } from './goalExamples';
import { GoalListItem } from './GoalListItem';
-import { shouldShowGoal } from './goalViewModel';
const styles = createStaticStyles(({ css }) => ({
countBadge: css`
@@ -62,6 +62,9 @@ const styles = createStaticStyles(({ css }) => ({
`,
}));
+/** Goals whose loop has stopped for good — hidden by the default "open" filter. */
+const TERMINAL_GOAL_STATUSES = new Set<GoalStatus>(['achieved', 'failed', 'canceled']);
+
interface AgentGoalsPageProps {
agentId?: string;
projectId?: string;
@@ -82,14 +85,14 @@ const AgentGoalsPage = memo<AgentGoalsPageProps>(({ agentId, projectId }) => {
const loadMoreGoals = useGoalStore((s) => s.loadMoreGoals);
const { error, isLoading } = useFetchGoals(agentId, projectId);
const summary = useMemo(() => {
- const delivered = goals.filter((goal) => goal.goal?.status === 'review').length;
+ const delivered = goals.filter(({ 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) => shouldShowGoal(goal.goal?.status ?? 'planning', 'active'));
+ return goals.filter(({ goal }) => !TERMINAL_GOAL_STATUSES.has(goal.status));
}, [filter, goals]);
const visibleGoalCount = filteredGoals.length;
const GoalItem = viewMode === 'list' ? GoalListItem : GoalCardItem;
@@ -237,13 +240,8 @@ const AgentGoalsPage = memo<AgentGoalsPageProps>(({ agentId, projectId }) => {
) : (
filteredGoals
.slice(0, visibleLimit)
- .map((goal) => (
- <GoalItem
- hideAchieved={filter === 'active'}
- key={goal.id}
- projectId={projectId}
- task={goal}
- />
+ .map((item) => (
+ <GoalItem goal={item} key={item.goal.id} projectId={projectId} />
))
)}
</div>
diff --git a/src/features/AgentGoals/CreateGoalModal/CreateGoalContent.tsx b/src/features/AgentGoals/CreateGoalModal/CreateGoalContent.tsx
index 03e57414065..a084335c2c3 100644
--- a/src/features/AgentGoals/CreateGoalModal/CreateGoalContent.tsx
+++ b/src/features/AgentGoals/CreateGoalModal/CreateGoalContent.tsx
@@ -1,5 +1,6 @@
'use client';
+import { buildGoalRequirement, resolveGoalAttemptBudget } from '@lobechat/builtin-tool-goal';
import type { CreateGoalParams, GoalCriterionDraft } from '@lobechat/builtin-tool-task';
import { DEFAULT_GOAL_MAX_ROUNDS } from '@lobechat/const/verify';
import { useEditor } from '@lobehub/editor/react';
@@ -20,7 +21,6 @@ import {
import { type KeyboardEvent, memo, useCallback, useEffect, useMemo, useRef, useState } from 'react';
import { useTranslation } from 'react-i18next';
-import { useActiveWorkspaceId } from '@/business/client/hooks/useActiveWorkspaceId';
import NeuralNetworkLoading from '@/components/NeuralNetworkLoading';
import {
CriterionList,
@@ -28,17 +28,13 @@ import {
CriterionRow,
openCriterionEditModal,
} from '@/features/Acceptance';
-import TaskVisibilityChipLabel from '@/features/AgentTasks/features/TaskVisibilityChipLabel';
-import TaskVisibilityTag from '@/features/AgentTasks/features/TaskVisibilityTag';
-import { useAgentVisibility } from '@/features/AgentTasks/shared/useAgentVisibility';
import { EditorCanvas } from '@/features/EditorCanvas';
import { pickAndInsertAttachments } from '@/features/EditorCanvas/editorAttachments';
import { usePermission } from '@/hooks/usePermission';
-import { verifyService } from '@/services/verify';
-import { useTaskStore } from '@/store/task';
+import { goalService } from '@/services/goal';
import { shinyTextStyles } from '@/styles';
-import { buildGoalTaskConfig } from './goalConfig';
+import { buildGoalCreateInput } from './goalConfig';
import { createFallbackGoalCriterion, generateGoalCriteria } from './goalCriteria';
import { deriveGoalTitle } from './goalTitle';
@@ -277,7 +273,7 @@ export interface CreateGoalContentProps {
initialRequirement?: string;
initialRoundBudget?: number;
initialTitle?: string;
- onCreated?: (goal: { agentId?: string; identifier: string }) => void;
+ onCreated?: (goal: { agentId?: string; goalId: string }) => void;
projectId?: string;
}
@@ -296,9 +292,7 @@ const CreateGoalContent = memo<CreateGoalContentProps>((props) => {
const { close } = useModalContext();
const { allowed: canCreate, reason } = usePermission('create_content');
- const createTask = useTaskStore((s) => s.createTask);
- const isCreating = useTaskStore((s) => s.isCreatingTask);
- const activeWorkspaceId = useActiveWorkspaceId();
+ const [isCreating, setIsCreating] = useState(false);
const [step, setStep] = useState<'describe' | 'preparing' | 'review'>('describe');
const [plan, setPlan] = useState<CreateGoalParams>({
@@ -308,17 +302,8 @@ const CreateGoalContent = memo<CreateGoalContentProps>((props) => {
maxTotalCost: null,
name: initialTitle ?? '',
});
- // Default to private in workspace mode so sharing is opt-in; personal mode
- // ignores the field and hides the chip.
- const [visibility, setVisibility] = useState<'private' | 'public'>('private');
const [remainingSeconds, setRemainingSeconds] = useState(GENERATION_ESTIMATE_SECONDS);
- // A private agent can only run a private task, goals included.
- const isPrivateAgent = useAgentVisibility(agentId) === 'private';
- useEffect(() => {
- if (isPrivateAgent && visibility === 'public') setVisibility('private');
- }, [isPrivateAgent, visibility]);
-
const editor = useEditor();
const instructionRef = useRef(plan.instruction);
const requirement = useMemo(() => criterionRequirement(plan.criteria), [plan.criteria]);
@@ -436,59 +421,48 @@ const CreateGoalContent = memo<CreateGoalContentProps>((props) => {
if (!canCreate) return;
const instruction =
instructionRef.current.trim() || plan.instruction.trim() || plan.name.trim();
- const editorData = instructionRef.current.trim()
- ? (editor?.getDocument?.('json') as unknown)
- : undefined;
const reviewedCriteria = plan.criteria.filter((criterion) => criterion.title.trim());
if (!instruction || reviewedCriteria.length === 0) return;
- let verifyCriteriaIds: string[] = [];
+ const title = plan.name.trim() || instruction;
+ const budget = buildGoalCreateInput({
+ costBudget: plan.maxTotalCost,
+ instruction,
+ requirement,
+ });
+
+ setIsCreating(true);
try {
- verifyCriteriaIds = await verifyService.createCriteria(reviewedCriteria);
- const { config, goal } = buildGoalTaskConfig({
- costBudget: plan.maxTotalCost,
- instruction,
- requirement,
- roundBudget: plan.maxIterations,
- verifyCriteriaIds,
- });
- const result = await createTask({
- assigneeAgentId: agentId,
- config,
- editorData,
- goal,
- instruction,
- name: plan.name.trim() || undefined,
+ const graph = await goalService.create({
+ agentId,
+ config: {
+ recovery: { maxAttemptsPerWork: resolveGoalAttemptBudget(plan.maxIterations) },
+ },
+ // `maxIterations` is the per-Work attempt budget above; it is not the
+ // graph-wide round cap, which counts runs across every Work and would
+ // strand the fourth task of a goal whose limit is three attempts.
+ maxTotalCost: budget.maxTotalCost ?? undefined,
projectId,
- visibility: activeWorkspaceId ? visibility : undefined,
+ requirement: buildGoalRequirement(title, reviewedCriteria, budget.requirement),
+ title,
+ work: [{ description: instruction, title }],
});
-
- if (!result) throw new Error('The goal was not created.');
+ // `goal.create` already queued an advance; this runs the same driver so
+ // the goal is visibly moving by the time the modal closes even where the
+ // queue is unavailable. It must be `advance`, not a single tick: whichever
+ // driver claims the Work has to carry it past binding the task into
+ // actually starting it, and the loser stops at `waiting_external`.
+ await goalService.advance(graph.goal.id);
close();
- onCreated?.({
- agentId: result.assigneeAgentId ?? undefined,
- identifier: result.identifier,
- });
+ onCreated?.({ agentId: graph.goal.agentId ?? undefined, goalId: graph.goal.id });
} catch (error) {
console.error('[CreateGoalContent] create failed:', error);
- await Promise.allSettled(verifyCriteriaIds.map((id) => verifyService.deleteCriterion(id)));
toast.error(t('createGoal.createFailed'));
+ } finally {
+ setIsCreating(false);
}
- }, [
- activeWorkspaceId,
- agentId,
- canCreate,
- close,
- createTask,
- editor,
- onCreated,
- plan,
- projectId,
- requirement,
- t,
- visibility,
- ]);
+ }, [agentId, canCreate, close, onCreated, plan, projectId, requirement, t]);
const handlePrimaryAction =
step === 'describe' ? handleNext : step === 'review' ? handleSubmit : undefined;
@@ -737,17 +711,6 @@ const CreateGoalContent = memo<CreateGoalContentProps>((props) => {
<Flexbox horizontal align={'center'} className={styles.footer} justify={'space-between'}>
<Flexbox horizontal align={'center'} gap={8} wrap={'wrap'}>
- {activeWorkspaceId && (
- <TaskVisibilityTag
- visibility={visibility}
- lockedReason={
- isPrivateAgent ? t('createTask.visibility.privateAgentLocked') : undefined
- }
- onChange={setVisibility}
- >
- <TaskVisibilityChipLabel visibility={visibility} />
- </TaskVisibilityTag>
- )}
{step === 'review' && (
<ActionIcon
icon={Paperclip}
diff --git a/src/features/AgentGoals/CreateGoalModal/goalConfig.test.ts b/src/features/AgentGoals/CreateGoalModal/goalConfig.test.ts
index ead9396ef49..7bf78c119dc 100644
--- a/src/features/AgentGoals/CreateGoalModal/goalConfig.test.ts
+++ b/src/features/AgentGoals/CreateGoalModal/goalConfig.test.ts
@@ -1,7 +1,6 @@
-import { DEFAULT_GOAL_MAX_ROUNDS, DEFAULT_MAX_REPAIR_ROUNDS } from '@lobechat/const/verify';
import { describe, expect, it } from 'vitest';
-import { buildGoalTaskConfig, deriveInitialGoalCriterionTitle } from './goalConfig';
+import { buildGoalCreateInput, deriveInitialGoalCriterionTitle } from './goalConfig';
describe('deriveInitialGoalCriterionTitle', () => {
it('uses the instruction when a free-form goal has no dedicated requirement', () => {
@@ -17,80 +16,31 @@ describe('deriveInitialGoalCriterionTitle', () => {
});
});
-describe('buildGoalTaskConfig', () => {
- it('keeps the round budget and the repair budget independent', () => {
- // Regression: the create-goal path used to reuse the task modal and write the
- // same number into both caps, so a 10-round goal also bought 10 auto-repair
- // re-runs per round (up to 100 agent runs).
- const payload = buildGoalTaskConfig({ instruction: 'ship it', roundBudget: 10 });
-
- expect(payload.goal.maxRounds).toBe(10);
- expect(payload.config.verify.maxIterations).toBe(DEFAULT_MAX_REPAIR_ROUNDS);
- });
-
- it('falls back to the documented round default when the budget is untouched', () => {
- expect(buildGoalTaskConfig({ instruction: 'ship it' }).goal.maxRounds).toBe(
- DEFAULT_GOAL_MAX_ROUNDS,
- );
- });
-
- it('preserves an explicit opt-out of the round cap', () => {
- expect(
- buildGoalTaskConfig({ instruction: 'ship it', roundBudget: null }).goal.maxRounds,
- ).toBeNull();
+describe('buildGoalCreateInput', () => {
+ it('never sets a graph-wide round cap', () => {
+ // The modal's only iteration field means "attempts on one Work". `maxRounds`
+ // counts runs across every Work in the graph, so deriving it from that field
+ // stranded the fourth task of a goal whose limit was three attempts.
+ expect(buildGoalCreateInput({ instruction: 'ship it' })).not.toHaveProperty('maxRounds');
});
- it('clamps a round budget to the supported range', () => {
- expect(buildGoalTaskConfig({ instruction: 'x', roundBudget: 1 }).goal.maxRounds).toBe(2);
- expect(buildGoalTaskConfig({ instruction: 'x', roundBudget: 99 }).goal.maxRounds).toBe(10);
- });
-
- it('writes a positive cost budget and leaves it independent of the round budget', () => {
- const payload = buildGoalTaskConfig({ instruction: 'x', roundBudget: 5, costBudget: 2.5 });
-
- expect(payload.goal.maxTotalCost).toBe(2.5);
- expect(payload.goal.maxRounds).toBe(5);
+ it('writes a positive cost budget', () => {
+ expect(buildGoalCreateInput({ costBudget: 2.5, instruction: 'x' }).maxTotalCost).toBe(2.5);
});
it('maps a blank or non-positive cost budget to uncapped (null)', () => {
- // The goal loop reads `null` as "no cap"; an empty or 0 input must not become a
- // 0-dollar budget that would stop the goal before its first run.
- expect(buildGoalTaskConfig({ instruction: 'x' }).goal.maxTotalCost).toBeNull();
- expect(buildGoalTaskConfig({ instruction: 'x', costBudget: 0 }).goal.maxTotalCost).toBeNull();
- expect(
- buildGoalTaskConfig({ instruction: 'x', costBudget: null }).goal.maxTotalCost,
- ).toBeNull();
+ // The coordinator reads `null` as "no cap"; an empty or 0 input must not
+ // become a 0-dollar budget that would stop the goal before its first run.
+ expect(buildGoalCreateInput({ instruction: 'x' }).maxTotalCost).toBeNull();
+ expect(buildGoalCreateInput({ costBudget: 0, instruction: 'x' }).maxTotalCost).toBeNull();
+ expect(buildGoalCreateInput({ costBudget: -3, instruction: 'x' }).maxTotalCost).toBeNull();
});
- it('uses the acceptance requirement when given', () => {
- const payload = buildGoalTaskConfig({
- instruction: 'clear the P0 backlog',
- requirement: 'every P0 has a linked PR with green CI',
- });
-
- expect(payload.config.verify.requirement).toBe('every P0 has a linked PR with green CI');
- expect(payload.goal.requirement).toBe('every P0 has a linked PR with green CI');
- expect(payload.config.verify.enabled).toBe(true);
- });
-
- it('associates user-reviewed acceptance criteria with the goal', () => {
- const payload = buildGoalTaskConfig({
- instruction: 'clear the P0 backlog',
- verifyCriteriaIds: ['criterion-1', 'criterion-2'],
- });
-
- expect(payload.config.verify.verifyCriteriaIds).toEqual(['criterion-1', 'criterion-2']);
- });
-
- it('falls back to the instruction so the goal stays judgeable', () => {
- // An empty requirement would leave `planInstantiation` with no source for the
- // holistic check, i.e. a goal that can never be accepted.
- const payload = buildGoalTaskConfig({
- instruction: 'clear the P0 backlog',
- requirement: ' ',
- });
-
- expect(payload.config.verify.requirement).toBe('clear the P0 backlog');
- expect(payload.goal.requirement).toBe('clear the P0 backlog');
+ it('falls back to the instruction when no requirement was drafted', () => {
+ expect(buildGoalCreateInput({ instruction: ' ship it ' }).requirement).toBe('ship it');
+ expect(
+ buildGoalCreateInput({ instruction: 'ship it', requirement: ' all links resolve ' })
+ .requirement,
+ ).toBe('all links resolve');
});
});
diff --git a/src/features/AgentGoals/CreateGoalModal/goalConfig.ts b/src/features/AgentGoals/CreateGoalModal/goalConfig.ts
index b599cc46d1f..260bac32c58 100644
--- a/src/features/AgentGoals/CreateGoalModal/goalConfig.ts
+++ b/src/features/AgentGoals/CreateGoalModal/goalConfig.ts
@@ -1,34 +1,18 @@
-import {
- DEFAULT_GOAL_MAX_ROUNDS,
- DEFAULT_MAX_REPAIR_ROUNDS,
- GOAL_MAX_ROUNDS_RANGE,
-} from '@lobechat/const/verify';
-import type { CreateTaskGoalInput, TaskVerifyConfig } from '@lobechat/types';
-
-/**
- * The goal-creation payload split along the storage boundary: `goal` becomes a
- * `goals` row bound to the created task, `config` stays a `tasks.config` merge
- * (`Record<string, unknown>`-shaped for `createTask`).
- */
-export type GoalTaskPayload = {
- config: { verify: TaskVerifyConfig } & Record<string, unknown>;
- goal: CreateTaskGoalInput;
-};
-
-export interface BuildGoalTaskConfigParams {
+export interface BuildGoalCreateInputParams {
/**
- * Total USD budget across all rounds and their verify runs. `null`/`undefined`
- * = uncapped (the user left it blank); a number is clamped to be non-negative.
+ * Total USD budget across all attempts. `null`/`undefined` = uncapped (the
+ * user left it blank); a number is clamped to be non-negative.
*/
costBudget?: number | null;
/** What the user typed as the goal itself; the acceptance fallback. */
instruction: string;
- /** "What counts as done" — the source the acceptance criteria are generated from. */
+ /** "What counts as done" — the source the acceptance criteria were generated from. */
requirement?: string;
- /** Outer-loop budget: how many rounds (task topics) the goal may spawn. */
- roundBudget?: number | null;
- /** User-reviewed acceptance criteria generated before the goal is created. */
- verifyCriteriaIds?: string[];
+}
+
+export interface GoalCreateInput {
+ maxTotalCost: number | null;
+ requirement: string;
}
/**
@@ -41,53 +25,17 @@ export const deriveInitialGoalCriterionTitle = (
): string => requirement?.trim() || instruction.trim();
/**
- * Build the goal-task creation payload: the goal entity (budget + requirement,
- * persisted as a `goals` row) and the verify gate config (`tasks.config.verify`).
- *
- * The two round-ish numbers look alike and mean different things, which is
- * exactly how they got conflated before this existed: the create-goal modal
- * reused the task modal and wrote the *same* number into both, so a goal
- * created with a 10-round budget also bought 10 auto-repair re-runs inside
- * every round — up to 100 agent runs for one goal.
- *
- * - `goal.maxRounds` — outer loop, rounds. User-facing ("轮次预算").
- * - `goal.maxTotalCost` — outer loop, total USD across all rounds. User-facing ("成本预算").
- * - `verify.maxIterations` — inner loop, repair re-runs within one round.
- * Not user-facing; pinned to the platform default.
+ * The budget half of the goal-creation payload. The criteria half is built by
+ * `buildGoalRequirement` in `@lobechat/builtin-tool-goal`, so the modal and the
+ * `/goal` tool write the same acceptance requirement.
*/
-export const buildGoalTaskConfig = ({
+export const buildGoalCreateInput = ({
costBudget,
instruction,
requirement,
- roundBudget,
- verifyCriteriaIds,
-}: BuildGoalTaskConfigParams): GoalTaskPayload => {
- const acceptance = requirement?.trim() || instruction.trim();
-
- return {
- config: {
- verify: {
- enabled: true,
- maxIterations: DEFAULT_MAX_REPAIR_ROUNDS,
- // Drives criteria generation on the first run (`planInstantiation`'s
- // holistic fallback), so an empty one would leave the goal unjudgeable.
- requirement: acceptance,
- verifyCriteriaIds,
- },
- },
- goal: {
- // `null` is the user's explicit "no cap" and must survive; `undefined`
- // means they never chose, which falls back to the documented default.
- maxRounds:
- roundBudget === null
- ? null
- : typeof roundBudget === 'number'
- ? Math.min(GOAL_MAX_ROUNDS_RANGE.max, Math.max(GOAL_MAX_ROUNDS_RANGE.min, roundBudget))
- : DEFAULT_GOAL_MAX_ROUNDS,
- // No cap unless the user set a positive number; the loop reads `null` as
- // uncapped, so an empty / non-positive input maps back to `null`.
- maxTotalCost: typeof costBudget === 'number' && costBudget > 0 ? costBudget : null,
- requirement: acceptance,
- },
- };
-};
+}: BuildGoalCreateInputParams): GoalCreateInput => ({
+ // No cap unless the user set a positive number; the coordinator reads `null`
+ // as uncapped, so an empty / non-positive input maps back to `null`.
+ maxTotalCost: typeof costBudget === 'number' && costBudget > 0 ? costBudget : null,
+ requirement: requirement?.trim() || instruction.trim(),
+});
diff --git a/src/features/AgentGoals/GoalAcceptance.tsx b/src/features/AgentGoals/GoalAcceptance.tsx
deleted file mode 100644
index 819a16c7259..00000000000
--- a/src/features/AgentGoals/GoalAcceptance.tsx
+++ /dev/null
@@ -1,40 +0,0 @@
-'use client';
-
-import type { ReactNode } from 'react';
-import { memo } from 'react';
-
-import type { AcceptanceBundle } from '@/services/verify';
-import { useVerifyStore, verifySelectors } from '@/store/verify';
-
-interface GoalAcceptanceRenderState {
- bundle?: AcceptanceBundle;
- error?: unknown;
- isLoading: boolean;
- retry: () => void;
-}
-
-interface GoalAcceptanceProps {
- children: (state: GoalAcceptanceRenderState) => ReactNode;
- taskId: string;
-}
-
-export const GoalAcceptance = memo<GoalAcceptanceProps>(({ children, taskId }) => {
- const useFetchAcceptanceBySubject = useVerifyStore((s) => s.useFetchAcceptanceBySubject);
- const useFetchAcceptanceBundle = useVerifyStore((s) => s.useFetchAcceptanceBundle);
- const acceptance = useVerifyStore(verifySelectors.acceptanceBySubject('task', taskId));
- const bundle = useVerifyStore(verifySelectors.acceptanceBundle(acceptance?.id));
- const acceptanceQuery = useFetchAcceptanceBySubject('task', taskId);
- const bundleQuery = useFetchAcceptanceBundle(acceptance?.id);
-
- return children({
- bundle,
- error: acceptanceQuery.error || bundleQuery.error,
- isLoading: acceptanceQuery.isLoading || (!!acceptance?.id && bundleQuery.isLoading),
- retry: () => {
- void acceptanceQuery.mutate();
- if (acceptance?.id) void bundleQuery.mutate();
- },
- });
-});
-
-GoalAcceptance.displayName = 'GoalAcceptance';
diff --git a/src/features/AgentGoals/GoalCardItem.tsx b/src/features/AgentGoals/GoalCardItem.tsx
index 7f69be0bc12..3c5e0455bf0 100644
--- a/src/features/AgentGoals/GoalCardItem.tsx
+++ b/src/features/AgentGoals/GoalCardItem.tsx
@@ -1,21 +1,17 @@
'use client';
import { Block, Flexbox, Icon } from '@lobehub/ui';
-import { ActionIcon, Text } from '@lobehub/ui/base-ui';
+import { Text } from '@lobehub/ui/base-ui';
import { createStaticStyles, cssVar } from 'antd-style';
-import { ArrowRightIcon, RefreshCwIcon } from 'lucide-react';
+import { ArrowRightIcon } from 'lucide-react';
import type { KeyboardEvent } from 'react';
import { memo } from 'react';
-import { useTranslation } from 'react-i18next';
import { useWorkspaceAwareNavigate } from '@/features/Workspace/useWorkspaceAwareNavigate';
import { useActiveRouteParams } from '@/hooks/useActiveRouteParams';
-import { GoalAcceptance } from './GoalAcceptance';
-import { getGoalPresentation } from './goalPresentation';
import { GoalProgress } from './GoalProgress';
import GoalStatusGlyph from './GoalStatusGlyph';
-import { getGoalDescription, shouldShowGoal } from './goalViewModel';
import type { GoalItemProps } from './types';
const styles = createStaticStyles(({ css }) => ({
@@ -34,17 +30,16 @@ const styles = createStaticStyles(({ css }) => ({
`,
}));
-export const GoalCardItem = memo<GoalItemProps>((props) => {
- const { t } = useTranslation('chat');
+export const GoalCardItem = memo<GoalItemProps>(({ goal: item }) => {
const navigate = useWorkspaceAwareNavigate();
const { aid } = useActiveRouteParams<{ aid?: string }>();
- const { hideAchieved = false, projectId, task } = props;
- const goal = task.goal;
- const title = task.name?.trim() || task.instruction.trim() || task.identifier;
- const description = getGoalDescription(task);
+ const { goal } = item;
+ // On the project Goals page there is no `aid` in the route, and a goal created
+ // there has no responsible agent either — so fall back the same way tasks do,
+ // to the bare detail route. Without this every card there is a dead link.
+ const agentId = aid ?? goal.agentId;
const handleClick = () => {
- if (projectId) navigate(`/task/${task.identifier}`);
- else if (aid) navigate(`/agent/${aid}/goal/${task.identifier}`);
+ navigate(agentId ? `/agent/${agentId}/goal/${goal.id}` : `/goal/${goal.id}`);
};
const handleKeyDown = (event: KeyboardEvent<HTMLDivElement>) => {
if (event.key !== 'Enter' && event.key !== ' ') return;
@@ -53,77 +48,42 @@ export const GoalCardItem = memo<GoalItemProps>((props) => {
};
return (
- <GoalAcceptance taskId={task.id}>
- {({ bundle, error, isLoading, retry }) => {
- const presentation = getGoalPresentation({
- checks: bundle?.checks,
- goalStatus: goal?.status ?? 'planning',
- maxRounds: goal?.maxRounds ?? null,
- rounds: task.totalTopics ?? 0,
- });
- if (
- !isLoading &&
- !shouldShowGoal(goal?.status ?? 'planning', hideAchieved ? 'active' : 'all')
- )
- return null;
-
- return (
- <Block
- clickable
- className={styles.card}
- gap={14}
- padding={16}
- role={'link'}
- tabIndex={0}
- variant={'outlined'}
- onClick={handleClick}
- onKeyDown={handleKeyDown}
- >
- <Flexbox
- horizontal
- align={'flex-start'}
- gap={12}
- justify={'space-between'}
- style={{ minWidth: 0 }}
- >
- <Flexbox gap={4} style={{ minWidth: 0 }}>
- <Flexbox horizontal align={'center'} gap={7}>
- <GoalStatusGlyph size={13} status={goal?.status ?? 'planning'} />
- <Text ellipsis fontSize={15} weight={600}>
- {title}
- </Text>
- </Flexbox>
- {description && description !== title && (
- <Text ellipsis fontSize={12} type={'secondary'}>
- {description}
- </Text>
- )}
- </Flexbox>
- {error ? (
- <ActionIcon
- icon={RefreshCwIcon}
- size={'small'}
- title={t('goalList.retry')}
- onClick={(event) => {
- event.stopPropagation();
- retry();
- }}
- />
- ) : (
- <Icon color={cssVar.colorTextQuaternary} icon={ArrowRightIcon} size={16} />
- )}
- </Flexbox>
- <GoalProgress
- isLoading={isLoading}
- presentation={presentation}
- totalRunCost={props.task.totalRunCost}
- totalRunDuration={props.task.totalRunDuration}
- totalRuns={props.task.totalTopics}
- />
- </Block>
- );
- }}
- </GoalAcceptance>
+ <Block
+ clickable
+ className={styles.card}
+ gap={12}
+ padding={16}
+ role={'link'}
+ tabIndex={0}
+ variant={'outlined'}
+ onClick={handleClick}
+ onKeyDown={handleKeyDown}
+ >
+ <Flexbox horizontal align={'flex-start'} gap={12} justify={'space-between'}>
+ <Flexbox gap={4} style={{ minWidth: 0 }}>
+ <Flexbox horizontal align={'center'} gap={7}>
+ <GoalStatusGlyph size={13} status={goal.status} />
+ <Text ellipsis fontSize={15} weight={600}>
+ {goal.title}
+ </Text>
+ </Flexbox>
+ {goal.requirement && goal.requirement !== goal.title && (
+ <Text ellipsis fontSize={12} type={'secondary'}>
+ {goal.requirement}
+ </Text>
+ )}
+ </Flexbox>
+ <Icon color={cssVar.colorTextQuaternary} icon={ArrowRightIcon} size={16} />
+ </Flexbox>
+ <GoalProgress
+ findingCount={item.findingCount}
+ pendingDecisions={item.pendingDecisions}
+ totalRunCost={item.totalRunCost}
+ totalRunDuration={item.totalRunDuration}
+ workDone={item.workDone}
+ workTotal={item.workTotal}
+ />
+ </Block>
);
});
diff --git a/src/features/AgentGoals/GoalDetailActions.tsx b/src/features/AgentGoals/GoalDetailActions.tsx
index c274ab0e6e8..f41d02a959a 100644
--- a/src/features/AgentGoals/GoalDetailActions.tsx
+++ b/src/features/AgentGoals/GoalDetailActions.tsx
@@ -15,11 +15,13 @@ import { usePermission } from '@/hooks/usePermission';
import { useGoalStore } from '@/store/goal';
interface GoalDetailActionsProps {
- agentId: string;
+ /** Absent for a goal with no responsible agent — e.g. one created from a project. */
+ agentId?: string;
goalId: string;
+ projectId?: string | null;
}
-const GoalDetailActions = memo<GoalDetailActionsProps>(({ agentId, goalId }) => {
+const GoalDetailActions = memo<GoalDetailActionsProps>(({ agentId, goalId, projectId }) => {
const { t } = useTranslation(['chat', 'common']);
const navigate = useWorkspaceAwareNavigate();
const { allowed: canEditTask } = usePermission('create_content');
@@ -58,15 +60,23 @@ const GoalDetailActions = memo<GoalDetailActionsProps>(({ agentId, goalId }) =>
okButtonProps: { danger: true },
okText: t('goalDetail.deleteConfirm.ok'),
onOk: async () => {
- await deleteGoal(agentId, goalId);
- navigate(`/agent/${agentId}/goals`);
+ // Mirrors the list scope the goal was rendered under, so the page
+ // the user lands on is the one whose cache was just refreshed.
+ await deleteGoal(agentId, goalId, projectId ? `project:${projectId}` : undefined);
+ navigate(
+ agentId
+ ? `/agent/${agentId}/goals`
+ : projectId
+ ? `/project/${projectId}/goals`
+ : '/',
+ );
},
title: t('goalDetail.deleteConfirm.title'),
});
},
},
],
- [agentId, canEditTask, deleteGoal, goalId, navigate, t],
+ [agentId, canEditTask, deleteGoal, goalId, navigate, projectId, t],
);
return (
diff --git a/src/features/AgentGoals/GoalDetailPage.tsx b/src/features/AgentGoals/GoalDetailPage.tsx
index f9a521895cd..5e00cabd7d2 100644
--- a/src/features/AgentGoals/GoalDetailPage.tsx
+++ b/src/features/AgentGoals/GoalDetailPage.tsx
@@ -1,53 +1,31 @@
'use client';
-import type { TaskDetailSubtask, TaskStatus } from '@lobechat/types';
-import { Accordion, AccordionItem, Flexbox, Icon } from '@lobehub/ui';
-import { Button, Tag, Text } from '@lobehub/ui/base-ui';
-import { Progress } from 'antd';
+import { Flexbox } from '@lobehub/ui';
+import { Text } from '@lobehub/ui/base-ui';
import { createStaticStyles, cssVar } from 'antd-style';
-import { BotIcon } from 'lucide-react';
-import { memo, useMemo } from 'react';
+import { memo } from 'react';
import { useTranslation } from 'react-i18next';
import NotFound from '@/components/404';
import AsyncError from '@/components/AsyncError';
-import { TASK_STATUS_VISUALS } from '@/components/ExecutionStatus';
import GoalDetailSkeleton from '@/components/Skeleton/GoalDetail';
-import {
- checkHeadMeta,
- CriterionList,
- CriterionRequiredChip,
- CriterionRow,
-} from '@/features/Acceptance';
import AgentBreadcrumb from '@/features/AgentBreadcrumb';
-import { useActiveTaskDetail } from '@/features/AgentTasks/AgentTaskDetail';
-import TaskDetailTitleInput from '@/features/AgentTasks/AgentTaskDetail/TaskDetailTitleInput';
-import TaskInstruction from '@/features/AgentTasks/AgentTaskDetail/TaskInstruction';
-import TopicCard from '@/features/AgentTasks/AgentTaskDetail/TopicCard';
-import AssigneeAvatar from '@/features/AgentTasks/features/AssigneeAvatar';
-import { useNavigateToTaskDetail } from '@/features/AgentTasks/shared/taskDetailPath';
import NavHeader from '@/features/NavHeader';
import WideScreenContainer from '@/features/WideScreenContainer';
-import { useActivityTime } from '@/hooks/useActivityTime';
-import { useTaskStore } from '@/store/task';
-import { taskDetailSelectors } from '@/store/task/selectors';
-import { useVerifyStore, verifySelectors } from '@/store/verify';
+import { goalSelectors, useGoalStore } from '@/store/goal';
import GoalDetailActions from './GoalDetailActions';
-import { getGoalPresentation } from './goalPresentation';
+import { goalStatusKey } from './goalPresentation';
import GoalStatusGlyph from './GoalStatusGlyph';
-import {
- formatGoalCost,
- formatGoalDuration,
- getGoalRunMetrics,
- getGoalRuns,
- getRecentGoalRuns,
-} from './goalViewModel';
+import ProcessControl from './ProcessControl';
+
+/**
+ * The goal detail page. A goal is a Goal Graph — it owns its own decomposition
+ * and dispatches Work Tasks — so the page reads the graph snapshot directly and
+ * the route is keyed by the `goals` row id.
+ */
const styles = createStaticStyles(({ css }) => ({
- executionSection: css`
- padding-block: 18px;
- `,
header: css`
padding-block: 8px 4px;
`,
@@ -59,335 +37,102 @@ const styles = createStaticStyles(({ css }) => ({
border-inline-start: 1px solid ${cssVar.colorBorderSecondary};
}
`,
- title: css`
- .ant-input {
- flex: none;
- }
- `,
- treeChildren: css`
- margin-inline-start: 13px;
- padding-inline-start: 20px;
- border-inline-start: 1px solid ${cssVar.colorBorderSecondary};
- `,
- treeRow: css`
- position: relative;
- min-height: 40px;
- padding-block: 8px;
-
- &::before {
- content: '';
-
- position: absolute;
- inset-block-start: 20px;
- inset-inline-start: -20px;
-
- width: 12px;
- border-block-start: 1px solid ${cssVar.colorBorderSecondary};
- }
- `,
}));
interface GoalDetailPageProps {
- agentId: string;
+ /** Absent for a goal with no responsible agent — e.g. one created from a project. */
+ agentId?: string;
goalId: string;
}
-const statusVisual = (status: string) =>
- TASK_STATUS_VISUALS[status as TaskStatus] ?? TASK_STATUS_VISUALS.backlog;
-
-const TaskTreeItem = memo<{ task: TaskDetailSubtask }>(({ task }) => {
- const navigateToTaskDetail = useNavigateToTaskDetail();
- const visual = statusVisual(task.status);
- const { text: updatedAt, title: updatedAtTitle } = useActivityTime(task.updatedAt);
-
- return (
- <Flexbox>
- <Flexbox
- horizontal
- align={'center'}
- className={styles.treeRow}
- gap={8}
- style={{ cursor: 'pointer' }}
- onClick={() => navigateToTaskDetail(task.identifier)}
- >
- <Icon color={visual.color} icon={visual.icon} size={14} />
- <Text fontSize={12} type={'secondary'}>
- {task.identifier}
- </Text>
- <Text ellipsis style={{ flex: 1, minWidth: 0 }}>
- {task.name || task.identifier}
- </Text>
- <AssigneeAvatar agentId={task.assignee?.id} size={18} />
- <Text fontSize={12} title={updatedAtTitle} type={'secondary'}>
- {updatedAt || '—'}
- </Text>
- </Flexbox>
- {task.children && task.children.length > 0 && (
- <Flexbox className={styles.treeChildren}>
- <TaskTreeRows tasks={task.children} />
- </Flexbox>
- )}
- </Flexbox>
- );
-});
-
-TaskTreeItem.displayName = 'GoalTaskTreeItem';
-
-const TaskTreeRows = memo<{ depth?: number; tasks: TaskDetailSubtask[] }>(({ tasks }) => {
- return tasks.map((item) => <TaskTreeItem key={item.identifier} task={item} />);
-});
-
-TaskTreeRows.displayName = 'GoalTaskTreeRows';
-
const GoalDetailPage = memo<GoalDetailPageProps>(({ agentId, goalId }) => {
- const { t } = useTranslation(['chat', 'verify']);
- const navigateToTaskDetail = useNavigateToTaskDetail();
- const { error, isInitialLoading, isNotFound, onRetry } = useActiveTaskDetail(goalId);
- const task = useTaskStore(taskDetailSelectors.taskDetailById(goalId));
- const useFetchAcceptanceBySubject = useVerifyStore((s) => s.useFetchAcceptanceBySubject);
- const useFetchAcceptanceBundle = useVerifyStore((s) => s.useFetchAcceptanceBundle);
- const acceptance = useVerifyStore(verifySelectors.acceptanceBySubject('task', task?.id));
- const bundle = useVerifyStore(verifySelectors.acceptanceBundle(acceptance?.id));
- const acceptanceQuery = useFetchAcceptanceBySubject('task', task?.id);
- const bundleQuery = useFetchAcceptanceBundle(acceptance?.id);
- const runs = useMemo(() => getGoalRuns(task?.activities), [task?.activities]);
- 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({
- checks: bundle?.checks,
- goalStatus,
- maxRounds: task?.goal?.maxRounds ?? null,
- rounds: task?.topicCount ?? 0,
- });
- const title = task?.name?.trim() || task?.instruction.trim() || goalId;
-
- if (error) return <AsyncError error={error} variant={'page'} onRetry={onRetry} />;
- if (isNotFound)
- return (
+ const { t } = useTranslation('chat');
+ const useFetchGoalGraph = useGoalStore((s) => s.useFetchGoalGraph);
+ const { error, isLoading, mutate } = useFetchGoalGraph(goalId);
+ const snapshot = useGoalStore(goalSelectors.goalGraph(goalId));
+
+ if (error && !snapshot) return <AsyncError error={error} variant={'page'} onRetry={mutate} />;
+ if (!snapshot)
+ return isLoading ? (
+ <GoalDetailSkeleton />
+ ) : (
<NotFound desc={t('goalDetail.notFoundDescription')} title={t('goalDetail.notFoundTitle')} />
);
+ const { goal, nodes } = snapshot;
+ const tasks = nodes.filter((node) => node.kind === 'work').length;
+ const findings = nodes.filter((node) => node.kind === 'finding').length;
+
return (
<Flexbox flex={1} height={'100%'}>
<NavHeader
left={
<Flexbox horizontal align={'center'} gap={4}>
- <AgentBreadcrumb agentId={agentId} extraItems={[title]} title={t('goalList.title')} />
- <GoalDetailActions agentId={agentId} goalId={goalId} />
+ {agentId ? (
+ <AgentBreadcrumb
+ agentId={agentId}
+ extraItems={[goal.title]}
+ title={t('goalList.title')}
+ />
+ ) : (
+ <Text fontSize={14} weight={500}>
+ {goal.title}
+ </Text>
+ )}
+ {/* Not nested under the breadcrumb: an agent-less goal still has to
+ be deletable, and this menu is the only place that can do it. */}
+ <GoalDetailActions agentId={agentId} goalId={goal.id} projectId={goal.projectId} />
</Flexbox>
}
/>
<Flexbox flex={1} style={{ overflowY: 'auto' }}>
<WideScreenContainer gap={20} paddingBlock={16}>
- {isInitialLoading || !task ? (
- <GoalDetailSkeleton chrome={'body'} />
- ) : (
- <>
- <Flexbox className={styles.header} gap={8}>
- <Flexbox horizontal align={'flex-start'} gap={12}>
- <Flexbox className={styles.title} gap={5} style={{ flex: 1, minWidth: 0 }}>
- <TaskDetailTitleInput />
- {task.description && (
- <Text fontSize={15} style={{ lineHeight: 1.65, whiteSpace: 'pre-wrap' }}>
- {task.description}
- </Text>
- )}
- </Flexbox>
- </Flexbox>
-
- <Flexbox horizontal gap={18} wrap={'wrap'}>
- <Flexbox className={styles.metric} gap={2}>
- <Flexbox horizontal align={'center'} gap={7}>
- <Progress
- percent={presentation.progress}
- showInfo={false}
- size={24}
- strokeColor={cssVar.colorSuccess}
- type={'circle'}
- />
- <Text fontSize={18} weight={600}>
- {presentation.total > 0
- ? `${presentation.passed}/${presentation.total}`
- : '—'}
- </Text>
- </Flexbox>
- <Text fontSize={12} type={'secondary'}>
- {t('goalDetail.metrics.progress')}
- </Text>
- </Flexbox>
- <Flexbox className={styles.metric} gap={2}>
- <Text fontSize={18} weight={600}>
- {task.topicCount ?? 0}
- </Text>
- <Text fontSize={12} type={'secondary'}>
- {t('goalDetail.metrics.taskExecutions')}
- </Text>
- </Flexbox>
- <Flexbox className={styles.metric} gap={2}>
- <Text fontSize={18} weight={600}>
- {runs.length}
- </Text>
- <Text fontSize={12} type={'secondary'}>
- {t('goalDetail.metrics.agentRuns')}
- </Text>
- </Flexbox>
- <Flexbox className={styles.metric} gap={2}>
- <Text fontSize={18} weight={600}>
- {formatGoalDuration(runMetrics.duration)}
- </Text>
- <Text fontSize={12} type={'secondary'}>
- {t('goalDetail.metrics.totalDuration')}
- </Text>
- </Flexbox>
- <Flexbox className={styles.metric} gap={2}>
- <Text fontSize={18} weight={600}>
- {formatGoalCost(runMetrics.cost)}
- </Text>
- <Text fontSize={12} type={'secondary'}>
- {t('goalDetail.metrics.totalCost')}
- </Text>
- </Flexbox>
- </Flexbox>
- <Flexbox gap={4} paddingBlock={'8px 0'}>
- <Text fontSize={12} type={'secondary'} weight={500}>
- {t('goalDetail.instruction')}
+ <Flexbox className={styles.header} gap={8}>
+ <Text as={'h1'} fontSize={22} weight={600}>
+ {goal.title}
+ </Text>
+ <Flexbox horizontal gap={18} wrap={'wrap'}>
+ <Flexbox className={styles.metric} gap={2}>
+ <Flexbox horizontal align={'center'} gap={7}>
+ <GoalStatusGlyph size={16} status={goal.status} />
+ <Text fontSize={16} weight={600}>
+ {t(goalStatusKey(goal.status))}
</Text>
- <TaskInstruction />
</Flexbox>
+ <Text fontSize={12} type={'secondary'}>
+ {t('goalProcess.metrics.status')}
+ </Text>
</Flexbox>
-
- <Flexbox gap={4}>
- <Accordion defaultExpandedKeys={['acceptance']} gap={0}>
- <AccordionItem
- itemKey={'acceptance'}
- paddingBlock={6}
- paddingInline={0}
- title={
- <Flexbox horizontal align={'center'} gap={8}>
- <Text fontSize={14} weight={600}>
- {t('goalDetail.acceptance')}
- </Text>
- {presentation.total > 0 && <Tag size={'small'}>{presentation.total}</Tag>}
- </Flexbox>
- }
- >
- <Flexbox paddingBlock={8}>
- {acceptanceQuery.error || bundleQuery.error ? (
- <AsyncError
- error={acceptanceQuery.error || bundleQuery.error}
- variant={'inline'}
- onRetry={() => {
- void acceptanceQuery.mutate();
- if (acceptance?.id) void bundleQuery.mutate();
- }}
- />
- ) : acceptanceQuery.isLoading || bundleQuery.isLoading ? (
- <Text type={'secondary'}>{t('goalPage.loadingProgress')}</Text>
- ) : presentation.total === 0 ? (
- <Text type={'secondary'}>{t('goalDetail.noChecks')}</Text>
- ) : (
- <CriterionList>
- {bundle?.checks.map((check, index) => {
- const meta = checkHeadMeta(check);
- const verifierType = check.planItem?.verifierType;
- return (
- <CriterionRow
- key={check.id}
- seq={index + 1}
- title={check.title}
- icon={
- <Icon
- color={meta.color}
- icon={meta.icon}
- size={16}
- style={{ flex: 'none' }}
- />
- }
- >
- {verifierType ? (
- <Tag>
- {t(`criterion.verifierType.${verifierType}` as const, {
- ns: 'verify',
- })}
- </Tag>
- ) : null}
- <CriterionRequiredChip required={check.required !== false} />
- </CriterionRow>
- );
- })}
- </CriterionList>
- )}
- </Flexbox>
- </AccordionItem>
- </Accordion>
-
- <Flexbox className={styles.executionSection} gap={12}>
- <Flexbox gap={5}>
- <Flexbox horizontal align={'center'} gap={8}>
- <Text fontSize={14} weight={600}>
- {t('goalDetail.executionOverview')}
- </Text>
- <Button
- size={'small'}
- type={'text'}
- onClick={() => navigateToTaskDetail(task.identifier, agentId)}
- >
- {t('goalDetail.viewPlan')}
- </Button>
- </Flexbox>
- </Flexbox>
- <Flexbox gap={4}>
- <Flexbox horizontal align={'center'} className={styles.treeRow} gap={8}>
- <GoalStatusGlyph size={14} status={goalStatus} />
- <Text fontSize={12} type={'secondary'}>
- {task.identifier}
- </Text>
- <Text ellipsis style={{ flex: 1, minWidth: 0 }} weight={600}>
- {task.name || task.identifier}
- </Text>
- <AssigneeAvatar agentId={task.agentId} size={18} />
- <Text fontSize={12} title={rootUpdatedAtTitle} type={'secondary'}>
- {rootUpdatedAt || '—'}
- </Text>
- </Flexbox>
- {task.subtasks && task.subtasks.length > 0 && (
- <Flexbox className={styles.treeChildren}>
- <TaskTreeRows tasks={task.subtasks} />
- </Flexbox>
- )}
- </Flexbox>
- <Flexbox horizontal align={'center'} gap={8} paddingBlock={'12px 0'}>
- <Text fontSize={13} weight={600}>
- {t('goalDetail.latestRuns')}
- </Text>
- </Flexbox>
- {runs.length > 0 ? (
- <Flexbox gap={12} paddingBlock={8}>
- {recentRuns.map((activity, index) => (
- <TopicCard
- activity={activity}
- key={activity.id || activity.topicId || index}
- />
- ))}
- </Flexbox>
- ) : (
- <Flexbox
- horizontal
- align={'center'}
- gap={8}
- paddingBlock={10}
- paddingInline={12}
- >
- <Icon color={cssVar.colorTextQuaternary} icon={BotIcon} size={15} />
- <Text type={'secondary'}>{t('goalDetail.noRuns')}</Text>
- </Flexbox>
- )}
- </Flexbox>
+ <Flexbox className={styles.metric} gap={2}>
+ <Text fontSize={18} weight={600}>
+ {tasks}
+ </Text>
+ <Text fontSize={12} type={'secondary'}>
+ {t('goalProcess.metrics.tasks')}
+ </Text>
</Flexbox>
- </>
- )}
+ <Flexbox className={styles.metric} gap={2}>
+ <Text fontSize={18} weight={600}>
+ {findings}
+ </Text>
+ <Text fontSize={12} type={'secondary'}>
+ {t('goalProcess.metrics.findings')}
+ </Text>
+ </Flexbox>
+ </Flexbox>
+ {goal.requirement && (
+ <Flexbox gap={4} paddingBlock={'8px 0'}>
+ <Text fontSize={12} type={'secondary'} weight={500}>
+ {t('goalProcess.requirement')}
+ </Text>
+ <Text fontSize={14} style={{ lineHeight: 1.65, whiteSpace: 'pre-wrap' }}>
+ {goal.requirement}
+ </Text>
+ </Flexbox>
+ )}
+ </Flexbox>
+
+ <ProcessControl goalId={goal.id} />
</WideScreenContainer>
</Flexbox>
</Flexbox>
diff --git a/src/features/AgentGoals/GoalListItem.tsx b/src/features/AgentGoals/GoalListItem.tsx
index 7267c18b59c..eee22d74edd 100644
--- a/src/features/AgentGoals/GoalListItem.tsx
+++ b/src/features/AgentGoals/GoalListItem.tsx
@@ -1,21 +1,17 @@
'use client';
import { Block, Flexbox, Icon } from '@lobehub/ui';
-import { ActionIcon, Text } from '@lobehub/ui/base-ui';
+import { Text } from '@lobehub/ui/base-ui';
import { createStaticStyles, cssVar } from 'antd-style';
-import { ArrowRightIcon, RefreshCwIcon } from 'lucide-react';
+import { ArrowRightIcon } from 'lucide-react';
import type { KeyboardEvent } from 'react';
import { memo } from 'react';
-import { useTranslation } from 'react-i18next';
import { useWorkspaceAwareNavigate } from '@/features/Workspace/useWorkspaceAwareNavigate';
import { useActiveRouteParams } from '@/hooks/useActiveRouteParams';
-import { GoalAcceptance } from './GoalAcceptance';
-import { getGoalPresentation } from './goalPresentation';
import { GoalProgress } from './GoalProgress';
import GoalStatusGlyph from './GoalStatusGlyph';
-import { getGoalDescription, shouldShowGoal } from './goalViewModel';
import type { GoalItemProps } from './types';
const styles = createStaticStyles(({ css }) => ({
@@ -33,17 +29,16 @@ const styles = createStaticStyles(({ css }) => ({
`,
}));
-export const GoalListItem = memo<GoalItemProps>((props) => {
- const { t } = useTranslation('chat');
+export const GoalListItem = memo<GoalItemProps>(({ goal: item }) => {
const navigate = useWorkspaceAwareNavigate();
const { aid } = useActiveRouteParams<{ aid?: string }>();
- const { hideAchieved = false, projectId, task } = props;
- const goal = task.goal;
- const title = task.name?.trim() || task.instruction.trim() || task.identifier;
- const description = getGoalDescription(task);
+ const { goal } = item;
+ // On the project Goals page there is no `aid` in the route, and a goal created
+ // there has no responsible agent either — so fall back the same way tasks do,
+ // to the bare detail route. Without this every card there is a dead link.
+ const agentId = aid ?? goal.agentId;
const handleClick = () => {
- if (projectId) navigate(`/task/${task.identifier}`);
- else if (aid) navigate(`/agent/${aid}/goal/${task.identifier}`);
+ navigate(agentId ? `/agent/${agentId}/goal/${goal.id}` : `/goal/${goal.id}`);
};
const handleKeyDown = (event: KeyboardEvent<HTMLDivElement>) => {
if (event.key !== 'Enter' && event.key !== ' ') return;
@@ -52,82 +47,44 @@ export const GoalListItem = memo<GoalItemProps>((props) => {
};
return (
- <GoalAcceptance taskId={task.id}>
- {({ bundle, error, isLoading, retry }) => {
- const presentation = getGoalPresentation({
- checks: bundle?.checks,
- goalStatus: goal?.status ?? 'planning',
- maxRounds: goal?.maxRounds ?? null,
- rounds: task.totalTopics ?? 0,
- });
- if (
- !isLoading &&
- !shouldShowGoal(goal?.status ?? 'planning', hideAchieved ? 'active' : 'all')
- )
- return null;
-
- return (
- <Block
- clickable
- horizontal
- align={'center'}
- className={styles.row}
- gap={12}
- justify={'space-between'}
- paddingBlock={10}
- paddingInline={0}
- role={'link'}
- tabIndex={0}
- variant={'borderless'}
- onClick={handleClick}
- onKeyDown={handleKeyDown}
- >
- <Flexbox
- horizontal
- align={'center'}
- flex={1}
- gap={12}
- justify={'space-between'}
- style={{ minWidth: 0 }}
- >
- <Flexbox gap={4} style={{ minWidth: 0 }}>
- <Flexbox horizontal align={'center'} gap={7}>
- <GoalStatusGlyph size={13} status={goal?.status ?? 'planning'} />
- <Text ellipsis fontSize={15} weight={600}>
- {title}
- </Text>
- </Flexbox>
- {description && description !== title && (
- <Text ellipsis fontSize={12} type={'secondary'}>
- {description}
- </Text>
- )}
- </Flexbox>
- </Flexbox>
- <GoalProgress
- isLoading={isLoading}
- presentation={presentation}
- totalRunCost={props.task.totalRunCost}
- totalRunDuration={props.task.totalRunDuration}
- totalRuns={props.task.totalTopics}
- />
- {error ? (
- <ActionIcon
- icon={RefreshCwIcon}
- size={'small'}
- title={t('goalList.retry')}
- onClick={(event) => {
- event.stopPropagation();
- retry();
- }}
- />
- ) : (
- <Icon color={cssVar.colorTextQuaternary} icon={ArrowRightIcon} size={16} />
- )}
- </Block>
- );
- }}
- </GoalAcceptance>
+ <Block
+ clickable
+ horizontal
+ align={'center'}
+ className={styles.row}
+ gap={12}
+ justify={'space-between'}
+ paddingBlock={10}
+ paddingInline={0}
+ role={'link'}
+ tabIndex={0}
+ variant={'borderless'}
+ onClick={handleClick}
+ onKeyDown={handleKeyDown}
+ >
+ <Flexbox gap={4} style={{ flex: 1, minWidth: 0 }}>
+ <Flexbox horizontal align={'center'} gap={7}>
+ <GoalStatusGlyph size={13} status={goal.status} />
+ <Text ellipsis fontSize={15} weight={600}>
+ {goal.title}
+ </Text>
+ </Flexbox>
+ {goal.requirement && goal.requirement !== goal.title && (
+ <Text ellipsis fontSize={12} type={'secondary'}>
+ {goal.requirement}
+ </Text>
+ )}
+ </Flexbox>
+ <GoalProgress
+ findingCount={item.findingCount}
+ pendingDecisions={item.pendingDecisions}
+ totalRunCost={item.totalRunCost}
+ totalRunDuration={item.totalRunDuration}
+ workDone={item.workDone}
+ workTotal={item.workTotal}
+ />
+ <Icon color={cssVar.colorTextQuaternary} icon={ArrowRightIcon} size={16} />
+ </Block>
);
});
diff --git a/src/features/AgentGoals/GoalProgress.tsx b/src/features/AgentGoals/GoalProgress.tsx
index 312f3f198fd..dc76aee7d94 100644
--- a/src/features/AgentGoals/GoalProgress.tsx
+++ b/src/features/AgentGoals/GoalProgress.tsx
@@ -4,29 +4,40 @@ import { createStaticStyles, cssVar } from 'antd-style';
import { memo } from 'react';
import { useTranslation } from 'react-i18next';
-import type { getGoalPresentation } from './goalPresentation';
-import { formatGoalCost, formatGoalDuration } from './goalViewModel';
+/** `3m` · `2.1h` · `1.4d` — the coarse grain a list row can carry. */
+export const formatGoalDuration = (milliseconds: number) => {
+ if (!milliseconds || milliseconds <= 0) return '—';
+ const minutes = milliseconds / 60_000;
+ if (minutes < 60) return `${Math.max(1, Math.round(minutes))}m`;
+ const hours = minutes / 60;
+ if (hours < 24) return `${hours.toFixed(1)}h`;
+ return `${(hours / 24).toFixed(1)}d`;
+};
+
+export const formatGoalCost = (cost: number) => (cost > 0 ? `$${cost.toFixed(2)}` : '—');
const styles = createStaticStyles(({ css }) => ({
acceptance: css`
min-width: 0;
`,
- loading: css`
- grid-column: 1 / -1;
- `,
metric: css`
justify-self: end;
white-space: nowrap;
`,
metrics: css`
display: grid;
- grid-template-columns: minmax(178px, 1fr) 64px 48px 64px;
+ grid-template-columns: minmax(178px, 1fr) 72px 48px 64px;
column-gap: 12px;
align-items: center;
width: min(100%, 390px);
min-width: 390px;
`,
+ needsYou: css`
+ justify-self: end;
+ color: ${cssVar.colorWarning};
+ white-space: nowrap;
+ `,
progress: css`
overflow: hidden;
@@ -44,57 +55,55 @@ const styles = createStaticStyles(({ css }) => ({
`,
}));
-interface GoalProgressProps {
- isLoading: boolean;
- presentation: ReturnType<typeof getGoalPresentation>;
- totalRunCost?: number | null;
- totalRunDuration?: number | null;
- totalRuns?: number | null;
+export interface GoalProgressProps {
+ findingCount: number;
+ pendingDecisions: number;
+ totalRunCost: number;
+ totalRunDuration: number;
+ workDone: number;
+ workTotal: number;
}
+/**
+ * The list row's roll-up: how far the graph got, what it produced, what it
+ * cost — and, taking priority over the findings count, whether anything is
+ * blocked on the user right now.
+ */
export const GoalProgress = memo<GoalProgressProps>(
- ({ isLoading, presentation, totalRunCost = 0, totalRunDuration = 0, totalRuns = 0 }) => {
+ ({ findingCount, pendingDecisions, totalRunCost, totalRunDuration, workDone, workTotal }) => {
const { t } = useTranslation('chat');
-
- if (isLoading)
- return (
- <div className={styles.metrics}>
- <Text className={styles.loading} fontSize={12} type={'secondary'}>
- {t('goalPage.loadingProgress')}
- </Text>
- </div>
- );
+ const progress = workTotal > 0 ? Math.round((workDone / workTotal) * 100) : 0;
return (
<div className={styles.metrics}>
- {presentation.total > 0 ? (
+ {workTotal > 0 ? (
<Flexbox horizontal align={'center'} className={styles.acceptance} gap={6}>
<div aria-hidden className={styles.progress}>
- <div
- className={styles.progressValue}
- style={{ width: `${presentation.progress}%` }}
- />
+ <div className={styles.progressValue} style={{ width: `${progress}%` }} />
</div>
<Text ellipsis color={cssVar.colorTextTertiary} fontSize={12}>
- {t('goalList.acceptanceProgress', presentation)}
+ {t('goalList.workProgress', { done: workDone, total: workTotal })}
</Text>
</Flexbox>
) : (
<Text ellipsis color={cssVar.colorTextTertiary} fontSize={12}>
- {t('goalList.roundProgress', {
- current: presentation.rounds,
- total: typeof presentation.maxRounds === 'number' ? presentation.maxRounds : '∞',
- })}
+ {t('goalList.noWork')}
+ </Text>
+ )}
+ {pendingDecisions > 0 ? (
+ <Text className={styles.needsYou} fontSize={12}>
+ {t('goalList.needsYou', { count: pendingDecisions })}
+ </Text>
+ ) : (
+ <Text className={styles.metric} color={cssVar.colorTextTertiary} fontSize={12}>
+ {t('goalList.findings', { count: findingCount })}
</Text>
)}
<Text className={styles.metric} color={cssVar.colorTextTertiary} fontSize={12}>
- {t('goalList.agentRuns', { count: totalRuns })}
- </Text>
- <Text className={styles.metric} color={cssVar.colorTextTertiary} fontSize={12}>
- {formatGoalDuration(totalRunDuration ?? 0)}
+ {formatGoalDuration(totalRunDuration)}
</Text>
<Text className={styles.metric} color={cssVar.colorTextTertiary} fontSize={12}>
- {formatGoalCost(totalRunCost ?? 0)}
+ {formatGoalCost(totalRunCost)}
</Text>
</div>
);
diff --git a/src/features/AgentGoals/GoalStatusGlyph.tsx b/src/features/AgentGoals/GoalStatusGlyph.tsx
index 76e7b6b149e..64b13aac865 100644
--- a/src/features/AgentGoals/GoalStatusGlyph.tsx
+++ b/src/features/AgentGoals/GoalStatusGlyph.tsx
@@ -1,12 +1,11 @@
import type { GoalStatus } from '@lobechat/const/goal';
-import type { TaskStatus } from '@lobechat/types';
import { Icon } from '@lobehub/ui';
import { memo } from 'react';
import { TASK_STATUS_VISUALS } from '@/components/ExecutionStatus';
import RunningGlyph from '@/features/Home/components/RunningGlyph';
-import { goalStatusToTaskStatus } from './goalViewModel';
+import { goalStatusToTaskStatus } from './goalPresentation';
/**
* The goal surfaces' status glyph. A live goal shows the same spinning ring as
@@ -17,9 +16,7 @@ import { goalStatusToTaskStatus } from './goalViewModel';
const GoalStatusGlyph = memo<{ size?: number; status: GoalStatus }>(({ status, size = 13 }) => {
if (status === 'running') return <RunningGlyph size={size} />;
- const visual =
- TASK_STATUS_VISUALS[goalStatusToTaskStatus(status) as TaskStatus] ??
- TASK_STATUS_VISUALS.backlog;
+ const visual = TASK_STATUS_VISUALS[goalStatusToTaskStatus(status)] ?? TASK_STATUS_VISUALS.backlog;
return <Icon color={visual.color} icon={visual.icon} size={size} style={{ flexShrink: 0 }} />;
});
diff --git a/src/features/AgentGoals/ProcessControl/Activity.tsx b/src/features/AgentGoals/ProcessControl/Activity.tsx
new file mode 100644
index 00000000000..ca1790377b9
--- /dev/null
+++ b/src/features/AgentGoals/ProcessControl/Activity.tsx
@@ -0,0 +1,245 @@
+'use client';
+
+import { Empty, Flexbox, Icon } from '@lobehub/ui';
+import { Text } from '@lobehub/ui/base-ui';
+import { createStaticStyles, cssVar, cx } from 'antd-style';
+import { BotMessageSquare, ChevronRight } from 'lucide-react';
+import { memo, useState } from 'react';
+import { useTranslation } from 'react-i18next';
+
+import { useActivityTime } from '@/hooks/useActivityTime';
+
+import type { GoalGraphView, GoalNodeView } from './goalGraphViewModel';
+import { KindDot } from './shared';
+import { useElapsed } from './useElapsed';
+
+/**
+ * 活动 — one row per node, not a raw event dump.
+ *
+ * A goal produces many runtime events (dispatch, evidence submission, verifier
+ * verdicts, lease renewals). Most of them belong *inside* a task: the verifier
+ * judging attempt #2 is part of that task's story, not a separate line in the
+ * goal's history. So each row is "what this task did, how it ended", with the
+ * per-attempt ledger folded underneath.
+ */
+
+const styles = createStaticStyles(({ css }) => ({
+ arrow: css`
+ flex: none;
+ color: ${cssVar.colorTextQuaternary};
+ transition: transform 0.2s;
+ `,
+ arrowOpen: css`
+ transform: rotate(90deg);
+ `,
+ attempt: css`
+ padding-block: 6px;
+
+ & + & {
+ border-block-start: 1px dashed ${cssVar.colorBorderSecondary};
+ }
+ `,
+ body: css`
+ padding-block: 0 10px;
+ padding-inline: 42px 9px;
+ `,
+ mono: css`
+ font-family: ${cssVar.fontFamilyCode};
+ font-variant-numeric: tabular-nums;
+ `,
+ row: css`
+ cursor: pointer;
+ padding-block: 6px;
+ padding-inline: 9px;
+ border-radius: ${cssVar.borderRadiusSM};
+
+ &:hover {
+ background: ${cssVar.colorFillQuaternary};
+ }
+ `,
+ time: css`
+ flex: none;
+ margin-inline-start: auto;
+ `,
+}));
+
+const lastTouch = (view: GoalNodeView): Date =>
+ [
+ view.node.resolvedAt,
+ view.node.updatedAt,
+ view.attempts.at(-1)?.endedAt,
+ view.attempts.at(-1)?.startedAt,
+ ]
+ .filter((date): date is Date => !!date)
+ .sort((a, b) => b.getTime() - a.getTime())[0] ?? view.node.createdAt;
+
+const useSummary = () => {
+ const { t } = useTranslation('chat');
+ return (view: GoalNodeView): string => {
+ const { node } = view;
+ const count = view.attempts.length;
+ if (node.kind === 'decision')
+ return node.status === 'waiting'
+ ? t('goalProcess.summary.gateOpen')
+ : t('goalProcess.summary.gateResolved', {
+ option: view.humanTouches[0]?.resolvedOptionId ?? '—',
+ });
+ switch (node.status) {
+ case 'active': {
+ return t('goalProcess.summary.running', { index: count });
+ }
+ case 'rejected':
+ case 'retired': {
+ return t('goalProcess.summary.retired', { count });
+ }
+ case 'resolved': {
+ return t('goalProcess.summary.done', { count });
+ }
+ case 'waiting': {
+ return t('goalProcess.summary.waiting', { count });
+ }
+ default: {
+ return t('goalProcess.summary.notStarted');
+ }
+ }
+ };
+};
+
+const RunningClock = memo<{ startedAt?: Date }>(({ startedAt }) => {
+ const { t } = useTranslation('chat');
+ const elapsed = useElapsed(startedAt);
+ if (!elapsed) return null;
+ return (
+ <Text className={styles.mono} fontSize={12} style={{ flex: 'none' }} type={'secondary'}>
+ {t('goalProcess.running.elapsed', { duration: elapsed })}
+ </Text>
+ );
+});
+
+RunningClock.displayName = 'GoalActivityRunningClock';
+
+const ActivityRow = memo<{ onSelect: (nodeId: string) => void; view: GoalNodeView }>(
+ ({ onSelect, view }) => {
+ const { t } = useTranslation('chat');
+ const summarize = useSummary();
+ const [open, setOpen] = useState(false);
+ const { text, title } = useActivityTime(lastTouch(view));
+ const hasDetail = view.attempts.length > 0 || view.findings.length > 0;
+
+ return (
+ <Flexbox gap={0}>
+ <Flexbox
+ horizontal
+ align={'center'}
+ className={styles.row}
+ gap={8}
+ onClick={() => (hasDetail ? setOpen(!open) : onSelect(view.node.id))}
+ >
+ <Icon
+ className={cx(styles.arrow, open && styles.arrowOpen)}
+ icon={ChevronRight}
+ size={14}
+ style={{ opacity: hasDetail ? 1 : 0 }}
+ />
+ <KindDot kind={view.node.kind} />
+ <Text ellipsis style={{ flexShrink: 1, minWidth: 0 }} weight={500}>
+ {view.node.title}
+ </Text>
+ <Text ellipsis fontSize={14} style={{ flexShrink: 1, minWidth: 0 }} type={'secondary'}>
+ {summarize(view)}
+ </Text>
+ {view.startedAt && <RunningClock startedAt={view.startedAt} />}
+ <Text
+ className={cx(styles.time, styles.mono)}
+ fontSize={12}
+ title={title}
+ type={'secondary'}
+ >
+ {text}
+ </Text>
+ </Flexbox>
+ {open && (
+ <Flexbox className={styles.body} gap={10}>
+ {view.attempts.length > 0 && (
+ <Flexbox gap={0}>
+ {view.attempts.map((attempt) => (
+ <Flexbox className={styles.attempt} gap={2} key={attempt.index}>
+ <Flexbox horizontal align={'center'} gap={8}>
+ <Text fontSize={12} style={{ flex: 'none' }} weight={600}>
+ {t('goalProcess.attempts.nth', { index: attempt.index })}
+ </Text>
+ <Text
+ fontSize={12}
+ style={{ flex: 'none' }}
+ type={
+ attempt.outcome === 'passed'
+ ? 'success'
+ : attempt.outcome === 'failed'
+ ? 'danger'
+ : 'secondary'
+ }
+ >
+ {t(`goalProcess.attempts.${attempt.outcome}` as const)}
+ </Text>
+ </Flexbox>
+ {attempt.reason && (
+ <Text fontSize={12} type={'secondary'}>
+ {attempt.reason}
+ </Text>
+ )}
+ </Flexbox>
+ ))}
+ </Flexbox>
+ )}
+ {view.findings.map((finding) => (
+ <Flexbox
+ horizontal
+ align={'center'}
+ gap={6}
+ key={finding.id}
+ style={{ cursor: 'pointer' }}
+ onClick={() => onSelect(finding.id)}
+ >
+ <KindDot kind={'finding'} />
+ <Text fontSize={13}>
+ {t('goalProcess.activity.finding', { title: finding.title })}
+ </Text>
+ </Flexbox>
+ ))}
+ </Flexbox>
+ )}
+ </Flexbox>
+ );
+ },
+);
+
+ActivityRow.displayName = 'GoalActivityRow';
+
+const Activity = memo<{ graph: GoalGraphView; onSelect: (nodeId: string) => void }>(
+ ({ graph, onSelect }) => {
+ const { t } = useTranslation('chat');
+ const rows = graph.nodes
+ .filter(
+ (view) =>
+ (view.node.kind === 'work' &&
+ (view.attempts.length > 0 || view.node.status !== 'proposed')) ||
+ (view.node.kind === 'decision' && view.node.status !== 'proposed'),
+ )
+ .sort((a, b) => lastTouch(b).getTime() - lastTouch(a).getTime());
+
+ if (rows.length === 0)
+ return <Empty description={t('goalProcess.activity.empty')} icon={BotMessageSquare} />;
+
+ return (
+ <Flexbox gap={2}>
+ {rows.map((view) => (
+ <ActivityRow key={view.node.id} view={view} onSelect={onSelect} />
+ ))}
+ </Flexbox>
+ );
+ },
+);
+
+Activity.displayName = 'GoalActivity';
+
+export default Activity;
diff --git a/src/features/AgentGoals/ProcessControl/Findings.tsx b/src/features/AgentGoals/ProcessControl/Findings.tsx
new file mode 100644
index 00000000000..c7255f8e58d
--- /dev/null
+++ b/src/features/AgentGoals/ProcessControl/Findings.tsx
@@ -0,0 +1,160 @@
+'use client';
+
+import { Flexbox, Icon } from '@lobehub/ui';
+import { Text } from '@lobehub/ui/base-ui';
+import { createStaticStyles, cssVar, cx } from 'antd-style';
+import { ChevronRight } from 'lucide-react';
+import { memo, useState } from 'react';
+import { useTranslation } from 'react-i18next';
+
+import { useActivityTime } from '@/hooks/useActivityTime';
+
+import type { GoalGraphView, GoalNodeView } from './goalGraphViewModel';
+import { KindDot } from './shared';
+
+/**
+ * What the goal currently believes. Borderless rows — a finding is reading
+ * material, not a control — and clicking one expands its evidence in place:
+ * the question it answers and the task that produced it.
+ */
+
+const styles = createStaticStyles(({ css }) => ({
+ arrow: css`
+ flex: none;
+ color: ${cssVar.colorTextQuaternary};
+ transition: transform 0.2s;
+ `,
+ arrowOpen: css`
+ transform: rotate(90deg);
+ `,
+ body: css`
+ padding-block: 0 10px;
+ padding-inline: 30px 8px;
+ `,
+ row: css`
+ cursor: pointer;
+ padding-block: 8px;
+ padding-inline: 8px;
+ border-radius: ${cssVar.borderRadiusSM};
+
+ &:hover {
+ background: ${cssVar.colorFillQuaternary};
+ }
+ `,
+}));
+
+const FindingRow = memo<{ onSelect: (nodeId: string) => void; view: GoalNodeView }>(
+ ({ onSelect, view }) => {
+ const { t } = useTranslation('chat');
+ const [open, setOpen] = useState(false);
+ const { text, title } = useActivityTime(view.node.resolvedAt ?? view.node.createdAt);
+ const answered = view.answers[0];
+
+ return (
+ <Flexbox gap={0}>
+ <Flexbox
+ horizontal
+ align={'center'}
+ className={styles.row}
+ gap={8}
+ onClick={() => setOpen(!open)}
+ >
+ <Icon
+ className={cx(styles.arrow, open && styles.arrowOpen)}
+ icon={ChevronRight}
+ size={14}
+ />
+ <KindDot kind={'finding'} />
+ <Text ellipsis style={{ flexShrink: 1, minWidth: 0 }} weight={500}>
+ {view.node.title}
+ </Text>
+ <Text ellipsis fontSize={12} style={{ flexShrink: 1, minWidth: 0 }} type={'secondary'}>
+ {answered
+ ? t('goalProcess.findings.answers', { title: answered.title })
+ : view.producedBy
+ ? t('goalProcess.findings.from', { title: view.producedBy.title })
+ : ''}
+ </Text>
+ <Text
+ fontSize={12}
+ style={{ flex: 'none', marginInlineStart: 'auto' }}
+ title={title}
+ type={'secondary'}
+ >
+ {text}
+ </Text>
+ </Flexbox>
+ {open && (
+ <Flexbox className={styles.body} gap={8}>
+ {view.answers.map((problem) => (
+ <Flexbox
+ horizontal
+ align={'center'}
+ gap={6}
+ key={problem.id}
+ style={{ cursor: 'pointer' }}
+ onClick={() => onSelect(problem.id)}
+ >
+ <KindDot kind={'problem'} />
+ <Text fontSize={12} type={'secondary'}>
+ {t('goalProcess.findings.answers', { title: problem.title })}
+ </Text>
+ </Flexbox>
+ ))}
+ {view.node.description && (
+ <Text fontSize={13} style={{ whiteSpace: 'pre-wrap' }}>
+ {view.node.description}
+ </Text>
+ )}
+ {view.producedBy && (
+ <Flexbox
+ horizontal
+ align={'center'}
+ gap={6}
+ style={{ cursor: 'pointer' }}
+ onClick={() => onSelect(view.producedBy!.id)}
+ >
+ <KindDot kind={'work'} />
+ <Text fontSize={12} type={'secondary'}>
+ {t('goalProcess.findings.from', { title: view.producedBy.title })}
+ </Text>
+ </Flexbox>
+ )}
+ </Flexbox>
+ )}
+ </Flexbox>
+ );
+ },
+);
+
+FindingRow.displayName = 'GoalFindingRow';
+
+const Findings = memo<{ graph: GoalGraphView; onSelect: (nodeId: string) => void }>(
+ ({ graph, onSelect }) => {
+ const { t } = useTranslation('chat');
+ const findings = [...graph.findings].sort(
+ (a, b) =>
+ (b.node.resolvedAt ?? b.node.createdAt).getTime() -
+ (a.node.resolvedAt ?? a.node.createdAt).getTime(),
+ );
+
+ if (findings.length === 0)
+ return (
+ <Text fontSize={13} type={'secondary'}>
+ {t('goalProcess.findings.empty')}
+ </Text>
+ );
+
+ return (
+ <Flexbox gap={0}>
+ {findings.map((view) => (
+ <FindingRow key={view.node.id} view={view} onSelect={onSelect} />
+ ))}
+ </Flexbox>
+ );
+ },
+);
+
+Findings.displayName = 'GoalFindings';
+
+export default Findings;
diff --git a/src/features/AgentGoals/ProcessControl/Frontier.tsx b/src/features/AgentGoals/ProcessControl/Frontier.tsx
new file mode 100644
index 00000000000..c614d1e753e
--- /dev/null
+++ b/src/features/AgentGoals/ProcessControl/Frontier.tsx
@@ -0,0 +1,555 @@
+'use client';
+
+import type { GoalDecisionOption } from '@lobechat/types';
+import { Block, Flexbox, Icon, TextArea, Tooltip } from '@lobehub/ui';
+import { Button, Tag, Text } from '@lobehub/ui/base-ui';
+import { Divider } from 'antd';
+import { createStaticStyles, cssVar } from 'antd-style';
+import { ChevronDown, ChevronRight, Plus } from 'lucide-react';
+import { Fragment, memo, useState } from 'react';
+import { useTranslation } from 'react-i18next';
+
+import { TASK_STATUS_VISUALS } from '@/components/ExecutionStatus';
+import RunningGlyph from '@/features/Home/components/RunningGlyph';
+import { useActivityTime } from '@/hooks/useActivityTime';
+
+import type { FrontierItem, GoalGraphView, GoalNodeView } from './goalGraphViewModel';
+import { useElapsed } from './useElapsed';
+
+/**
+ * 当前任务 — one row per thing that can change state now, in the AgentTaskItem
+ * shape: `#n · glyph · title · state tag · … · actions`. Rows that need a human
+ * open their whole case in place (why it stopped, what each option costs, the
+ * attempt ledger) instead of truncating it onto the title line. Just-finished
+ * tasks stay at the top, dimmed, so the list fades rather than items vanishing;
+ * blocked ones fold at the bottom and reference blockers by the same numbers
+ * the rows carry.
+ */
+
+const styles = createStaticStyles(({ css }) => ({
+ attempt: css`
+ padding-block: 6px;
+
+ & + & {
+ border-block-start: 1px dashed ${cssVar.colorBorderSecondary};
+ }
+ `,
+ blockedHead: css`
+ cursor: pointer;
+ user-select: none;
+
+ display: flex;
+ gap: 6px;
+ align-items: center;
+
+ padding-block: 8px;
+ padding-inline: 12px;
+
+ font-size: 12px;
+ color: ${cssVar.colorTextTertiary};
+
+ &:hover {
+ color: ${cssVar.colorTextSecondary};
+ }
+ `,
+ body: css`
+ padding-block: 2px 14px;
+ padding-inline: 46px 12px;
+ `,
+ deps: css`
+ font-family: ${cssVar.fontFamilyCode};
+ font-size: 12px;
+ color: ${cssVar.colorTextQuaternary};
+ `,
+ dim: css`
+ opacity: 0.55;
+ transition: opacity 0.15s;
+
+ &:hover {
+ opacity: 1;
+ }
+ `,
+ label: css`
+ font-size: 12px;
+ font-weight: 600;
+ color: ${cssVar.colorTextSecondary};
+ `,
+ list: css`
+ overflow: hidden;
+ border: 1px solid ${cssVar.colorBorderSecondary};
+ border-radius: ${cssVar.borderRadius};
+ background: ${cssVar.colorBgContainer};
+ `,
+ mono: css`
+ font-family: ${cssVar.fontFamilyCode};
+ font-variant-numeric: tabular-nums;
+ `,
+ num: css`
+ flex: none;
+
+ min-width: 22px;
+
+ font-family: ${cssVar.fontFamilyCode};
+ font-size: 12px;
+ color: ${cssVar.colorTextQuaternary};
+ `,
+ option: css`
+ display: grid;
+ grid-template-columns: 128px 1fr;
+ gap: 8px;
+ align-items: baseline;
+ `,
+}));
+
+export interface FrontierActions {
+ addTask: (title: string) => Promise<void>;
+ advance: () => void;
+ decide: (decisionId: string, optionId: string, resolution?: string) => void;
+}
+
+interface FrontierProps {
+ actions: FrontierActions;
+ canEdit: boolean;
+ graph: GoalGraphView;
+ onSelect: (nodeId: string) => void;
+}
+
+/** Server option ids are stable; their labels are English strings from the coordinator. */
+const useOptionLabel = () => {
+ const { t } = useTranslation('chat');
+ return (option: GoalDecisionOption) => {
+ switch (option.id) {
+ case 'fail': {
+ return t('goalProcess.gate.option.fail');
+ }
+ case 'retire': {
+ return t('goalProcess.gate.option.retire');
+ }
+ case 'retry': {
+ return t('goalProcess.gate.option.retry');
+ }
+ default: {
+ return option.label;
+ }
+ }
+ };
+};
+
+const RowGlyph = memo<{ kind: FrontierItem['kind']; view: GoalNodeView }>(({ kind, view }) => {
+ switch (kind) {
+ case 'done': {
+ const visual =
+ view.node.status === 'resolved'
+ ? TASK_STATUS_VISUALS.completed
+ : TASK_STATUS_VISUALS.canceled;
+ return <Icon color={visual.color} icon={visual.icon} size={16} />;
+ }
+ case 'gate': {
+ return (
+ <Icon
+ color={TASK_STATUS_VISUALS.paused.color}
+ icon={TASK_STATUS_VISUALS.paused.icon}
+ size={16}
+ />
+ );
+ }
+ case 'running': {
+ return <RunningGlyph size={16} />;
+ }
+ case 'stale': {
+ return (
+ <Icon
+ color={TASK_STATUS_VISUALS.failed.color}
+ icon={TASK_STATUS_VISUALS.failed.icon}
+ size={16}
+ />
+ );
+ }
+ default: {
+ return (
+ <Icon
+ color={TASK_STATUS_VISUALS.backlog.color}
+ icon={TASK_STATUS_VISUALS.backlog.icon}
+ size={16}
+ />
+ );
+ }
+ }
+});
+
+RowGlyph.displayName = 'GoalFrontierRowGlyph';
+
+const AttemptLedger = memo<{ view: GoalNodeView }>(({ view }) => {
+ const { t } = useTranslation('chat');
+ if (view.attempts.length === 0) return null;
+
+ return (
+ <Flexbox gap={0}>
+ <span className={styles.label}>{t('goalProcess.attempts.title')}</span>
+ {view.attempts.map((attempt) => (
+ <Flexbox
+ horizontal
+ align={'baseline'}
+ className={styles.attempt}
+ gap={10}
+ key={attempt.index}
+ >
+ <Text
+ className={styles.mono}
+ fontSize={12}
+ style={{ flex: 'none', width: 60 }}
+ type={'secondary'}
+ >
+ {t('goalProcess.attempts.nth', { index: attempt.index })}
+ </Text>
+ <Text
+ fontSize={12}
+ style={{ flex: 'none' }}
+ type={
+ attempt.outcome === 'passed'
+ ? 'success'
+ : attempt.outcome === 'failed'
+ ? 'danger'
+ : 'secondary'
+ }
+ >
+ {t(`goalProcess.attempts.${attempt.outcome}` as const)}
+ </Text>
+ <Text ellipsis fontSize={12} style={{ flex: 1, minWidth: 0 }} type={'secondary'}>
+ {attempt.reason ?? ''}
+ </Text>
+ </Flexbox>
+ ))}
+ </Flexbox>
+ );
+});
+
+AttemptLedger.displayName = 'GoalAttemptLedger';
+
+/** The running clock lives in its own component so the 1s tick never re-renders the list. */
+const RunningClock = memo<{ startedAt?: Date }>(({ startedAt }) => {
+ const elapsed = useElapsed(startedAt);
+ if (!elapsed) return null;
+ return (
+ <Text className={styles.mono} fontSize={12} type={'secondary'}>
+ {elapsed}
+ </Text>
+ );
+});
+
+RunningClock.displayName = 'GoalRunningClock';
+
+const DoneTime = memo<{ view: GoalNodeView }>(({ view }) => {
+ const { text, title } = useActivityTime(view.node.resolvedAt ?? view.node.updatedAt);
+ return (
+ <Text className={styles.mono} fontSize={12} title={title} type={'secondary'}>
+ {text || '—'}
+ </Text>
+ );
+});
+
+DoneTime.displayName = 'GoalDoneTime';
+
+const StaleBody = memo<{ view: GoalNodeView }>(({ view }) => {
+ const { t } = useTranslation('chat');
+ const { text } = useActivityTime(view.node.updatedAt);
+ return (
+ <Text fontSize={13} type={'secondary'}>
+ {t('goalProcess.stale.description', { duration: text })}
+ </Text>
+ );
+});
+
+StaleBody.displayName = 'GoalStaleBody';
+
+const FrontierRow = memo<{
+ actions: FrontierActions;
+ canEdit: boolean;
+ item: FrontierItem;
+ numbers: Map<string, number>;
+ onSelect: (nodeId: string) => void;
+ /** A gate's ledger is the ledger of the Work it was opened for. */
+ subject?: GoalNodeView;
+}>(({ actions, canEdit, item, numbers, onSelect, subject }) => {
+ const { t } = useTranslation('chat');
+ const optionLabel = useOptionLabel();
+ const [note, setNote] = useState('');
+ const { view } = item;
+ const { node } = view;
+ const deps = view.dependsOn.map((id) => numbers.get(id)).filter(Boolean);
+
+ const tag =
+ item.kind === 'gate'
+ ? { color: 'warning', text: t('goalProcess.tag.needsDecision') }
+ : item.kind === 'stale'
+ ? { color: 'error', text: t('goalProcess.tag.lost') }
+ : item.kind === 'done'
+ ? {
+ color: undefined,
+ text:
+ node.status === 'resolved'
+ ? t('goalProcess.tag.done')
+ : t('goalProcess.tag.retired'),
+ }
+ : null;
+
+ const stop = (event: React.MouseEvent) => event.stopPropagation();
+
+ return (
+ <Block
+ clickable
+ className={item.kind === 'done' ? styles.dim : undefined}
+ padding={12}
+ variant={'borderless'}
+ onClick={() => onSelect(node.id)}
+ >
+ <Flexbox horizontal align={'center'} gap={10}>
+ {view.seq !== undefined && <span className={styles.num}>#{view.seq}</span>}
+ <RowGlyph kind={item.kind} view={view} />
+ <Text ellipsis style={{ flexShrink: 1, maxWidth: '60%', minWidth: 0 }} weight={500}>
+ {node.title}
+ </Text>
+ {tag && (
+ <Tag color={tag.color} size={'small'}>
+ {tag.text}
+ </Tag>
+ )}
+ {deps.length > 0 && (
+ <span className={styles.deps}>
+ {t('goalProcess.frontier.dependsOn', { refs: deps.map((d) => `#${d}`).join(' ') })}
+ </span>
+ )}
+ <Flexbox flex={1} />
+ <Flexbox horizontal align={'center'} gap={8} style={{ flex: 'none' }}>
+ {item.kind === 'running' && <RunningClock startedAt={view.startedAt} />}
+ {item.kind === 'done' && <DoneTime view={view} />}
+ {item.kind === 'stale' && canEdit && (
+ <Button
+ size={'small'}
+ type={'primary'}
+ onClick={(event) => {
+ stop(event);
+ actions.advance();
+ }}
+ >
+ {t('goalProcess.advance.label')}
+ </Button>
+ )}
+ {item.kind === 'gate' &&
+ canEdit &&
+ view.decision?.options?.map((option) => (
+ <Tooltip key={option.id} title={option.description}>
+ <Button
+ size={'small'}
+ type={option.id === view.decision?.recommendedOptionId ? 'primary' : 'default'}
+ onClick={(event) => {
+ stop(event);
+ actions.decide(view.decision!.id, option.id, note.trim() || undefined);
+ }}
+ >
+ {optionLabel(option)}
+ </Button>
+ </Tooltip>
+ ))}
+ </Flexbox>
+ </Flexbox>
+
+ {item.rank === 0 && (
+ <Flexbox className={styles.body} gap={12} onClick={stop}>
+ {item.kind === 'gate' && view.decision && (
+ <>
+ <Flexbox gap={4}>
+ <span className={styles.label}>{t('goalProcess.gate.why')}</span>
+ <Text fontSize={13}>{view.decision.question}</Text>
+ </Flexbox>
+ {!!view.decision.options?.length && (
+ <Flexbox gap={6}>
+ <span className={styles.label}>{t('goalProcess.gate.options')}</span>
+ {view.decision.options.map((option) => (
+ <div className={styles.option} key={option.id}>
+ <Text fontSize={13} weight={500}>
+ {optionLabel(option)}
+ {option.id === view.decision?.recommendedOptionId
+ ? `(${t('goalProcess.gate.recommended')})`
+ : ''}
+ </Text>
+ <Text fontSize={13} type={'secondary'}>
+ {option.description ?? ''}
+ </Text>
+ </div>
+ ))}
+ </Flexbox>
+ )}
+ </>
+ )}
+ {item.kind === 'stale' && <StaleBody view={view} />}
+ <AttemptLedger view={subject ?? view} />
+ {item.kind === 'gate' && canEdit && (
+ <Flexbox gap={4}>
+ <span className={styles.label}>{t('goalProcess.gate.noteLabel')}</span>
+ <TextArea
+ autoSize={{ maxRows: 3, minRows: 1 }}
+ placeholder={t('goalProcess.gate.notePlaceholder')}
+ value={note}
+ onChange={(event) => setNote(event.target.value)}
+ />
+ </Flexbox>
+ )}
+ </Flexbox>
+ )}
+ </Block>
+ );
+});
+
+FrontierRow.displayName = 'GoalFrontierRow';
+
+const AddTaskRow = memo<{ onAdd: (title: string) => Promise<void> }>(({ onAdd }) => {
+ const { t } = useTranslation('chat');
+ const [open, setOpen] = useState(false);
+ const [title, setTitle] = useState('');
+ const [busy, setBusy] = useState(false);
+
+ const submit = async () => {
+ if (!title.trim() || busy) return;
+ setBusy(true);
+ try {
+ await onAdd(title.trim());
+ setTitle('');
+ setOpen(false);
+ } finally {
+ setBusy(false);
+ }
+ };
+
+ if (!open)
+ return (
+ <Button
+ icon={<Icon icon={Plus} />}
+ size={'small'}
+ type={'text'}
+ onClick={() => setOpen(true)}
+ >
+ {t('goalProcess.frontier.add')}
+ </Button>
+ );
+
+ return (
+ <Flexbox horizontal align={'center'} gap={8}>
+ <TextArea
+ autoFocus
+ autoSize={{ maxRows: 2, minRows: 1 }}
+ placeholder={t('goalProcess.frontier.add')}
+ style={{ width: 260 }}
+ value={title}
+ onChange={(event) => setTitle(event.target.value)}
+ onPressEnter={(event) => {
+ event.preventDefault();
+ void submit();
+ }}
+ />
+ <Button
+ disabled={!title.trim()}
+ loading={busy}
+ size={'small'}
+ type={'primary'}
+ onClick={submit}
+ >
+ {t('goalProcess.frontier.add')}
+ </Button>
+ </Flexbox>
+ );
+});
+
+AddTaskRow.displayName = 'GoalAddTaskRow';
+
+const Frontier = memo<FrontierProps>(({ actions, canEdit, graph, onSelect }) => {
+ const { t } = useTranslation('chat');
+ const [showBlocked, setShowBlocked] = useState(false);
+
+ const numbers = new Map(
+ graph.nodes.filter((view) => view.seq !== undefined).map((view) => [view.node.id, view.seq!]),
+ );
+ const achieved = graph.goal.status === 'achieved';
+
+ return (
+ <Flexbox gap={8}>
+ <Flexbox horizontal align={'baseline'} justify={'space-between'}>
+ <Flexbox horizontal align={'baseline'} gap={8}>
+ <Text fontSize={16} weight={600}>
+ {t('goalProcess.frontier.title')}
+ </Text>
+ {graph.frontier.length > 0 && (
+ <Text fontSize={12} type={'secondary'}>
+ {graph.needsYou > 0
+ ? `${t('goalProcess.frontier.needsYou', { count: graph.needsYou })} · `
+ : ''}
+ {t('goalProcess.frontier.advanceable', { count: graph.advanceable })}
+ </Text>
+ )}
+ </Flexbox>
+ {canEdit && <AddTaskRow onAdd={actions.addTask} />}
+ </Flexbox>
+
+ <div className={styles.list}>
+ <Block gap={0} padding={2} variant={'borderless'}>
+ {graph.frontier.length === 0 && (
+ <Flexbox gap={2} padding={12}>
+ <Text weight={500}>
+ {achieved
+ ? t('goalProcess.frontier.achievedTitle')
+ : t('goalProcess.frontier.emptyTitle')}
+ </Text>
+ <Text fontSize={12} type={'secondary'}>
+ {achieved
+ ? t('goalProcess.frontier.achievedDescription')
+ : t('goalProcess.frontier.emptyDescription')}
+ </Text>
+ </Flexbox>
+ )}
+ {graph.frontier.map((item, index) => (
+ <Fragment key={item.key}>
+ {index > 0 && <Divider dashed style={{ margin: 0 }} />}
+ <FrontierRow
+ actions={actions}
+ canEdit={canEdit}
+ item={item}
+ numbers={numbers}
+ subject={item.view.gateSubjectId ? graph.byId[item.view.gateSubjectId] : undefined}
+ onSelect={onSelect}
+ />
+ </Fragment>
+ ))}
+ </Block>
+ {graph.blocked.length > 0 && (
+ <>
+ <Divider dashed style={{ margin: 0 }} />
+ <div className={styles.blockedHead} onClick={() => setShowBlocked(!showBlocked)}>
+ <Icon icon={showBlocked ? ChevronDown : ChevronRight} size={12} />
+ <span>{t('goalProcess.frontier.blocked', { count: graph.blocked.length })}</span>
+ </div>
+ {showBlocked && (
+ <Block gap={0} padding={2} variant={'borderless'}>
+ {graph.blocked.map((view, index) => (
+ <Fragment key={view.node.id}>
+ {index > 0 && <Divider dashed style={{ margin: 0 }} />}
+ <FrontierRow
+ actions={actions}
+ canEdit={canEdit}
+ item={{ key: view.node.id, kind: 'ready', rank: 3, view }}
+ numbers={numbers}
+ onSelect={onSelect}
+ />
+ </Fragment>
+ ))}
+ </Block>
+ )}
+ </>
+ )}
+ </div>
+ </Flexbox>
+ );
+});
+
+Frontier.displayName = 'GoalFrontier';
+
+export default Frontier;
diff --git a/src/features/AgentGoals/ProcessControl/Graph/GraphNode.tsx b/src/features/AgentGoals/ProcessControl/Graph/GraphNode.tsx
new file mode 100644
index 00000000000..7b8b60a367c
--- /dev/null
+++ b/src/features/AgentGoals/ProcessControl/Graph/GraphNode.tsx
@@ -0,0 +1,285 @@
+'use client';
+
+import { Flexbox, Icon, Tooltip } from '@lobehub/ui';
+import { Text } from '@lobehub/ui/base-ui';
+import { Handle, type NodeProps, Position } from '@xyflow/react';
+import { createStaticStyles, cssVar, cx } from 'antd-style';
+import { FileBox, Repeat2, ShieldCheck } from 'lucide-react';
+import { memo } from 'react';
+import { useTranslation } from 'react-i18next';
+
+import { TASK_STATUS_VISUALS } from '@/components/ExecutionStatus';
+
+import type { GoalNodeView } from '../goalGraphViewModel';
+import { KIND_COLOR, KIND_ICON } from '../shared';
+import { useElapsed } from '../useElapsed';
+
+/**
+ * A graph card: leading kind icon on a tinted square, title plus a one-line
+ * subtitle, a state chip on the top edge, and — for a task — a metric strip
+ * (attempts · verifier · artifacts · running clock) so the map answers "who is
+ * on it, has it been checked, did it produce anything" without opening a node.
+ */
+
+export interface GraphNodeData extends Record<string, unknown> {
+ dim: boolean;
+ isGate: boolean;
+ running: boolean;
+ selected: boolean;
+ stale: boolean;
+ subtitle: string;
+ view: GoalNodeView;
+}
+
+const styles = createStaticStyles(({ css }) => ({
+ card: css`
+ box-sizing: border-box;
+ width: 100%;
+ border: 1px solid ${cssVar.colorBorderSecondary};
+ border-radius: ${cssVar.borderRadiusLG};
+
+ background: ${cssVar.colorBgContainer};
+
+ transition:
+ opacity 0.2s,
+ border-color 0.15s;
+ `,
+ chipDot: css`
+ flex: none;
+ width: 5px;
+ height: 5px;
+ border-radius: 50%;
+ `,
+ chipText: css`
+ font-size: 11px;
+ line-height: 16px;
+ white-space: nowrap;
+ `,
+ dim: css`
+ opacity: 0.45;
+ `,
+ gate: css`
+ border-color: ${cssVar.colorWarningBorder};
+ background: ${cssVar.colorWarningBg};
+ `,
+ glyph: css`
+ display: flex;
+ flex: none;
+ align-items: center;
+ justify-content: center;
+
+ width: 30px;
+ height: 30px;
+ border-radius: ${cssVar.borderRadius};
+ `,
+ handle: css`
+ width: 1px;
+ min-width: 0;
+ height: 1px;
+ min-height: 0;
+ border: none;
+
+ opacity: 0;
+ `,
+ head: css`
+ display: flex;
+ gap: 10px;
+ align-items: flex-start;
+
+ padding-block: 10px;
+ padding-inline: 12px;
+ `,
+ human: css`
+ display: flex;
+ flex: none;
+ align-items: center;
+ justify-content: center;
+
+ width: 16px;
+ height: 16px;
+ border-radius: 50%;
+
+ font-size: 9px;
+ font-weight: 600;
+ color: ${cssVar.colorTextTertiary};
+
+ background: ${cssVar.colorFillTertiary};
+ `,
+ metric: css`
+ display: flex;
+ gap: 4px;
+ align-items: center;
+ `,
+ metrics: css`
+ display: flex;
+ gap: 12px;
+ align-items: center;
+
+ padding-block: 6px;
+ padding-inline: 12px;
+ border-block-start: 1px dashed ${cssVar.colorBorderSecondary};
+
+ font-family: ${cssVar.fontFamilyCode};
+ font-size: 11px;
+ font-variant-numeric: tabular-nums;
+ color: ${cssVar.colorTextTertiary};
+ `,
+ selected: css`
+ border-color: ${cssVar.colorPrimaryBorder};
+ `,
+ stale: css`
+ border-color: ${cssVar.colorErrorBorder};
+ `,
+ subtitle: css`
+ overflow: hidden;
+
+ font-size: 11px;
+ color: ${cssVar.colorTextTertiary};
+ text-overflow: ellipsis;
+ white-space: nowrap;
+ `,
+ title: css`
+ font-size: 13px;
+ font-weight: 500;
+ line-height: 1.35;
+ `,
+}));
+
+const useStateChip = (data: GraphNodeData): { color: string; text: string } | null => {
+ const { t } = useTranslation('chat');
+ const { isGate, running, stale, view } = data;
+ const { node } = view;
+
+ if (isGate) return { color: cssVar.colorWarning, text: t('goalProcess.tag.needsDecision') };
+ if (stale) return { color: cssVar.colorError, text: t('goalProcess.tag.lost') };
+ if (running) return { color: cssVar.colorInfo, text: t('goalProcess.node.running') };
+ if (node.kind === 'work' && node.status === 'resolved')
+ return { color: cssVar.colorSuccess, text: t('goalProcess.node.done') };
+ if (node.kind === 'work' && (node.status === 'retired' || node.status === 'rejected'))
+ return { color: cssVar.colorTextTertiary, text: t('goalProcess.tag.retired') };
+ if (node.kind === 'decision' && node.status === 'resolved')
+ return {
+ color: cssVar.colorTextTertiary,
+ text: view.humanTouches.length
+ ? t('goalProcess.node.decidedByYou')
+ : t('goalProcess.node.decidedByAgent'),
+ };
+ return null;
+};
+
+const RunningClock = memo<{ startedAt?: Date }>(({ startedAt }) => {
+ const elapsed = useElapsed(startedAt);
+ if (!elapsed) return null;
+ return <span style={{ marginInlineStart: 'auto' }}>{elapsed}</span>;
+});
+
+RunningClock.displayName = 'GoalGraphRunningClock';
+
+const GraphNodeView = memo<NodeProps>(({ data }) => {
+ const { t } = useTranslation('chat');
+ const nodeData = data as GraphNodeData;
+ const { dim, isGate, running, selected, stale, subtitle, view } = nodeData;
+ const { node } = view;
+ const chip = useStateChip(nodeData);
+ const palette = KIND_COLOR[node.kind];
+ const isWork = node.kind === 'work';
+ const attempts = view.attempts.length;
+
+ return (
+ <div style={{ position: 'relative' }}>
+ <Handle
+ className={styles.handle}
+ isConnectable={false}
+ position={Position.Top}
+ type={'target'}
+ />
+ <div
+ className={cx(
+ styles.card,
+ isGate && styles.gate,
+ stale && styles.stale,
+ dim && styles.dim,
+ selected && styles.selected,
+ )}
+ >
+ <div className={styles.head}>
+ <div className={styles.glyph} style={{ background: palette.soft, color: palette.line }}>
+ <Icon icon={KIND_ICON[node.kind]} size={16} />
+ </div>
+ <Flexbox gap={2} style={{ flex: 1, minWidth: 0 }}>
+ <span className={styles.title}>{node.title}</span>
+ {subtitle && <span className={styles.subtitle}>{subtitle}</span>}
+ </Flexbox>
+ {/* State and human participation sit inside the card, on the header's
+ trailing edge. Floating them on the card's outline collided with
+ the edges and arrowheads routed around it. */}
+ <Flexbox horizontal align={'center'} gap={6} style={{ flex: 'none' }}>
+ {view.humanTouches.length > 0 && (
+ <Tooltip title={t('goalProcess.node.humanTouched')}>
+ <span className={styles.human}>@</span>
+ </Tooltip>
+ )}
+ {chip && (
+ <Flexbox horizontal align={'center'} gap={4}>
+ <span className={styles.chipDot} style={{ background: chip.color }} />
+ <span className={styles.chipText} style={{ color: chip.color }}>
+ {chip.text}
+ </span>
+ </Flexbox>
+ )}
+ </Flexbox>
+ </div>
+ {isWork && (
+ <div className={styles.metrics}>
+ {node.taskId ? (
+ <Tooltip title={t('goalProcess.node.verifierTooltip')}>
+ <span className={styles.metric}>
+ <Icon icon={ShieldCheck} size={13} />
+ {t('goalProcess.node.verifier')}
+ </span>
+ </Tooltip>
+ ) : (
+ <span className={styles.metric}>
+ <Icon
+ color={TASK_STATUS_VISUALS.backlog.color}
+ icon={TASK_STATUS_VISUALS.backlog.icon}
+ size={13}
+ />
+ <Text fontSize={11} type={'secondary'}>
+ {t('goalProcess.node.unassigned')}
+ </Text>
+ </span>
+ )}
+ <Tooltip title={t('goalProcess.node.attemptsTooltip', { count: attempts })}>
+ <span className={styles.metric}>
+ <Icon icon={Repeat2} size={13} />
+ {attempts}
+ </span>
+ </Tooltip>
+ {view.artifactCount > 0 && (
+ <Tooltip
+ title={t('goalProcess.node.artifactsTooltip', { count: view.artifactCount })}
+ >
+ <span className={styles.metric}>
+ <Icon icon={FileBox} size={13} />
+ {view.artifactCount}
+ </span>
+ </Tooltip>
+ )}
+ {running && <RunningClock startedAt={view.startedAt} />}
+ </div>
+ )}
+ </div>
+ <Handle
+ className={styles.handle}
+ isConnectable={false}
+ position={Position.Bottom}
+ type={'source'}
+ />
+ </div>
+ );
+});
+
+GraphNodeView.displayName = 'GoalGraphNodeView';
+
+export default GraphNodeView;
diff --git a/src/features/AgentGoals/ProcessControl/Graph/index.tsx b/src/features/AgentGoals/ProcessControl/Graph/index.tsx
new file mode 100644
index 00000000000..db6ccd23c03
--- /dev/null
+++ b/src/features/AgentGoals/ProcessControl/Graph/index.tsx
@@ -0,0 +1,374 @@
+'use client';
+
+import '@xyflow/react/dist/style.css';
+
+import type { GoalGraphEdge, GoalGraphNode } from '@lobechat/types';
+import { Flexbox } from '@lobehub/ui';
+import { ActionIcon, Segmented, Text } from '@lobehub/ui/base-ui';
+import {
+ Background,
+ BackgroundVariant,
+ Controls,
+ type Edge as FlowEdge,
+ MarkerType,
+ type Node as FlowNode,
+ ReactFlow,
+ ReactFlowProvider,
+ useReactFlow,
+} from '@xyflow/react';
+import { createStaticStyles, cssVar, cx } from 'antd-style';
+import { Maximize2, X } from 'lucide-react';
+import { memo, useCallback, useEffect, useMemo, useState } from 'react';
+import { useTranslation } from 'react-i18next';
+
+import type { GoalGraphView, GoalNodeView } from '../goalGraphViewModel';
+import { KindDot } from '../shared';
+import GraphNodeView, { type GraphNodeData } from './GraphNode';
+import { layoutGraph, NODE_WIDTH } from './layout';
+
+/**
+ * The exploration map. Two views: 当前阶段 (what got the goal here plus what the
+ * next advance unlocks) and 全图. Edges carry their relation as a label so the
+ * map reads without a legend; fullscreen is a real overlay, not a taller box.
+ */
+
+const styles = createStaticStyles(({ css }) => ({
+ canvas: css`
+ width: 100%;
+ height: 560px;
+
+ .react-flow__attribution {
+ display: none;
+ }
+
+ .react-flow__edge-path {
+ stroke: ${cssVar.colorBorder};
+ stroke-width: 1.25;
+ }
+
+ .react-flow__edge.goal-dep .react-flow__edge-path {
+ stroke-dasharray: 5 4;
+ }
+
+ .react-flow__edge.goal-hot .react-flow__edge-path {
+ stroke: ${cssVar.colorPrimary};
+ stroke-width: 1.75;
+ }
+
+ .react-flow__edge-textbg {
+ fill: ${cssVar.colorBgLayout};
+ }
+
+ .react-flow__edge-text {
+ font-size: 10px;
+ fill: ${cssVar.colorTextTertiary};
+ }
+
+ .react-flow__controls-button {
+ border-color: ${cssVar.colorBorderSecondary};
+ background: ${cssVar.colorBgContainer};
+ fill: ${cssVar.colorTextSecondary};
+
+ &:hover {
+ background: ${cssVar.colorFillTertiary};
+ }
+ }
+ `,
+ full: css`
+ height: 100%;
+ `,
+ legend: css`
+ font-size: 12px;
+ color: ${cssVar.colorTextTertiary};
+ `,
+ overlay: css`
+ position: fixed;
+ z-index: 1000;
+ inset: 0;
+
+ display: flex;
+ flex-direction: column;
+
+ padding-block: 12px 16px;
+ padding-inline: 24px;
+
+ background: ${cssVar.colorBgLayout};
+ `,
+}));
+
+type GraphViewMode = 'stage' | 'all';
+
+interface GraphProps {
+ graph: GoalGraphView;
+ onSelect: (nodeId: string) => void;
+ selectedId?: string;
+}
+
+/** `depends_on` is drawn blocker → blocked so the map always reads downward. */
+const orient = (edge: GoalGraphEdge): [string, string] =>
+ edge.kind === 'depends_on'
+ ? [edge.targetNodeId, edge.sourceNodeId]
+ : [edge.sourceNodeId, edge.targetNodeId];
+
+/** The nodes worth showing before the user asks for the whole map. */
+const stageNodeIds = (graph: GoalGraphView): Set<string> => {
+ const active = new Set<string>();
+ for (const view of graph.nodes) if (view.node.status !== 'proposed') active.add(view.node.id);
+ for (const item of graph.frontier) active.add(item.view.node.id);
+ const visible = new Set(active);
+ for (const view of graph.blocked)
+ if (view.blockers.every((blocker) => active.has(blocker.id))) visible.add(view.node.id);
+ return visible;
+};
+
+const useSubtitle = () => {
+ const { t } = useTranslation('chat');
+ return useCallback(
+ (view: GoalNodeView): string => {
+ const { node } = view;
+ switch (node.kind) {
+ case 'decision': {
+ return node.status === 'waiting'
+ ? t('goalProcess.tag.needsDecision')
+ : (view.humanTouches[0]?.resolution ?? node.description?.slice(0, 32) ?? '');
+ }
+ case 'finding': {
+ return view.producedBy?.title ?? '';
+ }
+ case 'problem': {
+ return node.status === 'resolved'
+ ? t('goalProcess.node.answered')
+ : t('goalProcess.node.unanswered');
+ }
+ default: {
+ return node.description?.slice(0, 34) ?? '';
+ }
+ }
+ },
+ [t],
+ );
+};
+
+const useEdgeLabel = () => {
+ const { t } = useTranslation('chat');
+ return useCallback(
+ (kind: GoalGraphEdge['kind']): string | undefined => {
+ switch (kind) {
+ case 'contradicts': {
+ return t('goalProcess.edge.contradicts');
+ }
+ case 'depends_on': {
+ return t('goalProcess.edge.dependsOn');
+ }
+ case 'investigates': {
+ return t('goalProcess.edge.investigates');
+ }
+ case 'leads_to': {
+ return t('goalProcess.edge.leadsTo');
+ }
+ case 'produces': {
+ return t('goalProcess.edge.produces');
+ }
+ case 'supports': {
+ return t('goalProcess.edge.supports');
+ }
+ // `decomposes` is the skeleton of the map; labelling every branch edge is noise.
+ default: {
+ return undefined;
+ }
+ }
+ },
+ [t],
+ );
+};
+
+const nodeTypes = { goalNode: GraphNodeView };
+
+const Canvas = memo<GraphProps & { className: string; interactive: boolean; view: GraphViewMode }>(
+ ({ className, graph, interactive, onSelect, selectedId, view }) => {
+ const { fitView } = useReactFlow();
+ const subtitleOf = useSubtitle();
+ const edgeLabel = useEdgeLabel();
+
+ const visibleIds = useMemo(
+ () =>
+ view === 'all' ? new Set(graph.nodes.map((item) => item.node.id)) : stageNodeIds(graph),
+ [graph, view],
+ );
+ const positions = useMemo(() => {
+ const nodes: GoalGraphNode[] = graph.nodes
+ .filter((item) => visibleIds.has(item.node.id))
+ .map((item) => item.node);
+ const edges = graph.edges.filter(
+ (edge) => visibleIds.has(edge.sourceNodeId) && visibleIds.has(edge.targetNodeId),
+ );
+ return layoutGraph(nodes, edges);
+ }, [graph, visibleIds]);
+
+ const flowNodes: FlowNode[] = useMemo(
+ () =>
+ graph.nodes
+ .filter((item) => visibleIds.has(item.node.id))
+ .map((item) => {
+ const box = positions[item.node.id];
+ const isGate = item.node.kind === 'decision' && item.node.status === 'waiting';
+ const data: GraphNodeData = {
+ // Not started and still blocked — it is context, not the story.
+ dim: item.node.status === 'proposed' && item.blockers.length > 0,
+ isGate,
+ running: item.node.status === 'active' && !item.isStale,
+ selected: selectedId === item.node.id,
+ stale: item.isStale,
+ subtitle: subtitleOf(item),
+ view: item,
+ };
+ return {
+ data,
+ draggable: false,
+ id: item.node.id,
+ position: { x: box?.x ?? 0, y: box?.y ?? 0 },
+ type: 'goalNode',
+ width: NODE_WIDTH[item.node.kind],
+ } satisfies FlowNode;
+ }),
+ [graph, visibleIds, positions, selectedId, subtitleOf],
+ );
+
+ const flowEdges: FlowEdge[] = useMemo(
+ () =>
+ graph.edges
+ .filter((edge) => visibleIds.has(edge.sourceNodeId) && visibleIds.has(edge.targetNodeId))
+ .map((edge) => {
+ const [source, target] = orient(edge);
+ const hot = selectedId === edge.sourceNodeId || selectedId === edge.targetNodeId;
+ return {
+ className: cx(edge.kind === 'depends_on' && 'goal-dep', hot && 'goal-hot'),
+ id: edge.id,
+ label: edgeLabel(edge.kind),
+ labelShowBg: true,
+ markerEnd: {
+ color: cssVar.colorBorder,
+ height: 12,
+ type: MarkerType.ArrowClosed,
+ width: 12,
+ },
+ source,
+ target,
+ type: 'default',
+ } satisfies FlowEdge;
+ }),
+ [graph, visibleIds, selectedId, edgeLabel],
+ );
+
+ useEffect(() => {
+ const timer = setTimeout(
+ () => fitView({ duration: 200, maxZoom: 1, minZoom: 0.6, padding: 0.12 }),
+ 30,
+ );
+ return () => clearTimeout(timer);
+ }, [view, flowNodes.length, fitView]);
+
+ return (
+ <div className={className}>
+ {/* Inline, the map is a picture: it settles on `fitView` and stays
+ there. Panning or zooming it inside a scrolling page moves the graph
+ under the cursor while the page moves too, and leaves no way back to
+ the framing the layout chose. Fullscreen is where it is navigable. */}
+ <ReactFlow
+ fitView
+ edges={flowEdges}
+ maxZoom={interactive ? 1.5 : 1}
+ minZoom={0.3}
+ nodeTypes={nodeTypes}
+ nodes={flowNodes}
+ nodesConnectable={false}
+ nodesDraggable={false}
+ panOnDrag={interactive}
+ panOnScroll={false}
+ preventScrolling={interactive}
+ proOptions={{ hideAttribution: true }}
+ zoomOnDoubleClick={interactive}
+ zoomOnPinch={interactive}
+ zoomOnScroll={interactive}
+ onNodeClick={(_, node) => onSelect(node.id)}
+ >
+ <Background
+ color={cssVar.colorBorderSecondary}
+ gap={18}
+ size={1}
+ variant={BackgroundVariant.Dots}
+ />
+ {interactive && <Controls position={'bottom-right'} showInteractive={false} />}
+ </ReactFlow>
+ </div>
+ );
+ },
+);
+
+Canvas.displayName = 'GoalGraphCanvas';
+
+const Graph = memo<GraphProps>((props) => {
+ const { t } = useTranslation('chat');
+ const [view, setView] = useState<GraphViewMode>('stage');
+ const [fullscreen, setFullscreen] = useState(false);
+
+ const head = (
+ <Flexbox horizontal align={'center'} justify={'space-between'} paddingBlock={4}>
+ <Flexbox horizontal align={'center'} gap={12}>
+ <Text fontSize={16} weight={600}>
+ {t('goalProcess.graph.title')}
+ </Text>
+ <Segmented
+ size={'small'}
+ value={view}
+ options={[
+ { label: t('goalProcess.graph.view.stage'), value: 'stage' },
+ { label: t('goalProcess.graph.view.all'), value: 'all' },
+ ]}
+ onChange={(value) => setView(value as GraphViewMode)}
+ />
+ </Flexbox>
+ <Flexbox horizontal align={'center'} gap={12}>
+ <Flexbox horizontal align={'center'} className={styles.legend} gap={10}>
+ {(['problem', 'work', 'finding', 'decision'] as const).map((kind) => (
+ <Flexbox horizontal align={'center'} gap={4} key={kind}>
+ <KindDot kind={kind} />
+ <span>{t(`goalProcess.kind.${kind}` as const)}</span>
+ </Flexbox>
+ ))}
+ </Flexbox>
+ <ActionIcon
+ icon={fullscreen ? X : Maximize2}
+ size={'small'}
+ title={
+ fullscreen ? t('goalProcess.graph.exitFullscreen') : t('goalProcess.graph.fullscreen')
+ }
+ onClick={() => setFullscreen(!fullscreen)}
+ />
+ </Flexbox>
+ </Flexbox>
+ );
+
+ if (fullscreen)
+ return (
+ <div className={styles.overlay}>
+ {head}
+ <ReactFlowProvider>
+ <Canvas {...props} interactive className={cx(styles.canvas, styles.full)} view={view} />
+ </ReactFlowProvider>
+ </div>
+ );
+
+ return (
+ <Flexbox gap={4}>
+ {head}
+ <ReactFlowProvider>
+ <Canvas {...props} className={styles.canvas} interactive={false} view={view} />
+ </ReactFlowProvider>
+ </Flexbox>
+ );
+});
+
+Graph.displayName = 'GoalExplorationGraph';
+
+export default Graph;
diff --git a/src/features/AgentGoals/ProcessControl/Graph/layout.test.ts b/src/features/AgentGoals/ProcessControl/Graph/layout.test.ts
new file mode 100644
index 00000000000..03e7e49f9e6
--- /dev/null
+++ b/src/features/AgentGoals/ProcessControl/Graph/layout.test.ts
@@ -0,0 +1,80 @@
+import type { GoalGraphEdge, GoalGraphNode } from '@lobechat/types';
+import { describe, expect, it } from 'vitest';
+
+import { layoutGraph } from './layout';
+
+const node = (id: string, kind: GoalGraphNode['kind'] = 'work'): GoalGraphNode => ({
+ confidence: null,
+ createdAt: new Date('2026-08-01T00:00:00Z'),
+ createdByAgentId: null,
+ createdByUserId: null,
+ description: null,
+ goalId: 'g',
+ id,
+ kind,
+ priority: 0,
+ resolvedAt: null,
+ status: 'proposed',
+ taskId: null,
+ title: id,
+ updatedAt: new Date('2026-08-01T00:00:00Z'),
+});
+
+const edge = (
+ sourceNodeId: string,
+ targetNodeId: string,
+ kind: GoalGraphEdge['kind'],
+): GoalGraphEdge => ({
+ createdAt: new Date('2026-08-01T00:00:00Z'),
+ goalId: 'g',
+ id: `${sourceNodeId}-${targetNodeId}`,
+ kind,
+ sourceNodeId,
+ targetNodeId,
+});
+
+describe('layoutGraph', () => {
+ it('puts a decomposed task below the problem it came from', () => {
+ const boxes = layoutGraph(
+ [node('p1', 'problem'), node('w1')],
+ [edge('p1', 'w1', 'decomposes')],
+ );
+
+ expect(boxes.w1.y).toBeGreaterThan(boxes.p1.y);
+ });
+
+ it('puts a blocker above the task waiting on it', () => {
+ const boxes = layoutGraph([node('w1'), node('w2')], [edge('w2', 'w1', 'depends_on')]);
+
+ expect(boxes.w1.y).toBeLessThan(boxes.w2.y);
+ });
+
+ it('does not let a finding-to-problem support edge push the problem down', () => {
+ const boxes = layoutGraph(
+ [node('p1', 'problem'), node('w1'), node('f1', 'finding')],
+ [edge('p1', 'w1', 'decomposes'), edge('w1', 'f1', 'produces'), edge('f1', 'p1', 'supports')],
+ );
+
+ expect(boxes.p1.y).toBeLessThan(boxes.w1.y);
+ expect(boxes.w1.y).toBeLessThan(boxes.f1.y);
+ });
+
+ it('spreads siblings across one row instead of stacking them', () => {
+ const boxes = layoutGraph(
+ [node('p1', 'problem'), node('w1'), node('w2')],
+ [edge('p1', 'w1', 'decomposes'), edge('p1', 'w2', 'decomposes')],
+ );
+
+ expect(boxes.w1.y).toBe(boxes.w2.y);
+ expect(boxes.w1.x).not.toBe(boxes.w2.x);
+ });
+
+ it('terminates on a cycle instead of relaxing forever', () => {
+ const boxes = layoutGraph(
+ [node('w1'), node('w2')],
+ [edge('w1', 'w2', 'leads_to'), edge('w2', 'w1', 'leads_to')],
+ );
+
+ expect(Object.keys(boxes)).toHaveLength(2);
+ });
+});
diff --git a/src/features/AgentGoals/ProcessControl/Graph/layout.ts b/src/features/AgentGoals/ProcessControl/Graph/layout.ts
new file mode 100644
index 00000000000..8ec95fe236b
--- /dev/null
+++ b/src/features/AgentGoals/ProcessControl/Graph/layout.ts
@@ -0,0 +1,116 @@
+import type { GoalGraphEdge, GoalGraphNode } from '@lobechat/types';
+
+/**
+ * Layered DAG layout for the exploration graph.
+ *
+ * The repo has no graph-layout library and the goal graph is small (tens of
+ * nodes) and shaped like a tree, so ranking by longest path plus a barycenter
+ * pass inside each rank is enough. Adding dagre/elk for this would be a new
+ * dependency for a layout that fits in a screen of code.
+ */
+
+export const NODE_WIDTH = { decision: 250, finding: 240, problem: 230, work: 260 } as const;
+export const NODE_HEIGHT = { decision: 76, finding: 76, problem: 76, work: 112 } as const;
+
+const RANK_GAP = 56;
+const COLUMN_GAP = 32;
+
+/**
+ * Which way an edge points on screen. `supports` / `contradicts` link a finding
+ * back to the problem it answers, so they are drawn but never rank a node —
+ * using them would fight the produce chain that put the finding there.
+ */
+const rankDirection = (edge: GoalGraphEdge): [string, string] | undefined => {
+ switch (edge.kind) {
+ case 'decomposes':
+ case 'investigates':
+ case 'leads_to':
+ case 'produces': {
+ return [edge.sourceNodeId, edge.targetNodeId];
+ }
+ // A blocker sits above the node waiting on it.
+ case 'depends_on': {
+ return [edge.targetNodeId, edge.sourceNodeId];
+ }
+ default: {
+ return undefined;
+ }
+ }
+};
+
+export interface LayoutBox {
+ height: number;
+ width: number;
+ x: number;
+ y: number;
+}
+
+export const layoutGraph = (
+ nodes: GoalGraphNode[],
+ edges: GoalGraphEdge[],
+): Record<string, LayoutBox> => {
+ const index = new Map(nodes.map((node, i) => [node.id, i]));
+ const links = edges.map(rankDirection).filter((link): link is [string, string] => {
+ return !!link && index.has(link[0]) && index.has(link[1]);
+ });
+
+ // Longest-path ranking by relaxation. Bounded by node count so a cycle
+ // introduced by a hand-authored edge cannot hang the render.
+ const rank = new Map(nodes.map((node) => [node.id, 0]));
+ for (let pass = 0; pass < nodes.length; pass++) {
+ let changed = false;
+ for (const [from, to] of links) {
+ const next = rank.get(from)! + 1;
+ if (next > rank.get(to)!) {
+ rank.set(to, next);
+ changed = true;
+ }
+ }
+ if (!changed) break;
+ }
+
+ const parents = new Map<string, string[]>();
+ for (const [from, to] of links) parents.set(to, [...(parents.get(to) ?? []), from]);
+
+ const rows = new Map<number, GoalGraphNode[]>();
+ for (const node of nodes) {
+ const r = rank.get(node.id)!;
+ rows.set(r, [...(rows.get(r) ?? []), node]);
+ }
+
+ const boxes: Record<string, LayoutBox> = {};
+ const order = new Map<string, number>();
+ let y = 0;
+ for (const r of [...rows.keys()].sort((a, b) => a - b)) {
+ const row = rows.get(r)!;
+ // Barycenter: sit under the average position of the parents already placed.
+ row.sort(
+ (a, b) =>
+ barycenter(a, parents, order) - barycenter(b, parents, order) ||
+ index.get(a.id)! - index.get(b.id)!,
+ );
+ const widths = row.map((node) => NODE_WIDTH[node.kind]);
+ const total = widths.reduce((sum, w) => sum + w, 0) + COLUMN_GAP * (row.length - 1);
+ let x = -total / 2;
+ let height = 0;
+ row.forEach((node, i) => {
+ boxes[node.id] = { height: NODE_HEIGHT[node.kind], width: widths[i], x, y };
+ order.set(node.id, x + widths[i] / 2);
+ x += widths[i] + COLUMN_GAP;
+ height = Math.max(height, NODE_HEIGHT[node.kind]);
+ });
+ y += height + RANK_GAP;
+ }
+ return boxes;
+};
+
+const barycenter = (
+ node: GoalGraphNode,
+ parents: Map<string, string[]>,
+ placed: Map<string, number>,
+) => {
+ const known = (parents.get(node.id) ?? [])
+ .map((id) => placed.get(id))
+ .filter((v) => v !== undefined);
+ return known.length === 0 ? 0 : known.reduce((sum, v) => sum + v!, 0) / known.length;
+};
diff --git a/src/features/AgentGoals/ProcessControl/goalGraphViewModel.test.ts b/src/features/AgentGoals/ProcessControl/goalGraphViewModel.test.ts
new file mode 100644
index 00000000000..fbfc52999eb
--- /dev/null
+++ b/src/features/AgentGoals/ProcessControl/goalGraphViewModel.test.ts
@@ -0,0 +1,297 @@
+import type {
+ GoalGraphDecision,
+ GoalGraphEdge,
+ GoalGraphEvent,
+ GoalGraphNode,
+ GoalGraphSnapshot,
+ GoalItem,
+} from '@lobechat/types';
+import { describe, expect, it } from 'vitest';
+
+import { buildGoalGraphView } from './goalGraphViewModel';
+
+const T0 = new Date('2026-08-01T00:00:00Z');
+const at = (minutes: number) => new Date(T0.getTime() + minutes * 60_000);
+const NOW = at(120).getTime();
+
+const goal = (overrides: Partial<GoalItem> = {}): GoalItem => ({
+ agentId: 'agt',
+ completedAt: null,
+ config: { recovery: { operationLeaseTimeoutMs: 15 * 60_000 } },
+ createdAt: T0,
+ id: 'goal-1',
+ maxRounds: null,
+ maxTotalCost: null,
+ projectId: null,
+ requirement: 'ship it',
+ startedAt: T0,
+ status: 'running',
+ subjectId: null,
+ subjectType: 'standalone',
+ title: 'Goal',
+ updatedAt: T0,
+ userId: 'user-1',
+ workspaceId: null,
+ ...overrides,
+});
+
+const node = (id: string, overrides: Partial<GoalGraphNode> = {}): GoalGraphNode => ({
+ confidence: null,
+ createdAt: at(1),
+ createdByAgentId: null,
+ createdByUserId: null,
+ description: null,
+ goalId: 'goal-1',
+ id,
+ kind: 'work',
+ priority: 0,
+ resolvedAt: null,
+ status: 'proposed',
+ taskId: null,
+ title: id,
+ updatedAt: at(1),
+ ...overrides,
+});
+
+const edge = (source: string, target: string, kind: GoalGraphEdge['kind']): GoalGraphEdge => ({
+ createdAt: at(1),
+ goalId: 'goal-1',
+ id: `${source}-${target}-${kind}`,
+ kind,
+ sourceNodeId: source,
+ targetNodeId: target,
+});
+
+const event = (
+ entityId: string,
+ eventType: GoalGraphEvent['eventType'],
+ minutes: number,
+ reason?: string,
+): GoalGraphEvent => ({
+ actorId: 'user-1',
+ actorType: 'agent',
+ createdAt: at(minutes),
+ entityId,
+ entityType: 'node',
+ eventType,
+ goalId: 'goal-1',
+ id: `${entityId}-${eventType}-${minutes}`,
+ operationId: null,
+ reason: reason ?? null,
+ taskId: null,
+});
+
+const snapshot = (partial: Partial<GoalGraphSnapshot>): GoalGraphSnapshot => ({
+ decisions: [],
+ edges: [],
+ events: [],
+ goal: goal(),
+ nodes: [],
+ workVersions: [],
+ ...partial,
+});
+
+describe('buildGoalGraphView', () => {
+ it('mirrors the coordinator frontier: unblocked work is ready, blocked work folds', () => {
+ const view = buildGoalGraphView(
+ snapshot({
+ edges: [edge('w2', 'w1', 'depends_on')],
+ nodes: [node('w1'), node('w2')],
+ }),
+ NOW,
+ );
+
+ expect(view.frontier.map((item) => [item.view.node.id, item.kind])).toEqual([['w1', 'ready']]);
+ expect(view.blocked.map((item) => item.node.id)).toEqual(['w2']);
+ });
+
+ it('numbers work nodes by graph creation order so dependency refs stay stable', () => {
+ const view = buildGoalGraphView(
+ snapshot({ nodes: [node('w1'), node('p1', { kind: 'problem' }), node('w2')] }),
+ NOW,
+ );
+
+ expect(view.byId.w1.seq).toBe(1);
+ expect(view.byId.w2.seq).toBe(2);
+ expect(view.byId.p1.seq).toBeUndefined();
+ });
+
+ it('builds the attempt ledger from the event trail', () => {
+ const view = buildGoalGraphView(
+ snapshot({
+ events: [
+ event('w1', 'activated', 5),
+ event('w1', 'updated', 20, 'Work attempt budget was exhausted'),
+ event('w1', 'activated', 25, 'retry with the missing directory created first'),
+ event('w1', 'resolved', 40, 'Responsible task completed'),
+ ],
+ nodes: [node('w1', { resolvedAt: at(40), status: 'resolved', updatedAt: at(40) })],
+ }),
+ NOW,
+ );
+
+ expect(view.byId.w1.attempts).toMatchObject([
+ { index: 1, outcome: 'failed', reason: 'Work attempt budget was exhausted' },
+ { index: 2, outcome: 'passed', reason: 'Responsible task completed' },
+ ]);
+ });
+
+ it('does not let a bookkeeping `updated` event close a live attempt', () => {
+ // The graph model writes `updated` for housekeeping too ("Attached Work
+ // version …"). Treating it as an outcome ended the running attempt one
+ // event early, which dropped the frontier row's live clock.
+ const view = buildGoalGraphView(
+ snapshot({
+ events: [
+ event('w1', 'activated', 115),
+ event('w1', 'updated', 115, 'Attached Work version 704ace21'),
+ ],
+ nodes: [node('w1', { status: 'active', taskId: 'task-1', updatedAt: at(115) })],
+ }),
+ NOW,
+ );
+
+ expect(view.byId.w1.attempts).toMatchObject([{ index: 1, outcome: 'running' }]);
+ expect(view.byId.w1.startedAt).toEqual(at(115));
+ expect(view.frontier[0]).toMatchObject({ kind: 'running' });
+ });
+
+ it('marks an active work stale once it outlives the operation lease', () => {
+ const view = buildGoalGraphView(
+ snapshot({
+ events: [event('w1', 'activated', 30)],
+ nodes: [node('w1', { status: 'active', taskId: 'task-1', updatedAt: at(30) })],
+ }),
+ NOW,
+ );
+
+ expect(view.byId.w1.isStale).toBe(true);
+ expect(view.frontier[0]).toMatchObject({ kind: 'stale', rank: 0 });
+ expect(view.needsYou).toBe(1);
+ });
+
+ it('keeps a fresh active work running, with the current attempt start for the clock', () => {
+ const view = buildGoalGraphView(
+ snapshot({
+ events: [event('w1', 'activated', 115)],
+ nodes: [node('w1', { status: 'active', taskId: 'task-1', updatedAt: at(115) })],
+ }),
+ NOW,
+ );
+
+ expect(view.frontier[0]).toMatchObject({ kind: 'running', rank: 1 });
+ expect(view.byId.w1.startedAt).toEqual(at(115));
+ });
+
+ it('closes the parked attempt of a Work waiting at a gate', () => {
+ // The gate is written as an `updated` event, which is not an attempt
+ // boundary — without the node-state fallback the parked Work kept
+ // reporting a running attempt, and the gate case read as still executing.
+ const view = buildGoalGraphView(
+ snapshot({
+ events: [
+ event('w1', 'activated', 5),
+ event('w1', 'updated', 40, 'Work attempt budget was exhausted'),
+ ],
+ nodes: [node('w1', { status: 'waiting', taskId: 'task-1', updatedAt: at(40) })],
+ }),
+ NOW,
+ );
+
+ expect(view.byId.w1.attempts).toMatchObject([
+ { endedAt: at(40), index: 1, outcome: 'failed', reason: 'Work attempt budget was exhausted' },
+ ]);
+ expect(view.byId.w1.startedAt).toBeUndefined();
+ });
+
+ it('surfaces a pending gate and hides the waiting work it was opened for', () => {
+ const decision: GoalGraphDecision = {
+ authority: 'user',
+ canceledAt: null,
+ createdAt: at(50),
+ id: 'dec-1',
+ nodeId: 'd1',
+ options: [
+ { id: 'retry', label: 'Retry work' },
+ { id: 'retire', label: 'Retire work' },
+ ],
+ question: 'Retry or retire?',
+ recommendedOptionId: 'retry',
+ requestedProjectRole: null,
+ requestedUserId: 'user-1',
+ resolution: null,
+ resolvedAt: null,
+ resolvedByAgentId: null,
+ resolvedByUserId: null,
+ resolvedOptionId: null,
+ status: 'pending',
+ updatedAt: at(50),
+ };
+ const view = buildGoalGraphView(
+ snapshot({
+ decisions: [decision],
+ edges: [edge('w1', 'd1', 'leads_to')],
+ nodes: [
+ node('w1', { status: 'waiting' }),
+ node('d1', { kind: 'decision', status: 'waiting' }),
+ ],
+ }),
+ NOW,
+ );
+
+ expect(view.frontier.map((item) => [item.view.node.id, item.kind])).toEqual([['d1', 'gate']]);
+ expect(view.byId.d1.decision?.id).toBe('dec-1');
+ // The gate's case is the failed Work's ledger, not the decision node's own.
+ expect(view.byId.d1.gateSubjectId).toBe('w1');
+ });
+
+ it('links a finding to the work that produced it and the problem it answers', () => {
+ const view = buildGoalGraphView(
+ snapshot({
+ edges: [edge('w1', 'f1', 'produces'), edge('f1', 'p1', 'supports')],
+ nodes: [
+ node('p1', { kind: 'problem' }),
+ node('w1', { resolvedAt: at(40), status: 'resolved' }),
+ node('f1', { kind: 'finding', status: 'resolved' }),
+ ],
+ }),
+ NOW,
+ );
+
+ expect(view.byId.f1.producedBy?.id).toBe('w1');
+ expect(view.byId.f1.answers.map((n) => n.id)).toEqual(['p1']);
+ expect(view.byId.w1.findings.map((n) => n.id)).toEqual(['f1']);
+ });
+
+ it('keeps only the most recent finished tasks, ahead of the live rows', () => {
+ const view = buildGoalGraphView(
+ snapshot({
+ nodes: [
+ node('w1', { resolvedAt: at(10), status: 'resolved' }),
+ node('w2', { resolvedAt: at(20), status: 'resolved' }),
+ node('w3', { resolvedAt: at(30), status: 'resolved' }),
+ node('w4'),
+ ],
+ }),
+ NOW,
+ );
+
+ expect(view.frontier.map((item) => item.view.node.id)).toEqual(['w3', 'w2', 'w4']);
+ expect(view.advanceable).toBe(1);
+ });
+
+ it('counts registered work versions per node', () => {
+ const view = buildGoalGraphView(
+ snapshot({
+ nodes: [node('w1')],
+ workVersions: [
+ { createdAt: at(5), id: 'l1', nodeId: 'w1', relation: 'produced', workVersionId: 'v1' },
+ { createdAt: at(9), id: 'l2', nodeId: 'w1', relation: 'produced', workVersionId: 'v2' },
+ ],
+ }),
+ NOW,
+ );
+
+ expect(view.byId.w1.artifactCount).toBe(2);
+ });
+});
diff --git a/src/features/AgentGoals/ProcessControl/goalGraphViewModel.ts b/src/features/AgentGoals/ProcessControl/goalGraphViewModel.ts
new file mode 100644
index 00000000000..c564e759dcd
--- /dev/null
+++ b/src/features/AgentGoals/ProcessControl/goalGraphViewModel.ts
@@ -0,0 +1,295 @@
+import type {
+ GoalGraphDecision,
+ GoalGraphEdge,
+ GoalGraphEvent,
+ GoalGraphNode,
+ GoalGraphSnapshot,
+ GoalItem,
+} from '@lobechat/types';
+
+/**
+ * Read model for the Goal process-control surface.
+ *
+ * Everything here is derived from one `goal.graph` snapshot — the server has no
+ * frontier projection, no per-node attempt/cost roll-up and no artifact
+ * hydration, so the client reproduces the coordinator's own selection rule
+ * (`GoalService.tick`) and reads the append-only `goal_events` trail for the
+ * per-node attempt ledger. Anything that cannot be derived honestly is left
+ * `undefined` and the UI omits it rather than inventing a value.
+ */
+
+/** Mirrors the reclaim window the coordinator uses when a Work holds no lease. */
+const DEFAULT_LEASE_TIMEOUT_MS = 15 * 60 * 1000;
+
+/** How many just-finished tasks stay visible so the list fades instead of items vanishing. */
+export const RECENT_DONE = 2;
+
+const TERMINAL_NODE_STATUSES = new Set(['resolved', 'rejected', 'retired']);
+
+export type GoalAttemptOutcome = 'passed' | 'failed' | 'retired' | 'running';
+
+export interface GoalAttempt {
+ endedAt?: Date;
+ /** 1-based attempt number on its node. */
+ index: number;
+ outcome: GoalAttemptOutcome;
+ /** The `reason` the coordinator recorded on the closing event. */
+ reason?: string;
+ startedAt: Date;
+ taskId?: string;
+}
+
+export interface GoalNodeView {
+ /** Problems this finding was linked to with a `supports` edge. */
+ answers: GoalGraphNode[];
+ /** Registered work versions. Names/urls need a server join that does not exist yet. */
+ artifactCount: number;
+ attempts: GoalAttempt[];
+ /** Unresolved `depends_on` targets — why this node cannot start. */
+ blockers: GoalGraphNode[];
+ /** Pending user decision opened on this node. */
+ decision?: GoalGraphDecision;
+ dependsOn: string[];
+ /** Findings produced by this Work. */
+ findings: GoalGraphNode[];
+ /** Decision only: the Work this gate was opened for — its ledger is the case. */
+ gateSubjectId?: string;
+ /** Decisions on this node a human already resolved. */
+ humanTouches: GoalGraphDecision[];
+ /** Active for longer than the lease window with no update — the coordinator would reclaim it. */
+ isStale: boolean;
+ node: GoalGraphNode;
+ /** The Work that produced this finding. */
+ producedBy?: GoalGraphNode;
+ /** Stable 1-based number over Work nodes in graph creation order. */
+ seq?: number;
+ /** When the current attempt started, for the running clock. */
+ startedAt?: Date;
+}
+
+export type FrontierItemKind = 'gate' | 'stale' | 'running' | 'ready' | 'done';
+
+export interface FrontierItem {
+ key: string;
+ kind: FrontierItemKind;
+ /** 0 = needs you, 1 = running, 2 = ready, -1 = recently finished. */
+ rank: number;
+ view: GoalNodeView;
+}
+
+export interface GoalGraphView {
+ /** Every node the frontier can move now, excluding the fading done rows. */
+ advanceable: number;
+ blocked: GoalNodeView[];
+ byId: Record<string, GoalNodeView>;
+ decisions: GoalGraphDecision[];
+ edges: GoalGraphEdge[];
+ findings: GoalNodeView[];
+ frontier: FrontierItem[];
+ goal: GoalItem;
+ needsYou: number;
+ /** Views in graph creation order. */
+ nodes: GoalNodeView[];
+}
+
+const leaseTimeoutMs = (goal: GoalItem) =>
+ goal.config?.recovery?.operationLeaseTimeoutMs ?? DEFAULT_LEASE_TIMEOUT_MS;
+
+/**
+ * Attempt ledger from the audit trail.
+ *
+ * Only `activated` opens an attempt, and only a *boundary* closes it: the next
+ * `activated` (the coordinator started another attempt, so this one did not
+ * succeed) or a terminal lifecycle event. `updated` is deliberately not a
+ * boundary — the model writes it for bookkeeping too ("Attached Work version
+ * …"), so treating it as an outcome ends every attempt one event too early and
+ * leaves a live attempt looking finished. Its reason is still the best
+ * description of why an attempt ended, so the last one before the boundary is
+ * carried onto the attempt.
+ *
+ * There is no cost or duration per attempt anywhere, so neither is reported.
+ */
+const buildAttempts = (node: GoalGraphNode, events: GoalGraphEvent[]): GoalAttempt[] => {
+ const own = events.filter((e) => e.entityType === 'node' && e.entityId === node.id);
+ const attempts: GoalAttempt[] = [];
+ let pendingReason: string | undefined;
+
+ const close = (
+ outcome: Exclude<GoalAttemptOutcome, 'running'>,
+ event: GoalGraphEvent,
+ reason?: string,
+ ) => {
+ const open = attempts.at(-1);
+ if (!open || open.outcome !== 'running') return;
+ open.endedAt = event.createdAt;
+ open.outcome = outcome;
+ open.reason = reason;
+ open.taskId = open.taskId ?? event.taskId ?? undefined;
+ };
+
+ for (const event of own) {
+ switch (event.eventType) {
+ case 'activated': {
+ // A new attempt starting means the previous one did not deliver. Its
+ // reason is the last `updated` note, not this event's — that one is the
+ // instruction the human attached to the *new* attempt.
+ close('failed', event, pendingReason);
+ attempts.push({
+ index: attempts.length + 1,
+ outcome: 'running',
+ startedAt: event.createdAt,
+ taskId: event.taskId ?? undefined,
+ });
+ pendingReason = event.reason ?? undefined;
+ break;
+ }
+ case 'rejected':
+ case 'retired': {
+ close('retired', event, event.reason ?? pendingReason);
+ break;
+ }
+ case 'resolved': {
+ close('passed', event, event.reason ?? pendingReason);
+ break;
+ }
+ case 'updated': {
+ if (event.reason) pendingReason = event.reason;
+ break;
+ }
+ default: {
+ break;
+ }
+ }
+ }
+
+ // A Work parked at a decision gate leaves its last attempt open: the gate is
+ // written as `updated`, which is not a boundary. Only an `active` node is
+ // still trying, so close the attempt against the node's own state.
+ const open = attempts.at(-1);
+ if (open?.outcome === 'running' && node.status !== 'active') {
+ open.endedAt = node.updatedAt;
+ open.outcome = node.status === 'resolved' ? 'passed' : 'failed';
+ open.reason = pendingReason;
+ }
+
+ return attempts;
+};
+
+export const buildGoalGraphView = (
+ snapshot: GoalGraphSnapshot,
+ now: number = Date.now(),
+): GoalGraphView => {
+ const { decisions, edges, events, goal, nodes, workVersions } = snapshot;
+ const nodeById = new Map(nodes.map((node) => [node.id, node]));
+ const lease = leaseTimeoutMs(goal);
+
+ const dependsOn = new Map<string, string[]>();
+ const producesByWork = new Map<string, GoalGraphNode[]>();
+ const gateSubject = new Map<string, string>();
+ const producedByFinding = new Map<string, GoalGraphNode>();
+ const supportsByFinding = new Map<string, GoalGraphNode[]>();
+ for (const edge of edges) {
+ const source = nodeById.get(edge.sourceNodeId);
+ const target = nodeById.get(edge.targetNodeId);
+ if (!source || !target) continue;
+ if (edge.kind === 'depends_on')
+ dependsOn.set(source.id, [...(dependsOn.get(source.id) ?? []), target.id]);
+ if (edge.kind === 'produces') {
+ producesByWork.set(source.id, [...(producesByWork.get(source.id) ?? []), target]);
+ producedByFinding.set(target.id, source);
+ }
+ // The coordinator links the failed Work to the gate it opened with `leads_to`.
+ if (edge.kind === 'leads_to' && target.kind === 'decision')
+ gateSubject.set(target.id, source.id);
+ if (edge.kind === 'supports')
+ supportsByFinding.set(source.id, [...(supportsByFinding.get(source.id) ?? []), target]);
+ }
+
+ const artifactCounts = new Map<string, number>();
+ for (const link of workVersions)
+ artifactCounts.set(link.nodeId, (artifactCounts.get(link.nodeId) ?? 0) + 1);
+
+ const decisionsByNode = new Map<string, GoalGraphDecision[]>();
+ for (const decision of decisions)
+ decisionsByNode.set(decision.nodeId, [
+ ...(decisionsByNode.get(decision.nodeId) ?? []),
+ decision,
+ ]);
+
+ let seq = 0;
+ const views: GoalNodeView[] = nodes.map((node) => {
+ const nodeDecisions = decisionsByNode.get(node.id) ?? [];
+ const attempts = buildAttempts(node, events);
+ const open = attempts.at(-1);
+ const isRunningAttempt = node.status === 'active' && open?.outcome === 'running';
+ return {
+ answers: supportsByFinding.get(node.id) ?? [],
+ artifactCount: artifactCounts.get(node.id) ?? 0,
+ attempts,
+ blockers: (dependsOn.get(node.id) ?? [])
+ .map((id) => nodeById.get(id))
+ .filter((dep): dep is GoalGraphNode => !!dep && !TERMINAL_NODE_STATUSES.has(dep.status)),
+ decision: nodeDecisions.find((d) => d.status === 'pending'),
+ dependsOn: dependsOn.get(node.id) ?? [],
+ findings: producesByWork.get(node.id) ?? [],
+ gateSubjectId: gateSubject.get(node.id),
+ humanTouches: nodeDecisions.filter((d) => d.status === 'resolved' && !!d.resolvedByUserId),
+ isStale:
+ node.kind === 'work' && node.status === 'active' && now - node.updatedAt.getTime() > lease,
+ node,
+ producedBy: producedByFinding.get(node.id),
+ seq: node.kind === 'work' ? ++seq : undefined,
+ startedAt: isRunningAttempt ? open.startedAt : undefined,
+ };
+ });
+ const byId = Object.fromEntries(views.map((view) => [view.node.id, view]));
+
+ // The coordinator's own frontier rule (GoalService.tick): a Work whose
+ // `depends_on` targets are all resolved. Blocked Work folds instead of listing.
+ const frontier: FrontierItem[] = [];
+ const blocked: GoalNodeView[] = [];
+ for (const view of views) {
+ const { node } = view;
+ if (node.kind === 'decision' && node.status === 'waiting' && view.decision) {
+ frontier.push({ key: node.id, kind: 'gate', rank: 0, view });
+ continue;
+ }
+ if (node.kind !== 'work') continue;
+ if (node.status === 'active') {
+ frontier.push({
+ key: node.id,
+ kind: view.isStale ? 'stale' : 'running',
+ rank: view.isStale ? 0 : 1,
+ view,
+ });
+ continue;
+ }
+ if (TERMINAL_NODE_STATUSES.has(node.status) || node.status === 'waiting') continue;
+ if (view.blockers.length > 0) blocked.push(view);
+ else frontier.push({ key: node.id, kind: 'ready', rank: 2, view });
+ }
+
+ const done = views
+ .filter((view) => view.node.kind === 'work' && TERMINAL_NODE_STATUSES.has(view.node.status))
+ .sort((a, b) => resolvedTime(b.node) - resolvedTime(a.node))
+ .slice(0, RECENT_DONE)
+ .map((view) => ({ key: `done:${view.node.id}`, kind: 'done' as const, rank: -1, view }));
+
+ frontier.sort((a, b) => a.rank - b.rank || b.view.node.priority - a.view.node.priority);
+
+ return {
+ advanceable: frontier.length,
+ blocked,
+ byId,
+ decisions,
+ edges,
+ findings: views.filter((view) => view.node.kind === 'finding'),
+ frontier: [...done, ...frontier],
+ goal,
+ needsYou: frontier.filter((item) => item.rank === 0).length,
+ nodes: views,
+ };
+};
+
+const resolvedTime = (node: GoalGraphNode) =>
+ (node.resolvedAt ?? node.updatedAt ?? node.createdAt).getTime();
diff --git a/src/features/AgentGoals/ProcessControl/index.tsx b/src/features/AgentGoals/ProcessControl/index.tsx
new file mode 100644
index 00000000000..c7e2b2e08d0
--- /dev/null
+++ b/src/features/AgentGoals/ProcessControl/index.tsx
@@ -0,0 +1,176 @@
+'use client';
+
+import { Accordion, AccordionItem, Flexbox, Icon, Tooltip } from '@lobehub/ui';
+import { Button, Tag, Text, toast } from '@lobehub/ui/base-ui';
+import { createStaticStyles } from 'antd-style';
+import { Pause, Play, StepForward } from 'lucide-react';
+import { memo, useCallback, useMemo, useState } from 'react';
+import { useTranslation } from 'react-i18next';
+
+import { usePermission } from '@/hooks/usePermission';
+import { goalService } from '@/services/goal';
+import { goalSelectors, useGoalStore } from '@/store/goal';
+
+import Activity from './Activity';
+import Findings from './Findings';
+import Frontier, { type FrontierActions } from './Frontier';
+import { buildGoalGraphView } from './goalGraphViewModel';
+import Graph from './Graph';
+
+/**
+ * The process-control band of the goal detail page: what can move now
+ * (frontier), the map of how the goal got here, what it believes, and what it
+ * has been doing. Renders only for goals that actually carry a Goal Graph —
+ * a plain task-carried goal has no nodes and keeps the page it always had.
+ */
+
+const styles = createStaticStyles(({ css }) => ({
+ section: css`
+ padding-block: 8px;
+ `,
+}));
+
+interface ProcessControlProps {
+ /** The `goals` row id — not the carrier task's identifier. */
+ goalId: string;
+}
+
+const ProcessControl = memo<ProcessControlProps>(({ goalId }) => {
+ const { t } = useTranslation('chat');
+ const { allowed: canEdit } = usePermission('create_content');
+ const [selectedId, setSelectedId] = useState<string>();
+ const [advancing, setAdvancing] = useState(false);
+
+ const useFetchGoalGraph = useGoalStore((s) => s.useFetchGoalGraph);
+ const decideGoal = useGoalStore((s) => s.decideGoal);
+ const pauseGoal = useGoalStore((s) => s.pauseGoal);
+ const resumeGoal = useGoalStore((s) => s.resumeGoal);
+ const advanceGoalNow = useGoalStore((s) => s.advanceGoal);
+ const refreshGoalGraph = useGoalStore((s) => s.refreshGoalGraph);
+ useFetchGoalGraph(goalId);
+ const snapshot = useGoalStore(goalSelectors.goalGraph(goalId));
+
+ const graph = useMemo(() => (snapshot ? buildGoalGraphView(snapshot) : undefined), [snapshot]);
+
+ // One press hands the goal to the server's coordinator, which runs it as far
+ // as it can go in one call and then keeps going on its own as each Work Task
+ // settles. A single coordinator step is an implementation unit — a press that
+ // only ticked once usually looked like it did nothing, because the very next
+ // step is what dispatches the task.
+ const advance = useCallback(async () => {
+ if (advancing) return;
+ setAdvancing(true);
+ try {
+ const result = await advanceGoalNow(goalId);
+ toast.info(result.message);
+ } catch (error) {
+ toast.error((error as Error).message);
+ } finally {
+ setAdvancing(false);
+ }
+ }, [advancing, advanceGoalNow, goalId]);
+
+ const actions: FrontierActions = useMemo(
+ () => ({
+ addTask: async (title: string) => {
+ await goalService.addNode({ id: goalId, kind: 'work', title });
+ await refreshGoalGraph(goalId);
+ },
+ advance: () => void advance(),
+ decide: (decisionId, optionId, resolution) =>
+ void decideGoal(goalId, { decisionId, optionId, resolution }),
+ }),
+ [advance, decideGoal, goalId, refreshGoalGraph],
+ );
+
+ // Task-carried goals share the `goals` table but never grow a graph. Nothing
+ // to control here, so the page keeps its original shape.
+ if (!graph || graph.nodes.length === 0) return null;
+
+ const paused = graph.goal.status === 'paused';
+ // A closed goal cannot move: the coordinator returns immediately for these,
+ // so Advance would report nothing happened and a Work added here would sit
+ // `proposed` forever. Stop offering actions that cannot land.
+ const closed = ['achieved', 'canceled', 'failed'].includes(graph.goal.status);
+ const canAct = canEdit && !closed;
+
+ return (
+ <Flexbox gap={20}>
+ <Flexbox gap={12}>
+ <Flexbox horizontal align={'center'} gap={8}>
+ {canAct && (
+ <>
+ <Tooltip title={t('goalProcess.advance.tooltip')}>
+ <Button
+ icon={<Icon icon={StepForward} />}
+ loading={advancing}
+ size={'small'}
+ type={'primary'}
+ onClick={advance}
+ >
+ {advancing ? t('goalProcess.advance.running') : t('goalProcess.advance.label')}
+ </Button>
+ </Tooltip>
+ <Button
+ icon={<Icon icon={paused ? Play : Pause} />}
+ size={'small'}
+ onClick={() => void (paused ? resumeGoal(goalId) : pauseGoal(goalId))}
+ >
+ {paused ? t('goalProcess.resume') : t('goalProcess.pause')}
+ </Button>
+ </>
+ )}
+ {paused && (
+ <Text fontSize={12} type={'secondary'}>
+ {t('goalProcess.paused')}
+ </Text>
+ )}
+ </Flexbox>
+
+ <Frontier actions={actions} canEdit={canAct} graph={graph} onSelect={setSelectedId} />
+ </Flexbox>
+
+ <Graph graph={graph} selectedId={selectedId} onSelect={setSelectedId} />
+
+ <Accordion defaultExpandedKeys={['findings', 'activity']} gap={0}>
+ <AccordionItem
+ itemKey={'findings'}
+ paddingBlock={6}
+ paddingInline={0}
+ title={
+ <Flexbox horizontal align={'center'} gap={8}>
+ <Text fontSize={14} weight={600}>
+ {t('goalProcess.findings.title')}
+ </Text>
+ {graph.findings.length > 0 && <Tag size={'small'}>{graph.findings.length}</Tag>}
+ </Flexbox>
+ }
+ >
+ <Flexbox className={styles.section}>
+ <Findings graph={graph} onSelect={setSelectedId} />
+ </Flexbox>
+ </AccordionItem>
+ <AccordionItem
+ itemKey={'activity'}
+ paddingBlock={6}
+ paddingInline={0}
+ title={
+ <Flexbox horizontal align={'center'} gap={8}>
+ <Text fontSize={14} weight={600}>
+ {t('goalProcess.activity.title')}
+ </Text>
+ </Flexbox>
+ }
+ >
+ <Flexbox className={styles.section}>
+ <Activity graph={graph} onSelect={setSelectedId} />
+ </Flexbox>
+ </AccordionItem>
+ </Accordion>
+ </Flexbox>
+ );
+});
+
+ProcessControl.displayName = 'GoalProcessControl';
+
+export default ProcessControl;
diff --git a/src/features/AgentGoals/ProcessControl/shared.tsx b/src/features/AgentGoals/ProcessControl/shared.tsx
new file mode 100644
index 00000000000..5c41ff394db
--- /dev/null
+++ b/src/features/AgentGoals/ProcessControl/shared.tsx
@@ -0,0 +1,65 @@
+import type { GoalNodeKind } from '@lobechat/types';
+import { Icon } from '@lobehub/ui';
+import { Text } from '@lobehub/ui/base-ui';
+import { createStaticStyles, cssVar } from 'antd-style';
+import { CircleHelp, GitBranch, Lightbulb, ListChecks, type LucideIcon } from 'lucide-react';
+import { memo } from 'react';
+
+/**
+ * One palette per node kind, used by both the graph cards and the inline
+ * references in the frontier / findings / activity lists, so the same node
+ * reads the same everywhere. State is carried by stroke and glyph, never by
+ * filling a node with its status color.
+ */
+export const KIND_COLOR: Record<GoalNodeKind, { line: string; soft: string }> = {
+ decision: { line: cssVar.orange6, soft: cssVar.orange1 },
+ finding: { line: cssVar.green6, soft: cssVar.green1 },
+ problem: { line: cssVar.purple6, soft: cssVar.purple1 },
+ work: { line: cssVar.blue6, soft: cssVar.blue1 },
+};
+
+export const KIND_ICON: Record<GoalNodeKind, LucideIcon> = {
+ decision: GitBranch,
+ finding: Lightbulb,
+ problem: CircleHelp,
+ work: ListChecks,
+};
+
+const styles = createStaticStyles(({ css }) => ({
+ dot: css`
+ display: inline-block;
+ flex: none;
+
+ width: 8px;
+ height: 8px;
+ border-radius: 2px;
+ `,
+ mono: css`
+ font-family: ${cssVar.fontFamilyCode};
+ font-variant-numeric: tabular-nums;
+ `,
+}));
+
+export const monoClass = styles.mono;
+
+export const KindDot = memo<{ kind: GoalNodeKind }>(({ kind }) => (
+ <span className={styles.dot} style={{ background: KIND_COLOR[kind].line }} />
+));
+
+KindDot.displayName = 'GoalKindDot';
+
+export const MonoText = memo<{ children: React.ReactNode; title?: string }>(
+ ({ children, title }) => (
+ <Text className={styles.mono} fontSize={12} title={title} type={'secondary'}>
+ {children}
+ </Text>
+ ),
+);
+
+MonoText.displayName = 'GoalMonoText';
+
+export const KindIcon = memo<{ kind: GoalNodeKind; size?: number }>(({ kind, size = 14 }) => (
+ <Icon color={KIND_COLOR[kind].line} icon={KIND_ICON[kind]} size={size} />
+));
+
+KindIcon.displayName = 'GoalKindIcon';
diff --git a/src/features/AgentGoals/ProcessControl/useElapsed.ts b/src/features/AgentGoals/ProcessControl/useElapsed.ts
new file mode 100644
index 00000000000..4121605c1d1
--- /dev/null
+++ b/src/features/AgentGoals/ProcessControl/useElapsed.ts
@@ -0,0 +1,24 @@
+import { useEffect, useState } from 'react';
+
+/** Same digit-unit shape the Task page's run cards use: `12s` · `3m 12s` · `1h 04m`. */
+export const formatElapsed = (ms: number): string => {
+ const seconds = Math.max(0, Math.floor(ms / 1000));
+ if (seconds < 60) return `${seconds}s`;
+ const minutes = Math.floor(seconds / 60);
+ if (minutes < 60) return `${minutes}m ${String(seconds % 60).padStart(2, '0')}s`;
+ const hours = Math.floor(minutes / 60);
+ return `${hours}h ${String(minutes % 60).padStart(2, '0')}m`;
+};
+
+/** Live "how long has this been running" label; idle when there is nothing running. */
+export const useElapsed = (startedAt?: Date): string => {
+ const [now, setNow] = useState(() => Date.now());
+
+ useEffect(() => {
+ if (!startedAt) return;
+ const interval = setInterval(() => setNow(Date.now()), 1000);
+ return () => clearInterval(interval);
+ }, [startedAt]);
+
+ return startedAt ? formatElapsed(now - startedAt.getTime()) : '';
+};
diff --git a/src/features/AgentGoals/goalPresentation.test.ts b/src/features/AgentGoals/goalPresentation.test.ts
index 4d3af69d05d..51d0d75c34e 100644
--- a/src/features/AgentGoals/goalPresentation.test.ts
+++ b/src/features/AgentGoals/goalPresentation.test.ts
@@ -1,58 +1,16 @@
import { describe, expect, it } from 'vitest';
-import { getGoalPresentation } from './goalPresentation';
+import { goalStatusKey } from './goalPresentation';
-describe('getGoalPresentation', () => {
- it('maps the goal lifecycle state to the goal list vocabulary', () => {
- expect(
- getGoalPresentation({
- checks: [{ state: 'passed' }, { state: 'failed' }, { state: 'passed' }],
- goalStatus: 'verifying',
- rounds: 2,
- }),
- ).toMatchObject({
- passed: 2,
- progress: 67,
- statusKey: 'goalList.status.verifying',
- total: 3,
- });
+describe('goalStatusKey', () => {
+ it('maps every lifecycle state to a list-vocabulary key', () => {
+ expect(goalStatusKey('planning')).toBe('goalList.status.planning');
+ expect(goalStatusKey('running')).toBe('goalList.status.running');
+ expect(goalStatusKey('review')).toBe('goalList.status.review');
+ expect(goalStatusKey('achieved')).toBe('goalList.status.achieved');
});
- it('shows achieved only when the goal state machine reached it', () => {
- expect(
- getGoalPresentation({
- checks: [{ state: 'passed' }],
- goalStatus: 'achieved',
- rounds: 3,
- }).statusKey,
- ).toBe('goalList.status.achieved');
- });
-
- 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('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'],
- ];
-
- for (const [goalStatus, statusKey] of cases) {
- expect(getGoalPresentation({ goalStatus, rounds: 0 }).statusKey).toBe(statusKey);
- }
+ it('reads a failed goal as needing attention rather than as an error state', () => {
+ expect(goalStatusKey('failed')).toBe('goalList.status.error');
});
});
diff --git a/src/features/AgentGoals/goalPresentation.ts b/src/features/AgentGoals/goalPresentation.ts
index e979916a23d..720dc2141cb 100644
--- a/src/features/AgentGoals/goalPresentation.ts
+++ b/src/features/AgentGoals/goalPresentation.ts
@@ -1,14 +1,8 @@
import type { GoalStatus } from '@lobechat/const/goal';
-
-export interface GoalPresentationInput {
- checks?: Array<{ state: string }>;
- goalStatus: GoalStatus;
- maxRounds?: number | null;
- rounds: number;
-}
+import type { TaskStatus } from '@lobechat/types';
/** Goal lifecycle state → i18n status key (goal list vocabulary). */
-const goalStatusKeyMap: Record<GoalStatus, string> = {
+const goalStatusKeyMap = {
achieved: 'goalList.status.achieved',
canceled: 'goalList.status.canceled',
failed: 'goalList.status.error',
@@ -17,19 +11,33 @@ const goalStatusKeyMap: Record<GoalStatus, string> = {
review: 'goalList.status.review',
running: 'goalList.status.running',
verifying: 'goalList.status.verifying',
-};
+} as const satisfies Record<GoalStatus, string>;
+
+export type GoalStatusKey = (typeof goalStatusKeyMap)[GoalStatus];
-export const getGoalPresentation = (input: GoalPresentationInput) => {
- const checks = input.checks ?? [];
- const passed = checks.filter((check) => check.state === 'passed').length;
- const total = checks.length;
+export const goalStatusKey = (status: GoalStatus): GoalStatusKey => goalStatusKeyMap[status];
- return {
- maxRounds: input.maxRounds,
- passed,
- progress: total > 0 ? Math.round((passed / total) * 100) : 0,
- rounds: input.rounds,
- statusKey: goalStatusKeyMap[input.goalStatus],
- total,
- };
+/** Goal lifecycle state → the execution-status vocabulary the shared glyphs use. */
+export const goalStatusToTaskStatus = (goalStatus: GoalStatus): TaskStatus => {
+ switch (goalStatus) {
+ case 'achieved': {
+ return 'completed';
+ }
+ case 'canceled': {
+ return 'canceled';
+ }
+ case 'failed': {
+ return 'failed';
+ }
+ case 'paused':
+ case 'review': {
+ return 'paused';
+ }
+ case 'planning': {
+ return 'backlog';
+ }
+ default: {
+ return 'running';
+ }
+ }
};
diff --git a/src/features/AgentGoals/goalViewModel.test.ts b/src/features/AgentGoals/goalViewModel.test.ts
deleted file mode 100644
index a5d618bbdce..00000000000
--- a/src/features/AgentGoals/goalViewModel.test.ts
+++ /dev/null
@@ -1,99 +0,0 @@
-import type { TaskDetailActivity } from '@lobechat/types';
-import { describe, expect, it } from 'vitest';
-
-import {
- formatGoalCost,
- formatGoalDuration,
- getGoalDescription,
- getGoalRunMetrics,
- getGoalRuns,
- getRecentGoalRuns,
- goalStatusToTaskStatus,
- shouldShowGoal,
-} from './goalViewModel';
-
-describe('goalViewModel', () => {
- it('formats compact run duration and cost metrics', () => {
- expect(formatGoalDuration(7500)).toBe('1m');
- expect(formatGoalDuration(3_900_000)).toBe('1h 5m');
- expect(formatGoalCost(0.0042)).toBe('$0.0042');
- expect(formatGoalCost(0)).toBe('—');
- });
- it('uses the persisted goal description before the execution instruction', () => {
- expect(
- getGoalDescription({
- description: 'Increase successful releases',
- instruction: 'Run the release checklist',
- }),
- ).toBe('Increase successful releases');
- });
-
- it('falls back to the instruction when no description exists', () => {
- expect(
- getGoalDescription({ description: null, instruction: 'Run the release checklist' }),
- ).toBe('Run the release checklist');
- });
-
- it('returns only Agent runs with the newest run first', () => {
- const activities = [
- { id: 'created', type: 'created' },
- { id: 'run-1', type: 'topic' },
- { id: 'comment', type: 'comment' },
- { id: 'run-2', type: 'topic' },
- ] as TaskDetailActivity[];
-
- expect(getGoalRuns(activities).map((activity) => activity.id)).toEqual(['run-2', 'run-1']);
- });
-
- it('limits the recent execution list to the latest 10 runs', () => {
- const activities = Array.from({ length: 12 }, (_, index) => ({
- id: `run-${index + 1}`,
- type: 'topic',
- })) as TaskDetailActivity[];
-
- expect(getRecentGoalRuns(activities).map((activity) => activity.id)).toEqual([
- 'run-12',
- 'run-11',
- 'run-10',
- 'run-9',
- 'run-8',
- 'run-7',
- 'run-6',
- 'run-5',
- 'run-4',
- 'run-3',
- ]);
- });
-
- it('hides achieved goals from the default active filter without hiding pending acceptance', () => {
- expect(shouldShowGoal('achieved', 'active')).toBe(false);
- expect(shouldShowGoal('review', 'active')).toBe(true);
- expect(shouldShowGoal('achieved', 'all')).toBe(true);
- });
-
- 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', () => {
- expect(
- getGoalRunMetrics([
- {
- completedAt: '2026-08-06T00:00:03.000Z',
- cost: 0.012,
- time: '2026-08-06T00:00:01.000Z',
- type: 'topic',
- },
- { content: 'comment', type: 'comment' },
- {
- completedAt: '2026-08-06T00:00:08.500Z',
- cost: 0.008,
- time: '2026-08-06T00:00:03.000Z',
- type: 'topic',
- },
- ]),
- ).toEqual({ cost: 0.02, duration: 7500 });
- });
-});
diff --git a/src/features/AgentGoals/goalViewModel.ts b/src/features/AgentGoals/goalViewModel.ts
deleted file mode 100644
index 4b3121d7e89..00000000000
--- a/src/features/AgentGoals/goalViewModel.ts
+++ /dev/null
@@ -1,75 +0,0 @@
-import type { GoalStatus } from '@lobechat/const/goal';
-import type { TaskDetailActivity } from '@lobechat/types';
-
-interface GoalDescriptionSource {
- description?: string | null;
- instruction: string;
-}
-
-export const getGoalDescription = ({ description, instruction }: GoalDescriptionSource) =>
- description?.trim() || instruction.trim();
-
-export const getGoalRuns = (activities?: TaskDetailActivity[]) =>
- activities?.filter((activity) => activity.type === 'topic').toReversed() ?? [];
-
-export const getRecentGoalRuns = (activities?: TaskDetailActivity[], limit = 10) =>
- getGoalRuns(activities).slice(0, limit);
-
-export const formatGoalDuration = (milliseconds: number) => {
- if (milliseconds <= 0) return '—';
- const totalMinutes = Math.max(1, Math.round(milliseconds / 60_000));
- if (totalMinutes < 60) return `${totalMinutes}m`;
- const hours = Math.floor(totalMinutes / 60);
- const minutes = totalMinutes % 60;
- return minutes > 0 ? `${hours}h ${minutes}m` : `${hours}h`;
-};
-
-export const formatGoalCost = (cost: number) =>
- cost > 0 ? `$${cost < 0.01 ? cost.toFixed(4) : cost.toFixed(2)}` : '—';
-
-export const getGoalRunMetrics = (activities?: TaskDetailActivity[]) =>
- getGoalRuns(activities).reduce(
- (metrics, activity) => {
- const startedAt = activity.time ? new Date(activity.time).getTime() : Number.NaN;
- const completedAt = activity.completedAt
- ? new Date(activity.completedAt).getTime()
- : Number.NaN;
- const duration = completedAt - startedAt;
-
- return {
- cost: metrics.cost + (activity.cost ?? 0),
- duration: metrics.duration + (Number.isFinite(duration) && duration > 0 ? duration : 0),
- };
- },
- { cost: 0, duration: 0 },
- );
-
-export const shouldShowGoal = (goalStatus: GoalStatus, filter: 'active' | 'all') =>
- filter === 'all' || goalStatus !== 'achieved';
-
-export const goalStatusToTaskStatus = (goalStatus: GoalStatus) => {
- switch (goalStatus) {
- case 'achieved': {
- return 'completed';
- }
- case 'failed': {
- return 'failed';
- }
- case 'canceled': {
- return 'canceled';
- }
- case 'paused':
- case 'review': {
- return 'paused';
- }
- case 'planning': {
- return 'backlog';
- }
- case 'verifying': {
- return 'running';
- }
- default: {
- return 'running';
- }
- }
-};
diff --git a/src/features/AgentGoals/types.ts b/src/features/AgentGoals/types.ts
index 4b9514288b0..a94d7451327 100644
--- a/src/features/AgentGoals/types.ts
+++ b/src/features/AgentGoals/types.ts
@@ -1,7 +1,6 @@
import type { GoalListItem } from '@/store/goal/initialState';
export interface GoalItemProps {
- hideAchieved?: boolean;
+ goal: GoalListItem;
projectId?: string;
- task: GoalListItem;
}
diff --git a/src/features/AgentSidebar/Task/index.tsx b/src/features/AgentSidebar/Task/index.tsx
index c180fe5f97e..07b529fa455 100644
--- a/src/features/AgentSidebar/Task/index.tsx
+++ b/src/features/AgentSidebar/Task/index.tsx
@@ -36,7 +36,7 @@ const TaskList = memo<TaskListProps>(({ itemKey }) => {
const { data, isLoading } = useClientDataSWR<{ data: TaskGroupItem[]; success: boolean }>(
enabled ? taskKeys.sidebarGroups(agentId) : null,
async ([, id]: [string, string]) =>
- taskService.groupList({ assigneeAgentId: id, groups: SIDEBAR_GROUPS, hasGoal: false }),
+ taskService.groupList({ assigneeAgentId: id, groups: SIDEBAR_GROUPS }),
{
fallbackData: { data: [], success: true },
revalidateOnFocus: false,
diff --git a/src/features/Conversation/Messages/GoalWorkCard/GoalStatusLine.tsx b/src/features/Conversation/Messages/GoalWorkCard/GoalStatusLine.tsx
index dcdc4ce1cce..ef86e5f0234 100644
--- a/src/features/Conversation/Messages/GoalWorkCard/GoalStatusLine.tsx
+++ b/src/features/Conversation/Messages/GoalWorkCard/GoalStatusLine.tsx
@@ -60,11 +60,9 @@ const styles = createStaticStyles(({ css }) => ({
}));
export interface GoalStatusLineProps {
- maxRounds?: number;
passed: number;
phase: GoalWorkPhase;
progress: number;
- round: number;
total: number;
}
@@ -74,45 +72,37 @@ export interface GoalStatusLineProps {
* Once the goal is achieved the coverage bar retires: "已达成" already implies
* full coverage, so repeating "4/4 项通过" is noise.
*/
-const GoalStatusLine = memo<GoalStatusLineProps>(
- ({ maxRounds, passed, phase, progress, round, total }) => {
- const { t } = useTranslation('chat');
- const meta = PHASE_META[phase];
- const showChecks = total > 0 && phase !== 'achieved';
+const GoalStatusLine = memo<GoalStatusLineProps>(({ passed, phase, progress, total }) => {
+ const { t } = useTranslation('chat');
+ const meta = PHASE_META[phase];
+ const showChecks = total > 0 && phase !== 'achieved';
- return (
- <Flexbox horizontal align={'center'} gap={6}>
- {phase !== 'running' && (
- <>
- <Icon
- className={styles.statusIcon}
- color={meta.color}
- icon={meta.icon}
- size={12}
- spin={meta.spin}
- />
- <Text className={styles.status}>{t(`goalWork.status.${phase}`)}</Text>
- <Text className={styles.status}>·</Text>
- </>
- )}
- <Text className={styles.status}>
- {maxRounds
- ? t('goalWork.roundWithBudget', { current: round, total: maxRounds })
- : t('goalWork.round', { current: round })}
- </Text>
- {showChecks && (
- <>
- <Text className={styles.status}>·</Text>
- <div className={styles.progress}>
- <div className={styles.progressFill} style={{ width: `${progress}%` }} />
- </div>
- <Text className={styles.status}>{t('goalWork.checks', { passed, total })}</Text>
- </>
- )}
- </Flexbox>
- );
- },
-);
+ return (
+ <Flexbox horizontal align={'center'} gap={6}>
+ {phase !== 'running' && (
+ <>
+ <Icon
+ className={styles.statusIcon}
+ color={meta.color}
+ icon={meta.icon}
+ size={12}
+ spin={meta.spin}
+ />
+ <Text className={styles.status}>{t(`goalWork.status.${phase}`)}</Text>
+ <Text className={styles.status}>·</Text>
+ </>
+ )}
+ {showChecks && (
+ <>
+ <div className={styles.progress}>
+ <div className={styles.progressFill} style={{ width: `${progress}%` }} />
+ </div>
+ <Text className={styles.status}>{t('goalWork.workDone', { passed, total })}</Text>
+ </>
+ )}
+ </Flexbox>
+ );
+});
GoalStatusLine.displayName = 'GoalStatusLine';
diff --git a/src/features/Conversation/Messages/GoalWorkCard/deriveOperationGoals.test.ts b/src/features/Conversation/Messages/GoalWorkCard/deriveOperationGoals.test.ts
index a4e756b7d69..2efb91a6791 100644
--- a/src/features/Conversation/Messages/GoalWorkCard/deriveOperationGoals.test.ts
+++ b/src/features/Conversation/Messages/GoalWorkCard/deriveOperationGoals.test.ts
@@ -26,7 +26,7 @@ describe('deriveOperationGoals', () => {
content: 'started',
id: 'tool-1',
state: {
- identifier: 'T-41',
+ goalId: 'goal-41',
name: 'San Francisco night fog',
success: true,
taskId: 'task-41',
@@ -38,13 +38,7 @@ describe('deriveOperationGoals', () => {
]);
expect(goals).toEqual([
- {
- criteriaCount: 2,
- identifier: 'T-41',
- maxRounds: 3,
- name: 'San Francisco night fog',
- taskId: 'task-41',
- },
+ { criteriaCount: 2, goalId: 'goal-41', name: 'San Francisco night fog' },
]);
});
@@ -68,7 +62,7 @@ describe('deriveOperationGoals', () => {
content: 'failed',
error: { message: 'boom' },
id: 'tool-failed',
- state: { identifier: 'T-42', success: false, taskId: 'task-42' },
+ state: { goalId: 'goal-42', success: false },
},
type: 'builtin',
},
@@ -80,7 +74,7 @@ describe('deriveOperationGoals', () => {
result: {
content: 'created',
id: 'tool-task',
- state: { identifier: 'T-43', success: true, taskId: 'task-43' },
+ state: { goalId: 'goal-43', success: true },
},
type: 'builtin',
},
diff --git a/src/features/Conversation/Messages/GoalWorkCard/deriveOperationGoals.ts b/src/features/Conversation/Messages/GoalWorkCard/deriveOperationGoals.ts
index dff613dd729..34dd5e0ea02 100644
--- a/src/features/Conversation/Messages/GoalWorkCard/deriveOperationGoals.ts
+++ b/src/features/Conversation/Messages/GoalWorkCard/deriveOperationGoals.ts
@@ -3,10 +3,9 @@ import { safeParseJSON } from '@lobechat/utils';
export interface OperationGoal {
criteriaCount: number;
- identifier: string;
- maxRounds?: number;
+ /** The `goals` row the tool created — the card's pointer and its link target. */
+ goalId: string;
name: string;
- taskId: string;
}
const isRecord = (value: unknown): value is Record<string, unknown> =>
@@ -28,20 +27,17 @@ export const deriveOperationGoals = (blocks: AssistantContentBlock[] = []): Oper
if (tool.result?.error || !isRecord(tool.result?.state) || tool.result.state.success !== true)
return [];
- const identifier = nonEmptyString(tool.result.state.identifier);
- const taskId = nonEmptyString(tool.result.state.taskId);
- if (!identifier || !taskId) return [];
+ const goalId = nonEmptyString(tool.result.state.goalId);
+ if (!goalId) return [];
const parsedArgs = safeParseJSON(tool.arguments);
const args = isRecord(parsedArgs) ? parsedArgs : undefined;
- const name =
- nonEmptyString(tool.result.state.name) ?? nonEmptyString(args?.name) ?? identifier;
+ const name = nonEmptyString(tool.result.state.name) ?? nonEmptyString(args?.name) ?? goalId;
const criteriaCount = Array.isArray(args?.criteria) ? args.criteria.length : 0;
- const maxRounds = typeof args?.maxIterations === 'number' ? args.maxIterations : undefined;
- return [{ criteriaCount, identifier, maxRounds, name, taskId }];
+ return [{ criteriaCount, goalId, name }];
}),
);
- return [...new Map(goals.map((goal) => [goal.taskId, goal])).values()];
+ return [...new Map(goals.map((goal) => [goal.goalId, goal])).values()];
};
diff --git a/src/features/Conversation/Messages/GoalWorkCard/goalWorkProgress.test.ts b/src/features/Conversation/Messages/GoalWorkCard/goalWorkProgress.test.ts
index d73c17547c1..5194988249b 100644
--- a/src/features/Conversation/Messages/GoalWorkCard/goalWorkProgress.test.ts
+++ b/src/features/Conversation/Messages/GoalWorkCard/goalWorkProgress.test.ts
@@ -3,53 +3,37 @@ import { describe, expect, it } from 'vitest';
import { getGoalWorkProgress } from './goalWorkProgress';
describe('getGoalWorkProgress', () => {
- it('keeps a planned acceptance in execution while its task is running', () => {
+ it('reports how much of the graph is closed while it runs', () => {
expect(
- getGoalWorkProgress({
- acceptanceStatus: 'planned',
- criteriaCount: 4,
- maxRounds: 3,
- rounds: 1,
- taskStatus: 'running',
- }),
- ).toEqual({
- maxRounds: 3,
+ getGoalWorkProgress({ criteriaCount: 4, status: 'running', workDone: 2, workTotal: 3 }),
+ ).toEqual({ passed: 2, phase: 'running', progress: 67, total: 3 });
+ });
+
+ it('falls back to the drafted criteria count before the graph is seeded', () => {
+ expect(getGoalWorkProgress({ criteriaCount: 4, status: 'planning' })).toEqual({
passed: 0,
phase: 'running',
progress: 0,
- round: 1,
total: 4,
});
});
- it('reports the verification phase and real acceptance coverage', () => {
+ it('lets a waiting decision gate outrank the goal status', () => {
+ // A goal keeps its `running` row while a gate is open; the card must still
+ // read as blocked on the user, not as work in progress.
expect(
- getGoalWorkProgress({
- acceptanceStatus: 'verifying',
- checks: [{ state: 'passed' }, { state: 'running' }, { state: 'passed' }],
- criteriaCount: 3,
- maxRounds: 3,
- rounds: 2,
- taskStatus: 'running',
- }),
- ).toEqual({
- maxRounds: 3,
- passed: 2,
- phase: 'verifying',
- progress: 67,
- round: 2,
- total: 3,
- });
+ getGoalWorkProgress({ criteriaCount: 1, pendingDecisions: 1, status: 'running' }).phase,
+ ).toBe('waiting');
});
it.each([
- ['repairing', 'repairing'],
- ['delivered', 'review'],
- ['accepted', 'achieved'],
- ['errored', 'error'],
- ])('maps acceptance status %s to phase %s', (acceptanceStatus, phase) => {
- expect(
- getGoalWorkProgress({ acceptanceStatus, criteriaCount: 1, taskStatus: 'running' }).phase,
- ).toBe(phase);
+ ['achieved', 'achieved'],
+ ['canceled', 'canceled'],
+ ['failed', 'error'],
+ ['paused', 'paused'],
+ ['review', 'review'],
+ ['verifying', 'verifying'],
+ ] as const)('maps goal status %s to phase %s', (status, phase) => {
+ expect(getGoalWorkProgress({ criteriaCount: 1, status }).phase).toBe(phase);
});
});
diff --git a/src/features/Conversation/Messages/GoalWorkCard/goalWorkProgress.ts b/src/features/Conversation/Messages/GoalWorkCard/goalWorkProgress.ts
index c2c12e742da..5607759dbda 100644
--- a/src/features/Conversation/Messages/GoalWorkCard/goalWorkProgress.ts
+++ b/src/features/Conversation/Messages/GoalWorkCard/goalWorkProgress.ts
@@ -1,3 +1,5 @@
+import type { GoalStatus } from '@lobechat/const/goal';
+
export type GoalWorkPhase =
| 'achieved'
| 'canceled'
@@ -10,38 +12,20 @@ export type GoalWorkPhase =
| 'waiting';
interface GoalWorkProgressInput {
- acceptanceStatus?: string;
- checks?: Array<{ state: string }>;
criteriaCount: number;
- maxRounds?: number | null;
- rounds?: number;
- taskStatus?: string;
+ /** Decision gates waiting on a human right now — they outrank the goal's own status. */
+ pendingDecisions?: number;
+ status?: GoalStatus;
+ workDone?: number;
+ workTotal?: number;
}
-const resolvePhase = (acceptanceStatus?: string, taskStatus?: string): GoalWorkPhase => {
- switch (acceptanceStatus) {
- case 'accepted': {
+const resolvePhase = (status?: GoalStatus, pendingDecisions = 0): GoalWorkPhase => {
+ if (pendingDecisions > 0) return 'waiting';
+ switch (status) {
+ case 'achieved': {
return 'achieved';
}
- case 'delivered': {
- return 'review';
- }
- case 'errored': {
- return 'error';
- }
- case 'rejected':
- case 'closed': {
- return 'paused';
- }
- case 'repairing': {
- return 'repairing';
- }
- case 'verifying': {
- return 'verifying';
- }
- }
-
- switch (taskStatus) {
case 'canceled': {
return 'canceled';
}
@@ -51,8 +35,11 @@ const resolvePhase = (acceptanceStatus?: string, taskStatus?: string): GoalWorkP
case 'paused': {
return 'paused';
}
- case 'scheduled': {
- return 'waiting';
+ case 'review': {
+ return 'review';
+ }
+ case 'verifying': {
+ return 'verifying';
}
default: {
return 'running';
@@ -60,18 +47,19 @@ const resolvePhase = (acceptanceStatus?: string, taskStatus?: string): GoalWorkP
}
};
-/** Honest Goal progress: lifecycle phase + round budget + acceptance coverage. */
+/**
+ * Honest Goal progress for the conversation card: lifecycle phase plus how much
+ * of the graph's Work is closed. The criteria count is only a fallback for a
+ * goal whose graph has not been seeded yet.
+ */
export const getGoalWorkProgress = (input: GoalWorkProgressInput) => {
- const checks = input.checks ?? [];
- const passed = checks.filter((check) => check.state === 'passed').length;
- const total = checks.length || input.criteriaCount;
+ const total = input.workTotal || input.criteriaCount;
+ const passed = input.workDone ?? 0;
return {
- maxRounds: input.maxRounds ?? undefined,
passed,
- phase: resolvePhase(input.acceptanceStatus, input.taskStatus),
+ phase: resolvePhase(input.status, input.pendingDecisions),
progress: total > 0 ? Math.round((passed / total) * 100) : 0,
- round: Math.max(1, input.rounds ?? 1),
total,
};
};
diff --git a/src/features/Conversation/Messages/GoalWorkCard/index.tsx b/src/features/Conversation/Messages/GoalWorkCard/index.tsx
index 3327ad76605..cd11d5e8ab3 100644
--- a/src/features/Conversation/Messages/GoalWorkCard/index.tsx
+++ b/src/features/Conversation/Messages/GoalWorkCard/index.tsx
@@ -1,13 +1,13 @@
'use client';
import { Center, Flexbox, Icon } from '@lobehub/ui';
-import { Tag, Text } from '@lobehub/ui/base-ui';
+import { Text } from '@lobehub/ui/base-ui';
import { createStaticStyles, cssVar } from 'antd-style';
import { ChevronRightIcon, TargetIcon } from 'lucide-react';
import { memo } from 'react';
import RingLoadingIcon from '@/components/RingLoading';
-import { useChatStore } from '@/store/chat';
+import { useWorkspaceAwareNavigate } from '@/features/Workspace/useWorkspaceAwareNavigate';
import type { OperationGoal } from './deriveOperationGoals';
import GoalElapsedTime from './GoalElapsedTime';
@@ -56,15 +56,15 @@ const styles = createStaticStyles(({ css }) => ({
}));
const GoalCard = memo<{ goal: OperationGoal }>(({ goal }) => {
- const openTaskDetail = useChatStore((s) => s.openTaskDetail);
- const { progress, startedAt } = useGoalWorkStatus({
+ const navigate = useWorkspaceAwareNavigate();
+ const { agentId, progress, startedAt, title } = useGoalWorkStatus({
criteriaCount: goal.criteriaCount,
- goalKnown: true,
- identifier: goal.identifier,
- maxRounds: goal.maxRounds,
- taskId: goal.taskId,
+ goalId: goal.goalId,
});
const isActive = ACTIVE_PHASES.has(progress.phase);
+ const openGoal = () => {
+ if (agentId) navigate(`/agent/${agentId}/goal/${goal.goalId}`);
+ };
return (
<Flexbox
@@ -74,11 +74,11 @@ const GoalCard = memo<{ goal: OperationGoal }>(({ goal }) => {
gap={10}
role={'button'}
tabIndex={0}
- onClick={() => openTaskDetail(goal.identifier)}
+ onClick={openGoal}
onKeyDown={(event) => {
if (event.key !== 'Enter' && event.key !== ' ') return;
event.preventDefault();
- openTaskDetail(goal.identifier);
+ openGoal();
}}
>
<Center className={styles.icon}>
@@ -93,12 +93,9 @@ const GoalCard = memo<{ goal: OperationGoal }>(({ goal }) => {
)}
</Center>
<Flexbox flex={1} gap={2} style={{ minWidth: 0 }}>
- <Flexbox horizontal align={'center'} gap={8}>
- <Text ellipsis className={styles.title}>
- {goal.name}
- </Text>
- <Tag size={'small'}>{goal.identifier}</Tag>
- </Flexbox>
+ <Text ellipsis className={styles.title}>
+ {title ?? goal.name}
+ </Text>
<GoalStatusLine {...progress} />
</Flexbox>
{isActive && <GoalElapsedTime startedAt={startedAt} />}
@@ -115,7 +112,7 @@ const GoalWorkCard = memo<{ goals: OperationGoal[] }>(({ goals }) => {
return (
<Flexbox gap={8}>
{goals.map((goal) => (
- <GoalCard goal={goal} key={goal.taskId} />
+ <GoalCard goal={goal} key={goal.goalId} />
))}
</Flexbox>
);
diff --git a/src/features/Conversation/Messages/GoalWorkCard/useGoalWorkStatus.test.ts b/src/features/Conversation/Messages/GoalWorkCard/useGoalWorkStatus.test.ts
index 0e537cd7f3f..6a051b6e17c 100644
--- a/src/features/Conversation/Messages/GoalWorkCard/useGoalWorkStatus.test.ts
+++ b/src/features/Conversation/Messages/GoalWorkCard/useGoalWorkStatus.test.ts
@@ -1,62 +1,84 @@
+import type { GoalGraphSnapshot } from '@lobechat/types';
import { renderHook } from '@testing-library/react';
import { beforeEach, describe, expect, it, vi } from 'vitest';
import { useGoalWorkStatus } from './useGoalWorkStatus';
const mocks = vi.hoisted(() => ({
- taskDetailMap: {} as Record<
- string,
- { config?: unknown; goal?: unknown; name?: string; startedAt?: string }
- >,
- useAcceptanceBundle: vi.fn(() => ({ data: undefined })),
- useAcceptanceBySubject: vi.fn(() => ({ data: undefined })),
- useFetchTaskDetail: vi.fn(),
+ goalGraphById: {} as Record<string, unknown>,
+ useFetchGoalGraph: vi.fn(),
}));
-vi.mock('@/features/Acceptance', () => ({
- useAcceptanceBundle: mocks.useAcceptanceBundle,
- useAcceptanceBySubject: mocks.useAcceptanceBySubject,
-}));
-
-vi.mock('@/store/task', () => ({
- useTaskStore: (selector: (state: unknown) => unknown) =>
+vi.mock('@/store/goal', () => ({
+ goalSelectors: {
+ goalGraph: (goalId?: string | null) => (state: { goalGraphById: Record<string, unknown> }) =>
+ goalId ? state.goalGraphById[goalId] : undefined,
+ },
+ useGoalStore: (selector: (state: unknown) => unknown) =>
selector({
- taskDetailMap: mocks.taskDetailMap,
- useFetchTaskDetail: mocks.useFetchTaskDetail,
+ goalGraphById: mocks.goalGraphById,
+ useFetchGoalGraph: mocks.useFetchGoalGraph,
}),
}));
+const node = (id: string, kind: string, status: string) => ({ id, kind, status });
+
+const snapshot = (overrides: Partial<GoalGraphSnapshot> = {}) =>
+ ({
+ decisions: [],
+ edges: [],
+ events: [],
+ goal: {
+ agentId: 'agt-1',
+ id: 'goal-1',
+ startedAt: new Date('2026-08-14T08:00:00.000Z'),
+ status: 'running',
+ title: 'Reproduce nanoGPT',
+ },
+ nodes: [],
+ workVersions: [],
+ ...overrides,
+ }) as unknown as GoalGraphSnapshot;
+
describe('useGoalWorkStatus', () => {
beforeEach(() => {
- mocks.taskDetailMap = {};
+ mocks.goalGraphById = {};
vi.clearAllMocks();
});
- it('does not poll acceptance for a plain task callback', () => {
- mocks.taskDetailMap['T-1'] = { config: {} };
-
- const { result } = renderHook(() => useGoalWorkStatus({ identifier: 'T-1', taskId: 'task-1' }));
+ it('falls back to the drafted criteria count until the graph resolves', () => {
+ const { result } = renderHook(() => useGoalWorkStatus({ criteriaCount: 3, goalId: 'goal-1' }));
- expect(result.current.isGoal).toBe(false);
- expect(mocks.useAcceptanceBySubject).toHaveBeenCalledWith('task', null);
+ expect(mocks.useFetchGoalGraph).toHaveBeenCalledWith('goal-1');
+ expect(result.current.progress).toMatchObject({ phase: 'running', total: 3 });
+ expect(result.current.title).toBeUndefined();
});
- it('polls acceptance after task detail identifies a Goal task', () => {
- mocks.taskDetailMap['T-2'] = {
- goal: { id: 'goal-1', status: 'running' },
- startedAt: '2026-08-14T08:00:00.000Z',
- };
+ it('counts every terminal Work node as closed', () => {
+ mocks.goalGraphById['goal-1'] = snapshot({
+ nodes: [
+ node('w1', 'work', 'resolved'),
+ node('w2', 'work', 'retired'),
+ node('w3', 'work', 'active'),
+ node('f1', 'finding', 'resolved'),
+ ] as never,
+ });
- const { result } = renderHook(() => useGoalWorkStatus({ identifier: 'T-2', taskId: 'task-2' }));
+ const { result } = renderHook(() => useGoalWorkStatus({ goalId: 'goal-1' }));
- expect(result.current.isGoal).toBe(true);
- expect(result.current.startedAt).toBe('2026-08-14T08:00:00.000Z');
- expect(mocks.useAcceptanceBySubject).toHaveBeenCalledWith('task', 'task-2');
+ expect(result.current.progress).toMatchObject({ passed: 2, total: 3 });
+ expect(result.current.agentId).toBe('agt-1');
+ expect(result.current.title).toBe('Reproduce nanoGPT');
});
- it('keeps polling for a Goal tracker before task detail loads', () => {
- renderHook(() => useGoalWorkStatus({ goalKnown: true, identifier: 'T-3', taskId: 'task-3' }));
+ it('reads a pending gate as waiting on the user', () => {
+ mocks.goalGraphById['goal-1'] = snapshot({
+ decisions: [{ status: 'pending' }] as never,
+ nodes: [node('w1', 'work', 'active')] as never,
+ });
+
+ const { result } = renderHook(() => useGoalWorkStatus({ goalId: 'goal-1' }));
- expect(mocks.useAcceptanceBySubject).toHaveBeenCalledWith('task', 'task-3');
+ expect(result.current.progress.phase).toBe('waiting');
});
});
diff --git a/src/features/Conversation/Messages/GoalWorkCard/useGoalWorkStatus.ts b/src/features/Conversation/Messages/GoalWorkCard/useGoalWorkStatus.ts
index ef0bc2d36be..daae926d372 100644
--- a/src/features/Conversation/Messages/GoalWorkCard/useGoalWorkStatus.ts
+++ b/src/features/Conversation/Messages/GoalWorkCard/useGoalWorkStatus.ts
@@ -1,50 +1,38 @@
-import { useAcceptanceBundle, useAcceptanceBySubject } from '@/features/Acceptance';
-import { useTaskStore } from '@/store/task';
+import { goalSelectors, useGoalStore } from '@/store/goal';
import { getGoalWorkProgress } from './goalWorkProgress';
-interface GoalWorkStatusInput {
- criteriaCount?: number;
- goalKnown?: boolean;
- identifier?: string;
- maxRounds?: number;
- taskId?: string;
-}
-
/**
- * Live Goal status for one task pointer (identifier + taskId): task detail +
- * acceptance aggregate → phase / round / checks coverage. Shared by the
- * running tracker card and the merged task-callback header — both only hold
- * the pointer, so everything else is fetched here. Callback cards wait for
- * task detail to classify the task before starting acceptance polling.
+ * Live Goal status for one `goals` row: the graph snapshot → phase and how much
+ * of its Work is closed. The card only holds the goal id, so everything else is
+ * fetched here.
*/
export const useGoalWorkStatus = ({
criteriaCount = 0,
- goalKnown = false,
- identifier,
- maxRounds,
- taskId,
-}: GoalWorkStatusInput) => {
- const useFetchTaskDetail = useTaskStore((s) => s.useFetchTaskDetail);
- useFetchTaskDetail(identifier);
- const task = useTaskStore((s) => (identifier ? s.taskDetailMap[identifier] : undefined));
- const isGoal = goalKnown || !!task?.goal;
- const { data: acceptance } = useAcceptanceBySubject('task', isGoal ? (taskId ?? null) : null);
- const { data: bundle } = useAcceptanceBundle(acceptance?.id ?? null);
+ goalId,
+}: {
+ criteriaCount?: number;
+ goalId?: string;
+}) => {
+ const useFetchGoalGraph = useGoalStore((s) => s.useFetchGoalGraph);
+ useFetchGoalGraph(goalId);
+ const snapshot = useGoalStore(goalSelectors.goalGraph(goalId));
- const progress = getGoalWorkProgress({
- acceptanceStatus: acceptance?.status,
- checks: bundle?.checks,
- criteriaCount,
- maxRounds: task?.goal?.maxRounds ?? maxRounds,
- rounds: task?.topicCount ?? 0,
- taskStatus: task?.status,
- });
+ const workNodes = snapshot?.nodes.filter((node) => node.kind === 'work') ?? [];
return {
- isGoal,
- progress,
- startedAt: task?.startedAt,
- taskName: task?.name ?? undefined,
+ agentId: snapshot?.goal.agentId ?? undefined,
+ progress: getGoalWorkProgress({
+ criteriaCount,
+ pendingDecisions:
+ snapshot?.decisions.filter((decision) => decision.status === 'pending').length ?? 0,
+ status: snapshot?.goal.status,
+ workDone: workNodes.filter((node) =>
+ ['rejected', 'resolved', 'retired'].includes(node.status),
+ ).length,
+ workTotal: workNodes.length,
+ }),
+ startedAt: snapshot?.goal.startedAt ?? undefined,
+ title: snapshot?.goal.title,
};
};
diff --git a/src/features/Conversation/Messages/GoalWorkCard/useOperationGoals.ts b/src/features/Conversation/Messages/GoalWorkCard/useOperationGoals.ts
index 09febbedf31..918464bedb7 100644
--- a/src/features/Conversation/Messages/GoalWorkCard/useOperationGoals.ts
+++ b/src/features/Conversation/Messages/GoalWorkCard/useOperationGoals.ts
@@ -1,23 +1,14 @@
import type { AssistantContentBlock } from '@lobechat/types';
-import isEqual from 'fast-deep-equal';
import { useMemo } from 'react';
-import { dataSelectors, useConversationStore } from '../../store';
import { deriveOperationGoals, type OperationGoal } from './deriveOperationGoals';
/**
* Display-only Goal artifacts derived from one settled assistant group.
*
- * Goals whose task already delivered its `role='taskCallback'` handoff into
- * this thread are dropped: the callback card absorbs the Goal status header
- * and becomes the single surface for that task, so the creating turn's
- * tracker card retires instead of duplicating it.
+ * The card tracks the goal itself, not one of the tasks its coordinator
+ * dispatches, so it stays for the whole life of the goal — a Work Task
+ * finishing is progress inside the goal, not the end of it.
*/
-export const useOperationGoals = (blocks?: AssistantContentBlock[]): OperationGoal[] => {
- const landedTaskIds = useConversationStore(dataSelectors.taskCallbackTaskIds, isEqual);
-
- return useMemo(
- () => deriveOperationGoals(blocks ?? []).filter((goal) => !landedTaskIds.includes(goal.taskId)),
- [blocks, landedTaskIds],
- );
-};
+export const useOperationGoals = (blocks?: AssistantContentBlock[]): OperationGoal[] =>
+ useMemo(() => deriveOperationGoals(blocks ?? []), [blocks]);
diff --git a/src/features/Conversation/Messages/TaskCallback/index.tsx b/src/features/Conversation/Messages/TaskCallback/index.tsx
index 4b1dea73ea5..bb4159d84e7 100644
--- a/src/features/Conversation/Messages/TaskCallback/index.tsx
+++ b/src/features/Conversation/Messages/TaskCallback/index.tsx
@@ -1,24 +1,16 @@
'use client';
-import { Center, Flexbox, Icon, Markdown } from '@lobehub/ui';
+import { Flexbox, Icon, Markdown } from '@lobehub/ui';
import { Button, Text } from '@lobehub/ui/base-ui';
import { createStaticStyles, cssVar } from 'antd-style';
import isEqual from 'fast-deep-equal';
-import {
- CircleAlert,
- CircleCheck,
- CircleSlash,
- SquareArrowOutUpRight,
- TargetIcon,
-} from 'lucide-react';
+import { CircleAlert, CircleCheck, CircleSlash, SquareArrowOutUpRight } from 'lucide-react';
import { memo } from 'react';
import { useTranslation } from 'react-i18next';
import { useChatStore } from '@/store/chat';
import { dataSelectors, useConversationStore } from '../../store';
-import GoalStatusLine from '../GoalWorkCard/GoalStatusLine';
-import { useGoalWorkStatus } from '../GoalWorkCard/useGoalWorkStatus';
const styles = createStaticStyles(({ css, cssVar }) => ({
card: css`
@@ -31,48 +23,6 @@ const styles = createStaticStyles(({ css, cssVar }) => ({
background: ${cssVar.colorBgElevated};
`,
- goalDivider: css`
- margin-inline: -16px;
- border-block-start: 1px dashed ${cssVar.colorBorderSecondary};
- `,
- // Full-bleed clickable Goal header inside the card: negative margins undo the
- // card padding so the hover surface reaches the card edges.
- goalHeader: css`
- margin-block: -12px 0;
- margin-inline: -16px;
- padding-block: 12px 10px;
- padding-inline: 16px;
- `,
- goalHeaderMain: css`
- cursor: pointer;
- min-width: 0;
-
- &:hover {
- background: ${cssVar.colorFillQuaternary};
- }
- `,
- goalIcon: css`
- flex-shrink: 0;
-
- width: 36px;
- height: 36px;
- border-radius: 8px;
-
- color: ${cssVar.colorTextSecondary};
-
- background: ${cssVar.colorFillTertiary};
- `,
- goalIdentifier: css`
- flex-shrink: 0;
- font-family: ${cssVar.fontFamilyCode};
- font-size: 12px;
- color: ${cssVar.colorTextTertiary};
- `,
- goalTitle: css`
- min-width: 0;
- font-size: 14px;
- font-weight: 500;
- `,
identifier: css`
font-family: ${cssVar.fontFamilyCode};
color: ${cssVar.colorTextSecondary};
@@ -105,11 +55,6 @@ const reasonMeta: Record<
* task pointer (identifier / reason / taskId) is carried on
* `metadata.taskCallback`; the handoff summary lives in the message content.
* Renders as a standalone card (no avatar bubble), like the verify card.
- *
- * For Goal tasks (an acceptance aggregate exists) the card absorbs the Goal
- * status header — 🎯 title + live phase/round/coverage line — and becomes the
- * single surface for that task; the creating turn's tracker card retires (see
- * `useOperationGoals`). Plain tasks keep the simple outcome header.
*/
const TaskCallbackMessage = memo<TaskCallbackMessageProps>(({ id }) => {
const { t } = useTranslation('chat');
@@ -119,12 +64,6 @@ const TaskCallbackMessage = memo<TaskCallbackMessageProps>(({ id }) => {
const item = useConversationStore(dataSelectors.getDisplayMessageById(id), isEqual);
const callback = item?.metadata?.taskCallback;
- // Hooks stay unconditional; the status hook waits for Goal classification
- // before enabling acceptance polling.
- const { isGoal, progress, taskName } = useGoalWorkStatus({
- identifier: callback?.identifier,
- taskId: callback?.taskId,
- });
if (!callback) return null;
const reason = (callback.reason ?? 'done') as CallbackReason;
@@ -140,52 +79,15 @@ const TaskCallbackMessage = memo<TaskCallbackMessageProps>(({ id }) => {
return (
<Flexbox paddingBlock={8}>
- <Flexbox className={styles.card} gap={isGoal ? 12 : 8}>
- {isGoal ? (
- <>
- <Flexbox horizontal align={'center'} className={styles.goalHeader} gap={10}>
- <Flexbox
- horizontal
- align={'center'}
- className={styles.goalHeaderMain}
- flex={1}
- gap={10}
- role={'button'}
- tabIndex={0}
- onClick={openTask}
- onKeyDown={(event) => {
- if (event.key !== 'Enter' && event.key !== ' ') return;
- event.preventDefault();
- openTask();
- }}
- >
- <Center className={styles.goalIcon}>
- <Icon icon={TargetIcon} size={20} />
- </Center>
- <Flexbox flex={1} gap={2} style={{ minWidth: 0 }}>
- <Flexbox horizontal align={'center'} gap={8}>
- <Text ellipsis className={styles.goalTitle}>
- {taskName ?? callback.identifier}
- </Text>
- <span className={styles.goalIdentifier}>{callback.identifier}</span>
- </Flexbox>
- <GoalStatusLine {...progress} />
- </Flexbox>
- </Flexbox>
- {viewTaskButton}
- </Flexbox>
- <div className={styles.goalDivider} />
- </>
- ) : (
- <Flexbox horizontal align={'center'} gap={8} justify={'space-between'}>
- <Flexbox horizontal align={'center'} gap={8}>
- <Icon color={cssVar[color]} icon={icon} size={18} />
- <Text strong>{t(i18nKey)}</Text>
- <span className={styles.identifier}>{callback.identifier}</span>
- </Flexbox>
- {viewTaskButton}
+ <Flexbox className={styles.card} gap={8}>
+ <Flexbox horizontal align={'center'} gap={8} justify={'space-between'}>
+ <Flexbox horizontal align={'center'} gap={8}>
+ <Icon color={cssVar[color]} icon={icon} size={18} />
+ <Text strong>{t(i18nKey)}</Text>
+ <span className={styles.identifier}>{callback.identifier}</span>
</Flexbox>
- )}
+ {viewTaskButton}
+ </Flexbox>
{content ? <Markdown variant={'chat'}>{content}</Markdown> : null}
</Flexbox>
</Flexbox>
diff --git a/src/features/HomeInbox/GoalsRailCard.tsx b/src/features/HomeInbox/GoalsRailCard.tsx
index bae97f044ff..c33591ee5bc 100644
--- a/src/features/HomeInbox/GoalsRailCard.tsx
+++ b/src/features/HomeInbox/GoalsRailCard.tsx
@@ -118,16 +118,16 @@ const GoalRow = memo<GoalRowProps>(({ bare, entry }) => {
{entry.title}
</Text>
<GoalAgentAvatar agentId={entry.agentId} />
- {/* A goal is measured in rounds, not in time — how far into its budget it
- is says more at a glance than when it last moved. */}
+ {/* A goal is measured in the work it has closed, not in time — how far
+ through its own decomposition it is says more at a glance. */}
<span className={cx(homeType.meta, styles.rounds)}>
- {entry.maxRounds
- ? t('goalList.roundProgress', {
- current: entry.rounds,
+ {entry.pendingDecisions > 0
+ ? t('goalList.needsYou', { count: entry.pendingDecisions, ns: 'chat' })
+ : t('goalList.workProgress', {
+ done: entry.workDone,
ns: 'chat',
- total: entry.maxRounds,
- })
- : t('goalList.agentRuns', { count: entry.rounds, ns: 'chat' })}
+ total: entry.workTotal,
+ })}
</span>
<Icon color={cssVar.colorTextQuaternary} icon={ChevronRightIcon} size={14} />
</Flexbox>
diff --git a/src/features/HomeInbox/homeGoals.test.ts b/src/features/HomeInbox/homeGoals.test.ts
index 3ccf6a172dc..02ee14872dd 100644
--- a/src/features/HomeInbox/homeGoals.test.ts
+++ b/src/features/HomeInbox/homeGoals.test.ts
@@ -3,47 +3,32 @@ import { describe, expect, it } from 'vitest';
import type { GoalListItem } from '@/store/goal/initialState';
-import {
- buildHomeGoalEntries,
- homeGoalHref,
- indexAcceptanceStatuses,
- resolveHomeGoalView,
-} from './homeGoals';
-
-type GoalOverrides = Omit<Partial<GoalListItem>, 'goal' | 'id'> & {
- goal?: Partial<NonNullable<GoalListItem['goal']>>;
+import { buildHomeGoalEntries, homeGoalHref, resolveHomeGoalView } from './homeGoals';
+
+interface GoalOverrides {
+ agentId?: string | null;
+ goal?: Partial<GoalListItem['goal']>;
id: string;
-};
+ pendingDecisions?: number;
+ title?: string;
+ workDone?: number;
+ workTotal?: number;
+}
-const goal = (overrides: GoalOverrides): GoalListItem =>
+const goal = ({ agentId = 'agt_1', id, goal: overrides, ...rest }: GoalOverrides): GoalListItem =>
({
- assigneeAgentId: 'agt_1',
- goal: { id: `g-${overrides.id}`, maxRounds: 3, status: 'running' },
- identifier: `T-${overrides.id}`,
- instruction: 'do the thing',
- name: `goal ${overrides.id}`,
- status: 'running',
- totalTopics: 1,
- ...overrides,
+ findingCount: 0,
+ goal: { agentId, id: `g-${id}`, status: 'running', title: `goal ${id}`, ...overrides },
+ pendingDecisions: 0,
+ totalRunCost: 0,
+ totalRunDuration: 0,
+ workDone: 1,
+ workTotal: 3,
+ ...rest,
}) as GoalListItem;
const titlesOf = (entries: { title: string }[]) => entries.map(({ title }) => title);
-describe('indexAcceptanceStatuses', () => {
- it('indexes acceptances by subject id', () => {
- expect(
- indexAcceptanceStatuses([
- { status: 'delivered', subjectId: 'task_1' },
- { status: 'accepted', subjectId: 'task_2' },
- ]),
- ).toEqual({ task_1: 'delivered', task_2: 'accepted' });
- });
-
- it('tolerates a read that has not landed', () => {
- expect(indexAcceptanceStatuses()).toEqual({});
- });
-});
-
describe('buildHomeGoalEntries', () => {
it('puts the goals waiting on the user ahead of the ones still working', () => {
const goals = [
@@ -88,30 +73,18 @@ describe('buildHomeGoalEntries', () => {
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: { id: 'g-x', maxRounds: 5, status: 'running' },
- id: 'x',
- instruction: '',
- name: null,
- totalTopics: 1,
- }),
- ];
+ it('carries the graph roll-up the row renders', () => {
+ const goals = [goal({ id: 'x', pendingDecisions: 2, workDone: 2, workTotal: 5 })];
expect(buildHomeGoalEntries(goals)[0]).toMatchObject({
agentId: 'agt_1',
- maxRounds: 5,
- rounds: 1,
- title: 'T-x',
+ id: 'g-x',
+ pendingDecisions: 2,
+ title: 'goal x',
+ workDone: 2,
+ workTotal: 5,
});
});
-
- it('reports no round budget when the goal entity carries none', () => {
- const goals = [goal({ goal: { id: 'g-x', maxRounds: null, status: 'running' }, id: 'x' })];
-
- expect(buildHomeGoalEntries(goals)[0].maxRounds).toBeNull();
- });
});
describe('resolveHomeGoalView', () => {
@@ -171,11 +144,11 @@ describe('homeGoalHref', () => {
it('routes to the goal detail page under its owning agent', () => {
const [entry] = buildHomeGoalEntries([goal({ id: 'g1' })]);
- expect(homeGoalHref(entry)).toBe('/agent/agt_1/goal/T-g1');
+ expect(homeGoalHref(entry)).toBe('/agent/agt_1/goal/g-g1');
});
it('has nowhere to go for an unassigned goal', () => {
- const [entry] = buildHomeGoalEntries([goal({ assigneeAgentId: null, id: 'g1' })]);
+ const [entry] = buildHomeGoalEntries([goal({ agentId: null, id: 'g1' })]);
expect(homeGoalHref(entry)).toBeUndefined();
});
diff --git a/src/features/HomeInbox/homeGoals.ts b/src/features/HomeInbox/homeGoals.ts
index 12fb74e04ee..5b1cee012c8 100644
--- a/src/features/HomeInbox/homeGoals.ts
+++ b/src/features/HomeInbox/homeGoals.ts
@@ -1,4 +1,4 @@
-import { getGoalPresentation } from '@/features/AgentGoals/goalPresentation';
+import { goalStatusKey } from '@/features/AgentGoals/goalPresentation';
import type { GoalListItem } from '@/store/goal/initialState';
/** Past this the rail card stops being a card and starts being a page. */
@@ -9,13 +9,15 @@ export type HomeGoalBucket = 'review' | 'running';
export interface HomeGoalEntry {
agentId: string | null;
bucket: HomeGoalBucket;
+ /** The `goals` row id — what the detail route is keyed by. */
id: string;
- identifier: string;
- maxRounds: number | null;
- rounds: number;
+ /** Decision gates waiting on the user right now. */
+ pendingDecisions: number;
/** Key in the `chat` namespace — the same label the goal pages use. */
statusKey: GoalStatusKey;
title: string;
+ workDone: number;
+ workTotal: number;
}
/**
@@ -41,46 +43,22 @@ const isOpenGoalStatus = (statusKey: string): statusKey is GoalStatusKey =>
/** Actionable first: a delivered goal is blocked on the user, a running one isn't. */
const BUCKET_ORDER: HomeGoalBucket[] = ['review', 'running'];
-/**
- * Acceptance status per goal task, from the one batched read the home rail
- * makes. One acceptance per subject is a scope invariant, so this is a plain
- * index — no recency tie-break to get wrong.
- */
-export const indexAcceptanceStatuses = (
- acceptances: Array<{ status: string; subjectId: string }> = [],
-): Record<string, string> =>
- Object.fromEntries(acceptances.map(({ status, subjectId }) => [subjectId, status]));
-
-const goalTitle = (goal: GoalListItem) =>
- goal.name?.trim() || goal.instruction.trim() || goal.identifier;
-
-/**
- * The rail's goal rows, bucketed and ordered.
- *
- * A goal with no acceptance row at all falls back to its task status, which is
- * the right reading: nothing has judged it yet.
- */
+/** The rail's goal rows, bucketed and ordered. */
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({
- goalStatus: goal.goal?.status ?? 'planning',
- maxRounds,
- rounds,
- });
+ const entries = goals.flatMap<HomeGoalEntry>((item) => {
+ const statusKey = goalStatusKey(item.goal.status);
if (!isOpenGoalStatus(statusKey)) return [];
return [
{
- agentId: goal.assigneeAgentId ?? null,
+ agentId: item.goal.agentId ?? null,
bucket: BUCKET_BY_STATUS_KEY[statusKey],
- id: goal.id,
- identifier: goal.identifier,
- maxRounds,
- rounds,
+ id: item.goal.id,
+ pendingDecisions: item.pendingDecisions,
statusKey,
- title: goalTitle(goal),
+ title: item.goal.title,
+ workDone: item.workDone,
+ workTotal: item.workTotal,
},
];
});
@@ -123,4 +101,4 @@ export const resolveHomeGoalView = (
/** Where a goal row goes: its own detail page under the agent that owns it. */
export const homeGoalHref = (entry: HomeGoalEntry): string | undefined =>
- entry.agentId ? `/agent/${entry.agentId}/goal/${entry.identifier}` : undefined;
+ entry.agentId ? `/agent/${entry.agentId}/goal/${entry.id}` : undefined;
diff --git a/src/features/Projects/Workspace/ProjectDashboard.tsx b/src/features/Projects/Workspace/ProjectDashboard.tsx
index f964b179791..887083a06a6 100644
--- a/src/features/Projects/Workspace/ProjectDashboard.tsx
+++ b/src/features/Projects/Workspace/ProjectDashboard.tsx
@@ -107,8 +107,6 @@ const styles = createStaticStyles(({ css }) => ({
const TERMINAL_STATUSES = new Set<TaskStatus | string>(['canceled', 'completed']);
const ATTENTION_STATUSES = new Set<TaskStatus | string>(['failed', 'paused']);
-const isGoalTask = (task: NonNullable<ProjectDetail['tasks']>[number]) => Boolean(task.goal);
-
interface ProjectDashboardProps {
detail: ProjectDetail;
projectId: string;
@@ -156,10 +154,10 @@ const ProjectDashboard = memo<ProjectDashboardProps>(({ detail, projectId }) =>
}),
);
- const tasks = (detail.tasks ?? []).filter((task) => !isGoalTask(task));
+ const tasks = detail.tasks ?? [];
const activeTasks = tasks.filter((task) => !TERMINAL_STATUSES.has(task.status)).slice(0, 5);
const attentionTasks = tasks.filter((task) => ATTENTION_STATUSES.has(task.status)).slice(0, 3);
- const completedGoals = goals.filter((goal) => goal.status === 'completed').length;
+ const completedGoals = goals.filter(({ goal }) => goal.status === 'achieved').length;
const progress = goals.length ? Math.round((completedGoals / goals.length) * 100) : 0;
const works = workSWR.data?.items ?? [];
const goalPreview = useMemo(() => goals.slice(0, 3), [goals]);
@@ -202,16 +200,16 @@ const ProjectDashboard = memo<ProjectDashboardProps>(({ detail, projectId }) =>
</Flexbox>
<Progress percent={progress} showInfo={false} />
<div className={styles.goalGrid}>
- {goalPreview.map((goal) => (
+ {goalPreview.map(({ goal }) => (
<Flexbox className={styles.goal} gap={5} key={goal.id}>
<Flexbox horizontal align={'center'} gap={6}>
<Icon
- color={goal.status === 'completed' ? cssVar.colorSuccess : undefined}
- icon={goal.status === 'completed' ? CheckCircle2Icon : CircleDotIcon}
+ color={goal.status === 'achieved' ? cssVar.colorSuccess : undefined}
+ icon={goal.status === 'achieved' ? CheckCircle2Icon : CircleDotIcon}
size={15}
/>
<Text ellipsis weight={500}>
- {goal.name || goal.instruction}
+ {goal.title}
</Text>
</Flexbox>
<Text fontSize={12} type={'secondary'}>
diff --git a/src/libs/swr/keys.ts b/src/libs/swr/keys.ts
index 512940b3549..3935597f01b 100644
--- a/src/libs/swr/keys.ts
+++ b/src/libs/swr/keys.ts
@@ -317,6 +317,14 @@ export const isTaskListKey = (key: unknown): boolean =>
export const isScheduledTaskListKey = (key: unknown): boolean =>
Array.isArray(key) && key[0] === 'task:scheduledList';
+/**
+ * Goal Graph reads. Keyed by the `goals` row id (not the carrier task's
+ * identifier) because that is what every `goal.*` procedure takes.
+ */
+export const goalKeys = {
+ graph: def('goal:graph', (goalId: string) => ['goal:graph', goalId]),
+};
+
export const taskKeys = {
detail: def('task:detail', (taskId: string) => ['task:detail', taskId]),
groupList: def(
@@ -1344,6 +1352,7 @@ export const swrKeys = {
file: fileKeys,
fork: forkKeys,
gateway: gatewayKeys,
+ goal: goalKeys,
global: globalKeys,
group: groupKeys,
home: homeKeys,
diff --git a/src/routes/(main)/eval/features/SegmentBar.tsx b/src/routes/(main)/eval/features/SegmentBar.tsx
index 5c2b723c206..5ede726cb8b 100644
--- a/src/routes/(main)/eval/features/SegmentBar.tsx
+++ b/src/routes/(main)/eval/features/SegmentBar.tsx
@@ -6,7 +6,6 @@ import { memo } from 'react';
const styles = createStaticStyles(({ css }) => ({
segment: css`
height: 100%;
-
transition: width 0.3s ease;
@media (prefers-reduced-motion: reduce) {
@@ -14,8 +13,8 @@ const styles = createStaticStyles(({ css }) => ({
}
`,
track: css`
- display: flex;
overflow: hidden;
+ display: flex;
width: 100%;
border-radius: 999px;
diff --git a/src/routes/(main)/goal/[goalId]/index.tsx b/src/routes/(main)/goal/[goalId]/index.tsx
new file mode 100644
index 00000000000..c0917e9a13b
--- /dev/null
+++ b/src/routes/(main)/goal/[goalId]/index.tsx
@@ -0,0 +1,20 @@
+'use client';
+
+import { useParams } from 'react-router';
+
+import { GoalDetailPage } from '@/features/AgentGoals';
+
+/**
+ * Goal detail without an agent in the path, mirroring the bare `/task/:taskId`
+ * route. A goal created from a project page has no responsible agent, so this
+ * is the only way to open one.
+ */
+const GoalDetailRoute = () => {
+ const { goalId } = useParams<{ goalId?: string }>();
+
+ if (!goalId) return null;
+
+ return <GoalDetailPage goalId={goalId} />;
+};
+
+export default GoalDetailRoute;
diff --git a/src/services/__tests__/task.test.ts b/src/services/__tests__/task.test.ts
index cea0c41680a..32c0942089d 100644
--- a/src/services/__tests__/task.test.ts
+++ b/src/services/__tests__/task.test.ts
@@ -103,11 +103,6 @@ describe('TaskService', () => {
expect(lambdaClient.task.delete.mutate).toHaveBeenCalledWith({ id: 'T-1' });
});
- it('deleteGoal should call the subtree deletion endpoint', async () => {
- await taskService.deleteGoal('GOAL-1');
- expect(lambdaClient.task.deleteGoal.mutate).toHaveBeenCalledWith({ id: 'GOAL-1' });
- });
-
it('updateStatus should pass status directly', async () => {
await taskService.updateStatus('T-1', 'running');
expect(lambdaClient.task.updateStatus.mutate).toHaveBeenCalledWith({
diff --git a/src/services/goal.ts b/src/services/goal.ts
index 55a4162b9bf..7041b6caca7 100644
--- a/src/services/goal.ts
+++ b/src/services/goal.ts
@@ -1,4 +1,5 @@
import type { GoalStatus } from '@lobechat/const/goal';
+import type { GoalConfig, GoalGraphSnapshot, GoalNodeKind, GoalTickResult } from '@lobechat/types';
import { lambdaClient } from '@/libs/trpc/client';
@@ -10,12 +11,80 @@ export interface GoalListParams {
statuses?: GoalStatus[];
}
+/** Every graph method takes the `goals` row id. */
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);
+
+ /** Create a goal and seed its graph with a problem node and the given Work. */
+ create = async (params: {
+ agentId?: string;
+ config?: GoalConfig;
+ maxRounds?: number;
+ maxTotalCost?: number;
+ projectId?: string;
+ requirement?: string;
+ title: string;
+ work?: Array<{ description?: string; title: string } | string>;
+ }): Promise<GoalGraphSnapshot> => {
+ const { data } = await lambdaClient.goal.create.mutate(params);
+ return data;
+ };
+
+ /** Delete a goal and its graph. The dispatched Work Tasks are left in place. */
+ delete = async (id: string) => lambdaClient.goal.delete.mutate({ id });
+
+ /** The whole Goal Graph in one read: nodes, edges, decisions, events, work-version links. */
+ getGraph = async (id: string): Promise<GoalGraphSnapshot> => {
+ const { data } = await lambdaClient.goal.graph.query({ id });
+ return data;
+ };
+
+ /**
+ * Run the coordinator now and report where it stopped. The goal also advances
+ * on its own as its Work Tasks settle — this is the explicit nudge, not the
+ * engine, so the surface never has to hold a tick loop open.
+ */
+ advance = async (id: string): Promise<GoalTickResult & { ticks: number }> => {
+ const { data } = await lambdaClient.goal.advance.mutate({ id });
+ return data;
+ };
+
+ /** Advance the graph by exactly one coordinator step. */
+ tick = async (id: string): Promise<GoalTickResult> => {
+ const { data } = await lambdaClient.goal.tick.mutate({ id });
+ return data;
+ };
+
+ /** Stop scheduling new work. Does not abort the operation already running. */
+ pause = async (id: string) => lambdaClient.goal.pause.mutate({ id });
+
+ resume = async (id: string) => lambdaClient.goal.resume.mutate({ id });
+
+ /** Resolve a pending decision gate. Does not resume a paused goal by itself. */
+ decide = async (params: {
+ decisionId: string;
+ id: string;
+ optionId: string;
+ resolution?: string;
+ }) => lambdaClient.goal.decide.mutate(params);
+
+ setBudget = async (params: {
+ id: string;
+ maxRounds?: number | null;
+ maxTotalCost?: number | null;
+ }) => lambdaClient.goal.setBudget.mutate(params);
+
+ addNode = async (params: {
+ description?: string;
+ id: string;
+ kind: GoalNodeKind;
+ priority?: number;
+ title: string;
+ }) => lambdaClient.goal.addNode.mutate(params);
}
export const goalService = new GoalService();
diff --git a/src/services/task.ts b/src/services/task.ts
index 72cf9229423..c8ac82904a5 100644
--- a/src/services/task.ts
+++ b/src/services/task.ts
@@ -1,9 +1,4 @@
-import type {
- CheckpointConfig,
- CreateTaskGoalInput,
- TaskAutomationMode,
- TaskStatus,
-} from '@lobechat/types';
+import type { CheckpointConfig, TaskAutomationMode, TaskStatus } from '@lobechat/types';
import { lambdaClient } from '@/libs/trpc/client';
@@ -17,7 +12,6 @@ class TaskService {
list = async (params: {
assigneeAgentId?: string;
automated?: boolean;
- hasGoal?: boolean;
orderBy?: 'createdAt' | 'updatedAt';
limit?: number;
offset?: number;
@@ -40,7 +34,6 @@ class TaskService {
offset?: number;
statuses: string[];
}>;
- hasGoal?: boolean;
parentTaskId?: string | null;
projectId?: string;
visibility?: 'private' | 'public';
@@ -73,7 +66,6 @@ class TaskService {
description?: string;
editorData?: unknown;
/** Bind a goal entity (`goals` row) to the created task. */
- goal?: CreateTaskGoalInput;
identifierPrefix?: string;
instruction: string;
name?: string;
@@ -116,8 +108,6 @@ class TaskService {
delete = async (id: string) => lambdaClient.task.delete.mutate({ id });
- deleteGoal = async (id: string) => lambdaClient.task.deleteGoal.mutate({ id });
-
clearAll = async () => lambdaClient.task.clearAll.mutate();
updateStatus = async (id: string, status: TaskStatus, error?: string) =>
diff --git a/src/spa/router/desktopRouter.shared.tsx b/src/spa/router/desktopRouter.shared.tsx
index 5c10b5ce529..2f79bac5674 100644
--- a/src/spa/router/desktopRouter.shared.tsx
+++ b/src/spa/router/desktopRouter.shared.tsx
@@ -985,6 +985,20 @@ export const sharedMainAreaChildren: RouteObject[] = [
errorElement: <ErrorBoundary resetPath="../tasks" />,
path: 'task',
},
+ {
+ children: [
+ {
+ element: dynamicElement(
+ () => import('@/routes/(main)/goal/[goalId]'),
+ 'Desktop > Goal Detail',
+ ),
+ handle: { meta: goalDetailRouteMeta },
+ path: ':goalId',
+ },
+ ],
+ errorElement: <ErrorBoundary resetPath="../tasks" />,
+ path: 'goal',
+ },
],
element: dynamicLayout(
() => import('@/routes/(main)/(task-workspace)/_layout'),
diff --git a/src/store/goal/action.test.ts b/src/store/goal/action.test.ts
index 2c48cdec5d7..18313cdb4cc 100644
--- a/src/store/goal/action.test.ts
+++ b/src/store/goal/action.test.ts
@@ -2,13 +2,13 @@ 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/goal', () => ({ goalService: { list: vi.fn() } }));
-vi.mock('@/services/task', () => ({ taskService: { deleteGoal: vi.fn() } }));
+vi.mock('@/services/goal', () => ({
+ goalService: { delete: vi.fn(), list: vi.fn() },
+}));
beforeEach(() => {
vi.clearAllMocks();
@@ -24,6 +24,43 @@ beforeEach(() => {
});
describe('GoalAction', () => {
+ describe('useFetchGoalGraph', () => {
+ const refreshIntervalFor = (status: string) => {
+ useGoalStore.getState().useFetchGoalGraph('goal-1');
+ const options = vi.mocked(useClientDataSWR).mock.calls.at(-1)?.[2] as {
+ refreshInterval: (graph?: { goal: { status: string } }) => number;
+ };
+ return options.refreshInterval({ goal: { status } });
+ };
+
+ it.each(['planning', 'running', 'verifying'])(
+ 'keeps re-reading a %s goal the server is still advancing',
+ (status) => {
+ // The goal advances from server events now; without this the page would
+ // sit on its first snapshot until the tab lost and regained focus.
+ expect(refreshIntervalFor(status)).toBeGreaterThan(0);
+ },
+ );
+
+ it.each(['review', 'paused', 'achieved', 'failed', 'canceled'])(
+ 'stops polling a %s goal',
+ (status) => {
+ // Nothing on the server will move these — the next change comes from a
+ // person, and the action that makes it refreshes the snapshot itself.
+ expect(refreshIntervalFor(status)).toBe(0);
+ },
+ );
+
+ it('does not poll before the first snapshot arrives', () => {
+ useGoalStore.getState().useFetchGoalGraph('goal-1');
+ const options = vi.mocked(useClientDataSWR).mock.calls.at(-1)?.[2] as {
+ refreshInterval: (graph?: unknown) => number;
+ };
+
+ expect(options.refreshInterval(undefined)).toBe(0);
+ });
+ });
+
it('stores goal lists independently for each agent', () => {
useGoalStore.getState().useFetchGoals('agent-1');
const options = vi.mocked(useClientDataSWR).mock.calls[0][2] as {
@@ -122,23 +159,18 @@ describe('GoalAction', () => {
});
});
- it('deletes a goal subtree through the goal endpoint and removes it from local state', async () => {
+ it('deletes a goal 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: { goals: Array<{ id: string; identifier: string }> }) => void;
+ onSuccess: (value: { goals: Array<{ goal: { id: string } }> }) => void;
};
- options.onSuccess({
- goals: [
- { id: 'goal-1', identifier: 'GOAL-1' },
- { id: 'goal-2', identifier: 'GOAL-2' },
- ],
- });
+ options.onSuccess({ goals: [{ goal: { id: 'goal-1' } }, { goal: { id: 'goal-2' } }] });
- await useGoalStore.getState().deleteGoal('agent-1', 'GOAL-1');
+ await useGoalStore.getState().deleteGoal('agent-1', 'goal-1');
- expect(taskService.deleteGoal).toHaveBeenCalledWith('GOAL-1');
+ expect(goalService.delete).toHaveBeenCalledWith('goal-1');
expect(useGoalStore.getState().goalListByAgentId['agent-1']).toEqual([
- { id: 'goal-2', identifier: 'GOAL-2' },
+ { goal: { id: 'goal-2' } },
]);
});
});
diff --git a/src/store/goal/action.ts b/src/store/goal/action.ts
index 389fc5f1eac..ccf89de1864 100644
--- a/src/store/goal/action.ts
+++ b/src/store/goal/action.ts
@@ -1,9 +1,9 @@
import { type GoalStatus, goalStatuses } from '@lobechat/const/goal';
+import type { GoalTickResult } from '@lobechat/types';
import { mutate, useClientDataSWR } from '@/libs/swr';
-import { taskKeys } from '@/libs/swr/keys';
+import { goalKeys, 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';
@@ -28,6 +28,20 @@ const GOAL_STATUSES: GoalStatus[] = [...goalStatuses];
const HOME_GOAL_STATUSES: GoalStatus[] = ['planning', 'running', 'verifying', 'review'];
const HOME_GOAL_FETCH_LIMIT = 100;
+/**
+ * Statuses in which the *server* is the one making progress. A goal now
+ * advances from server events, so nothing tells an open page to re-read: the
+ * frontier, activity and findings would sit frozen — a spinner still turning
+ * on a goal that already finished — until the tab lost and regained focus.
+ *
+ * `review` and `paused` are deliberately out: those wait on a person, and the
+ * action that moves them refreshes the snapshot itself.
+ */
+const SERVER_ADVANCING_STATUSES = new Set<GoalStatus>(['planning', 'running', 'verifying']);
+
+/** Kept coarse on purpose — this is liveness, not a progress bar. */
+const GOAL_GRAPH_POLL_INTERVAL = 5000;
+
export type GoalStore = GoalState & GoalAction;
type Setter = StoreSetter<GoalStore>;
@@ -41,22 +55,104 @@ export class GoalActionImpl {
this.#set = set;
}
- deleteGoal = async (agentId: string, goalId: string): Promise<void> => {
- await taskService.deleteGoal(goalId);
- const current = this.#get().goalListByAgentId[agentId] ?? [];
- this.#set(
- ({ goalListByAgentId }) => ({
- goalListByAgentId: {
- ...goalListByAgentId,
- [agentId]: current.filter(({ id, identifier }) => id !== goalId && identifier !== goalId),
- },
- }),
- false,
- 'deleteGoal/success',
- );
- await this.refreshGoals(agentId);
+ /**
+ * `agentId` is absent for a goal with no responsible agent — one created from
+ * a project page. There is no per-agent list to prune in that case, so only
+ * the scoped refetch happens, against the list scope the caller was rendering
+ * (`project:<id>` on a project page, the agent id otherwise).
+ */
+ deleteGoal = async (
+ agentId: string | undefined,
+ goalId: string,
+ scopeId?: string,
+ ): Promise<void> => {
+ await goalService.delete(goalId);
+ if (agentId) {
+ const current = this.#get().goalListByAgentId[agentId] ?? [];
+ this.#set(
+ ({ goalListByAgentId }) => ({
+ goalListByAgentId: {
+ ...goalListByAgentId,
+ [agentId]: current.filter(({ goal }) => goal.id !== goalId),
+ },
+ }),
+ false,
+ 'deleteGoal/success',
+ );
+ }
+ const scope = scopeId ?? agentId;
+ if (scope) await this.refreshGoals(scope);
+ };
+
+ /**
+ * Resolve a pending decision gate. `goalId` is the `goals` row id.
+ *
+ * Resolving a gate does not advance the graph — the coordinator only moves on
+ * the next tick — so the caller decides whether to follow up with `tickGoal`.
+ */
+ decideGoal = async (
+ goalId: string,
+ params: { decisionId: string; optionId: string; resolution?: string },
+ ): Promise<void> => {
+ await goalService.decide({ id: goalId, ...params });
+ await this.refreshGoalGraph(goalId);
};
+ pauseGoal = async (goalId: string): Promise<void> => {
+ await goalService.pause(goalId);
+ await this.refreshGoalGraph(goalId);
+ };
+
+ refreshGoalGraph = async (goalId: string): Promise<void> => {
+ await mutate(goalKeys.graph(goalId));
+ };
+
+ resumeGoal = async (goalId: string): Promise<void> => {
+ await goalService.resume(goalId);
+ await this.refreshGoalGraph(goalId);
+ };
+
+ setGoalBudget = async (
+ goalId: string,
+ budget: { maxRounds?: number | null; maxTotalCost?: number | null },
+ ): Promise<void> => {
+ await goalService.setBudget({ id: goalId, ...budget });
+ await this.refreshGoalGraph(goalId);
+ };
+
+ /**
+ * Ask the server to run the coordinator now. The goal keeps advancing on its
+ * own afterwards as its Work Tasks settle, so this is a nudge rather than the
+ * loop the surface used to hold open.
+ */
+ advanceGoal = async (goalId: string): Promise<GoalTickResult> => {
+ const result = await goalService.advance(goalId);
+ await this.refreshGoalGraph(goalId);
+ return result;
+ };
+
+ /** Exactly one coordinator step, for a caller that wants to inspect a single move. */
+ tickGoal = async (goalId: string): Promise<GoalTickResult> => {
+ const result = await goalService.tick(goalId);
+ await this.refreshGoalGraph(goalId);
+ return result;
+ };
+
+ /** The Goal Graph snapshot behind the process-control surface. */
+ useFetchGoalGraph = (goalId?: string | null) =>
+ useClientDataSWR(goalId ? goalKeys.graph(goalId) : null, () => goalService.getGraph(goalId!), {
+ onSuccess: (graph) => {
+ this.#set(
+ ({ goalGraphById }) => ({ goalGraphById: { ...goalGraphById, [goalId!]: graph } }),
+ false,
+ 'useFetchGoalGraph/success',
+ );
+ },
+ refreshInterval: (graph) =>
+ graph && SERVER_ADVANCING_STATUSES.has(graph.goal.status) ? GOAL_GRAPH_POLL_INTERVAL : 0,
+ revalidateOnFocus: true,
+ });
+
loadMoreGoals = (): void => {
this.#set(
({ goalListVisibleLimit }) => ({ goalListVisibleLimit: goalListVisibleLimit + 10 }),
diff --git a/src/store/goal/initialState.ts b/src/store/goal/initialState.ts
index e2139497588..9b377b97efa 100644
--- a/src/store/goal/initialState.ts
+++ b/src/store/goal/initialState.ts
@@ -1,3 +1,5 @@
+import type { GoalGraphSnapshot } from '@lobechat/types';
+
import type { GoalListItem } from '@/services/goal';
export type { GoalListItem };
@@ -5,6 +7,8 @@ export type GoalListFilter = 'active' | 'all';
export type GoalViewMode = 'card' | 'list';
export interface GoalState {
+ /** Goal Graph snapshots keyed by `goals.id` — the process-control surface's read model. */
+ goalGraphById: Record<string, GoalGraphSnapshot>;
goalListByAgentId: Record<string, GoalListItem[]>;
goalListFilter: GoalListFilter;
goalListInitializedAgentIds: string[];
@@ -21,6 +25,7 @@ export interface GoalState {
}
export const initialState: GoalState = {
+ goalGraphById: {},
goalListByAgentId: {},
goalListFilter: 'active',
goalListInitializedAgentIds: [],
diff --git a/src/store/goal/selectors.ts b/src/store/goal/selectors.ts
index c396612fab7..f0d9030fc5b 100644
--- a/src/store/goal/selectors.ts
+++ b/src/store/goal/selectors.ts
@@ -2,6 +2,9 @@ import type { GoalStore } from './action';
const EMPTY_GOALS: GoalStore['goalListByAgentId'][string] = [];
+const goalGraph = (goalId?: string | null) => (s: GoalStore) =>
+ goalId ? s.goalGraphById[goalId] : undefined;
+
const goalList = (agentId: string) => (s: GoalStore) => s.goalListByAgentId[agentId] ?? EMPTY_GOALS;
const isGoalListInitialized = (agentId: string) => (s: GoalStore) =>
@@ -13,6 +16,7 @@ const isHomeGoalsInitialized = (scope: string) => (s: GoalStore) =>
s.homeGoalsInitializedScopes.includes(scope);
export const goalSelectors = {
+ goalGraph,
goalList,
homeGoals,
isGoalListInitialized,
diff --git a/src/store/task/slices/detail/action.ts b/src/store/task/slices/detail/action.ts
index 6b5253340eb..7f7be10ec80 100644
--- a/src/store/task/slices/detail/action.ts
+++ b/src/store/task/slices/detail/action.ts
@@ -1,4 +1,4 @@
-import type { CreateTaskGoalInput, TaskDetailData, TaskDetailSubtask } from '@lobechat/types';
+import type { TaskDetailData, TaskDetailSubtask } from '@lobechat/types';
import { toast } from '@lobehub/ui/base-ui';
import isEqual from 'fast-deep-equal';
import { t } from 'i18next';
@@ -190,7 +190,6 @@ export class TaskDetailSliceActionImpl {
description?: string;
editorData?: unknown;
/** Bind a goal entity (`goals` row) to the created task. */
- goal?: CreateTaskGoalInput;
instruction: string;
name?: string;
parentTaskId?: string;
diff --git a/src/store/task/slices/list/action.test.ts b/src/store/task/slices/list/action.test.ts
index f411c207cda..be274afc4cd 100644
--- a/src/store/task/slices/list/action.test.ts
+++ b/src/store/task/slices/list/action.test.ts
@@ -114,7 +114,6 @@ describe('TaskListSliceAction', () => {
automated: false,
excludeStatuses: ['completed', 'canceled'],
groupBy: 'assignee',
- hasGoal: false,
projectId: undefined,
visibility: undefined,
});
diff --git a/src/store/task/slices/list/action.ts b/src/store/task/slices/list/action.ts
index 8a564ff0781..c1f9a881322 100644
--- a/src/store/task/slices/list/action.ts
+++ b/src/store/task/slices/list/action.ts
@@ -246,7 +246,6 @@ export class TaskListSliceActionImpl {
...(automated === undefined ? {} : { automated }),
excludeStatuses: excludeStatuses?.length ? [...excludeStatuses] : undefined,
...(groupBy === 'status' ? { groups: DEFAULT_KANBAN_GROUPS } : { groupBy }),
- hasGoal: false,
projectId,
visibility: filterToServerVisibility(listVisibility),
});
@@ -304,7 +303,6 @@ export class TaskListSliceActionImpl {
this.fetchTaskList({
...(projectId ? { projectId } : agentId ? { assigneeAgentId: agentId } : {}),
automated: true,
- hasGoal: false,
limit,
offset,
orderBy: 'updatedAt',
@@ -397,7 +395,6 @@ export class TaskListSliceActionImpl {
return this.fetchTaskList({
...(allAgents || projectId ? {} : { assigneeAgentId: id }),
automated,
- hasGoal: false,
orderBy,
projectId,
statuses: statuses?.length ? [...statuses] : undefined,