π€― 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): replace a planning turn that never started, and let the owner confirm a stuck one (#20185)
Arvin Xubce1692b0534
diff --git a/apps/cli/src/commands/goal.test.ts b/apps/cli/src/commands/goal.test.tsindex 9f3508fdfe6..8ef9ad66cff 100644--- a/apps/cli/src/commands/goal.test.ts+++ b/apps/cli/src/commands/goal.test.ts@@ -16,6 +16,7 @@ const { mockClient } = vi.hoisted(() => ({submitOperationReport: { mutate: vi.fn() },submitReport: { mutate: vi.fn() },graph: { query: vi.fn() },+ resume: { mutate: vi.fn() },setBudget: { mutate: vi.fn() },supervision: { query: vi.fn() },tick: { mutate: vi.fn() },@@ -155,6 +156,28 @@ describe('goal report authentication', () => {);});+describe('goal resume', () => {+ it('asks the server to settle the stuck planning turn only with --confirm-exit', async () => {+ vi.clearAllMocks();+ mockClient.goal.resume.mutate.mockResolvedValue({ message: 'Goal resumed' });+ await createProgram().parseAsync(['node', 'test', 'goal', 'resume', 'goal-1']);+ expect(mockClient.goal.resume.mutate).toHaveBeenLastCalledWith({ id: 'goal-1' });++ await createProgram().parseAsync([+ 'node',+ 'test',+ 'goal',+ 'resume',+ 'goal-1',+ '--confirm-exit',+ ]);+ expect(mockClient.goal.resume.mutate).toHaveBeenLastCalledWith({+ confirmExit: true,+ id: 'goal-1',+ });+ });+});+describe('goal run command', () => {beforeEach(() => {vi.clearAllMocks();diff --git a/apps/cli/src/commands/goal.ts b/apps/cli/src/commands/goal.tsindex 41fa7c76ca3..9bab24b733f 100644--- a/apps/cli/src/commands/goal.ts+++ b/apps/cli/src/commands/goal.ts@@ -550,16 +550,30 @@ export function registerGoalCommand(program: Command) {},);- for (const action of ['pause', 'resume'] as const) {- goal- .command(`${action} <id>`)- .description(`${action === 'pause' ? 'Pause' : 'Resume'} goal coordination`)- .action(async (id: string) => {- const client = await getTrpcClient();- const result = await client.goal[action].mutate({ id });- log.info(result.message);+ goal+ .command('pause <id>')+ .description('Pause goal coordination')+ .action(async (id: string) => {+ const client = await getTrpcClient();+ const result = await client.goal.pause.mutate({ id });+ log.info(result.message);+ });++ goal+ .command('resume <id>')+ .description('Resume goal coordination')+ .option(+ '--confirm-exit',+ 'Confirm the main Agent planning turn the goal paused on has ended, and settle it before resuming',+ )+ .action(async (id: string, options: { confirmExit?: boolean }) => {+ const client = await getTrpcClient();+ const result = await client.goal.resume.mutate({+ id,+ ...(options.confirmExit ? { confirmExit: true } : {}),});- }+ log.info(result.message);+ });goal.command('delete <id>')diff --git a/apps/server/src/routers/lambda/goal.ts b/apps/server/src/routers/lambda/goal.tsindex f30ceac3399..9300815cfb2 100644--- a/apps/server/src/routers/lambda/goal.ts+++ b/apps/server/src/routers/lambda/goal.ts@@ -654,26 +654,42 @@ export const goalRouter = router({}}),- resume: goalWriteProcedure.input(idInput).mutation(async ({ ctx, input }) => {- try {- const data = await ctx.goalService.resume(input.id);- await scheduleGoalAdvance({- goalId: input.id,- trigger: 'resume',- userId: ctx.userId,- workspaceId: ctx.workspaceId ?? undefined,- });- // Resuming does not give the main Agent more turns, so a goal it paused- // for running out would stop again on the next tick. Say how to continue- // it instead of leaving the caller to replace it with a new goal.- const message = managerTurnsSpent(data.config)- ? `Goal resumed, but its main Agent has used all ${data.config?.manager?.maxTurns ?? DEFAULT_MANAGER_MAX_TURNS} turns and it will pause again. Raise the cap with: lh goal set-budget ${input.id} --max-manager-turns <n>`- : 'Goal resumed';- return { data, message, success: true };- } catch (error) {- mapGoalError(error, 'resume');- }- }),+ resume: goalWriteProcedure+ .input(+ idInput.extend({+ /**+ * The owner confirms the planning turn the Goal paused on has ended, so+ * it is settled before resuming instead of pausing the Goal again.+ */+ confirmExit: z.boolean().optional(),+ }),+ )+ .mutation(async ({ ctx, input }) => {+ try {+ if (input.confirmExit)+ await new GoalManagerService(+ ctx.serverDB,+ ctx.userId,+ ctx.workspaceId ?? undefined,+ ).confirmTurnExit(input.id);+ const data = await ctx.goalService.resume(input.id);+ await scheduleGoalAdvance({+ goalId: input.id,+ trigger: 'resume',+ userId: ctx.userId,+ workspaceId: ctx.workspaceId ?? undefined,+ });+ // Resuming does not give the main Agent more turns, so a goal it paused+ // for running out would stop again on the next tick. Say how to continue+ // it instead of leaving the caller to replace it with a new goal.+ const message = managerTurnsSpent(data.config)+ ? `Goal resumed, but its main Agent has used all ${data.config?.manager?.maxTurns ?? DEFAULT_MANAGER_MAX_TURNS} turns and it will pause again. Raise the cap with: lh goal set-budget ${input.id} --max-manager-turns <n>`+ : 'Goal resumed';+ return { data, message, success: true };+ } catch (error) {+ mapGoalError(error, 'resume');+ }+ }),/*** Start every unfinished Task node over (cancel stale runs, back todiff --git a/apps/server/src/services/aiAgent/index.ts b/apps/server/src/services/aiAgent/index.tsindex 8a56700f605..eb71ebe1533 100644--- a/apps/server/src/services/aiAgent/index.ts+++ b/apps/server/src/services/aiAgent/index.ts@@ -82,7 +82,7 @@ import { createRunFacts, type RunFacts } from './runFacts';import { applyShareGateToAgentConfig } from './shareGate';import type { SubAgentRunDeps } from './subAgentRuns';import { execAgentMember, execAgentThreadRun } from './subAgentRuns';-import { acquireTopicStartReservation } from './topicStartReservation';+import { acquireTopicStartReservation, TopicStartReservationError } from './topicStartReservation';import type {BindTopicWorkingDirectoryParams,ExecRunContext,@@ -639,7 +639,7 @@ export class AiAgentService {});if (!reserved) {- throw new Error(`Topic not found: ${topicId}`);+ throw new TopicStartReservationError(`Topic not found: ${topicId}`);}try {diff --git a/apps/server/src/services/aiAgent/topicStartReservation.ts b/apps/server/src/services/aiAgent/topicStartReservation.tsindex 32bf337b4f4..ec065953295 100644--- a/apps/server/src/services/aiAgent/topicStartReservation.ts+++ b/apps/server/src/services/aiAgent/topicStartReservation.ts@@ -7,6 +7,19 @@ const MAX_RESERVATION_ATTEMPTS = 6;const delay = (milliseconds: number): Promise<void> =>new Promise((resolve) => setTimeout(resolve, milliseconds));+/**+ * The topic could not be reserved for a new run. Thrown before anything of the+ * run is written β no user message, no operation β so a caller that sees it+ * knows the dispatch never started and never will. The message is unchanged+ * for callers that still match on it.+ */+export class TopicStartReservationError extends Error {+ constructor(message: string) {+ super(message);+ this.name = 'TopicStartReservationError';+ }+}+/*** Claim the gap between choosing a conversation parent and publishing the* operation's `runningOperation` marker. Every existing-topic start uses the@@ -58,5 +71,7 @@ export const acquireTopicStartReservation = async ({}}- throw new Error(`Topic ${topicId} remained busy while starting operation ${reservationId}`);+ throw new TopicStartReservationError(+ `Topic ${topicId} remained busy while starting operation ${reservationId}`,+ );};diff --git a/apps/server/src/services/goal/manager.test.ts b/apps/server/src/services/goal/manager.test.tsindex 38609097733..a488f158c59 100644--- a/apps/server/src/services/goal/manager.test.ts+++ b/apps/server/src/services/goal/manager.test.ts@@ -7,6 +7,7 @@ import { getTestDB } from '@/database/core/getTestDB';import { AgentOperationModel } from '@/database/models/agentOperation';import { GoalModel } from '@/database/models/goal';import { GoalGraphModel } from '@/database/models/goalGraph';+import { MessageModel } from '@/database/models/message';import { TaskModel } from '@/database/models/task';import {acceptances,@@ -17,6 +18,7 @@ import {goalNodeDecisions,goalNodes,goals,+ messages,tasks,taskTopics,topics,@@ -24,6 +26,7 @@ import {} from '@/database/schemas';import { goalRouter } from '@/server/routers/lambda/goal';import { AiAgentService } from '@/server/services/aiAgent';+import { TopicStartReservationError } from '@/server/services/aiAgent/topicStartReservation';import { GoalService } from './index';import { GoalManagerService } from './manager';@@ -89,6 +92,7 @@ afterEach(async () => {goals,acceptances,agentOperations,+ messages,taskTopics,topics,tasks,@@ -690,6 +694,170 @@ describe('CLI main Agent planning', () => {expect(vi.mocked(AiAgentService.prototype.execAgent)).toHaveBeenCalledTimes(1);});+ it('replaces a timed-out turn that never started instead of pausing on it', async () => {+ // A refused topic reservation β the planning topic was busy β is raised+ // before the planning message or any operation is written.+ const original = vi.mocked(AiAgentService.prototype.execAgent).getMockImplementation()!;+ vi.mocked(AiAgentService.prototype.execAgent).mockImplementationOnce(async () => {+ throw new TopicStartReservationError('Topic tpc remained busy while starting operation x');+ });+ const { id, state, op } = await start();+ expect(op).toBeUndefined();+ expect((await model().findById(id))!.config!.managerState!.dispatchNeverStarted).toBe(true);++ const now = Date.now();+ vi.spyOn(Date, 'now').mockReturnValue(now + 21 * 60_000);+ expect((await service().tick(id)).outcome).toBe('advanced');+ const settled = (await model().findById(id))!;+ expect(settled.status).toBe('running');+ expect(settled.config!.managerState!.token).toBe(state.token);+ expect(settled.config!.managerState!.consumed).toBe(true);++ vi.mocked(AiAgentService.prototype.execAgent).mockImplementation(original);+ expect((await service().tick(id)).outcome).toBe('waiting_external');+ const next = (await model().findById(id))!.config!.managerState!;+ expect(next.token).not.toBe(state.token);+ expect(next.turns).toBe(state.turns + 1);+ expect(vi.mocked(AiAgentService.prototype.execAgent)).toHaveBeenCalledTimes(2);+ });++ it('keeps pausing when the planning message is deleted after a dispatch that had started', async () => {+ // The message was written and the call failed later, so a run may be live.+ // The owner then deletes the message from their conversation; a later+ // lookup must not turn that into "never started".+ vi.mocked(AiAgentService.prototype.execAgent).mockImplementationOnce(async (params) => {+ await new MessageModel(db, userId).create(+ {+ agentId: params.agentId,+ content: 'plan',+ role: 'user',+ topicId: params.appContext!.topicId!,+ },+ params.clientIds!.userMessageId,+ );+ throw new Error('Topic metadata update failed');+ });+ const { id, state } = await start();+ expect(state.dispatchNeverStarted).toBeUndefined();+ await db.delete(messages).where(eq(messages.id, `msg_goal_manager_${state.token}`));++ const now = Date.now();+ vi.spyOn(Date, 'now').mockReturnValue(now + 21 * 60_000);+ expect((await service().tick(id)).outcome).toBe('no_progress');+ const fresh = (await model().findById(id))!;+ expect(fresh.status).toBe('paused');+ expect(fresh.config!.managerState!.consumed).not.toBe(true);+ expect(vi.mocked(AiAgentService.prototype.execAgent)).toHaveBeenCalledTimes(1);+ });++ it('keeps pausing a turn whose dispatch failed for any reason other than a refused reservation', async () => {+ // No message and no operation, but an ordinary failure can come after a run+ // went live; only the error decides, never the absence of rows.+ vi.mocked(AiAgentService.prototype.execAgent).mockImplementationOnce(async () => {+ throw new Error('Something failed while starting');+ });+ const { id, state } = await start();+ expect(state.dispatchNeverStarted).toBeUndefined();++ const now = Date.now();+ vi.spyOn(Date, 'now').mockReturnValue(now + 21 * 60_000);+ expect((await service().tick(id)).outcome).toBe('no_progress');+ expect((await model().findById(id))!.status).toBe('paused');+ });++ /**+ * Regression: the pause asked the owner to "confirm its exit before resuming"+ * with no way to do so, so a Goal paused on a turn recorded before the+ * never-started verdict existed could not be resumed at all.+ */+ it('lets the owner confirm a stuck turn has ended and resume with a fresh one', async () => {+ vi.mocked(AiAgentService.prototype.execAgent).mockImplementationOnce(+ async (params) =>+ ({+ agentId: params.agentId!,+ operationId: 'op-lost',+ topicId: params.appContext!.topicId!,+ }) as any,+ );+ const { id, state } = await start();+ const now = Date.now();+ vi.spyOn(Date, 'now').mockReturnValue(now + 21 * 60_000);+ await service().tick(id);+ expect((await model().findById(id))!.status).toBe('paused');++ // A plain resume pauses again on the same turn.+ await service().resume(id);+ expect((await service().tick(id)).outcome).toBe('no_progress');++ expect(await manager().confirmTurnExit(id)).toBe(true);+ await service().resume(id);+ // The settled turn no longer holds the Goal: the next advance plans afresh.+ expect((await service().tick(id)).outcome).toBe('waiting_external');+ expect((await model().findById(id))!.status).toBe('running');+ const next = (await model().findById(id))!.config!.managerState!;+ expect(next.token).not.toBe(state.token);+ expect(vi.mocked(AiAgentService.prototype.execAgent)).toHaveBeenCalledTimes(2);+ });++ it('refuses to confirm the exit of a turn whose run is still live', async () => {+ const { id } = await start();+ await expect(manager().confirmTurnExit(id)).rejects.toMatchObject({ code: 'CONFLICT' });+ expect((await model().findById(id))!.config!.managerState!.consumed).not.toBe(true);+ });++ it('keeps pausing a timed-out turn whose dispatch never reported failure', async () => {+ // No message and no operation, but the dispatch call never ended in an+ // error: it may still be initialising and start a paid run later, so the+ // turn cannot be replaced.+ vi.mocked(AiAgentService.prototype.execAgent).mockImplementationOnce(+ async (params) =>+ ({+ agentId: params.agentId!,+ operationId: 'op-still-starting',+ topicId: params.appContext!.topicId!,+ }) as any,+ );+ const { id, state, op } = await start();+ expect(op).toBeUndefined();++ const now = Date.now();+ vi.spyOn(Date, 'now').mockReturnValue(now + 21 * 60_000);+ expect((await service().tick(id)).outcome).toBe('no_progress');+ const fresh = (await model().findById(id))!;+ expect(fresh.status).toBe('paused');+ expect(fresh.config!.managerState!.token).toBe(state.token);+ expect(fresh.config!.managerState!.consumed).not.toBe(true);+ expect(vi.mocked(AiAgentService.prototype.execAgent)).toHaveBeenCalledTimes(1);+ });++ it('keeps pausing a timed-out turn whose message exists but whose operation row is missing', async () => {+ // The runtime keeps running when its operation insert fails, so a written+ // planning message with no operation is still an unconfirmed process.+ vi.mocked(AiAgentService.prototype.execAgent).mockImplementationOnce(async (params) => {+ await new MessageModel(db, userId).create(+ {+ agentId: params.agentId,+ content: 'plan',+ role: 'user',+ topicId: params.appContext!.topicId!,+ },+ params.clientIds!.userMessageId,+ );+ throw new Error('Operation insert failed');+ });+ const { id, state, op } = await start();+ expect(op).toBeUndefined();++ const now = Date.now();+ vi.spyOn(Date, 'now').mockReturnValue(now + 21 * 60_000);+ expect((await service().tick(id)).outcome).toBe('no_progress');+ const fresh = (await model().findById(id))!;+ expect(fresh.status).toBe('paused');+ expect(fresh.config!.managerState!.token).toBe(state.token);+ expect(fresh.config!.managerState!.consumed).not.toBe(true);+ expect(vi.mocked(AiAgentService.prototype.execAgent)).toHaveBeenCalledTimes(1);+ });+it('rejects an open human Gate without planning or dispatching work', async () => {const { id, state, op } = await start();const graph = new GoalGraphModel(db, userId);diff --git a/apps/server/src/services/goal/manager.ts b/apps/server/src/services/goal/manager.tsindex c845fb10c1c..34a24dc0440 100644--- a/apps/server/src/services/goal/manager.ts+++ b/apps/server/src/services/goal/manager.ts@@ -22,6 +22,7 @@ import { TopicModel } from '@/database/models/topic';import { goals } from '@/database/schemas/goal';import type { LobeChatDatabase } from '@/database/type';import { AiAgentService } from '@/server/services/aiAgent';+import { TopicStartReservationError } from '@/server/services/aiAgent/topicStartReservation';import { countDeviceOfflineRuns, DEFAULT_MANAGER_MAX_TURNS } from './recoveryPolicy';import { scheduleGoalAdvance } from './scheduler';@@ -383,7 +384,30 @@ export class GoalManagerService {// An adopted local desktop run has no server operation to watch exit; its// submitted plan is the only settlement the server can observe.const settledLocally = !!state.adopted && !operation && !!state.submitted;- if (!settledLocally && (!operation || !terminalOperations.has(operation.status))) {+ // A dispatched turn never ran when its dispatch was refused the topic+ // reservation β the verdict `recordUnstartedDispatch` stored from the+ // error itself. That refusal comes before the planning message or any+ // operation is written, and the planning topic can be the owner's busy+ // conversation, which is how a turn gets stuck. With no run to confirm,+ // settle it like a turn that exited without a plan instead of pausing:+ // pausing left the Goal stuck for good, because every resume re-read this+ // same turn and paused again.+ //+ // Nothing is inferred from rows: a missing operation row proves nothing+ // (the runtime keeps going when that insert fails), and a missing planning+ // message may be one the owner deleted or one a still-pending call has not+ // written yet. Every other turn still pauses as unconfirmed; the owner can+ // confirm its exit on resume. An adopted turn is exempt.+ const neverStarted =+ !state.adopted &&+ !operation &&+ !!state.dispatchNeverStarted &&+ Date.now() - Date.parse(state.startedAt) > TIMEOUT_MS;+ if (+ !settledLocally &&+ !neverStarted &&+ (!operation || !terminalOperations.has(operation.status))+ ) {if (operation?.status === 'waiting_for_human') {await this.wait(goal.id, 'Main Agent is waiting for a human decision');return {@@ -395,7 +419,7 @@ export class GoalManagerService {if (Date.now() - Date.parse(state.startedAt) > TIMEOUT_MS) {return this.pause(goal.id,- 'Main Agent execution is unconfirmed or timed out. Confirm its exit before resuming; no replacement was dispatched.',+ `Main Agent execution is unconfirmed or timed out; no replacement was dispatched. Once its run has ended, confirm and resume with: lh goal resume ${goal.id} --confirm-exit`,);}return this.wait(goal.id, 'Waiting for main Agent CLI planning turn');@@ -418,7 +442,9 @@ export class GoalManagerService {outcome: 'advanced',message: state.submitted? 'Main Agent plan committed; normal Task coordination continues'- : 'Main Agent exited without a plan; a new bounded turn will reread durable state',+ : neverStarted+ ? 'Main Agent turn never started; a new bounded turn will reread durable state'+ : 'Main Agent exited without a plan; a new bounded turn will reread durable state',};}return null;@@ -583,10 +609,52 @@ export class GoalManagerService {'[goal:manager] dispatch failed; next wakeup adopts any persisted operation',error,);+ // Only a refused topic reservation proves the turn never started: it is+ // raised before the planning message or any operation is written, and the+ // call has returned. Any other failure may come after a run went live, so+ // it stays unconfirmed. Decided from the error, never from rows the owner+ // can edit or delete.+ if (error instanceof TopicStartReservationError)+ await this.recordUnstartedDispatch(goal.id, claimed.token).catch((saveError) =>+ console.error('[goal:manager] failed to record the refused dispatch', saveError),+ );}return this.wait(goal.id, 'Main Agent dispatched with CLI planning access');};+ /**+ * The owner confirms that the planning turn the Goal is paused on has ended,+ * so resuming can settle it and plan afresh β the repair for a turn the server+ * cannot classify on its own, including turns recorded before+ * `dispatchNeverStarted` existed. Refused while the turn's run is still live:+ * interrupt it first, or a replacement would run beside it.+ */+ confirmTurnExit = async (goalId: string) =>+ this.db.transaction(async (db) => {+ const fresh = await new GoalModel(db, this.userId, this.workspaceId).lockById(goalId);+ const state = fresh?.config?.managerState;+ if (!state || state.consumed) return false;+ const operation = await this.turnOperation(+ new AgentOperationModel(db, this.userId, this.workspaceId),+ state,+ );+ if (operation && !terminalOperations.has(operation.status))+ throw new TRPCError({+ code: 'CONFLICT',+ message: `The main Agent run ${operation.id} is still ${operation.status}; interrupt it before confirming its exit`,+ });+ await this.save(db, goalId, { ...state, consumed: true });+ return true;+ });++ /** Mark a turn whose dispatch was refused its topic reservation as never started. */+ private recordUnstartedDispatch = async (goalId: string, token: string) =>+ this.db.transaction(async (db) => {+ const fresh = await new GoalModel(db, this.userId, this.workspaceId).lockById(goalId);+ if (fresh?.config?.managerState?.token === token)+ await this.save(db, goalId, { ...fresh.config.managerState, dispatchNeverStarted: true });+ });+submit = async (goalId: string, token: string, operationId: string, input: GoalPlan) => {const plan = goalPlanSchema.parse(input);return this.db.transaction(async (db) => {diff --git a/packages/types/src/goal.ts b/packages/types/src/goal.tsindex 0f7e47cf361..1c866270b20 100644--- a/packages/types/src/goal.ts+++ b/packages/types/src/goal.ts@@ -237,6 +237,13 @@ export interface GoalManagerState {*/adoptedOperationId?: string;consumed?: boolean;+ /**+ * Set when the dispatch for this turn was refused its topic reservation β the+ * one failure raised before anything of the run is written β so no run exists+ * and none can start. Decided from the error itself, never from rows the+ * owner can edit.+ */+ dispatchNeverStarted?: boolean;operationId?: string;/*** The problem this turn was invited to take over, when the coordinator handed