🤯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.
TypeScript agentagent-collaborationagent-harnessloop-engineeringmcppersonal-assistantproactive-agentskillssuper-agenttask-management
🐛 fix(goal): close a goal stuck on a planning turn that never ran (#22760)
Rdmclin2211e7466e2c5
diff --git a/apps/server/src/services/goal/GoalService/__tests__/lifecycle.test.ts b/apps/server/src/services/goal/GoalService/__tests__/lifecycle.test.tsindex 6ff065612d0..0282f18d80c 100644--- a/apps/server/src/services/goal/GoalService/__tests__/lifecycle.test.ts+++ b/apps/server/src/services/goal/GoalService/__tests__/lifecycle.test.ts@@ -301,6 +301,113 @@ describe('GoalService', () => {// Still fenced so nothing new starts, but not claimed as ended.expect((await new GoalModel(serverDB, userId).findById(goalId))?.status).toBe('paused');});++ // A dispatch that failed before its run was written (a database timeout in+ // `execAgent`) leaves a claimed turn with no operation to interrupt.+ const strandedGoal = async (+ title: string,+ startedAt: Date,+ receipt: Record<string, unknown> = {},+ ) => {+ const service = new GoalService(serverDB, userId);+ const graph = await service.create({ tasks: ['Managed'], title });+ await serverDB+ .update(goals)+ .set({+ config: {+ ...graph.goal.config,+ manager: {},+ managerState: {+ startedAt: startedAt.toISOString(),+ token: `turn-${title}`,+ topicId: 'management-topic',+ turns: 3,+ ...receipt,+ },+ } as never,+ })+ .where(eq(goals.id, graph.goal.id));+ return { goalId: graph.goal.id, service };+ };++ it('ends a goal whose timed-out main Agent turn never wrote a run', async () => {+ const { goalId, service } = await strandedGoal(+ 'stranded',+ new Date(Date.now() - 2 * 60 * 60_000),+ { dispatchReturnedWithoutRun: true },+ );+ const interrupt = vi.spyOn(AiAgentService.prototype, 'interruptTask');++ expect((await service.close(goalId, 'achieved')).status).toBe('achieved');+ expect(interrupt).not.toHaveBeenCalled();+ const goal = await new GoalModel(serverDB, userId).findById(goalId);+ expect(goal?.config?.managerState?.consumed).toBe(true);+ });++ // A straggling dispatch can record its run between the first lookup and the+ // locked re-check; that run is interrupted, not settled as never started.+ it('interrupts a run recorded while the stranded turn was being settled', async () => {+ const { goalId, service } = await strandedGoal(+ 'late-run',+ new Date(Date.now() - 2 * 60 * 60_000),+ { dispatchReturnedWithoutRun: true },+ );+ vi.spyOn(AgentOperationModel.prototype, 'findByTopicSourceMessage')+ .mockResolvedValueOnce(undefined)+ .mockResolvedValueOnce({ id: 'op-late', status: 'running' } as never);+ 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-late' }));+ const goal = await new GoalModel(serverDB, userId).findById(goalId);+ expect(goal?.config?.managerState?.consumed).toBeFalsy();+ });++ it('deletes a goal whose timed-out main Agent turn never wrote a run', async () => {+ const { goalId, service } = await strandedGoal(+ 'stranded-delete',+ new Date(Date.now() - 2 * 60 * 60_000),+ { dispatchReturnedWithoutRun: true },+ );++ await service.delete(goalId);+ expect(await new GoalModel(serverDB, userId).findById(goalId)).toBeFalsy();+ });++ // `execAgent` returned an operation id, so the run may be live even though+ // its row was never written; only the explicit --confirm-exit settles it.+ it('still refuses a timed-out turn that did get an operation id', async () => {+ const { goalId, service } = await strandedGoal(+ 'dispatched',+ new Date(Date.now() - 2 * 60 * 60_000),+ { operationId: 'op-without-row' },+ );++ await expect(service.close(goalId, 'achieved')).rejects.toThrow(/not closed/);+ const goal = await new GoalModel(serverDB, userId).findById(goalId);+ expect(goal?.config?.managerState?.consumed).toBeFalsy();+ });++ // Receipts recorded before the dispatch outcome was: the call may in+ // principle still be pending, so only an age no request could reach counts.+ it('settles a turn with no recorded dispatch outcome only once no request could still run it', async () => {+ const recent = await strandedGoal('legacy-recent', new Date(Date.now() - 2 * 60 * 60_000));+ await expect(recent.service.close(recent.goalId, 'achieved')).rejects.toThrow(/not closed/);++ const old = await strandedGoal('legacy-old', new Date(Date.now() - 25 * 60 * 60_000));+ expect((await old.service.close(old.goalId, 'achieved')).status).toBe('achieved');+ });++ it('still refuses while a main Agent turn without a run may be starting', async () => {+ const { goalId, service } = await strandedGoal('starting', new Date());++ await expect(service.close(goalId, 'achieved')).rejects.toThrow(/not closed/);+ const goal = await new GoalModel(serverDB, userId).findById(goalId);+ expect(goal?.status).toBe('paused');+ expect(goal?.config?.managerState?.consumed).toBeFalsy();+ });});it('restarts a split-role goal under a new executor without replacing its supervisor', async () => {diff --git a/apps/server/src/services/goal/GoalService/lifecycle.ts b/apps/server/src/services/goal/GoalService/lifecycle.tsindex 35dc8b95bca..037f061d78f 100644--- a/apps/server/src/services/goal/GoalService/lifecycle.ts+++ b/apps/server/src/services/goal/GoalService/lifecycle.ts@@ -69,7 +69,11 @@ export const deleteGoal = async (ctx: GoalServiceContext, goalId: string) => {});graph = await ctx.graphModel.getGraph(goalId);if (graph) {- if (managed) await new GoalManagerService(ctx.db, ctx.userId, ctx.workspaceId).stop(graph);+ // Deleting is the person's own word too; see `GoalManagerService.stop`.+ if (managed)+ await new GoalManagerService(ctx.db, ctx.userId, ctx.workspaceId).stop(graph, {+ ownerConfirmsExit: true,+ });if (supervised)await new GoalSupervisorService(ctx.db, ctx.userId, ctx.workspaceId).stop(graph);}@@ -361,8 +365,14 @@ export const close = async ('Could not stop the work still running for this goal, so it was not closed. Try again once the run is reachable.',});try {+ // Ending the goal is the person's own word that its stranded planning turn+ // is over; see `GoalManagerService.stop`. The turn stays settled even if the+ // Task pass below refuses the close: the person asked to end the goal, so a+ // later resume plans afresh instead of pausing on that turn again.if (graph.goal.config?.manager)- await new GoalManagerService(ctx.db, ctx.userId, ctx.workspaceId).stop(graph);+ await new GoalManagerService(ctx.db, ctx.userId, ctx.workspaceId).stop(graph, {+ ownerConfirmsExit: true,+ });if (graph.goal.config?.supervision?.enabled || graph.goal.config?.supervisorState)await new GoalSupervisorService(ctx.db, ctx.userId, ctx.workspaceId).stop(graph);} catch (error) {diff --git a/apps/server/src/services/goal/manager.strandedTurn.test.ts b/apps/server/src/services/goal/manager.strandedTurn.test.tsnew file mode 100644index 00000000000..cdc2bd6c80f--- /dev/null+++ b/apps/server/src/services/goal/manager.strandedTurn.test.ts@@ -0,0 +1,177 @@+// @vitest-environment node+import { eq } from 'drizzle-orm';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';++import { getTestDB } from '@/database/core/getTestDB';+import { GoalModel } from '@/database/models/goal';+import {+ agentOperations,+ agents,+ goalEdges,+ goalEvents,+ goalNodes,+ goals,+ messages,+ topics,+ users,+} from '@/database/schemas';+import { AiAgentService } from '@/server/services/aiAgent';++import { GoalService } from './index';+import * as scheduler from './scheduler';++vi.mock('@/database/core/db-adaptor', () => ({ getServerDB: () => db }));++const db = await getTestDB();+const userId = 'goal-stranded-turn-user';+const agentId = 'goal-stranded-turn-agent';+const service = () => new GoalService(db, userId);+const model = () => new GoalModel(db, userId);++/** Rewrite the claimed turn's receipt, e.g. to age it past a timeout. */+const editReceipt = async (goalId: string, patch: Record<string, unknown>) => {+ const goal = await model().findById(goalId);+ const config = goal!.config!;+ await db+ .update(goals)+ .set({ config: { ...config, managerState: { ...config.managerState!, ...patch } } })+ .where(eq(goals.id, goalId));+};+const hoursAgo = (hours: number) => new Date(Date.now() - hours * 60 * 60_000).toISOString();++const managedGoal = async () => {+ const graph = await service().create({+ config: { manager: { maxTurns: 4 } },+ createdByAgentId: agentId,+ title: 'Stranded planning',+ });+ await db+ .update(goals)+ .set({ config: { manager: { maxTurns: 4 } } })+ .where(eq(goals.id, graph.goal.id));+ return graph.goal.id;+};++const started = (params: Parameters<AiAgentService['execAgent']>[0], operationId: string) => ({+ agentId: params.agentId!,+ assistantMessageId: 'm',+ autoStarted: true,+ createdAt: new Date().toISOString(),+ message: 'started',+ operationId,+ status: 'running',+ success: true,+ timestamp: new Date().toISOString(),+ topicId: params.appContext!.topicId!,+ userMessageId: 'u',+});++beforeEach(async () => {+ await db.insert(users).values({ id: userId }).onConflictDoNothing();+ await db.insert(agents).values({ id: agentId, userId });+ vi.spyOn(scheduler, 'scheduleGoalAdvance').mockResolvedValue();+});++afterEach(async () => {+ vi.restoreAllMocks();+ for (const table of [goalEdges, goalEvents, goalNodes, goals, agentOperations, messages, topics])+ await db.delete(table);+ await db.delete(agents);+ await db.delete(users);+});++describe('GoalManagerService with a planning turn whose dispatch never wrote a run', () => {+ // The production failure: `execAgent` failed on a database timeout before+ // writing the planning message or the operation.+ it('lets the owner close the goal once the failed dispatch is past the turn timeout', async () => {+ const goalId = await managedGoal();+ vi.spyOn(AiAgentService.prototype, 'execAgent').mockRejectedValue(+ new Error('timeout exceeded when trying to connect'),+ );+ await service().tick(goalId);+ const receipt = (await model().findById(goalId))!.config!.managerState!;+ expect(receipt.dispatchReturnedWithoutRun).toBe(true);++ await editReceipt(goalId, { startedAt: hoursAgo(2) });+ expect((await service().close(goalId, 'achieved')).status).toBe('achieved');+ });++ it('refuses to settle a turn whose dispatch may still be pending', async () => {+ const goalId = await managedGoal();+ vi.spyOn(AiAgentService.prototype, 'execAgent').mockImplementation(async (params) => {+ await editReceipt(goalId, { startedAt: hoursAgo(2) });+ await expect(service().close(goalId, 'achieved')).rejects.toThrow(/not closed/);+ return started(params, 'op-stranded-pending') as never;+ });++ await service().tick(goalId);+ expect((await model().findById(goalId))!.config!.managerState!.consumed).toBeFalsy();+ });+});++/**+ * A dispatch that returns after the owner settled its turn has a run nothing+ * else will stop, so the dispatch stops it itself.+ */+describe('GoalManagerService with a dispatch that returns after the owner settled the turn', () => {+ it('interrupts the late run of a closed goal', async () => {+ const goalId = await managedGoal();+ const interrupt = vi+ .spyOn(AiAgentService.prototype, 'interruptTask')+ .mockResolvedValue({ success: true } as never);+ vi.spyOn(AiAgentService.prototype, 'execAgent').mockImplementation(async (params) => {+ await editReceipt(goalId, { startedAt: hoursAgo(25) });+ expect((await service().close(goalId, 'achieved')).status).toBe('achieved');+ return started(params, 'op-stranded-late') as never;+ });++ await service().tick(goalId);++ expect(interrupt).toHaveBeenCalledWith(+ expect.objectContaining({ operationId: 'op-stranded-late' }),+ );+ expect((await model().findById(goalId))!.status).toBe('achieved');+ });++ it('interrupts the late run once a newer turn replaced its receipt', async () => {+ const goalId = await managedGoal();+ const interrupt = vi+ .spyOn(AiAgentService.prototype, 'interruptTask')+ .mockResolvedValue({ success: true } as never);+ vi.spyOn(AiAgentService.prototype, 'execAgent').mockImplementation(async (params) => {+ await editReceipt(goalId, { startedAt: hoursAgo(25) });+ await service().close(goalId, 'achieved');+ // Reopened, and the next tick claimed a fresh turn.+ await editReceipt(goalId, { consumed: false, token: 'newer-turn' });+ return started(params, 'op-stranded-superseded') as never;+ });++ await service().tick(goalId);++ expect(interrupt).toHaveBeenCalledWith(+ expect.objectContaining({ operationId: 'op-stranded-superseded' }),+ );+ });++ it('keeps an unconfirmed late run stoppable by pausing the closed goal', async () => {+ const goalId = await managedGoal();+ vi.spyOn(AiAgentService.prototype, 'interruptTask').mockResolvedValue({+ deviceCancellationConfirmed: false,+ success: true,+ } as never);+ vi.spyOn(AiAgentService.prototype, 'execAgent').mockImplementation(async (params) => {+ await editReceipt(goalId, { startedAt: hoursAgo(25) });+ await service().close(goalId, 'achieved');+ return started(params, 'op-stranded-unconfirmed') as never;+ });++ await service().tick(goalId);++ const goal = (await model().findById(goalId))!;+ expect(goal.status).toBe('paused');+ expect(goal.config!.managerState).toMatchObject({+ consumed: false,+ operationId: 'op-stranded-unconfirmed',+ });+ });+});diff --git a/apps/server/src/services/goal/manager/index.ts b/apps/server/src/services/goal/manager/index.tsindex 020ed7fe1da..1d6d03301ac 100644--- a/apps/server/src/services/goal/manager/index.ts+++ b/apps/server/src/services/goal/manager/index.ts@@ -63,6 +63,12 @@ export {} from './turnState';const TIMEOUT_MS = 20 * 60_000;+/**+ * How old a turn whose dispatch outcome was never recorded must be before its+ * owner may settle it: far beyond any request that could still be running+ * `execAgent`. Covers receipts recorded before `dispatchReturnedWithoutRun`.+ */+const STRANDED_DISPATCH_MS = 24 * 60 * 60_000;/** Task comments listed in one planning turn's message; older ones are counted, not shown. */const FEEDBACK_NOTE_LIMIT = 20;@@ -143,13 +149,60 @@ export class GoalManagerService {return { goalId, outcome: 'no_progress', message };};- stop = async (graph: GoalGraphSnapshot) => {+ /**+ * Interrupt the main Agent turn the Goal is on.+ *+ * `ownerConfirmsExit` is a person ending or deleting the Goal themselves. A+ * turn with no operation id and no operation row is one nothing here can+ * interrupt — its dispatch failed before the run was written, e.g. a database+ * timeout in `execAgent`. That person's decision settles it the way+ * `confirmTurnExit` does once the dispatch is known to be over: it returned+ * without a run (`dispatchReturnedWithoutRun`) and the turn is past the turn+ * timeout, or no outcome was recorded and the turn is older than any request+ * could run. Otherwise such a Goal could never be closed from the product. A+ * turn that did get an operation id (or was adopted from a local run) may be+ * live without a row, so it keeps refusing; should a dispatch still return+ * late, `startTurn` stops its run.+ */+ stop = async (graph: GoalGraphSnapshot, options?: { ownerConfirmsExit?: boolean }) => {const state = graph.goal.config?.managerState;if (!state || state.consumed) return;- const operations = new AgentOperationModel(this.db, this.userId, this.workspaceId);- const op = state.operationId- ? await operations.findById(state.operationId)- : await operations.findByTopicSourceMessage(state.topicId, `msg_goal_manager_${state.token}`);+ const findRun = (db: LobeChatDatabase, receipt: GoalManagerState) => {+ const operations = new AgentOperationModel(db, this.userId, this.workspaceId);+ return receipt.operationId+ ? operations.findById(receipt.operationId)+ : operations.findByTopicSourceMessage(receipt.topicId, `msg_goal_manager_${receipt.token}`);+ };+ let op = await findRun(this.db, state);+ if (+ !op &&+ options?.ownerConfirmsExit &&+ !state.operationId &&+ !state.adopted &&+ Date.now() - Date.parse(state.startedAt) >+ (state.dispatchReturnedWithoutRun ? TIMEOUT_MS : STRANDED_DISPATCH_MS)+ ) {+ // Decide again under the goal row lock the dispatch records its+ // operation id under: a straggling `execAgent` may have written its run+ // since the read above, and that run must be interrupted, not settled.+ const settled = await this.db.transaction(async (db) => {+ const fresh = await new GoalRepository(db, this.userId, this.workspaceId).lockById(+ graph.goal.id,+ );+ const current = fresh?.config?.managerState;+ if (current?.token !== state.token || current.consumed) return { done: true as const };+ const run = await findRun(db, current);+ if (run || current.operationId || current.adopted) return { done: false as const, run };+ await saveManagerState(db, graph.goal.id, { ...current, consumed: true });+ console.warn('[goal:manager] owner settled a main Agent turn that never wrote a run', {+ goalId: graph.goal.id,+ token: state.token,+ });+ return { done: true as const };+ });+ if (settled.done) return;+ op = settled.run;+ }if (!op)throw new TRPCError({code: 'CONFLICT',@@ -618,6 +671,8 @@ export class GoalManagerService {};});if (!claimed) return this.wait(goal.id, 'Another advance owns the planning turn');+ let lateRun: string | undefined;+ let returned = false;try {const result = await new AiAgentService(this.db, this.userId, {workspaceId: this.workspaceId,@@ -650,15 +705,21 @@ export class GoalManagerService {: undefined),}),});- await this.db.transaction(async (db) => {+ returned = true;+ const orphaned = await this.db.transaction(async (db) => {const fresh = await new GoalRepository(db, this.userId, this.workspaceId).lockById(goal.id);- if (fresh?.config?.managerState?.token === claimed.token) {- await saveManagerState(db, goal.id, {- ...fresh.config.managerState,- operationId: result.operationId,- });- }+ // The other half of the owner's settle in `stop`: a dispatch that+ // returns after the owner settled this turn as never started — and the+ // Goal was ended, deleted, or moved on to a newer turn — has a run+ // nothing else will stop. Whichever side takes the lock second stops it:+ // `stop` when the id is already recorded here, this dispatch otherwise.+ if (!fresh) return true;+ const current = fresh.config?.managerState;+ if (current?.token !== claimed.token) return true;+ await saveManagerState(db, goal.id, { ...current, operationId: result.operationId });+ return !!current.consumed && !current.operationId;});+ if (orphaned && result.operationId) lateRun = result.operationId;} catch (error) {console.error('[goal:manager] dispatch failed; next wakeup adopts any persisted operation',@@ -679,8 +740,13 @@ export class GoalManagerService {return false;});if (recorded && declineRefused) return null;+ } else if (!returned) {+ await this.recordReturnedWithoutRun(goal.id, claimed.token).catch((saveError) =>+ console.error('[goal:manager] failed to record the failed dispatch', saveError),+ );}}+ if (lateRun) await this.stopLateRun(goal.id, claimed.token, lateRun, claimed.topicId);return this.wait(goal.id, 'Main Agent dispatched with CLI planning access');};@@ -709,6 +775,58 @@ export class GoalManagerService {return true;});+ /** The dispatch call is over without an operation id; see `stop`. */+ private recordReturnedWithoutRun = async (goalId: string, token: string) =>+ this.db.transaction(async (db) => {+ const fresh = await new GoalRepository(db, this.userId, this.workspaceId).lockById(goalId);+ const current = fresh?.config?.managerState;+ if (current?.token !== token || current.operationId) return;+ await saveManagerState(db, goalId, { ...current, dispatchReturnedWithoutRun: true });+ });++ /**+ * Stop a run whose dispatch returned after its turn was settled. When the+ * stop is not confirmed and the Goal still holds that turn, the run is put+ * back on the receipt and an ended Goal is paused, so closing it again+ * interrupts the run the confirmed way through `stop`.+ */+ private stopLateRun = async (+ goalId: string,+ token: string,+ operationId: string,+ topicId: string,+ ) => {+ const result = await new AiAgentService(this.db, this.userId, {+ workspaceId: this.workspaceId,+ })+ .interruptTask({ operationId, topicId })+ .catch((error) => {+ console.error('[goal:manager] failed to stop a run its turn no longer owns', error);+ return undefined;+ });+ if (result?.success && result.deviceCancellationConfirmed !== false) return;+ console.error('[goal:manager] stop of a late planning run was not confirmed', {+ goalId,+ operationId,+ });+ await this.db+ .transaction(async (db) => {+ const model = new GoalRepository(db, this.userId, this.workspaceId);+ const fresh = await model.lockById(goalId);+ const current = fresh?.config?.managerState;+ if (!fresh || current?.token !== token) return;+ await saveManagerState(db, goalId, { ...current, consumed: false, operationId });+ if (!['achieved', 'canceled', 'failed'].includes(fresh.status)) return;+ const message =+ 'A planning run that started after the Goal was closed could not be stopped; close the Goal again to stop it';+ await model.updateStatus(goalId, 'paused');+ await this.coordinatorGraph(db).recordGoalStatus(goalId, fresh.status, 'paused', message);+ })+ .catch((error) =>+ console.error('[goal:manager] failed to keep a late planning run stoppable', error),+ );+ };+/*** Mark a turn whose dispatch was refused its topic reservation as never* started; `settle` also consumes it, for a caller that will not wait it out.diff --git a/locales/en-US/chat.json b/locales/en-US/chat.jsonindex 90ab0b512f8..d335e43b5e3 100644--- a/locales/en-US/chat.json+++ b/locales/en-US/chat.json@@ -632,6 +632,7 @@"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.closeConfirm.failed": "Couldn’t close this goal. Try again in a moment.","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",diff --git a/locales/zh-CN/chat.json b/locales/zh-CN/chat.jsonindex 8bd759ac977..2024342d1e2 100644--- a/locales/zh-CN/chat.json+++ b/locales/zh-CN/chat.json@@ -632,6 +632,7 @@"goalDetail.closeConfirm.canceled.content": "仍在运行的任务会被中止,也不会再开始新的任务。之后可以在这个菜单里重新打开目标。","goalDetail.closeConfirm.canceled.ok": "取消目标","goalDetail.closeConfirm.canceled.title": "取消这个目标?",+ "goalDetail.closeConfirm.failed": "无法结束这个目标,请稍后再试。","goalDetail.definition": "目标定义","goalDetail.deleteConfirm.content": "该目标及其任务计划将被永久删除;对话历史会保留。","goalDetail.deleteConfirm.ok": "删除目标",diff --git a/packages/locales/src/default/chat.ts b/packages/locales/src/default/chat.tsindex 14a2908049b..758cfb9627b 100644--- a/packages/locales/src/default/chat.ts+++ b/packages/locales/src/default/chat.ts@@ -2547,6 +2547,7 @@ export default {'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.closeConfirm.failed': 'Couldn’t close this goal. Try again in a moment.','goalDetail.deleteConfirm.content':'This goal and its task plan will be permanently deleted. Conversation history is retained.','goalDetail.deleteConfirm.ok': 'Delete goal',diff --git a/packages/types/src/goal.ts b/packages/types/src/goal.tsindex e8518bf491b..85192602758 100644--- a/packages/types/src/goal.ts+++ b/packages/types/src/goal.ts@@ -305,6 +305,13 @@ export interface GoalManagerState {* owner can edit.*/dispatchNeverStarted?: boolean;+ /**+ * Set when this turn's `execAgent` call failed and returned without an+ * operation id. Unlike `dispatchNeverStarted` it does not prove no run exists,+ * but the call is over, so no late operation id can still be recorded; an+ * owner closing the Goal may settle the turn once it is past the turn timeout.+ */+ dispatchReturnedWithoutRun?: boolean;/*** Consecutive turns that ended in an error without committing a plan. Reset by* a turn that commits a plan or ends without an error. Reaching the limitdiff --git a/src/features/AgentGoals/useGoalMenuItems.test.ts b/src/features/AgentGoals/useGoalMenuItems.test.tsindex a57b8084a14..d8261e341e0 100644--- a/src/features/AgentGoals/useGoalMenuItems.test.ts+++ b/src/features/AgentGoals/useGoalMenuItems.test.ts@@ -19,9 +19,17 @@ const mocks = vi.hoisted(() => ({resumeGoal: vi.fn(),startGoal: vi.fn(),},+ toastError: vi.fn(),transferItems: null as DropdownItem[] | null,}));+vi.mock('@lobehub/ui', async (importOriginal) => ({+ ...(await importOriginal<Record<string, unknown>>()),+ // Run the confirmation straight away, as if the person clicked OK.+ confirmModal: (props: { onOk?: () => Promise<void> | void }) => props.onOk?.(),+ toast: { error: mocks.toastError, success: vi.fn() },+}));+vi.mock('@/business/client/hooks/useGoalTransferMenuItem', () => ({useGoalTransferMenuItem: () => mocks.transferItems,}));@@ -93,6 +101,25 @@ describe('useGoalItemMenu', () => {expect(mocks.store.refreshGoals).toHaveBeenCalledWith('agt_1');});+ // The server refuses to close while it cannot confirm a run has stopped; the+ // dialog used to swallow that, so nothing told the person why it stayed open.+ it('says why a goal could not be closed', async () => {+ mocks.store.closeGoal.mockRejectedValue(+ new Error('Could not stop the work still running for this goal, so it was not closed.'),+ );+ const { result } = renderHook(() =>+ useGoalItemMenu({ agentId: 'agt_1', goal: { ...goal, status: 'paused' }, projectId: 'p' }),+ );++ await act(async () => pickStatus(result.current, 'achieved'));++ expect(mocks.store.closeGoal).toHaveBeenCalledWith('goal_1', 'achieved');+ expect(mocks.toastError).toHaveBeenCalledWith('goalDetail.closeConfirm.failed');+ // The refused close has still paused the goal, so the list must not keep+ // showing it as it was.+ expect(mocks.store.refreshGoals).toHaveBeenCalledWith('project:p');+ });+it('keeps the reader on the list after a delete', () => {renderHook(() => useGoalItemMenu({ agentId: 'agt_1', goal, routeAgentId: 'agt_1' }));diff --git a/src/features/AgentGoals/useGoalMenuItems.tsx b/src/features/AgentGoals/useGoalMenuItems.tsxindex dfd0a2f556e..529ec973a81 100644--- a/src/features/AgentGoals/useGoalMenuItems.tsx+++ b/src/features/AgentGoals/useGoalMenuItems.tsx@@ -107,7 +107,15 @@ export const useGoalMenuItems = ({okButtonProps: { danger: next === 'canceled' },okText: t(`goalDetail.closeConfirm.${next}.ok`),onOk: async () => {- await closeGoal(goalId, next);+ try {+ await closeGoal(goalId, next);+ } catch (error) {+ // The server refuses while it cannot confirm a run has stopped. Say+ // so instead of leaving the dialog sitting there; it has already+ // paused the goal, so the list is refreshed either way.+ console.error('[goal:close] failed to close goal', error);+ toast.error(t('goalDetail.closeConfirm.failed'));+ }onStatusChanged?.();},title: t(`goalDetail.closeConfirm.${next}.title`),diff --git a/src/store/goal/action.test.ts b/src/store/goal/action.test.tsindex 17bb1cb8f05..a8b063ac2cc 100644--- a/src/store/goal/action.test.ts+++ b/src/store/goal/action.test.ts@@ -32,6 +32,7 @@ vi.mock('@/services/goal', () => ({goalService: {advance: vi.fn(),archive: vi.fn(),+ close: vi.fn(),delete: vi.fn(),getGraph: vi.fn(),list: vi.fn(),@@ -442,6 +443,29 @@ describe('GoalAction', () => {error.mockRestore();});+ it('reports a close that landed as done even when the refresh after it fails', async () => {+ const error = vi.spyOn(console, 'error').mockImplementation(() => {});+ vi.mocked(goalService.close).mockResolvedValueOnce(undefined as never);+ vi.mocked(mutate).mockRejectedValueOnce(new Error('offline'));++ await expect(useGoalStore.getState().closeGoal('goal-1', 'achieved')).resolves.toBeUndefined();++ expect(goalService.close).toHaveBeenCalledWith('goal-1', 'achieved');+ expect(mutate).toHaveBeenCalled();+ expect(error).toHaveBeenCalled();+ error.mockRestore();+ });++ // The server pauses the goal before it refuses, so the graph is re-read anyway.+ it('still refreshes the goal when the server refuses to close it', async () => {+ const refused = new Error('not closed');+ vi.mocked(goalService.close).mockRejectedValueOnce(refused);++ await expect(useGoalStore.getState().closeGoal('goal-1', 'achieved')).rejects.toBe(refused);++ expect(mutate).toHaveBeenCalled();+ });+it('relays the provider the goal actually plans on when advancing it', async () => {vi.mocked(goalService.advance).mockResolvedValue({ ticks: 1 } as never);vi.mocked(goalService.tick).mockResolvedValue({} as never);diff --git a/src/store/goal/action.ts b/src/store/goal/action.tsindex f70ef13a75f..b436b0c81f0 100644--- a/src/store/goal/action.ts+++ b/src/store/goal/action.ts@@ -373,8 +373,18 @@ export class GoalActionImpl {};closeGoal = async (goalId: string, status: 'achieved' | 'canceled'): Promise<void> => {- await goalService.close(goalId, status);- await this.refreshGoalGraph(goalId);+ let refused: unknown;+ try {+ await goalService.close(goalId, status);+ } catch (error) {+ refused = error;+ }+ // Refresh either way — a refused close has still paused the goal on the+ // server — but a failed refresh must not read as a failed close.+ await this.refreshGoalGraph(goalId).catch((error) =>+ console.error('[goal:close] refresh failed after closing', error),+ );+ if (refused) throw refused;};refreshGoalGraph = async (goalId: string): Promise<void> => {