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): change goal status from the detail page menu (#20159)

Arvin Xub1bf94376ad0
diff --git a/apps/server/src/routers/lambda/goal.ts b/apps/server/src/routers/lambda/goal.ts
index c0d763e6ebb..a90d4bf93ce 100644
--- a/apps/server/src/routers/lambda/goal.ts
+++ b/apps/server/src/routers/lambda/goal.ts
@@ -723,6 +723,26 @@ export const goalRouter = router({
}
}),
+ /**
+ * End the goal by hand — achieved or canceled — and interrupt its live runs.
+ * Reopening a closed goal is `resume`.
+ */
+ close: goalWriteProcedure
+ .input(idInput.extend({ status: z.enum(['achieved', 'canceled']) }))
+ .mutation(async ({ ctx, input: { id, status } }) => {
+ try {
+ // Closing cancels live runs, so it carries the same ownership check as restart.
+ const goal = await ctx.goalModel.findById(id);
+ if (!goal) throw new TRPCError({ code: 'NOT_FOUND', message: 'Goal not found' });
+ assertWorkspaceRowManageable(ctx, goal.userId, 'goal');
+
+ const data = await ctx.goalService.close(id, status);
+ return { data, message: `Goal ${status}`, success: true };
+ } catch (error) {
+ mapGoalError(error, 'close');
+ }
+ }),
+
/**
* Start every unfinished Task node over (cancel stale runs, back to
* `backlog`), optionally under a different agent, and kick the coordinator
diff --git a/apps/server/src/services/goal/index.test.ts b/apps/server/src/services/goal/index.test.ts
index 3874feeceda..918efd5bd6e 100644
--- a/apps/server/src/services/goal/index.test.ts
+++ b/apps/server/src/services/goal/index.test.ts
@@ -34,6 +34,7 @@ import {
} from '@/database/schemas';
import type { LobeChatDatabase } from '@/database/type';
import { AgentRuntimeCoordinator } from '@/server/modules/AgentRuntime/AgentRuntimeCoordinator';
+import { AiAgentService } from '@/server/services/aiAgent';
import { deviceGateway } from '../deviceGateway';
import { TaskService } from '../task';
@@ -460,6 +461,36 @@ describe('GoalService', () => {
expect((await taskModel.findById(created.taskId!))?.status).toBe(settledAs);
});
+ it.each([LEASE_EXPIRED_ERROR, VERIFICATION_ERRORED_ERROR])(
+ 'does not start a recovery run once the goal is fenced for closing (%s)',
+ async (error) => {
+ const runSpy = vi
+ .spyOn(TaskRunnerService.prototype, 'runTask')
+ .mockResolvedValue({} as never);
+ const service = new GoalService(serverDB, userId);
+ const taskModel = new TaskModel(serverDB, userId);
+ const graph = await service.create({ title: `Fenced recovery ${error}`, tasks: ['Stop'] });
+ const created = await service.tick(graph.goal.id);
+ await taskModel.updateStatus(created.taskId!, 'paused', { error });
+ // The tick decided on a running goal; `close` then paused it under the
+ // goal row lock before scanning live runs.
+ const decidedOn = (await service.graph(graph.goal.id)).goal;
+ const task = (await taskModel.findById(created.taskId!))!;
+ await service.pause(graph.goal.id);
+ runSpy.mockClear();
+
+ const recovery = await new TaskRecoveryCoordinator(serverDB, userId).recover({
+ goal: decidedOn,
+ task,
+ });
+
+ expect(recovery.outcome).toBe('goal-stopped');
+ expect(runSpy).not.toHaveBeenCalled();
+ expect((await taskModel.findById(created.taskId!))?.status).toBe('paused');
+ expect((await service.graph(graph.goal.id)).goal.status).toBe('paused');
+ },
+ );
+
it('does not restart a Task a person paused themselves', async () => {
const runSpy = vi.spyOn(TaskRunnerService.prototype, 'runTask').mockResolvedValue({} as never);
const service = new GoalService(serverDB, userId);
@@ -1218,6 +1249,282 @@ describe('GoalService', () => {
expect(resumed.goal.status).not.toBe('paused');
});
+ it('closes a goal by hand, stops its live runs and stops the coordinator', async () => {
+ const cancelSpy = vi.spyOn(TaskService.prototype, 'cancelTopic').mockResolvedValue();
+ const service = new GoalService(serverDB, userId);
+ const graph = await service.create({ tasks: ['First', 'Second'], title: 'Closable' });
+ const created = await service.tick(graph.goal.id);
+ await new TaskModel(serverDB, userId).update(created.taskId!, { status: 'running' });
+ await serverDB.insert(topics).values({ id: 'tpc_close', userId });
+ await new TaskTopicModel(serverDB, userId).add(created.taskId!, 'tpc_close', { seq: 1 });
+ await new TaskTopicModel(serverDB, userId).updateStatus(
+ created.taskId!,
+ 'tpc_close',
+ 'running',
+ );
+
+ const closed = await service.close(graph.goal.id, 'canceled');
+
+ expect(closed.status).toBe('canceled');
+ expect(cancelSpy).toHaveBeenCalledWith('tpc_close');
+ // Back to backlog, not parked on a person, so a reopen runs it again.
+ expect((await new TaskModel(serverDB, userId).findById(created.taskId!))?.status).toBe(
+ 'backlog',
+ );
+ expect(await service.tick(graph.goal.id)).toMatchObject({ outcome: 'failed' });
+ const [closeEvent] = await serverDB
+ .select()
+ .from(goalEvents)
+ .where(eq(goalEvents.reason, 'canceled by user'));
+ // Filed under the person, not the coordinator.
+ expect(closeEvent).toMatchObject({ actorId: userId, eventType: 'rejected' });
+
+ // A closed goal reopens through the ordinary resume.
+ expect((await service.resume(graph.goal.id)).status).toBe('running');
+ expect((await service.close(graph.goal.id, 'achieved')).status).toBe('achieved');
+ });
+
+ it('fences new dispatch before interrupting the runs of a goal being closed', async () => {
+ // A tick overlapping the close must not claim another Task while the scan
+ // and cancellation are under way, so the goal stops reading `running` first.
+ const service = new GoalService(serverDB, userId);
+ const graph = await service.create({ tasks: ['Runs'], title: 'Fenced' });
+ const created = await service.tick(graph.goal.id);
+ await new TaskModel(serverDB, userId).update(created.taskId!, { status: 'running' });
+ await serverDB.insert(topics).values({ id: 'tpc_fence', userId });
+ await new TaskTopicModel(serverDB, userId).add(created.taskId!, 'tpc_fence', { seq: 1 });
+ await new TaskTopicModel(serverDB, userId).updateStatus(
+ created.taskId!,
+ 'tpc_fence',
+ 'running',
+ );
+ const statusDuringCancel: string[] = [];
+ vi.spyOn(TaskService.prototype, 'cancelTopic').mockImplementation(async () => {
+ const goal = await new GoalModel(serverDB, userId).findById(graph.goal.id);
+ statusDuringCancel.push(goal!.status);
+ });
+
+ await service.close(graph.goal.id, 'canceled');
+
+ expect(statusDuringCancel).toEqual(['paused']);
+ });
+
+ it('refuses to close while a claimed run is still starting, so it can be stopped with confirmation', async () => {
+ // `dispatchWork` marks the Task running before `runTask` records the topic,
+ // so the close scan finds no run to cancel — and a run nobody recorded
+ // cannot be interrupted with confirmation. The close waits for it instead.
+ const cancelSpy = vi.spyOn(TaskService.prototype, 'cancelTopic').mockResolvedValue();
+ const service = new GoalService(serverDB, userId);
+ const graph = await service.create({ tasks: ['Starting'], title: 'Claimed, not recorded' });
+ const created = await service.tick(graph.goal.id);
+ await new TaskModel(serverDB, userId).update(created.taskId!, { status: 'running' });
+
+ await expect(service.close(graph.goal.id, 'canceled')).rejects.toMatchObject({
+ code: 'PRECONDITION_FAILED',
+ });
+
+ expect(cancelSpy).not.toHaveBeenCalled();
+ // Fenced, so nothing new starts, and the claim is left for its run to record.
+ expect((await new GoalModel(serverDB, userId).findById(graph.goal.id))?.status).toBe('paused');
+ expect((await new TaskModel(serverDB, userId).findById(created.taskId!))?.status).toBe(
+ 'running',
+ );
+ });
+
+ it('withdraws a claim whose startup died long ago and closes the goal', async () => {
+ const service = new GoalService(serverDB, userId);
+ const graph = await service.create({ tasks: ['Dead start'], title: 'Stale claim' });
+ const created = await service.tick(graph.goal.id);
+ await serverDB
+ .update(tasks)
+ .set({ status: 'running', updatedAt: new Date(Date.now() - 24 * 60 * 60 * 1000) })
+ .where(eq(tasks.id, created.taskId!));
+
+ expect((await service.close(graph.goal.id, 'canceled')).status).toBe('canceled');
+ expect((await new TaskModel(serverDB, userId).findById(created.taskId!))?.status).toBe(
+ 'backlog',
+ );
+ });
+
+ it('keeps a closed goal closed when a stale decision is answered', async () => {
+ const service = new GoalService(serverDB, userId);
+ const taskModel = new TaskModel(serverDB, userId);
+ const graph = await service.create({ tasks: ['Risky task'], title: 'Closed with a gate' });
+ const created = await service.tick(graph.goal.id);
+ await taskModel.updateStatus(created.taskId!, 'paused', { error: 'Verifier rejected output' });
+ await service.tick(graph.goal.id);
+ const [decision] = (await service.graph(graph.goal.id)).decisions;
+
+ await service.close(graph.goal.id, 'canceled');
+
+ // Another tab still showing the gate answers it.
+ await expect(service.decide(graph.goal.id, decision.id, 'retry')).rejects.toMatchObject({
+ code: 'CONFLICT',
+ });
+ expect((await new GoalModel(serverDB, userId).findById(graph.goal.id))?.status).toBe(
+ 'canceled',
+ );
+ });
+
+ it('does not reopen a goal closed while a decision was being answered', async () => {
+ const service = new GoalService(serverDB, userId);
+ const taskModel = new TaskModel(serverDB, userId);
+ const graph = await service.create({ tasks: ['Risky task'], title: 'Closed mid-answer' });
+ const created = await service.tick(graph.goal.id);
+ await taskModel.updateStatus(created.taskId!, 'paused', { error: 'Verifier rejected output' });
+ await service.tick(graph.goal.id);
+ const [decision] = (await service.graph(graph.goal.id)).decisions;
+ // The close lands after the answer is written, before the status moves.
+ const graphModel = (service as unknown as { graphModel: GoalGraphModel }).graphModel;
+ const resolve = graphModel.resolveDecision;
+ vi.spyOn(graphModel, 'resolveDecision').mockImplementation(async (...args) => {
+ const resolved = await resolve(...args);
+ await new GoalService(serverDB, userId).close(graph.goal.id, 'canceled');
+ return resolved;
+ });
+
+ await service.decide(graph.goal.id, decision.id, 'retry');
+
+ expect((await new GoalModel(serverDB, userId).findById(graph.goal.id))?.status).toBe(
+ 'canceled',
+ );
+ });
+
+ it('refuses to end a goal someone resumed while its runs were being interrupted', async () => {
+ const service = new GoalService(serverDB, userId);
+ const graph = await service.create({ tasks: ['Runs'], title: 'Resumed mid-close' });
+ const created = await service.tick(graph.goal.id);
+ await new TaskModel(serverDB, userId).update(created.taskId!, { status: 'running' });
+ await serverDB.insert(topics).values({ id: 'tpc_race', userId });
+ await new TaskTopicModel(serverDB, userId).add(created.taskId!, 'tpc_race', { seq: 1 });
+ await new TaskTopicModel(serverDB, userId).updateStatus(created.taskId!, 'tpc_race', 'running');
+ // Another tab resumes the goal while the interruption pass is running.
+ vi.spyOn(TaskService.prototype, 'cancelTopic').mockImplementation(async () => {
+ await new GoalService(serverDB, userId).resume(graph.goal.id);
+ });
+
+ await expect(service.close(graph.goal.id, 'canceled')).rejects.toMatchObject({
+ code: 'CONFLICT',
+ });
+ expect((await new GoalModel(serverDB, userId).findById(graph.goal.id))?.status).toBe('running');
+ });
+
+ it('does not let a resume that read the goal before a close reopen it afterwards', async () => {
+ // The resume read the fenced `paused` goal; the close then committed the
+ // terminal status. The stale resume must not write `running` over it.
+ const service = new GoalService(serverDB, userId);
+ const graph = await service.create({ tasks: ['Runs'], title: 'Resume after close' });
+ await service.pause(graph.goal.id);
+ const requireGraph = (service as unknown as { requireGraph: GoalService['graph'] })
+ .requireGraph;
+ vi.spyOn(service as any, 'requireGraph').mockImplementationOnce(async (id) => {
+ const snapshot = await requireGraph(id as string);
+ await new GoalService(serverDB, userId).close(graph.goal.id, 'canceled');
+ return snapshot;
+ });
+
+ await expect(service.resume(graph.goal.id)).rejects.toMatchObject({ code: 'CONFLICT' });
+ expect((await new GoalModel(serverDB, userId).findById(graph.goal.id))?.status).toBe(
+ 'canceled',
+ );
+ // An explicit reopen of the ended goal still works.
+ expect((await service.resume(graph.goal.id)).status).toBe('running');
+ });
+
+ it('keeps runs already stopped reopenable when a later interruption fails', async () => {
+ const service = new GoalService(serverDB, userId);
+ const taskModel = new TaskModel(serverDB, userId);
+ const topicModel = new TaskTopicModel(serverDB, userId);
+ const graph = await service.create({ tasks: ['First', 'Second'], title: 'Partial close' });
+ const [first, second] = graph.nodes.filter((node) => node.kind === 'task');
+ const taskIds: string[] = [];
+ for (const [index, node] of [first, second].entries()) {
+ const task = await new TaskService(serverDB, userId).createTask({
+ instruction: node.title,
+ name: node.title,
+ });
+ await new GoalGraphModel(serverDB, userId).bindTask(graph.goal.id, node.id, task.id);
+ await taskModel.update(task.id, { status: 'running' });
+ const topicId = `tpc_partial_${index}`;
+ await serverDB.insert(topics).values({ id: topicId, userId });
+ await topicModel.add(task.id, topicId, { seq: 1 });
+ await topicModel.updateStatus(task.id, topicId, 'running');
+ taskIds.push(task.id);
+ }
+ // The first interruption lands (the task reads `paused`, as cancelTopic
+ // leaves it); the second is unreachable.
+ let calls = 0;
+ vi.spyOn(TaskService.prototype, 'cancelTopic').mockImplementation(async (topicId) => {
+ calls += 1;
+ if (calls > 1) throw new Error('run unreachable');
+ const index = Number(topicId.at(-1));
+ await taskModel.update(taskIds[index], { status: 'paused' });
+ await topicModel.updateStatus(taskIds[index], topicId, 'canceled');
+ });
+
+ await expect(service.close(graph.goal.id, 'canceled')).rejects.toMatchObject({
+ code: 'PRECONDITION_FAILED',
+ });
+ const stopped = (await taskModel.findByIds(taskIds)).filter(
+ (task) => task.status !== 'running',
+ );
+ expect(stopped).toHaveLength(1);
+ expect(stopped[0].status).toBe('backlog');
+ });
+
+ describe('closing a goal with a main Agent turn in flight', () => {
+ const managedGoal = async (title: string) => {
+ const service = new GoalService(serverDB, userId);
+ const graph = await service.create({ tasks: ['Managed'], title });
+ await new AgentOperationModel(serverDB, userId).recordStart({
+ operationId: `op-manager-${title}`,
+ });
+ await serverDB
+ .update(goals)
+ .set({
+ config: {
+ ...graph.goal.config,
+ manager: {},
+ managerState: {
+ operationId: `op-manager-${title}`,
+ startedAt: new Date().toISOString(),
+ token: 'turn',
+ topicId: 'management-topic',
+ turns: 1,
+ },
+ } as never,
+ })
+ .where(eq(goals.id, graph.goal.id));
+ return { goalId: graph.goal.id, service };
+ };
+
+ it('interrupts the main Agent turn before ending the goal', async () => {
+ // The coordinator's own operation is not a graph Task topic, so the
+ // topic scan alone would leave it spending after the goal ended.
+ const { goalId, service } = await managedGoal('interrupted');
+ const interrupt = vi
+ .spyOn(AiAgentService.prototype, 'interruptTask')
+ .mockResolvedValue({ success: true } as never);
+
+ expect((await service.close(goalId, 'achieved')).status).toBe('achieved');
+ expect(interrupt).toHaveBeenCalledWith(
+ expect.objectContaining({ operationId: 'op-manager-interrupted' }),
+ );
+ });
+
+ it('refuses to end the goal when the interruption is not confirmed', async () => {
+ const { goalId, service } = await managedGoal('unconfirmed');
+ vi.spyOn(AiAgentService.prototype, 'interruptTask').mockResolvedValue({
+ deviceCancellationConfirmed: false,
+ success: true,
+ } as never);
+
+ await expect(service.close(goalId, 'canceled')).rejects.toThrow(/not closed/);
+ // Still fenced so nothing new starts, but not claimed as ended.
+ expect((await new GoalModel(serverDB, userId).findById(goalId))?.status).toBe('paused');
+ });
+ });
+
it('restarts a split-role goal under a new executor without replacing its supervisor', async () => {
vi.spyOn(TaskService.prototype, 'cancelTopic').mockResolvedValue();
await serverDB.insert(agents).values([
diff --git a/apps/server/src/services/goal/index.ts b/apps/server/src/services/goal/index.ts
index 080c638b7a9..81ec2ea14bb 100644
--- a/apps/server/src/services/goal/index.ts
+++ b/apps/server/src/services/goal/index.ts
@@ -113,6 +113,8 @@ const REPORT_CHECK_OUTCOMES = new Set<GoalTickResult['outcome']>([
/** A Goal whose delivery the owner can still send back for rework. */
const REOPENABLE_GOAL_STATUSES = new Set(['achieved', 'running']);
const TASK_DESCRIPTION_MAX_LENGTH = 255;
+/** Ends a person reached, or the coordinator's verdict of success: nothing reopens these but `resume`. */
+const GOAL_ENDED_STATUSES = new Set<string>(['achieved', 'canceled']);
/** Advisory-lock namespace for goal dispatch. `0x676f_6469` is ASCII `godi`. */
const GOAL_DISPATCH_LOCK_NAMESPACE = 0x67_6f_64_69;
@@ -1644,13 +1646,177 @@ export class GoalService {
const status = graph.decisions.some((decision) => decision.status === 'pending')
? 'review'
: 'running';
- await this.setPauseReason(goalId, undefined);
- const goal = await this.transitionStatus(graph.goal, status, 'resumed by user', 'user');
- return goal ?? graph.goal;
+ // Compare-and-set under the row lock `close` commits under: a resume that
+ // read the goal before a concurrent close ended it must not write its stale
+ // `running` over the ended goal, where the close already put interrupted
+ // Tasks back to `backlog` and they would dispatch again. Reopening an ended
+ // goal still works — that resume reads the ended status itself.
+ return this.db.transaction(async (tx) => {
+ const model = new GoalModel(tx, this.userId, this.workspaceId);
+ const current = await model.lockById(goalId);
+ if (!current) throw new TRPCError({ code: 'NOT_FOUND', message: 'Goal not found' });
+ if (current.status !== graph.goal.status) {
+ throw new TRPCError({
+ code: 'CONFLICT',
+ message: 'The goal changed while it was being resumed; try again.',
+ });
+ }
+ await model.updatePauseReason(goalId, undefined);
+ if (current.status === status) return current;
+ const updated = await model.updateStatus(goalId, status);
+ await new GoalGraphModel(tx, this.userId, this.workspaceId)
+ .recordGoalStatus(goalId, current.status, status, 'resumed by user')
+ .catch((error) => console.error('[GoalService] failed to record goal status:', error));
+ return updated ?? current;
+ });
+ };
+
+ /**
+ * A person ends the goal themselves — declaring it achieved or dropping it.
+ *
+ * Everything still spending on the goal is interrupted first — the main
+ * Agent's planning turn, the supervisor's diagnosis and every Task run — the
+ * same way `delete` does, because a terminal status alone only stops the
+ * coordinator from dispatching more. Reopening goes through `resume`, which
+ * accepts any status.
+ */
+ close = async (goalId: string, to: 'achieved' | 'canceled') => {
+ // Fence new claims before scanning: `dispatchWork` claims under this row
+ // lock and only while the goal reads `running`, so an advance overlapping
+ // the close cannot start a Task after the scan below. The pause is the
+ // person's, so no measurement lifts it if the close is refused later on.
+ await this.db.transaction(async (db) => {
+ const model = new GoalModel(db, this.userId, this.workspaceId);
+ const current = await model.lockById(goalId);
+ // Only a goal that can still dispatch needs fencing.
+ if (!current || ['paused', 'achieved', 'failed', 'canceled'].includes(current.status)) return;
+ await model.updateStatus(goalId, 'paused');
+ await model.updatePauseReason(goalId, 'user');
+ await new GoalGraphModel(db, this.userId, this.workspaceId).recordGoalStatus(
+ goalId,
+ current.status,
+ 'paused',
+ 'Stopping Goal before closing',
+ );
+ });
+ const graph = await this.requireGraph(goalId);
+
+ // Deliberately not swallowed, as in `delete`: an operation whose exit is
+ // unconfirmed keeps spending, and a goal reading "ended" would hide it. The
+ // goal stays paused so nothing new starts, and the person can retry.
+ const notClosed = (error: unknown) =>
+ new TRPCError({
+ cause: error,
+ code: 'PRECONDITION_FAILED',
+ message:
+ 'Could not stop the work still running for this goal, so it was not closed. Try again once the run is reachable.',
+ });
+ try {
+ if (graph.goal.config?.manager)
+ await new GoalManagerService(this.db, this.userId, this.workspaceId).stop(graph);
+ if (graph.goal.config?.supervision?.enabled || graph.goal.config?.supervisorState)
+ await new GoalSupervisorService(this.db, this.userId, this.workspaceId).stop(graph);
+ } catch (error) {
+ throw notClosed(error);
+ }
+
+ const unfinishedTaskIds = graph.nodes.flatMap((node) =>
+ node.kind === 'task' && node.taskId && !TERMINAL_NODE_STATUSES.has(node.status)
+ ? [node.taskId]
+ : [],
+ );
+ if (unfinishedTaskIds.length > 0) {
+ // Claims whose run has not been recorded yet. `dispatchWork` marks the
+ // Task `running` before `runTask` records the topic, so the scan below
+ // cannot see that run, and only a recorded run can be interrupted with
+ // confirmation. A fresh claim therefore refuses the close: the goal stays
+ // fenced, and a retry a moment later finds the run recorded and stops it
+ // the confirmed way. A claim older than the operation lease is one whose
+ // startup died; it is withdrawn to `backlog` under the task row lock the
+ // recording also takes, so a straggler recording stops its own run.
+ const staleBefore = Date.now() - resolveOperationLeaseTimeout(graph.goal);
+ let starting = false;
+ for (const taskId of unfinishedTaskIds) {
+ await this.db.transaction(async (tx) => {
+ const taskModel = new TaskModel(tx, this.userId, this.workspaceId);
+ if (!(await taskModel.lockForUpdate(taskId))) return;
+ const task = await taskModel.findById(taskId);
+ if (task?.status !== 'running') return;
+ const recorded = await new TaskTopicModel(
+ tx,
+ this.userId,
+ this.workspaceId,
+ ).findRunningByTaskIds([taskId]);
+ if (recorded.length > 0) return;
+ if (task.updatedAt.getTime() > staleBefore) {
+ starting = true;
+ return;
+ }
+ await taskModel.updateStatusIfCurrent(taskId, 'running', 'backlog', { error: null });
+ });
+ }
+ if (starting)
+ throw new TRPCError({
+ code: 'PRECONDITION_FAILED',
+ message:
+ 'A run for this goal is still starting, so it was not closed. No new work will start; try again in a moment.',
+ });
+
+ const runningTopics = await this.taskTopicModel.findRunningByTaskIds(unfinishedTaskIds);
+ for (const topic of runningTopics) {
+ if (!topic.topicId) continue;
+ try {
+ await this.taskService.cancelTopic(topic.topicId);
+ } catch (error) {
+ throw notClosed(error);
+ }
+ // Reset right after its own interruption, as in `restart`: left `paused`
+ // it reads as parked on a person and a reopened goal waits on it. Doing
+ // it per run means a later failed interruption cannot strand the ones
+ // already stopped — a retry no longer sees them as running. CAS so a
+ // row a concurrent tick just moved is never yanked.
+ const task = await this.taskModel.findById(topic.taskId);
+ if (task && task.status !== 'completed') {
+ await this.taskModel.updateStatusIfCurrent(task.id, task.status, 'backlog', {
+ error: null,
+ });
+ }
+ }
+ }
+ // Commit under the same lock the fence took, and only if the fence still
+ // holds: a resume from another tab during the interruption pass lets an
+ // advance claim work this pass never saw, and ending the goal over it
+ // would leave that run spending on a goal reading "ended".
+ const reason = to === 'achieved' ? 'marked achieved by user' : 'canceled by user';
+ const goal = await this.db.transaction(async (db) => {
+ const model = new GoalModel(db, this.userId, this.workspaceId);
+ const current = await model.lockById(goalId);
+ if (!current) throw new TRPCError({ code: 'NOT_FOUND', message: 'Goal not found' });
+ if (!['paused', 'achieved', 'failed', 'canceled'].includes(current.status)) {
+ throw new TRPCError({
+ code: 'CONFLICT',
+ message: 'The goal was resumed while it was being closed, so it was not closed.',
+ });
+ }
+ await model.updatePauseReason(goalId, undefined);
+ if (current.status === to) return current;
+ const updated = await model.updateStatus(goalId, to);
+ await new GoalGraphModel(db, this.userId, this.workspaceId)
+ .recordGoalStatus(goalId, current.status, to, reason)
+ .catch((error) => console.error('[GoalService] failed to record goal status:', error));
+ return updated;
+ });
+ if (!goal) throw new TRPCError({ code: 'NOT_FOUND', message: 'Goal not found' });
+ return goal;
};
decide = async (goalId: string, decisionId: string, optionId: string, resolution?: string) => {
const graph = await this.requireGraph(goalId);
+ // A goal a person ended stays ended: a gate another tab still shows must
+ // not reopen it. Checked again under the lock before the status moves.
+ if (GOAL_ENDED_STATUSES.has(graph.goal.status)) {
+ throw new TRPCError({ code: 'CONFLICT', message: 'This goal has ended' });
+ }
const decision = graph.decisions.find((item) => item.id === decisionId);
if (!decision || decision.status !== 'pending') {
throw new TRPCError({ code: 'NOT_FOUND', message: 'Pending decision not found' });
@@ -1702,11 +1868,25 @@ export class GoalService {
: terminalAcceptance && optionId === 'retire'
? 'canceled'
: 'running';
- await this.transitionStatus(
- graph.goal,
- nextStatus,
- `decision "${decision.question}" resolved: ${optionId}`,
- );
+ // Serialized with `close`, which commits under this row lock: a goal that
+ // ended while this answer was being written is left ended.
+ await this.db.transaction(async (tx) => {
+ const current = await new GoalModel(tx, this.userId, this.workspaceId).lockById(goalId);
+ if (!current || GOAL_ENDED_STATUSES.has(current.status)) return;
+ if (current.status === nextStatus) return;
+ await new GoalModel(tx, this.userId, this.workspaceId).updateStatus(goalId, nextStatus);
+ await new GoalGraphModel(tx, this.userId, this.workspaceId, {
+ id: GOAL_COORDINATOR_ACTOR_ID,
+ type: 'system',
+ })
+ .recordGoalStatus(
+ goalId,
+ current.status,
+ nextStatus,
+ `decision "${decision.question}" resolved: ${optionId}`,
+ )
+ .catch((error) => console.error('[GoalService] failed to record goal status:', error));
+ });
return resolved;
};
@@ -2405,6 +2585,18 @@ export class GoalService {
};
}
+ // The goal was paused or ended (a close fenced it) while this advance was
+ // deciding: start nothing and do not reopen it.
+ if (recovery.outcome === 'goal-stopped') {
+ return {
+ goalId: graph.goal.id,
+ message: 'Goal stopped while recovery was being decided',
+ nodeId,
+ outcome: 'no_progress',
+ taskId: task.id,
+ };
+ }
+
// Nothing failed: somebody settled the Task while this advance was deciding.
// Opening a gate would ask them to judge their own decision.
if (recovery.outcome === 'settled') {
@@ -2742,6 +2934,18 @@ export class GoalService {
};
}
+ // The goal was paused or ended (a close fenced it) while this advance was
+ // deciding: start nothing and do not reopen it.
+ if (recovery.outcome === 'goal-stopped') {
+ return {
+ goalId: graph.goal.id,
+ message: 'Goal stopped while recovery was being decided',
+ nodeId,
+ outcome: 'no_progress',
+ taskId: task.id,
+ };
+ }
+
// Nothing failed: somebody settled the Task while this advance was deciding.
// Opening a gate would ask them to judge their own decision.
if (recovery.outcome === 'settled') {
diff --git a/apps/server/src/services/goal/taskRecoveryCoordinator.ts b/apps/server/src/services/goal/taskRecoveryCoordinator.ts
index e925644ad58..456b0fce6f0 100644
--- a/apps/server/src/services/goal/taskRecoveryCoordinator.ts
+++ b/apps/server/src/services/goal/taskRecoveryCoordinator.ts
@@ -2,6 +2,7 @@ import type { GoalItem, TaskItem } from '@lobechat/types';
import debug from 'debug';
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 type { LobeChatDatabase } from '@/database/type';
@@ -19,6 +20,13 @@ import { claimGoalTask } from './taskClaim';
const log = debug('lobe-server:goal-task-recovery');
+/**
+ * Goal statuses under which no recovery may start a run. `close` fences a goal
+ * by pausing it under its row lock before scanning live runs, so a recovery
+ * claim has to recheck the goal under that same lock.
+ */
+const GOAL_FENCED_STATUSES = new Set(['paused', 'achieved', 'failed', 'canceled']);
+
export type TaskRecoveryOutcome =
/** This call spawned the retry, and `operationId` is its run. */
| 'started'
@@ -26,6 +34,8 @@ export type TaskRecoveryOutcome =
| 'already-running'
/** Someone settled the Task while this recovery was being decided. */
| 'settled'
+ /** The goal was paused or ended (e.g. being closed) before the claim. */
+ | 'goal-stopped'
| 'exhausted-cost'
| 'exhausted-rounds'
| 'spawn-failed';
@@ -110,10 +120,24 @@ export class TaskRecoveryCoordinator {
log('task %s was paused by an actor; leaving it alone', task.identifier);
return { outcome: 'settled' };
}
- const claimed = await claimGoalTask(taskModel, { id: task.id, status: 'paused' }, 'running', {
- error: null,
- startedAt: new Date(),
+ // Claimed under the goal row lock, like `dispatchWork`: the tick decided on
+ // a goal snapshot, and a `close` may have fenced the goal (paused it) since.
+ // Claiming after that fence would start a run its running-topic scan never
+ // sees, and the goal would then be closed over a run still spending.
+ const claimed = await this.db.transaction(async (tx) => {
+ const currentGoal = await new GoalModel(tx, this.userId, this.workspaceId).lockById(goal.id);
+ if (!currentGoal || GOAL_FENCED_STATUSES.has(currentGoal.status)) return 'goal-stopped';
+ return claimGoalTask(
+ new TaskModel(tx, this.userId, this.workspaceId),
+ { id: task.id, status: 'paused' },
+ 'running',
+ { error: null, startedAt: new Date() },
+ );
});
+ if (claimed === 'goal-stopped') {
+ log('task %s recovery skipped: goal %s is no longer running', task.identifier, goal.id);
+ return { outcome: 'goal-stopped' };
+ }
if (!claimed) {
log('task %s recovery lost the claim race', task.identifier);
return { outcome: 'already-running' };
diff --git a/apps/server/src/services/taskRunner/index.ts b/apps/server/src/services/taskRunner/index.ts
index 7dc4db1fa5d..bbc3b5ba237 100644
--- a/apps/server/src/services/taskRunner/index.ts
+++ b/apps/server/src/services/taskRunner/index.ts
@@ -381,13 +381,15 @@ export class TaskRunnerService {
// node — while this run was being dispatched, whoever did it found no
// topic to stop yet. Nobody else will stop it, so stop it here instead
// of recording an operation that keeps running behind the cancellation.
+ // A claim withdrawn mid-startup is the same case: closing or restarting
+ // a goal puts a claimed Task with no recorded run back to `backlog`.
const recorded = await this.db.transaction(async (tx) => {
const taskModel = new TaskModel(tx, this.userId, this.workspaceId);
const taskTopicModel = new TaskTopicModel(tx, this.userId, this.workspaceId);
if (!(await taskModel.lockForUpdate(task.id))) return 'deleted' as const;
- if ((await taskModel.findById(task.id))?.status === 'canceled') {
- return 'canceled' as const;
- }
+ const current = await taskModel.findById(task.id);
+ if (current?.status === 'canceled') return 'canceled' as const;
+ if (current?.status === 'backlog') return 'withdrawn' as const;
if (continueTopicId) {
await taskTopicModel.updateStatus(task.id, continueTopicId, 'running');
await taskTopicModel.updateOperationId(task.id, continueTopicId, result.operationId);
diff --git a/apps/server/src/services/taskRunner/runTask.deleteRace.test.ts b/apps/server/src/services/taskRunner/runTask.deleteRace.test.ts
index 8673feb6313..b5cfa6e8f49 100644
--- a/apps/server/src/services/taskRunner/runTask.deleteRace.test.ts
+++ b/apps/server/src/services/taskRunner/runTask.deleteRace.test.ts
@@ -126,6 +126,19 @@ describe('TaskRunnerService.runTask vs. a concurrent delete', () => {
expect(taskTopicModel.add).not.toHaveBeenCalled();
});
+ it('stops the run it just dispatched when its claim was withdrawn meanwhile', async () => {
+ // Closing or restarting a goal puts a claimed Task whose run is not yet
+ // recorded back to `backlog`; the run must not be recorded over that.
+ taskModel.findById.mockResolvedValue({ ...task, status: 'backlog' });
+
+ await expect(new TaskRunnerService(db, 'user-1').runTask({ taskId: 'T-1' })).rejects.toThrow(
+ 'The task was withdrawn while its run was starting',
+ );
+
+ expect(mocks.interruptTask).toHaveBeenCalledWith({ operationId: 'op-new' });
+ expect(taskTopicModel.add).not.toHaveBeenCalled();
+ });
+
it.each([{ success: false }, { deviceCancellationConfirmed: false, success: true }])(
'does not claim the orphaned run stopped when the stop is unconfirmed (%j)',
async (stop) => {
diff --git a/locales/en-US/chat.json b/locales/en-US/chat.json
index a4d78736e5f..8697d704440 100644
--- a/locales/en-US/chat.json
+++ b/locales/en-US/chat.json
@@ -446,6 +446,12 @@
"goalDetail.acceptanceError": "Could not load acceptance checks.",
"goalDetail.acceptanceProgress": "Acceptance progress",
"goalDetail.agentRun": "Agent run",
+ "goalDetail.closeConfirm.achieved.content": "Runs still in progress will be stopped and no new tasks will start. You can reopen the goal from this menu.",
+ "goalDetail.closeConfirm.achieved.ok": "Mark achieved",
+ "goalDetail.closeConfirm.achieved.title": "Mark this goal as achieved?",
+ "goalDetail.closeConfirm.canceled.content": "Runs still in progress will be stopped and no new tasks will start. You can reopen the goal from this menu.",
+ "goalDetail.closeConfirm.canceled.ok": "Cancel goal",
+ "goalDetail.closeConfirm.canceled.title": "Cancel this goal?",
"goalDetail.definition": "Goal definition",
"goalDetail.deleteConfirm.content": "This goal and its task plan will be permanently deleted. Conversation history is retained.",
"goalDetail.deleteConfirm.ok": "Delete goal",
@@ -777,6 +783,7 @@
"goalProcess.node.producedByTitle": "Produced by",
"goalProcess.node.producedFindings": "Produced findings",
"goalProcess.node.running": "Running",
+ "goalProcess.node.stopped": "Stopped",
"goalProcess.node.terminalAcceptance": "Complete full goal acceptance",
"goalProcess.node.unanswered": "Unanswered",
"goalProcess.node.unassigned": "Not dispatched",
diff --git a/locales/zh-CN/chat.json b/locales/zh-CN/chat.json
index 29330d23d2b..2f98612e1ae 100644
--- a/locales/zh-CN/chat.json
+++ b/locales/zh-CN/chat.json
@@ -446,6 +446,12 @@
"goalDetail.acceptanceError": "无法加载验收检查。",
"goalDetail.acceptanceProgress": "验收进度",
"goalDetail.agentRun": "Agent 运行",
+ "goalDetail.closeConfirm.achieved.content": "仍在运行的任务会被中止,也不会再开始新的任务。之后可以在这个菜单里重新打开目标。",
+ "goalDetail.closeConfirm.achieved.ok": "标记为已达成",
+ "goalDetail.closeConfirm.achieved.title": "将这个目标标记为已达成?",
+ "goalDetail.closeConfirm.canceled.content": "仍在运行的任务会被中止,也不会再开始新的任务。之后可以在这个菜单里重新打开目标。",
+ "goalDetail.closeConfirm.canceled.ok": "取消目标",
+ "goalDetail.closeConfirm.canceled.title": "取消这个目标?",
"goalDetail.definition": "目标定义",
"goalDetail.deleteConfirm.content": "该目标及其任务计划将被永久删除;对话历史会保留。",
"goalDetail.deleteConfirm.ok": "删除目标",
@@ -777,6 +783,7 @@
"goalProcess.node.producedByTitle": "来自任务",
"goalProcess.node.producedFindings": "产出结论",
"goalProcess.node.running": "进行中",
+ "goalProcess.node.stopped": "已中止",
"goalProcess.node.terminalAcceptance": "完成目标整体验收",
"goalProcess.node.unanswered": "待回答",
"goalProcess.node.unassigned": "未派发",
diff --git a/packages/locales/src/default/chat.ts b/packages/locales/src/default/chat.ts
index 97ada5060ec..7b4b339461d 100644
--- a/packages/locales/src/default/chat.ts
+++ b/packages/locales/src/default/chat.ts
@@ -2012,6 +2012,14 @@ export default {
'The complete task tree and latest runs for this goal.',
'goalDetail.instruction': 'Goal instruction',
'goalDetail.latestRuns': 'Recent executions',
+ 'goalDetail.closeConfirm.achieved.content':
+ 'Runs still in progress will be stopped and no new tasks will start. You can reopen the goal from this menu.',
+ 'goalDetail.closeConfirm.achieved.ok': 'Mark achieved',
+ 'goalDetail.closeConfirm.achieved.title': 'Mark this goal as achieved?',
+ 'goalDetail.closeConfirm.canceled.content':
+ 'Runs still in progress will be stopped and no new tasks will start. You can reopen the goal from this menu.',
+ 'goalDetail.closeConfirm.canceled.ok': 'Cancel goal',
+ 'goalDetail.closeConfirm.canceled.title': 'Cancel this goal?',
'goalDetail.deleteConfirm.content':
'This goal and its task plan will be permanently deleted. Conversation history is retained.',
'goalDetail.deleteConfirm.ok': 'Delete goal',
@@ -2307,6 +2315,7 @@ export default {
'goalProcess.kind.finding': 'Finding',
'goalProcess.kind.decision': 'Decision',
'goalProcess.node.running': 'Running',
+ 'goalProcess.node.stopped': 'Stopped',
'goalProcess.node.done': 'Done',
'goalProcess.node.waiting': 'Waiting',
'goalProcess.node.terminalAcceptance': 'Complete full goal acceptance',
diff --git a/src/features/AgentGoals/GoalDetailActions.tsx b/src/features/AgentGoals/GoalDetailActions.tsx
index f0f77168210..0f548c1500b 100644
--- a/src/features/AgentGoals/GoalDetailActions.tsx
+++ b/src/features/AgentGoals/GoalDetailActions.tsx
@@ -1,11 +1,28 @@
import { copyToClipboard, Icon } from '@lobehub/ui';
-import { ActionIcon, type DropdownItem, DropdownMenu, toast } from '@lobehub/ui/base-ui';
-import { CopyIcon, LinkIcon, MoreHorizontalIcon, TrashIcon } from 'lucide-react';
-import { memo, useMemo } from 'react';
+import {
+ ActionIcon,
+ confirmModal,
+ type DropdownItem,
+ DropdownMenu,
+ toast,
+} from '@lobehub/ui/base-ui';
+import { CircleDashedIcon, CopyIcon, LinkIcon, MoreHorizontalIcon, TrashIcon } from 'lucide-react';
+import { memo, useCallback, useMemo } from 'react';
import { useTranslation } from 'react-i18next';
+import { TASK_STATUS_VISUALS } from '@/components/ExecutionStatus';
+import { renderMenuCheck } from '@/features/AgentTasks/features/menuExtra';
import { usePermission } from '@/hooks/usePermission';
+import { useResourceManageable } from '@/hooks/useResourceManageable';
+import { goalSelectors, useGoalStore } from '@/store/goal';
+import { goalStatusToTaskStatus } from './goalPresentation';
+import {
+ isStatusChoiceDisabled,
+ MANUAL_STATUSES,
+ type ManualGoalStatus,
+ toManualStatus,
+} from './goalStatusMenu';
import { useConfirmDeleteGoal, useGoalShareUrl } from './useGoalActions';
interface GoalDetailActionsProps {
@@ -20,9 +37,56 @@ const GoalDetailActions = memo<GoalDetailActionsProps>(({ agentId, goalId, proje
const { allowed: canEditTask } = usePermission('create_content');
const shareUrl = useGoalShareUrl({ agentId, goalId });
const confirmDelete = useConfirmDeleteGoal({ agentId, goalId, projectId });
+ const status = useGoalStore((s) => goalSelectors.goalGraph(goalId)(s)?.goal.status);
+ const creatorUserId = useGoalStore((s) => goalSelectors.goalGraph(goalId)(s)?.goal.userId);
+ // Closing interrupts runs, so the server only lets the creator or a
+ // workspace owner do it — the same rule as restart.
+ const canClose = useResourceManageable(creatorUserId);
+ const pauseGoal = useGoalStore((s) => s.pauseGoal);
+ const resumeGoal = useGoalStore((s) => s.resumeGoal);
+ const closeGoal = useGoalStore((s) => s.closeGoal);
+
+ const current = toManualStatus(status);
+
+ const changeStatus = useCallback(
+ (next: ManualGoalStatus) => {
+ if (next === current) return;
+ if (next === 'running') return void resumeGoal(goalId);
+ if (next === 'paused') return void pauseGoal(goalId);
+ // Closing interrupts live runs, so it asks first.
+ confirmModal({
+ cancelText: t('cancel', { ns: 'common' }),
+ content: t(`goalDetail.closeConfirm.${next}.content`),
+ okButtonProps: { danger: next === 'canceled' },
+ okText: t(`goalDetail.closeConfirm.${next}.ok`),
+ onOk: () => closeGoal(goalId, next),
+ title: t(`goalDetail.closeConfirm.${next}.title`),
+ });
+ },
+ [closeGoal, current, goalId, pauseGoal, resumeGoal, t],
+ );
const items = useMemo<DropdownItem[]>(
() => [
+ // Same shape as a task's status submenu: status-colored glyphs, a check on the current one.
+ {
+ children: MANUAL_STATUSES.map((next) => {
+ const visual = TASK_STATUS_VISUALS[goalStatusToTaskStatus(next)];
+ return {
+ disabled: isStatusChoiceDisabled(next, status, canClose),
+ extra: renderMenuCheck(next === current),
+ icon: <Icon color={visual.color} icon={visual.icon} />,
+ key: `status-${next}`,
+ label: t(`goalList.status.${next}`),
+ onClick: () => changeStatus(next),
+ };
+ }),
+ disabled: !canEditTask || !status,
+ icon: <Icon icon={CircleDashedIcon} />,
+ key: 'status',
+ label: t('taskList.contextMenu.status'),
+ },
+ { type: 'divider' },
{
icon: <Icon icon={CopyIcon} />,
key: 'copyId',
@@ -53,7 +117,7 @@ const GoalDetailActions = memo<GoalDetailActionsProps>(({ agentId, goalId, proje
onClick: confirmDelete,
},
],
- [canEditTask, confirmDelete, goalId, shareUrl, t],
+ [canClose, canEditTask, changeStatus, confirmDelete, current, goalId, shareUrl, status, t],
);
return (
diff --git a/src/features/AgentGoals/ProcessControl/Graph/GraphNode.tsx b/src/features/AgentGoals/ProcessControl/Graph/GraphNode.tsx
index e7ef268e95c..fb89ff76d7c 100644
--- a/src/features/AgentGoals/ProcessControl/Graph/GraphNode.tsx
+++ b/src/features/AgentGoals/ProcessControl/Graph/GraphNode.tsx
@@ -232,6 +232,13 @@ const useStateChip = (data: GraphNodeData): StateChip | null => {
// Running renders the same animated ring the frontier and home surfaces use.
if (running)
return { color: TASK_STATUS_VISUALS.running.color, text: t('goalProcess.node.running') };
+ // The goal ended under this run: it was stopped, not still going.
+ if (view.halted)
+ return {
+ color: TASK_STATUS_VISUALS.canceled.color,
+ icon: TASK_STATUS_VISUALS.canceled.icon,
+ text: t('goalProcess.node.stopped'),
+ };
if (node.kind === 'task' && node.status === 'resolved')
return {
color: TASK_STATUS_VISUALS.completed.color,
diff --git a/src/features/AgentGoals/ProcessControl/goalGraphViewModel.test.ts b/src/features/AgentGoals/ProcessControl/goalGraphViewModel.test.ts
index faaa0113899..59c0a4d5a27 100644
--- a/src/features/AgentGoals/ProcessControl/goalGraphViewModel.test.ts
+++ b/src/features/AgentGoals/ProcessControl/goalGraphViewModel.test.ts
@@ -304,6 +304,25 @@ describe('buildGoalGraphView', () => {
expect(view.byId.w1.startedAt).toEqual(at(115));
});
+ it.each(['canceled', 'achieved', 'failed'] as const)(
+ 'stops calling a task running once its goal is %s',
+ (status) => {
+ const view = buildGoalGraphView(
+ snapshot({
+ events: [event('w1', 'activated', 115)],
+ goal: goal({ status, updatedAt: at(118) }),
+ nodes: [node('w1', { status: 'active', taskId: 'task-1', updatedAt: at(115) })],
+ }),
+ NOW,
+ );
+
+ expect(view.frontier).toHaveLength(0);
+ expect(isRunningNode(view.byId.w1)).toBe(false);
+ expect(view.byId.w1.startedAt).toBeUndefined();
+ expect(view.byId.w1.attempts.at(-1)).toMatchObject({ endedAt: at(118), outcome: 'retired' });
+ },
+ );
+
it('closes the parked attempt of a Task 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 Task kept
@@ -366,6 +385,48 @@ describe('buildGoalGraphView', () => {
expect(view.byId.d1.gateSubjectId).toBe('w1');
});
+ it.each(['canceled', 'achieved'] as const)(
+ 'offers no gate to answer once the goal is %s',
+ (status) => {
+ // The server refuses every answer on an ended goal until it is reopened.
+ const view = buildGoalGraphView(
+ snapshot({
+ decisions: [
+ {
+ authority: 'user',
+ canceledAt: null,
+ createdAt: at(50),
+ id: 'dec-1',
+ nodeId: 'd1',
+ options: [{ id: 'retry', label: 'Retry task' }],
+ question: 'Retry?',
+ recommendedOptionId: 'retry',
+ requestedProjectRole: null,
+ requestedUserId: 'user-1',
+ resolution: null,
+ resolvedAt: null,
+ resolvedByAgentId: null,
+ resolvedByUserId: null,
+ resolvedOptionId: null,
+ status: 'pending',
+ updatedAt: at(50),
+ },
+ ],
+ edges: [edge('w1', 'd1', 'leads_to')],
+ goal: goal({ status }),
+ nodes: [
+ node('w1', { status: 'waiting' }),
+ node('d1', { kind: 'decision', status: 'waiting' }),
+ ],
+ }),
+ NOW,
+ );
+
+ expect(view.frontier).toHaveLength(0);
+ expect(view.needsYou).toBe(0);
+ },
+ );
+
it('links a finding to the task that produced it and the problem it answers', () => {
const view = buildGoalGraphView(
snapshot({
diff --git a/src/features/AgentGoals/ProcessControl/goalGraphViewModel.ts b/src/features/AgentGoals/ProcessControl/goalGraphViewModel.ts
index 97cb7b69a5d..44a70d4c9e4 100644
--- a/src/features/AgentGoals/ProcessControl/goalGraphViewModel.ts
+++ b/src/features/AgentGoals/ProcessControl/goalGraphViewModel.ts
@@ -109,6 +109,12 @@ export interface GoalNodeView {
findings: GoalGraphNode[];
/** Decision only: the Task this gate was opened for — its ledger is the case. */
gateSubjectId?: string;
+ /**
+ * Still `active` on a goal that has ended (achieved / canceled / failed).
+ * Closing a goal interrupts its runs but leaves the node where it was so a
+ * reopen can pick it up, so the row must not keep claiming it is running.
+ */
+ halted?: boolean;
/** Latest liveness signal: node row update or the run operation's lease heartbeat. */
heartbeatAt: Date;
/** Decisions on this node a human already resolved. */
@@ -178,9 +184,14 @@ export const opensOnResultSurface = (view: GoalNodeView): boolean => {
*/
export const isRunningNode = (view: GoalNodeView): boolean => {
if (view.node.kind === 'problem') return false;
- return view.node.status === 'active' && !view.isStale;
+ return view.node.status === 'active' && !view.isStale && !view.halted;
};
+/** A goal in one of these states runs nothing, whatever its nodes still say. */
+const CLOSED_GOAL_STATUSES = new Set<string>(['achieved', 'canceled', 'failed']);
+/** Ended by a person or by success: `GoalService.decide` refuses gates until a reopen. */
+const GOAL_ENDED_STATUSES = new Set<string>(['achieved', 'canceled']);
+
export type FrontierItemKind = 'gate' | 'stale' | 'verifying' | 'running' | 'ready' | 'done';
export interface FrontierItem {
@@ -327,6 +338,7 @@ export const buildGoalGraphView = (
} = snapshot;
const nodeById = new Map(nodes.map((node) => [node.id, node]));
const lease = leaseTimeoutMs(goal);
+ const goalClosed = CLOSED_GOAL_STATUSES.has(goal.status);
const dependsOn = new Map<string, string[]>();
const producesByTask = new Map<string, GoalGraphNode[]>();
@@ -396,7 +408,14 @@ export const buildGoalGraphView = (
const attempts = buildAttempts(node, events);
const closedReason = closedReasonOf(node, events);
const open = attempts.at(-1);
- const isRunningAttempt = node.status === 'active' && open?.outcome === 'running';
+ const halted = goalClosed && node.kind === 'task' && node.status === 'active';
+ const live = node.status === 'active' && !goalClosed;
+ // The goal ended under this attempt: it was interrupted, not still going.
+ if (halted && open?.outcome === 'running') {
+ open.endedAt = goal.updatedAt;
+ open.outcome = 'retired';
+ }
+ const isRunningAttempt = live && open?.outcome === 'running';
// Liveness = the newer of the node row (moves on observations / status
// changes) and the run operation's lease heartbeat (refreshed ~90s while
// the agent works). Judging from the node row alone flags any long quiet
@@ -420,7 +439,7 @@ export const buildGoalGraphView = (
acceptances?.[node.id]?.status === 'repairing';
const isVerifying =
node.kind === 'task' &&
- node.status === 'active' &&
+ live &&
(acceptanceVerifying || (!!delivered && now - delivered.getTime() <= VERIFY_SETTLE_GRACE_MS));
return {
@@ -445,12 +464,9 @@ export const buildGoalGraphView = (
gateSubjectId: gateSubject.get(node.id),
heartbeatAt,
humanTouches: nodeDecisions.filter((d) => d.status === 'resolved' && !!d.resolvedByUserId),
- isStale:
- node.kind === 'task' &&
- node.status === 'active' &&
- !isVerifying &&
- now - heartbeatAt.getTime() > lease,
+ isStale: node.kind === 'task' && live && !isVerifying && now - heartbeatAt.getTime() > lease,
isVerifying,
+ ...(halted ? { halted } : {}),
node,
producedBy: producedByFinding.get(node.id),
seq: node.kind === 'experiment' ? ++experimentSeq : node.kind === 'task' ? ++seq : undefined,
@@ -466,11 +482,16 @@ export const buildGoalGraphView = (
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 });
+ // An ended goal refuses answers until it is reopened, so its gates are
+ // not something the reader can act on.
+ if (!GOAL_ENDED_STATUSES.has(goal.status))
+ frontier.push({ key: node.id, kind: 'gate', rank: 0, view });
continue;
}
if (node.kind !== 'task') continue;
if (node.status === 'active') {
+ // Stopped by the goal ending: nothing can advance it until a reopen.
+ if (goalClosed) continue;
frontier.push({
key: node.id,
kind: view.isStale ? 'stale' : view.isVerifying ? 'verifying' : 'running',
diff --git a/src/features/AgentGoals/goalStatusMenu.test.ts b/src/features/AgentGoals/goalStatusMenu.test.ts
new file mode 100644
index 00000000000..7cfc6c33163
--- /dev/null
+++ b/src/features/AgentGoals/goalStatusMenu.test.ts
@@ -0,0 +1,29 @@
+import { describe, expect, it } from 'vitest';
+
+import { isStatusChoiceDisabled, toManualStatus } from './goalStatusMenu';
+
+describe('goal status menu', () => {
+ it.each(['review', 'achieved', 'canceled', 'failed'])(
+ 'does not offer pausing a goal that is %s',
+ (status) => {
+ expect(isStatusChoiceDisabled('paused', status, true)).toBe(true);
+ },
+ );
+
+ it.each(['planning', 'running', 'verifying', 'paused'])('offers pausing a %s goal', (status) => {
+ expect(isStatusChoiceDisabled('paused', status, true)).toBe(false);
+ });
+
+ it('only offers closing to a viewer who may manage the goal', () => {
+ expect(isStatusChoiceDisabled('achieved', 'running', false)).toBe(true);
+ expect(isStatusChoiceDisabled('canceled', 'running', false)).toBe(true);
+ expect(isStatusChoiceDisabled('canceled', 'running', true)).toBe(false);
+ // Reopening stays available: resume has no creator check.
+ expect(isStatusChoiceDisabled('running', 'canceled', false)).toBe(false);
+ });
+
+ it('reads coordinator verdicts as running and leaves a failed goal unchecked', () => {
+ expect(toManualStatus('review')).toBe('running');
+ expect(toManualStatus('failed')).toBeUndefined();
+ });
+});
diff --git a/src/features/AgentGoals/goalStatusMenu.ts b/src/features/AgentGoals/goalStatusMenu.ts
new file mode 100644
index 00000000000..627f50f4364
--- /dev/null
+++ b/src/features/AgentGoals/goalStatusMenu.ts
@@ -0,0 +1,33 @@
+/**
+ * The states a person may put a goal in. The rest (planning / verifying /
+ * review / failed) are the coordinator's verdicts, so they read as "running"
+ * here and picking "running" on a closed goal reopens it.
+ */
+export type ManualGoalStatus = 'running' | 'paused' | 'achieved' | 'canceled';
+
+export const MANUAL_STATUSES: ManualGoalStatus[] = ['running', 'paused', 'achieved', 'canceled'];
+
+/** Same rule as the page's pause button: pausing only paces a goal that is moving. */
+const PAUSABLE_STATUSES = new Set(['paused', 'planning', 'running', 'verifying']);
+
+export const toManualStatus = (status: string | undefined): ManualGoalStatus | undefined => {
+ if (status === 'paused' || status === 'achieved' || status === 'canceled') return status;
+ if (status === 'failed') return;
+ return status ? 'running' : undefined;
+};
+
+/**
+ * Whether a status choice would be refused or meaningless for this viewer.
+ * Pausing a goal in review or already ended would overwrite that state without
+ * pacing anything; closing interrupts runs, which the server only lets the
+ * goal's creator or a workspace owner do.
+ */
+export const isStatusChoiceDisabled = (
+ next: ManualGoalStatus,
+ status: string | undefined,
+ canClose: boolean,
+): boolean => {
+ if (next === 'paused') return !PAUSABLE_STATUSES.has(status ?? '');
+ if (next === 'achieved' || next === 'canceled') return !canClose;
+ return false;
+};
diff --git a/src/services/goal.ts b/src/services/goal.ts
index 15c31bf435f..3a063939672 100644
--- a/src/services/goal.ts
+++ b/src/services/goal.ts
@@ -105,6 +105,10 @@ class GoalService {
return data ?? [];
};
+ /** End the goal by hand and interrupt its live runs. Reopen with `resume`. */
+ close = async (id: string, status: 'achieved' | 'canceled') =>
+ lambdaClient.goal.close.mutate({ id, status });
+
/** Resolve a pending decision gate. Does not resume a paused goal by itself. */
decide = async (params: {
decisionId: string;
diff --git a/src/store/goal/action.ts b/src/store/goal/action.ts
index 423cb9b165c..1dee20920f0 100644
--- a/src/store/goal/action.ts
+++ b/src/store/goal/action.ts
@@ -135,6 +135,11 @@ export class GoalActionImpl {
await this.refreshGoalGraph(goalId);
};
+ closeGoal = async (goalId: string, status: 'achieved' | 'canceled'): Promise<void> => {
+ await goalService.close(goalId, status);
+ await this.refreshGoalGraph(goalId);
+ };
+
refreshGoalGraph = async (goalId: string): Promise<void> => {
await mutate(goalKeys.graph(goalId));
};