🤯 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): stop an abandoned diagnosis from looping goal advances (#22648)
Arvin Xuf8d1df8032e3
diff --git a/apps/server/src/services/goal/manager/index.ts b/apps/server/src/services/goal/manager/index.tsindex 72bb288e331..020ed7fe1da 100644--- a/apps/server/src/services/goal/manager/index.ts+++ b/apps/server/src/services/goal/manager/index.ts@@ -26,7 +26,7 @@ import { deviceGateway } from '@/server/services/deviceGateway';import { goalModelOverride } from '../modelConfig';import { countUnchargedRuns, DEFAULT_MANAGER_MAX_TURNS } from '../recoveryPolicy';-import { scheduleGoalAdvance } from '../scheduler';+import { goalPollDelay, scheduleGoalAdvance } from '../scheduler';import { recoveryEligibility } from '../supervisor/policy';import { GoalWaitService } from '../wait';import { assertOperationOwnsTurn, planAdmission } from './admission';@@ -106,12 +106,17 @@ export class GoalManagerService {type: 'system',});- private wait = async (goalId: string, message: string): Promise<GoalTickResult> => {+ private wait = async (+ goalId: string,+ message: string,+ since?: string,+ ): Promise<GoalTickResult> => {await scheduleGoalAdvance({goalId,userId: this.userId,workspaceId: this.workspaceId,- delay: 5,+ delay: goalPollDelay(since),+ poll: true,});return { goalId, outcome: 'waiting_external', message };};@@ -316,7 +321,7 @@ export class GoalManagerService {(!operation || isAgentOperationInFlight(operation.status))) {if (operation?.status === 'waiting_for_human') {- await this.wait(goal.id, 'Main Agent is waiting for a human decision');+ await this.wait(goal.id, 'Main Agent is waiting for a human decision', state.startedAt);return {goalId: goal.id,outcome: 'waiting_human',@@ -329,7 +334,7 @@ export class GoalManagerService {`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');+ return this.wait(goal.id, 'Waiting for main Agent CLI planning turn', state.startedAt);}const failed = await this.db.transaction(async (db) => {const fresh = await new GoalRepository(db, this.userId, this.workspaceId).lockById(goal.id);diff --git a/apps/server/src/services/goal/scheduler/impls/qstash.test.ts b/apps/server/src/services/goal/scheduler/impls/qstash.test.tsnew file mode 100644index 00000000000..57c1f142b88--- /dev/null+++ b/apps/server/src/services/goal/scheduler/impls/qstash.test.ts@@ -0,0 +1,58 @@+// @vitest-environment node+import type { Client } from '@upstash/qstash';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';++import { QStashGoalScheduler } from './qstash';++const publishJSON = vi.fn().mockResolvedValue({ messageId: 'msg' });+const scheduler = new QStashGoalScheduler({+ baseUrl: 'https://app.test/',+ qstashClient: { publishJSON } as unknown as Client,+});+const params = { goalId: 'goal_a', userId: 'user' };+const poll = { ...params, delay: 5, poll: true };+const sentId = (call: number) => publishJSON.mock.calls[call][0].deduplicationId;++describe('QStashGoalScheduler', () => {+ beforeEach(() => {+ publishJSON.mockClear();+ vi.useFakeTimers({ now: 1_000_000 });+ });++ afterEach(() => {+ vi.useRealTimers();+ });++ it('collapses polls of one goal that land on the same moment', async () => {+ await scheduler.scheduleAdvance(poll);+ vi.advanceTimersByTime(1000);+ await scheduler.scheduleAdvance(poll);++ expect(sentId(0)).toBeDefined();+ expect(sentId(1)).toBe(sentId(0));+ });++ it('keeps a polling chain alive: the next poll is a different message', async () => {+ await scheduler.scheduleAdvance(poll);+ vi.advanceTimersByTime(5000);+ await scheduler.scheduleAdvance(poll);++ expect(sentId(1)).not.toBe(sentId(0));+ });++ it('does not collapse polls of different goals', async () => {+ await scheduler.scheduleAdvance(poll);+ await scheduler.scheduleAdvance({ ...poll, goalId: 'goal_b' });++ expect(sentId(1)).not.toBe(sentId(0));+ });++ it.each([+ ['an immediate advance', {}],+ ['a wait timer', { delay: 4 }],+ ])('never collapses %s, which has to fire itself', async (_name, extra) => {+ await scheduler.scheduleAdvance({ ...params, ...extra });++ expect(publishJSON.mock.calls[0][0]).not.toHaveProperty('deduplicationId');+ });+});diff --git a/apps/server/src/services/goal/scheduler/impls/qstash.ts b/apps/server/src/services/goal/scheduler/impls/qstash.tsindex 1a4523c861d..979038a9da2 100644--- a/apps/server/src/services/goal/scheduler/impls/qstash.ts+++ b/apps/server/src/services/goal/scheduler/impls/qstash.ts@@ -7,6 +7,9 @@ const log = debug('goal-scheduler:qstash');export const GOAL_ADVANCE_PATH = '/api/workflows/goal/advance';+/** Polls of one goal aimed within this window are the same re-check. */+const POLL_WINDOW_MS = 5000;+export interface QStashGoalSchedulerConfig {/** Absolute base URL (e.g. `process.env.APP_URL`) used to build the callback URL. */baseUrl: string;@@ -31,14 +34,24 @@ export class QStashGoalScheduler implements GoalSchedulerImpl {}async scheduleAdvance(params: ScheduleGoalAdvanceParams): Promise<string> {- const { delay = 0, goalId, trigger, userId, workspaceId } = params;+ const { delay = 0, goalId, poll, trigger, userId, workspaceId } = params;const url = `${this.baseUrl}${GOAL_ADVANCE_PATH}`;+ // Every advance that ends in a poll books the next one, so without this each+ // extra message (a sweep, a retry) starts a chain that never merges back. The+ // id is the target time: chains collapse, and a chain's own next poll, aimed+ // later, still goes through. Only polls: a wait timer sharing the window would+ // be dropped, and `rearm` will not book it again before its deadline.+ const deduplicationId = poll+ ? `goal-advance-${goalId}-${Math.floor((Date.now() + delay * 1000) / POLL_WINDOW_MS)}`+ : undefined;+log('publishing advance: goal=%s delay=%ds url=%s', goalId, delay, url);const response = await this.qstashClient.publishJSON({body: { goalId, trigger, userId, workspaceId },delay,url,+ ...(deduplicationId ? { deduplicationId } : {}),});return 'messageId' in response ? response.messageId : '';diff --git a/apps/server/src/services/goal/scheduler/impls/type.ts b/apps/server/src/services/goal/scheduler/impls/type.tsindex 77567d7f399..29631de50f3 100644--- a/apps/server/src/services/goal/scheduler/impls/type.ts+++ b/apps/server/src/services/goal/scheduler/impls/type.ts@@ -4,6 +4,11 @@ export interface ScheduleGoalAdvanceParams {/** Seconds to wait before advancing. Defaults to 0 (as soon as possible). */delay?: number;goalId: string;+ /**+ * This advance only re-checks something still pending, so another one aimed at+ * the same moment can replace it. Leave unset for a timer that must fire itself.+ */+ poll?: boolean;/** What made this goal advanceable. Survives the queue hop onto the trajectory. */trigger?: GoalAdvanceTrigger;userId: string;diff --git a/apps/server/src/services/goal/scheduler/index.ts b/apps/server/src/services/goal/scheduler/index.tsindex 1b35d490f16..a4ae4b29702 100644--- a/apps/server/src/services/goal/scheduler/index.ts+++ b/apps/server/src/services/goal/scheduler/index.ts@@ -28,3 +28,4 @@ export const scheduleGoalAdvance = async (params: ScheduleGoalAdvanceParams): Prexport type { GoalSchedulerImpl, ScheduleGoalAdvanceParams } from './impls';export { createGoalSchedulerModule, GOAL_ADVANCE_PATH } from './impls';+export { goalPollDelay } from './pollDelay';diff --git a/apps/server/src/services/goal/scheduler/pollDelay.test.ts b/apps/server/src/services/goal/scheduler/pollDelay.test.tsnew file mode 100644index 00000000000..60dfd593350--- /dev/null+++ b/apps/server/src/services/goal/scheduler/pollDelay.test.ts@@ -0,0 +1,24 @@+import { describe, expect, it } from 'vitest';++import { goalPollDelay } from './pollDelay';++const now = Date.parse('2026-11-09T00:00:00Z');+const ago = (seconds: number) => new Date(now - seconds * 1000).toISOString();++describe('goalPollDelay', () => {+ it.each([+ [0, 5],+ [50, 5],+ [120, 12],+ [300, 30],+ [600, 60],+ [86_400, 60],+ ])('after %ss without progress polls in %ss', (elapsed, delay) => {+ expect(goalPollDelay(ago(elapsed), now)).toBe(delay);+ });++ it('polls at the base rate when the start of the wait is unknown', () => {+ expect(goalPollDelay(undefined, now)).toBe(5);+ expect(goalPollDelay('not a date', now)).toBe(5);+ });+});diff --git a/apps/server/src/services/goal/scheduler/pollDelay.ts b/apps/server/src/services/goal/scheduler/pollDelay.tsnew file mode 100644index 00000000000..3d2f30dca4a--- /dev/null+++ b/apps/server/src/services/goal/scheduler/pollDelay.ts@@ -0,0 +1,16 @@+const BASE_POLL_DELAY_S = 5;+const MAX_POLL_DELAY_S = 60;++/**+ * Seconds until the next poll of something that has not settled yet. Grows with+ * the time already waited, so a late answer is noticed within about a tenth of+ * that wait while a wait that never ends costs one advance a minute.+ *+ * Derived from when the wait began instead of a retry counter: parallel advances+ * and lost messages cannot skew it, and it needs no state of its own.+ */+export const goalPollDelay = (waitingSince?: Date | string, now = Date.now()): number => {+ const elapsedMs = waitingSince ? now - new Date(waitingSince).getTime() : Number.NaN;+ if (!Number.isFinite(elapsedMs)) return BASE_POLL_DELAY_S;+ return Math.min(MAX_POLL_DELAY_S, Math.max(BASE_POLL_DELAY_S, Math.ceil(elapsedMs / 10_000)));+};diff --git a/apps/server/src/services/goal/supervisor/README.md b/apps/server/src/services/goal/supervisor/README.mdindex 0c62c734d69..14708a630b0 100644--- a/apps/server/src/services/goal/supervisor/README.md+++ b/apps/server/src/services/goal/supervisor/README.md@@ -32,7 +32,7 @@ recovery through the ordinary dispatcher. Recovery instructions require checkingand reusing saved work and reconciling external side effects before replay. Thisinstruction is not an exactly-once guarantee for arbitrary external systems.-A five-second scheduled Goal advance checks the asynchronous diagnosis. Existing+A scheduled Goal advance checks the asynchronous diagnosis, every five seconds at first and backing off to once a minute the longer it stays open. Existingsweep infrastructure provides the fallback if the callback is lost. Queue modeis required for durable wakeups; local in-process timers alone cannot survive arestart. A lost diagnostic dispatch response can be adopted from the dedicateddiff --git a/apps/server/src/services/goal/supervisor/index.test.ts b/apps/server/src/services/goal/supervisor/index.test.tsindex 5b7c676997d..6f44f1a5849 100644--- a/apps/server/src/services/goal/supervisor/index.test.ts+++ b/apps/server/src/services/goal/supervisor/index.test.ts@@ -33,6 +33,7 @@ import { GoalService } from '../index';import * as modelConfig from '../modelConfig';import * as scheduler from '../scheduler';import { GoalSupervisorService } from './index';+import { SUPERVISOR_DIAGNOSIS_TIMEOUT_MS } from './policy';import { GoalSupervisorTools } from './tools';const db = await getTestDB();@@ -564,6 +565,84 @@ describe('Goal Supervisor integration', () => {expect(after.incidents.at(-1)?.status).toBe('escalated');});+ describe('a diagnosis left open by another Task', () => {+ /** A second failed run on the Goal, while the first incident is still `diagnosing`. */+ const failAgain = async (taskId: string) => {+ const topicId = `topic-second-${++sequence}`;+ const operationId = `op-second-${sequence}`;+ await db.insert(topics).values({ id: topicId, userId });+ await operationModel.recordStart({ operationId, taskId, topicId });+ await operationModel.recordCompletion(operationId, {+ completionReason: 'done',+ status: 'done',+ });+ await db+ .insert(taskTopics)+ .values({ operationId, seq: 2, status: 'completed', taskId, topicId, userId });+ return operationId;+ };++ const ageFirstIncident = async (goalId: string) => {+ const state = (await goalModel.findById(goalId))!.config!.supervisorState!;+ await goalModel.updateSupervisorState(goalId, state.revision, {+ ...state,+ incidents: state.incidents.map((item) => ({+ ...item,+ createdAt: new Date(Date.now() - SUPERVISOR_DIAGNOSIS_TIMEOUT_MS - 1000).toISOString(),+ })),+ });+ };++ it('keeps waiting while that diagnosis is inside its window', async () => {+ const { goalId, taskId } = await pipelineFailureGoal();+ await service().tick(goalId);+ await failAgain(taskId);+ vi.mocked(scheduler.scheduleGoalAdvance).mockClear();++ const result = await service().tick(goalId);++ expect(result.message).toBe('Another interruption is being diagnosed');+ expect(scheduler.scheduleGoalAdvance).toHaveBeenCalledTimes(1);+ const { incidents } = (await goalModel.findById(goalId))!.config!.supervisorState!;+ expect(incidents.map((item) => item.status)).toEqual(['diagnosing']);+ });++ it('backs off the poll the longer that diagnosis has been open', async () => {+ const { goalId, taskId } = await pipelineFailureGoal();+ await service().tick(goalId);+ await failAgain(taskId);+ const state = (await goalModel.findById(goalId))!.config!.supervisorState!;+ await goalModel.updateSupervisorState(goalId, state.revision, {+ ...state,+ incidents: state.incidents.map((item) => ({+ ...item,+ createdAt: new Date(Date.now() - 5 * 60_000).toISOString(),+ })),+ });+ vi.mocked(scheduler.scheduleGoalAdvance).mockClear();++ await service().tick(goalId);++ const [params] = vi.mocked(scheduler.scheduleGoalAdvance).mock.calls[0];+ expect(params.delay).toBeGreaterThanOrEqual(30);+ });++ it('escalates it once expired instead of rescheduling forever', async () => {+ const { goalId, taskId } = await pipelineFailureGoal();+ await service().tick(goalId);+ const operationId = await failAgain(taskId);+ await ageFirstIncident(goalId);++ const result = await service().tick(goalId);++ expect(result.message).not.toBe('Another interruption is being diagnosed');+ const { incidents } = (await goalModel.findById(goalId))!.config!.supervisorState!;+ expect(incidents[0].status).toBe('escalated');+ expect(incidents[0].resolvedAt).toBeDefined();+ expect(incidents[1].failedOperationId).toBe(operationId);+ });+ });+it('leaves a paused transport failure alone once a person marks it failed', async () => {// The run errored with a recoverable transport error and the lifecycle paused the// Task. A person then marks it failed without supplying a new error, so thediff --git a/apps/server/src/services/goal/supervisor/index.ts b/apps/server/src/services/goal/supervisor/index.tsindex b432bb2c1ff..2df0a6e63b4 100644--- a/apps/server/src/services/goal/supervisor/index.ts+++ b/apps/server/src/services/goal/supervisor/index.ts@@ -22,7 +22,7 @@ import { AiAgentService } from '@/server/services/aiAgent';import { resolveGoalModelConfig } from '../modelConfig';import { countUnchargedRuns } from '../recoveryPolicy';-import { scheduleGoalAdvance } from '../scheduler';+import { goalPollDelay, scheduleGoalAdvance } from '../scheduler';import { claimGoalTask } from '../taskClaim';import {RECOVERABLE_TASK_STATUSES,@@ -124,9 +124,10 @@ export class GoalSupervisorService {): Promise<GoalTickResult | null> => {if (!graph.goal.config?.supervision?.enabled) return null;const goalId = graph.goal.id;- const waiting = async (message: string): Promise<GoalTickResult> => {+ const waiting = async (message: string, since?: string): Promise<GoalTickResult> => {await scheduleGoalAdvance({- delay: 5,+ delay: goalPollDelay(since),+ poll: true,goalId,userId: this.userId,workspaceId: this.workspaceId,@@ -143,11 +144,29 @@ export class GoalSupervisorService {// identity and settlement redesigned, so it still reaches a person for now.if (!latest?.operationId) return null;const failedOperation = await operations.findById(latest.operationId);- const state = graph.goal.config.supervisorState ?? (await this.initialize(graph));+ let state = graph.goal.config.supervisorState ?? (await this.initialize(graph));let incident = state.incidents.find((item) => item.failedOperationId === latest.operationId);if (!incident) {- if (state.incidents.some((item) => item.status === 'diagnosing'))- return waiting('Another interruption is being diagnosed');+ // An incident is only re-read while its own Task is the failing one, so a+ // diagnosis abandoned by a Task that later finished stays `diagnosing` for+ // good. Waiting on it unbounded polled every five seconds and, with the+ // sweep seeding another chain each pass, took the database pool down.+ const diagnosing = state.incidents.filter((item) => item.status === 'diagnosing');+ const expired = diagnosing.filter(+ (item) => Date.now() - new Date(item.createdAt).getTime() > SUPERVISOR_DIAGNOSIS_TIMEOUT_MS,+ );+ if (expired.length < diagnosing.length)+ return waiting('Another interruption is being diagnosed', diagnosing[0].createdAt);+ if (expired.length > 0) {+ for (const stale of expired) {+ await this.updateIncident(goalId, stale.id, {+ reason: 'Supervisor diagnosis never settled; no recovery was applied',+ status: 'escalated',+ });+ }+ const fresh = await new GoalModel(this.db, this.userId, this.workspaceId).findById(goalId);+ state = fresh?.config?.supervisorState ?? state;+ }if (state.incidents.length >= supervisionLimit(graph.goal)) {for (const previous of state.incidents.filter((item) => item.taskId === task.id && item.status === 'retrying',@@ -199,7 +218,8 @@ export class GoalSupervisorService {incident,],});- if (!claimed) return waiting('Another supervisor advance claimed this incident');+ if (!claimed)+ return waiting('Another supervisor advance claimed this incident', incident.createdAt);if (!incident.eligible) return null;// The durable incident precedes dispatch. If the process dies afterwards,// a sweep adopts the topic operation instead of starting another diagnosis.@@ -278,7 +298,7 @@ export class GoalSupervisorService {const expired =Date.now() - new Date(incident.createdAt).getTime() > SUPERVISOR_DIAGNOSIS_TIMEOUT_MS;if (!operation || ['idle', 'running'].includes(operation.status)) {- if (!expired) return waiting('Waiting for supervisor diagnosis');+ if (!expired) return waiting('Waiting for supervisor diagnosis', incident.createdAt);await this.updateIncident(goalId, incident.id, {reason: 'Supervisor diagnosis timed out; no recovery was applied',status: 'escalated',@@ -388,7 +408,7 @@ export class GoalSupervisorService {fresh?.config?.supervisorState?.incidents.find((item) => item.id === incident.id)?.status === 'retrying') {- return waiting('Supervisor recovery already queued');+ return waiting('Supervisor recovery already queued', incident.createdAt);}await this.updateIncident(goalId, incident.id, {reason: 'Recovery preconditions changed; no recovery was applied',