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.

πŸ› fix(goal): stop offline-device runs from spending the Task attempt budget (#20172)

Arvin Xu76bff555acb6
diff --git a/apps/server/src/services/goal/index.test.ts b/apps/server/src/services/goal/index.test.ts
index ba21c03ca13..25a5f358fa2 100644
--- a/apps/server/src/services/goal/index.test.ts
+++ b/apps/server/src/services/goal/index.test.ts
@@ -1,5 +1,6 @@
// @vitest-environment node
-import { GOAL_COORDINATOR_ACTOR_ID } from '@lobechat/const/goal';
+import { DEVICE_OFFLINE_RUN_STATUS, GOAL_COORDINATOR_ACTOR_ID } from '@lobechat/const/goal';
+import type { ChatTopicMetadata } from '@lobechat/types';
import * as goalGraphUtils from '@lobechat/utils/goalGraph';
import { eq, sql } from 'drizzle-orm';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
@@ -44,7 +45,7 @@ import {
} from './decideNextMove';
import { GoalExplorationPlanner } from './explorationPlanner';
import { GoalService } from './index';
-import { VERIFY_SETTLE_GRACE_MS } from './recoveryPolicy';
+import { DEVICE_OFFLINE_GATE_REASON, VERIFY_SETTLE_GRACE_MS } from './recoveryPolicy';
import { TaskRecoveryCoordinator } from './taskRecoveryCoordinator';
import type { GoalTickObservation } from './traceObservation';
@@ -3134,28 +3135,274 @@ describe('GoalService', () => {
expect((await service.graph(graph.goal.id)).decisions).toHaveLength(0);
});
- it('asks a person once the device has been gone past the reconnect window', async () => {
+ it('retries on the offline schedule even while the device still looks offline', async () => {
vi.spyOn(deviceGateway, 'queryDeviceList').mockResolvedValue([]);
- const { created, graph, service } = await setup('Device gone for good');
+ const runSpy = vi
+ .spyOn(TaskRunnerService.prototype, 'runTask')
+ .mockResolvedValue({ operationId: 'op-on-schedule', success: true } as never);
+ const { created, graph, service } = await setup('Device gone past the first backoff');
await serverDB
.update(tasks)
- .set({ updatedAt: new Date(Date.now() - 13 * 60 * 60 * 1000) })
+ .set({ updatedAt: new Date(Date.now() - 31 * 60 * 1000) })
.where(eq(tasks.id, created.taskId!));
- const gated = await service.tick(graph.goal.id);
+ const retried = await service.tick(graph.goal.id);
- expect(gated).toMatchObject({ outcome: 'waiting_human', taskId: created.taskId });
+ expect(runSpy).toHaveBeenCalledWith(
+ expect.objectContaining({ taskId: created.taskId, trigger: 'goal' }),
+ );
+ expect(retried).toMatchObject({ outcome: 'waiting_external', taskId: created.taskId });
+ expect((await service.graph(graph.goal.id)).decisions).toHaveLength(0);
});
- it('does not wait on a deployment without a device gateway', async () => {
+ it('waits out the backoff without presence on a deployment without a device gateway', async () => {
const listSpy = vi.spyOn(deviceGateway, 'queryDeviceList');
+ const runSpy = vi.spyOn(TaskRunnerService.prototype, 'runTask');
const { created, graph, service } = await setup('Self-hosted without devices');
vi.spyOn(deviceGateway, 'isConfigured', 'get').mockReturnValue(false);
- const gated = await service.tick(graph.goal.id);
+ const waiting = await service.tick(graph.goal.id);
expect(listSpy).not.toHaveBeenCalled();
+ expect(runSpy).not.toHaveBeenCalled();
+ expect(waiting).toMatchObject({ outcome: 'waiting_external', taskId: created.taskId });
+ });
+ });
+
+ describe('a Task whose runs its device lost', () => {
+ const MINUTE = 60 * 1000;
+ const HOUR = 60 * MINUTE;
+
+ const setup = async (title: string, maxAttemptsPerTask: number) => {
+ vi.spyOn(deviceGateway, 'isConfigured', 'get').mockReturnValue(true);
+ vi.spyOn(deviceGateway, 'queryDeviceList').mockResolvedValue([]);
+ const runSpy = vi
+ .spyOn(TaskRunnerService.prototype, 'runTask')
+ .mockResolvedValue({ operationId: 'op-retry', success: true } as never);
+ const service = new GoalService(serverDB, userId);
+ const taskModel = new TaskModel(serverDB, userId);
+ const graph = await service.create({
+ config: { recovery: { maxAttemptsPerTask, operationLeaseTimeoutMs: 60_000 } },
+ title,
+ tasks: ['Run on the laptop'],
+ });
+ const created = await service.tick(graph.goal.id);
+ runSpy.mockClear();
+ return { created, graph, runSpy, service, taskModel };
+ };
+
+ const addRun = async (
+ taskId: string,
+ seq: number,
+ status: string,
+ options: { metadata?: ChatTopicMetadata; operationId?: string; updatedAt?: Date } = {},
+ ) => {
+ const topicId = `tpc_offline_${seq}`;
+ await serverDB.insert(topics).values({ id: topicId, metadata: options.metadata, userId });
+ await serverDB.insert(taskTopics).values({
+ operationId: options.operationId,
+ seq,
+ status,
+ taskId,
+ topicId,
+ userId,
+ ...(options.updatedAt && { updatedAt: options.updatedAt }),
+ });
+ return topicId;
+ };
+
+ /** `count` consecutive offline runs, the newest `sinceLast` ago. */
+ const addOfflineRuns = async (taskId: string, count: number, sinceLast: number) => {
+ for (let seq = 1; seq <= count; seq++) {
+ await addRun(taskId, seq, DEVICE_OFFLINE_RUN_STATUS, {
+ updatedAt: new Date(Date.now() - sinceLast - (count - seq) * HOUR),
+ });
+ }
+ };
+
+ const decisionReasons = async (service: GoalService, goalId: string) =>
+ (await service.graph(goalId)).nodes
+ .filter((node) => node.kind === 'decision')
+ .map((node) => node.description);
+
+ it('does not charge a run lost while its device was offline to the attempt budget', async () => {
+ const { created, graph, runSpy, service, taskModel } = await setup(
+ 'Laptop went offline mid-run',
+ 1,
+ );
+ await taskModel.update(created.taskId!, { totalTopics: 1 });
+ await taskModel.updateStatus(created.taskId!, 'running');
+ const operationModel = new AgentOperationModel(serverDB, userId);
+ await operationModel.recordStart({ operationId: 'op-lost', taskId: created.taskId });
+ await serverDB
+ .update(agentOperations)
+ .set({ updatedAt: new Date('2026-01-01T00:00:00.000Z') })
+ .where(eq(agentOperations.id, 'op-lost'));
+ const topicId = await addRun(created.taskId!, 1, 'running', {
+ metadata: {
+ runningOperation: {
+ assistantMessageId: 'msg-lost',
+ deviceId: 'device-laptop',
+ operationId: 'op-lost',
+ },
+ },
+ operationId: 'op-lost',
+ });
+
+ const waiting = await service.tick(graph.goal.id);
+
+ expect(waiting).toMatchObject({
+ message: expect.stringContaining('waiting for its device to reconnect'),
+ outcome: 'waiting_external',
+ taskId: created.taskId,
+ });
+ expect(runSpy).not.toHaveBeenCalled();
+ expect(await decisionReasons(service, graph.goal.id)).toHaveLength(0);
+ const [lost] = await new TaskTopicModel(serverDB, userId).findByTaskId(created.taskId!);
+ expect(lost.status).toBe(DEVICE_OFFLINE_RUN_STATUS);
+
+ // Once the first backoff has passed, the retry goes out on the budget the
+ // lost run did not spend.
+ await serverDB
+ .update(taskTopics)
+ .set({ updatedAt: new Date(Date.now() - 31 * MINUTE) })
+ .where(eq(taskTopics.topicId, topicId));
+ await service.tick(graph.goal.id);
+
+ expect(runSpy).toHaveBeenCalledWith(
+ expect.objectContaining({ taskId: created.taskId, trigger: 'goal' }),
+ );
+ expect(await decisionReasons(service, graph.goal.id)).toHaveLength(0);
+ });
+
+ it('still charges a lost run whose device is online when it is reclaimed', async () => {
+ const { created, graph, runSpy, service, taskModel } = await setup(
+ 'Run died on a connected laptop',
+ 1,
+ );
+ vi.spyOn(deviceGateway, 'queryDeviceList').mockResolvedValue([
+ { deviceId: 'device-laptop' } as never,
+ ]);
+ await taskModel.update(created.taskId!, { totalTopics: 1 });
+ await taskModel.updateStatus(created.taskId!, 'running');
+ const operationModel = new AgentOperationModel(serverDB, userId);
+ await operationModel.recordStart({ operationId: 'op-died', taskId: created.taskId });
+ await serverDB
+ .update(agentOperations)
+ .set({ updatedAt: new Date('2026-01-01T00:00:00.000Z') })
+ .where(eq(agentOperations.id, 'op-died'));
+ await addRun(created.taskId!, 1, 'running', {
+ metadata: { boundDeviceId: 'device-laptop' },
+ operationId: 'op-died',
+ });
+
+ const gated = await service.tick(graph.goal.id);
+
expect(gated).toMatchObject({ outcome: 'waiting_human', taskId: created.taskId });
+ expect(runSpy).not.toHaveBeenCalled();
+ });
+
+ it.each([
+ { before: 29 * MINUTE, after: 31 * MINUTE, offlineRuns: 1, schedule: '30min' },
+ { before: 59 * MINUTE, after: 61 * MINUTE, offlineRuns: 2, schedule: '1h' },
+ { before: 119 * MINUTE, after: 121 * MINUTE, offlineRuns: 3, schedule: '2h' },
+ { before: 7 * HOUR + 59 * MINUTE, after: 8 * HOUR + MINUTE, offlineRuns: 5, schedule: '8h' },
+ {
+ before: 7 * HOUR + 59 * MINUTE,
+ after: 8 * HOUR + MINUTE,
+ offlineRuns: 6,
+ schedule: '8h (capped)',
+ },
+ ])(
+ 'waits $schedule after offline run $offlineRuns before retrying',
+ async ({ after, before, offlineRuns }) => {
+ const { created, graph, runSpy, service, taskModel } = await setup(
+ `Offline backoff ${offlineRuns}`,
+ 1,
+ );
+ await taskModel.update(created.taskId!, { totalTopics: offlineRuns });
+ await addOfflineRuns(created.taskId!, offlineRuns, before);
+ await taskModel.updateStatus(created.taskId!, 'paused', { error: 'DEVICE_OFFLINE' });
+
+ const waiting = await service.tick(graph.goal.id);
+ expect(waiting).toMatchObject({ outcome: 'waiting_external', taskId: created.taskId });
+ expect(runSpy).not.toHaveBeenCalled();
+
+ await serverDB
+ .update(taskTopics)
+ .set({ updatedAt: new Date(Date.now() - after) })
+ .where(eq(taskTopics.topicId, `tpc_offline_${offlineRuns}`));
+ await service.tick(graph.goal.id);
+
+ expect(runSpy).toHaveBeenCalledWith(
+ expect.objectContaining({ taskId: created.taskId, trigger: 'goal' }),
+ );
+ expect(await decisionReasons(service, graph.goal.id)).toHaveLength(0);
+ },
+ );
+
+ it('retries at once when presence shows the device back before the backoff ends', async () => {
+ const { created, graph, runSpy, service, taskModel } = await setup('Laptop woke up', 1);
+ vi.spyOn(deviceGateway, 'queryDeviceList').mockResolvedValue([
+ { deviceId: 'device-laptop' } as never,
+ ]);
+ await taskModel.update(created.taskId!, { totalTopics: 1 });
+ await addRun(created.taskId!, 1, DEVICE_OFFLINE_RUN_STATUS, {
+ metadata: { boundDeviceId: 'device-laptop' },
+ });
+ await taskModel.updateStatus(created.taskId!, 'paused', { error: 'DEVICE_OFFLINE' });
+
+ await service.tick(graph.goal.id);
+
+ expect(runSpy).toHaveBeenCalledOnce();
+ });
+
+ it('asks a person once every offline retry found the device gone', async () => {
+ const { created, graph, runSpy, service, taskModel } = await setup(
+ 'Laptop never came back',
+ 1,
+ );
+ await taskModel.update(created.taskId!, { totalTopics: 7 });
+ await addOfflineRuns(created.taskId!, 7, 10 * HOUR);
+ await taskModel.updateStatus(created.taskId!, 'paused', { error: 'DEVICE_OFFLINE' });
+
+ const gated = await service.tick(graph.goal.id);
+
+ expect(gated).toMatchObject({ outcome: 'waiting_human', taskId: created.taskId });
+ expect(runSpy).not.toHaveBeenCalled();
+ expect(await decisionReasons(service, graph.goal.id)).toEqual([DEVICE_OFFLINE_GATE_REASON]);
+ });
+
+ it('keeps charging verification-rejected attempts to the budget', async () => {
+ const { created, graph, runSpy, service, taskModel } = await setup(
+ 'Rejections still count',
+ 2,
+ );
+ await addRun(created.taskId!, 1, DEVICE_OFFLINE_RUN_STATUS);
+ await addRun(created.taskId!, 2, 'completed');
+ await taskModel.update(created.taskId!, { totalTopics: 2 });
+ await taskModel.updateStatus(created.taskId!, 'paused', {
+ error: VERIFICATION_FAILED_ERROR,
+ });
+
+ // One offline run and one rejection: only the rejection is charged.
+ await service.tick(graph.goal.id);
+ expect(runSpy).toHaveBeenCalledOnce();
+
+ await addRun(created.taskId!, 3, 'completed');
+ await taskModel.update(created.taskId!, { totalTopics: 3 });
+ await taskModel.updateStatus(created.taskId!, 'paused', {
+ error: VERIFICATION_FAILED_ERROR,
+ });
+ runSpy.mockClear();
+
+ const gated = await service.tick(graph.goal.id);
+
+ expect(gated).toMatchObject({ outcome: 'waiting_human', taskId: created.taskId });
+ expect(runSpy).not.toHaveBeenCalled();
+ expect(await decisionReasons(service, graph.goal.id)).toEqual([
+ 'Task attempt budget was exhausted',
+ ]);
});
});
diff --git a/apps/server/src/services/goal/index.ts b/apps/server/src/services/goal/index.ts
index fcbb64920e7..8f69386f5d7 100644
--- a/apps/server/src/services/goal/index.ts
+++ b/apps/server/src/services/goal/index.ts
@@ -1,11 +1,13 @@
import type { GoalAdvanceEffect, GoalMetricCriteriaState } from '@lobechat/agent-tracing';
import { buildGoalRequirement } from '@lobechat/builtin-tool-goal';
import {
+ DEVICE_OFFLINE_RUN_STATUS,
GOAL_CLARIFICATION_OPTION,
GOAL_CLARIFICATION_TITLE,
GOAL_COORDINATOR_ACTOR_ID,
} from '@lobechat/const/goal';
import type {
+ ChatTopicMetadata,
GoalConfig,
GoalCreateConfig,
GoalDecisionOption,
@@ -65,10 +67,12 @@ import {
import { experimentResults, exploreGraph } from './exploreGraph';
import { answeredProblem, GoalManagerService, problemKey } from './manager';
import {
+ countConsecutiveDeviceOfflineRuns,
DEFAULT_MANAGER_MAX_TURNS,
- DEVICE_RECONNECT_WAIT_MS,
+ DEVICE_OFFLINE_GATE_REASON,
isDeviceUnavailableFailure,
managerTurnsSpent,
+ nextDeviceOfflineRetryAt,
resolveMaxConcurrentTasks,
resolveOperationLeaseTimeout,
resolveTaskMaxSteps,
@@ -1832,9 +1836,7 @@ export class GoalService {
}
case 'recover_lease': {
- return observe(
- await this.resumeAbandonedTaskRecovery(graph, acting!.id, task, effects),
- );
+ return observe(await this.recoverLostRun(graph, acting!.id, task, effects));
}
case 'recover_verification': {
@@ -2434,9 +2436,42 @@ export class GoalService {
});
if (!reclaimed) return undefined;
+ return this.recoverLostRun(graph, nodeId, task, effects);
+ };
+
+ /**
+ * Recover a Task whose run was lost rather than judged β€” its lease expired or
+ * the gateway watchdog abandoned it.
+ *
+ * A run lost because its device went offline mid-run is the same failure as a
+ * dispatch that never reached the device, only noticed later: the laptop went
+ * to sleep with the run on it. It is re-marked as an offline run so it neither
+ * spends the attempt budget nor retries into a device that is still gone.
+ */
+ private recoverLostRun = async (
+ graph: GoalGraphSnapshot,
+ nodeId: string,
+ task: TaskItem,
+ effects: GoalAdvanceEffect[] = [],
+ ): Promise<GoalTickResult> => {
+ await this.markRunLostToOfflineDevice(task.id);
+ const held = await this.holdForOfflineDevice(graph, nodeId, task, effects);
+ if (held) return held;
return this.resumeAbandonedTaskRecovery(graph, nodeId, task, effects);
};
+ /**
+ * Re-mark the Task's latest lost run as an offline run when the device it ran
+ * on is offline now. Only a device the gateway can vouch for counts: without
+ * presence the run stays a charged attempt, exactly as before.
+ */
+ private markRunLostToOfflineDevice = async (taskId: string) => {
+ const [latest] = await this.taskTopicModel.findWithHandoff(taskId, 1);
+ if (!latest?.topicId || (latest.status !== 'timeout' && latest.status !== 'failed')) return;
+ if ((await this.readRunDevicePresence(latest)) !== 'offline') return;
+ await this.taskTopicModel.updateStatus(taskId, latest.topicId, DEVICE_OFFLINE_RUN_STATUS);
+ };
+
private resumeAbandonedTaskRecovery = async (
graph: GoalGraphSnapshot,
nodeId: string,
@@ -2511,18 +2546,9 @@ export class GoalService {
*
* A sleeping laptop or a restarting desktop app is the usual cause, and it
* fixes itself: the gate it used to open waited hours for someone to press
- * Retry once the device had long reconnected. While that device is offline
- * the goal simply waits β€” the sweep keeps asking β€” and spends nothing. Once
- * it is back, the Task retries through the ordinary recovery path, so a
- * binding that stays broken still ends at the attempt budget's gate. Past the
- * reconnect window a person is asked after all, since the device is not
- * coming back on its own.
- *
- * Presence is read for the exact device the failed dispatch was routed to,
- * in the pool it was routed through: a workspace goal may run on a personal
- * device, and another device coming online proves nothing about this one.
- * Without a recorded route, or without a device gateway at all, there is
- * nothing to wait for and the existing failure path decides.
+ * Retry once the device had long reconnected. While the device is offline the
+ * goal waits β€” the sweep keeps asking β€” and spends nothing; the retry then
+ * goes through the ordinary recovery path.
*/
private waitForDevice = async (
graph: GoalGraphSnapshot,
@@ -2531,31 +2557,105 @@ export class GoalService {
effects: GoalAdvanceEffect[],
): Promise<GoalTickResult | undefined> => {
if (task.status !== 'paused' || !isDeviceUnavailableFailure(task.error)) return;
- if (!deviceGateway.isConfigured) return;
- if (new Date(task.updatedAt).getTime() < Date.now() - DEVICE_RECONNECT_WAIT_MS) return;
+ const held = await this.holdForOfflineDevice(graph, nodeId, task, effects);
+ if (held) return held;
+ return this.resumeAbandonedTaskRecovery(graph, nodeId, task, effects);
+ };
- const [latestRun] = await this.taskTopicModel.findWithHandoff(task.id, 1);
- const operation = latestRun?.operationId
- ? await new AgentOperationModel(this.db, this.userId, this.workspaceId).findById(
- latestRun.operationId,
- )
- : undefined;
- const route = readDeviceDispatchRoute(operation?.error);
- if (!route) return;
+ /**
+ * The offline retry schedule. Offline runs are not charged to the attempt
+ * budget, so this is what bounds them: each consecutive one pushes the next
+ * retry further out (see `nextDeviceOfflineRetryAt`), and once the offline
+ * retries are spent a person is asked. Presence only brings a retry forward β€”
+ * a device seen back online is retried at once β€” so a deployment without a
+ * device gateway, or a run with no recorded device, still retries on schedule.
+ *
+ * Returns nothing when the Task should retry now.
+ */
+ private holdForOfflineDevice = async (
+ graph: GoalGraphSnapshot,
+ nodeId: string,
+ task: TaskItem,
+ effects: GoalAdvanceEffect[],
+ ): Promise<GoalTickResult | undefined> => {
+ const runs = await this.taskTopicModel.findByTaskId(task.id);
+ const offlineRuns = countConsecutiveDeviceOfflineRuns(runs);
+ // A dispatch failure is an offline run even when it left no run behind.
+ if (!offlineRuns && !isDeviceUnavailableFailure(task.error)) return;
- const devices = await deviceGateway.queryDeviceList(route.userId, route.workspaceId);
- if (devices.some((device) => device.deviceId === route.deviceId))
- return this.resumeAbandonedTaskRecovery(graph, nodeId, task, effects);
+ const lastFailureAt = new Date(offlineRuns ? runs[0].updatedAt : task.updatedAt);
+ const retryAt = nextDeviceOfflineRetryAt(offlineRuns, lastFailureAt);
+ if (!retryAt)
+ return this.gateOrTakeOver(graph, nodeId, task.id, DEVICE_OFFLINE_GATE_REASON, effects);
+ if (retryAt.getTime() <= Date.now()) return;
+
+ const [latest] = await this.taskTopicModel.findWithHandoff(task.id, 1);
+ if (latest && (await this.readRunDevicePresence(latest)) === 'online') return;
return {
goalId: graph.goal.id,
- message: `Task ${task.identifier} is waiting for its device to reconnect`,
+ message: `Task ${task.identifier} is waiting for its device to reconnect; next retry at ${retryAt.toISOString()}`,
nodeId,
outcome: 'waiting_external',
taskId: task.id,
};
};
+ /**
+ * Whether the device a run was routed to is connected right now.
+ *
+ * Presence is read for the exact device the run used, in the pool it was
+ * routed through: a workspace goal may run on a personal device, and another
+ * device coming online proves nothing about this one. A failed dispatch
+ * records its route on the operation error; a run that got going leaves its
+ * device on the topic. A topic bound to a device without a recorded pool is
+ * looked up in every pool this goal can route through.
+ */
+ private readRunDevicePresence = async (run: {
+ metadata?: ChatTopicMetadata | null;
+ operationId?: string | null;
+ }): Promise<'offline' | 'online' | 'unknown'> => {
+ if (!deviceGateway.isConfigured) return 'unknown';
+
+ const operation = run.operationId
+ ? await new AgentOperationModel(this.db, this.userId, this.workspaceId).findById(
+ run.operationId,
+ )
+ : undefined;
+ const dispatchRoute = readDeviceDispatchRoute(operation?.error);
+ const running = run.metadata?.runningOperation;
+ const runningDevice =
+ running?.deviceId && running.operationId === run.operationId ? running : undefined;
+
+ let deviceId: string | undefined;
+ let pools: { userId: string; workspaceId?: string }[];
+ if (dispatchRoute) {
+ deviceId = dispatchRoute.deviceId;
+ pools = [{ userId: dispatchRoute.userId, workspaceId: dispatchRoute.workspaceId }];
+ } else if (runningDevice) {
+ deviceId = runningDevice.deviceId;
+ pools = [
+ {
+ userId: runningDevice.deviceUserId ?? this.userId,
+ workspaceId: runningDevice.deviceWorkspaceId,
+ },
+ ];
+ } else {
+ deviceId = run.metadata?.boundDeviceId;
+ pools = [
+ { userId: this.userId },
+ ...(this.workspaceId ? [{ userId: this.userId, workspaceId: this.workspaceId }] : []),
+ ];
+ }
+ if (!deviceId) return 'unknown';
+
+ for (const pool of pools) {
+ const devices = await deviceGateway.queryDeviceList(pool.userId, pool.workspaceId);
+ if (devices.some((device) => device.deviceId === deviceId)) return 'online';
+ }
+ return 'offline';
+ };
+
private buildTaskInstruction = (
graph: GoalGraphSnapshot,
title: string,
diff --git a/apps/server/src/services/goal/manager.ts b/apps/server/src/services/goal/manager.ts
index 91f905aed5e..c845fb10c1c 100644
--- a/apps/server/src/services/goal/manager.ts
+++ b/apps/server/src/services/goal/manager.ts
@@ -23,7 +23,7 @@ import { goals } from '@/database/schemas/goal';
import type { LobeChatDatabase } from '@/database/type';
import { AiAgentService } from '@/server/services/aiAgent';
-import { DEFAULT_MANAGER_MAX_TURNS } from './recoveryPolicy';
+import { countDeviceOfflineRuns, DEFAULT_MANAGER_MAX_TURNS } from './recoveryPolicy';
import { scheduleGoalAdvance } from './scheduler';
import { recoveryEligibility } from './supervisor/policy';
@@ -450,7 +450,7 @@ export class GoalManagerService {
runs[0].operationId,
)
: undefined;
- return !recoveryEligibility(graph, failed, op).eligible;
+ return !recoveryEligibility(graph, failed, op, false, countDeviceOfflineRuns(runs)).eligible;
};
private startTurn = async (
@@ -770,7 +770,7 @@ export class GoalManagerService {
if (
!task ||
runs[0]?.operationId !== plan.failedOperationId ||
- !recoveryEligibility(graph, task, failure).eligible
+ !recoveryEligibility(graph, task, failure, false, countDeviceOfflineRuns(runs)).eligible
)
throw new TRPCError({
code: 'CONFLICT',
diff --git a/apps/server/src/services/goal/recoveryPolicy.test.ts b/apps/server/src/services/goal/recoveryPolicy.test.ts
index 993c3457775..4e3476714a4 100644
--- a/apps/server/src/services/goal/recoveryPolicy.test.ts
+++ b/apps/server/src/services/goal/recoveryPolicy.test.ts
@@ -2,9 +2,13 @@ import type { GoalItem } from '@lobechat/types';
import { describe, expect, it } from 'vitest';
import {
+ countChargedTaskAttempts,
+ countConsecutiveDeviceOfflineRuns,
DEFAULT_MANAGER_MAX_TURNS,
managerTurnsSpent,
MIN_OPERATION_LEASE_TIMEOUT_MS,
+ nextDeviceOfflineRetryAt,
+ resolveFailedRunStatus,
resolveOperationLeaseTimeout,
} from './recoveryPolicy';
@@ -36,3 +40,41 @@ describe('managerTurnsSpent', () => {
expect(managerTurnsSpent(config(12, 20))).toBe(false);
});
});
+
+describe('nextDeviceOfflineRetryAt', () => {
+ const MINUTE = 60 * 1000;
+ const lastFailureAt = new Date('2026-01-01T00:00:00.000Z');
+ const delayAfter = (failures: number) => {
+ const at = nextDeviceOfflineRetryAt(failures, lastFailureAt);
+ return at && (at.getTime() - lastFailureAt.getTime()) / MINUTE;
+ };
+
+ it('doubles from 30 minutes and caps each interval at 8 hours', () => {
+ expect([1, 2, 3, 4, 5, 6].map(delayAfter)).toEqual([30, 60, 120, 240, 480, 480]);
+ });
+
+ it('stops scheduling once six offline retries have been spent', () => {
+ expect(nextDeviceOfflineRetryAt(7, lastFailureAt)).toBeUndefined();
+ });
+});
+
+describe('offline run accounting', () => {
+ it('counts only the offline streak since the last run that reached its device', () => {
+ const runs = [
+ { status: 'device_offline' },
+ { status: 'device_offline' },
+ { status: 'completed' },
+ { status: 'device_offline' },
+ ];
+ expect(countConsecutiveDeviceOfflineRuns(runs)).toBe(2);
+ });
+
+ it('does not charge offline runs to the attempt budget', () => {
+ expect(countChargedTaskAttempts({ totalTopics: 4 }, 3)).toBe(1);
+ });
+
+ it('marks a failed run offline only for device-unavailable errors', () => {
+ expect(resolveFailedRunStatus('DEVICE_OFFLINE (HTTP 503)')).toBe('device_offline');
+ expect(resolveFailedRunStatus('Delivery did not pass verification.')).toBe('failed');
+ });
+});
diff --git a/apps/server/src/services/goal/recoveryPolicy.ts b/apps/server/src/services/goal/recoveryPolicy.ts
index b10fef47fab..0d07db07d7c 100644
--- a/apps/server/src/services/goal/recoveryPolicy.ts
+++ b/apps/server/src/services/goal/recoveryPolicy.ts
@@ -1,4 +1,5 @@
-import type { GoalItem } from '@lobechat/types';
+import { DEVICE_OFFLINE_RUN_STATUS } from '@lobechat/const/goal';
+import type { GoalItem, TaskItem } from '@lobechat/types';
import { HETERO_DISPATCH_ERROR_HEADLINES } from '@/server/services/aiAgent/helpers/heteroErrors';
@@ -70,11 +71,66 @@ export const resolveOperationLeaseTimeout = (goal: GoalItem): number => {
};
/**
- * How long a Task that could not reach its device waits for the device to come
- * back before the coordinator asks a person instead. Long enough to span a
- * laptop sleeping overnight, which is how these goals usually lose the device.
+ * Retry schedule for a Task whose runs keep ending because its device is
+ * unavailable. Such a run is not charged to the attempt budget β€” nothing judged
+ * the work β€” so it needs a bound of its own: a laptop asleep overnight should
+ * resume on its own, a device that never returns should reach a person within
+ * about a day.
+ *
+ * After the Nth consecutive offline run the next retry waits
+ * `min(FIRST * 2^(N-1), MAX)`: 30min, 1h, 2h, 4h, 8h, 8h β€” 23.5h across
+ * `MAX_DEVICE_OFFLINE_RETRIES` retries. A device that reconnects earlier is
+ * retried as soon as presence shows it back.
+ */
+export const DEVICE_OFFLINE_FIRST_RETRY_DELAY_MS = 30 * 60 * 1000;
+export const DEVICE_OFFLINE_MAX_RETRY_DELAY_MS = 8 * 60 * 60 * 1000;
+export const MAX_DEVICE_OFFLINE_RETRIES = 6;
+/** Why the gate opens once the offline retries are spent. */
+export const DEVICE_OFFLINE_GATE_REASON = 'Task device stayed offline';
+
+/**
+ * When the next retry after `offlineFailures` consecutive offline runs is due,
+ * or `undefined` once every offline retry has been spent.
+ */
+export const nextDeviceOfflineRetryAt = (
+ offlineFailures: number,
+ lastFailureAt: Date,
+): Date | undefined => {
+ const failures = Math.max(1, offlineFailures);
+ // Every failure after the first is a retry that also found the device gone.
+ if (failures - 1 >= MAX_DEVICE_OFFLINE_RETRIES) return undefined;
+ const delay = Math.min(
+ DEVICE_OFFLINE_FIRST_RETRY_DELAY_MS * 2 ** (failures - 1),
+ DEVICE_OFFLINE_MAX_RETRY_DELAY_MS,
+ );
+ return new Date(lastFailureAt.getTime() + delay);
+};
+
+/** Runs that ended because their device was unavailable. */
+export const isDeviceOfflineRun = (run: { status: string }): boolean =>
+ run.status === DEVICE_OFFLINE_RUN_STATUS;
+
+export const countDeviceOfflineRuns = (runs: readonly { status: string }[]): number =>
+ runs.filter(isDeviceOfflineRun).length;
+
+/**
+ * Offline runs since the Task's last run that reached its device, `runs` newest
+ * first. The schedule restarts once a run gets through, so a device that drops
+ * once a week is not held to the budget of the week before.
*/
-export const DEVICE_RECONNECT_WAIT_MS = 12 * 60 * 60 * 1000;
+export const countConsecutiveDeviceOfflineRuns = (runs: readonly { status: string }[]): number => {
+ const firstReached = runs.findIndex((run) => !isDeviceOfflineRun(run));
+ return firstReached === -1 ? runs.length : firstReached;
+};
+
+/**
+ * Attempts charged to a Task's budget: every run it produced except the ones
+ * its device lost. Those retry on the offline schedule above instead.
+ */
+export const countChargedTaskAttempts = (
+ task: Pick<TaskItem, 'totalTopics'>,
+ deviceOfflineRuns: number,
+): number => Math.max(0, (task.totalTopics ?? 0) - deviceOfflineRuns);
/**
* Dispatch failures that only say the device is not reachable right now. A
@@ -98,6 +154,15 @@ export const isDeviceUnavailableFailure = (error?: string | null): boolean =>
(code) => error.includes(code) || error.includes(HETERO_DISPATCH_ERROR_HEADLINES[code]),
);
+/**
+ * The `task_topics.status` a run that errored ends with. Every writer of a failed
+ * run goes through this, so the dispatch result and a lifecycle hook delivered
+ * later agree on an offline run instead of the later one turning it back into a
+ * charged failure.
+ */
+export const resolveFailedRunStatus = (error?: string | null): string =>
+ isDeviceUnavailableFailure(error) ? DEVICE_OFFLINE_RUN_STATUS : 'failed';
+
/** Whether a goal's main Agent has used every turn its policy allows. */
export const managerTurnsSpent = (config: GoalItem['config']): boolean =>
!!config?.manager &&
diff --git a/apps/server/src/services/goal/supervisor/index.test.ts b/apps/server/src/services/goal/supervisor/index.test.ts
index b5968da4161..1c246a236fa 100644
--- a/apps/server/src/services/goal/supervisor/index.test.ts
+++ b/apps/server/src/services/goal/supervisor/index.test.ts
@@ -118,12 +118,13 @@ const failedGoal = async (enabled = true, error = 'fetch failed: ECONNRESET') =>
};
/**
- * The run itself settled cleanly and something around it broke: the device link
- * dropped, or verification could not run. The Task is left `paused`, not `failed`,
- * and its operation is `done`, not `error`.
+ * The run itself settled cleanly and something around it broke: the device
+ * gateway errored, or verification could not run. The Task is left `paused`, not
+ * `failed`, and its operation is `done`, not `error`. (An offline device is not
+ * supervision's: the coordinator's offline retry schedule owns that failure.)
*/
const pipelineFailureGoal = async (
- error = '{"error":"DEVICE_OFFLINE","success":false}',
+ error = '{"error":"DEVICE_GATEWAY_ERROR","success":false}',
withRun = true,
) => {
const graph = await service().create({
@@ -517,7 +518,10 @@ describe('Goal Supervisor integration', () => {
// Routed as `paused`; a person then marks it `failed` without supplying a new
// error, so the run's transport reason survives and the policy still accepts it.
// Only claiming against the status the incident was opened on keeps this decision.
- const { goalId, taskId } = await failedGoal(true, '{"error":"DEVICE_OFFLINE","success":false}');
+ const { goalId, taskId } = await failedGoal(
+ true,
+ '{"error":"DEVICE_GATEWAY_ERROR","success":false}',
+ );
await taskModel.update(taskId, { status: 'paused' });
expect((await service().tick(goalId)).outcome).toBe('waiting_external');
await diagnose(goalId);
diff --git a/apps/server/src/services/goal/supervisor/index.ts b/apps/server/src/services/goal/supervisor/index.ts
index e4bb9524b96..3852b3aedd7 100644
--- a/apps/server/src/services/goal/supervisor/index.ts
+++ b/apps/server/src/services/goal/supervisor/index.ts
@@ -21,6 +21,7 @@ import type { LobeChatDatabase } from '@/database/type';
import { AiAgentService } from '@/server/services/aiAgent';
import { resolveGoalModelConfig } from '../modelConfig';
+import { countDeviceOfflineRuns } from '../recoveryPolicy';
import { scheduleGoalAdvance } from '../scheduler';
import { claimGoalTask } from '../taskClaim';
import {
@@ -164,6 +165,7 @@ export class GoalSupervisorService {
task,
failedOperation,
statusAuthoredByActor(await taskModel.getActivities(task.id, 20), task.status),
+ countDeviceOfflineRuns(runs),
);
if (eligibility.eligible && (await this.budgetBlocked(graph))) {
eligibility = {
@@ -339,6 +341,7 @@ export class GoalSupervisorService {
await new TaskModel(tx, this.userId, this.workspaceId).getActivities(task.id, 20),
currentTask.status,
),
+ countDeviceOfflineRuns(currentRuns),
).eligible ||
(await new GoalSupervisorService(tx, this.userId, this.workspaceId).budgetBlocked(
currentGraph,
diff --git a/apps/server/src/services/goal/supervisor/policy.ts b/apps/server/src/services/goal/supervisor/policy.ts
index a57dd8a7276..e114efcb95f 100644
--- a/apps/server/src/services/goal/supervisor/policy.ts
+++ b/apps/server/src/services/goal/supervisor/policy.ts
@@ -9,7 +9,7 @@ import { isAgentOperationInFlight } from '@lobechat/types';
import type { AgentOperationItem } from '@/database/schemas/agentOperations';
import { HETERO_DISPATCH_ERROR_HEADLINES } from '@/server/services/aiAgent/helpers/heteroErrors';
-import { resolveTaskAttemptBudget } from '../recoveryPolicy';
+import { countChargedTaskAttempts, resolveTaskAttemptBudget } from '../recoveryPolicy';
export const SUPERVISOR_DIAGNOSIS_TIMEOUT_MS = 10 * 60 * 1000;
export const MAX_SUPERVISION_INCIDENTS = 100;
@@ -93,6 +93,8 @@ export const recoveryEligibility = (
operation?: AgentOperationItem,
/** Whether the Task's current status was written by a person or an agent tool. */
actorAuthoredStatus = false,
+ /** Runs the Task's device lost; they are not charged to its attempt budget. */
+ deviceOfflineRuns = 0,
): { eligible: boolean; reason: string } => {
if (!graph.goal.config?.supervision?.enabled && !graph.goal.config?.manager)
return { eligible: false, reason: 'Supervision is disabled' };
@@ -120,7 +122,7 @@ export const recoveryEligibility = (
if (actorAuthoredStatus) {
return { eligible: false, reason: 'Someone set this status themselves' };
}
- if ((task.totalTopics ?? 0) >= resolveTaskAttemptBudget(graph.goal)) {
+ if (countChargedTaskAttempts(task, deviceOfflineRuns) >= resolveTaskAttemptBudget(graph.goal)) {
return { eligible: false, reason: 'Task attempt budget exhausted' };
}
const error = `${operation?.error?.type ?? ''} ${operation?.error?.message ?? ''} ${task.error ?? ''}`;
diff --git a/apps/server/src/services/goal/taskRecoveryCoordinator.ts b/apps/server/src/services/goal/taskRecoveryCoordinator.ts
index 6e3857b64cb..e925644ad58 100644
--- a/apps/server/src/services/goal/taskRecoveryCoordinator.ts
+++ b/apps/server/src/services/goal/taskRecoveryCoordinator.ts
@@ -3,10 +3,13 @@ import debug from 'debug';
import { AgentOperationModel } from '@/database/models/agentOperation';
import { TaskModel } from '@/database/models/task';
+import { TaskTopicModel } from '@/database/models/taskTopic';
import type { LobeChatDatabase } from '@/database/type';
import { TaskRunnerService } from '@/server/services/taskRunner';
import {
+ countChargedTaskAttempts,
+ countDeviceOfflineRuns,
isDeviceUnavailableFailure,
resolveTaskAttemptBudget,
resolveTaskMaxSteps,
@@ -55,7 +58,12 @@ export class TaskRecoveryCoordinator {
task: TaskItem;
}): Promise<TaskRecoveryResult> => {
const { goal, task } = params;
- const attempts = task.totalTopics || 0;
+ // A run its device lost was never judged, so it does not spend the budget;
+ // the coordinator's offline schedule bounds those retries instead.
+ const runs = await new TaskTopicModel(this.db, this.userId, this.workspaceId).findByTaskId(
+ task.id,
+ );
+ const attempts = countChargedTaskAttempts(task, countDeviceOfflineRuns(runs));
const attemptBudget = resolveTaskAttemptBudget(goal);
if (attempts >= attemptBudget) return { outcome: 'exhausted-rounds' };
diff --git a/apps/server/src/services/taskLifecycle/index.ts b/apps/server/src/services/taskLifecycle/index.ts
index 779350ca941..3e04fef0eca 100644
--- a/apps/server/src/services/taskLifecycle/index.ts
+++ b/apps/server/src/services/taskLifecycle/index.ts
@@ -43,6 +43,7 @@ import { VerifyRunModel } from '@/database/models/verifyRun';
import type { LobeChatDatabase } from '@/database/type';
import { translation } from '@/libs/i18n/serverTranslation';
import { initModelRuntimeFromDB } from '@/server/modules/ModelRuntime';
+import { resolveFailedRunStatus } from '@/server/services/goal/recoveryPolicy';
import { SystemAgentService } from '@/server/services/systemAgent';
import { TaskResultBridgeService } from '@/server/services/taskResultBridge';
import { createTaskSchedulerModule } from '@/server/services/taskScheduler';
@@ -337,7 +338,12 @@ export class TaskLifecycleService {
);
}
} else if (reason === 'error') {
- if (topicId) await this.taskTopicModel.updateStatus(taskId, topicId, 'failed');
+ if (topicId)
+ await this.taskTopicModel.updateStatus(
+ taskId,
+ topicId,
+ resolveFailedRunStatus(errorMessage),
+ );
const errorText = errorMessage || 'Unknown error';
diff --git a/apps/server/src/services/taskRunner/buildTaskPrompt.ts b/apps/server/src/services/taskRunner/buildTaskPrompt.ts
index 8bcf205395f..d2dabd171f6 100644
--- a/apps/server/src/services/taskRunner/buildTaskPrompt.ts
+++ b/apps/server/src/services/taskRunner/buildTaskPrompt.ts
@@ -13,7 +13,11 @@ import { VerifyRunModel } from '@/database/models/verifyRun';
import type { LobeChatDatabase } from '@/database/type';
import { extractFileIdsFromEditorData } from '@/server/services/file/extractFileIdsFromEditorData';
import { resolveAttachmentMetadata } from '@/server/services/file/resolveAttachments';
-import { resolveTaskAttemptBudget } from '@/server/services/goal/recoveryPolicy';
+import {
+ countChargedTaskAttempts,
+ countDeviceOfflineRuns,
+ resolveTaskAttemptBudget,
+} from '@/server/services/goal/recoveryPolicy';
import { resolveTaskAcceptance } from '@/server/services/verify/taskAcceptance';
/** Cap on unresolved checks carried into the next round's prompt. */
@@ -35,9 +39,14 @@ const resolveGoalLoopContext = async (
if (!goal || !task.totalTopics) return undefined;
const budget = resolveTaskAttemptBudget(goal);
+ // Runs its device lost are not rounds the budget counts, so the agent is not
+ // told it is on a later round than the coordinator thinks.
+ const offlineRuns = countDeviceOfflineRuns(
+ await deps.taskTopicModel.findByTaskId(task.id).catch(() => []),
+ );
const context: TaskRunPromptGoalLoop = {
maxRounds: Number.isFinite(budget) ? budget : null,
- round: (task.totalTopics || 0) + 1,
+ round: countChargedTaskAttempts(task, offlineRuns) + 1,
};
try {
diff --git a/apps/server/src/services/taskRunner/index.ts b/apps/server/src/services/taskRunner/index.ts
index ba202b527ca..564f5de5456 100644
--- a/apps/server/src/services/taskRunner/index.ts
+++ b/apps/server/src/services/taskRunner/index.ts
@@ -13,6 +13,7 @@ import { TaskModel } from '@/database/models/task';
import { TaskTopicModel } from '@/database/models/taskTopic';
import type { LobeChatDatabase } from '@/database/type';
import { AiAgentService } from '@/server/services/aiAgent';
+import { resolveFailedRunStatus } from '@/server/services/goal/recoveryPolicy';
import { TaskLifecycleService } from '@/server/services/taskLifecycle';
import { buildTaskPrompt } from './buildTaskPrompt';
@@ -290,7 +291,11 @@ export class TaskRunnerService {
});
}
if (result.topicId) {
- await this.taskTopicModel.updateStatus(task.id, result.topicId, 'failed');
+ await this.taskTopicModel.updateStatus(
+ task.id,
+ result.topicId,
+ resolveFailedRunStatus(result.error),
+ );
}
throw new Error(result.error || result.message || 'Agent run failed to start');
}
diff --git a/packages/const/src/goal.ts b/packages/const/src/goal.ts
index 0ae2f9d5c11..ec84e57edf2 100644
--- a/packages/const/src/goal.ts
+++ b/packages/const/src/goal.ts
@@ -81,6 +81,13 @@ export const LEASE_EXPIRED_ERROR = 'Goal Task operation lease expired.';
* coordinator recovers it the same way instead of asking a person.
*/
export const ABANDONED_OPERATION_ERROR_PREFIX = 'Operation abandoned:';
+/**
+ * `task_topics.status` of a run that ended because its device was unavailable:
+ * the dispatch could not reach it, or the run was lost while the device was
+ * offline. Nothing judged the work, so the Goal coordinator does not charge the
+ * run to the Task's attempt budget and retries it on its own offline schedule.
+ */
+export const DEVICE_OFFLINE_RUN_STATUS = 'device_offline';
/** The verifier ran and judged the delivery short of the criteria. */
export const VERIFICATION_FAILED_ERROR = 'Delivery did not pass verification.';
/** The verifier itself could not run, so the delivery was never evaluated. */
diff --git a/packages/database/src/models/taskTopic.ts b/packages/database/src/models/taskTopic.ts
index f5e61e70ed1..02272f2db61 100644
--- a/packages/database/src/models/taskTopic.ts
+++ b/packages/database/src/models/taskTopic.ts
@@ -1,3 +1,4 @@
+import { DEVICE_OFFLINE_RUN_STATUS } from '@lobechat/const/goal';
import type { BriefDecision, TaskTopicHandoff } from '@lobechat/types';
import { and, count, desc, eq, gte, inArray, sql } from 'drizzle-orm';
@@ -7,7 +8,13 @@ import { topics } from '../schemas/topic';
import type { LobeChatDatabase } from '../type';
import { buildWorkspaceWhere } from '../utils/workspace';
-const TERMINAL_TOPIC_STATUSES = new Set(['canceled', 'completed', 'failed', 'timeout']);
+const TERMINAL_TOPIC_STATUSES = new Set([
+ 'canceled',
+ 'completed',
+ DEVICE_OFFLINE_RUN_STATUS,
+ 'failed',
+ 'timeout',
+]);
export class TaskTopicModel {
private readonly userId: string;
diff --git a/src/features/AgentTasks/AgentTaskDetail/TopicStatusIcon.tsx b/src/features/AgentTasks/AgentTaskDetail/TopicStatusIcon.tsx
index 76dd7f75fa9..e2c2d4bdd2c 100644
--- a/src/features/AgentTasks/AgentTaskDetail/TopicStatusIcon.tsx
+++ b/src/features/AgentTasks/AgentTaskDetail/TopicStatusIcon.tsx
@@ -5,11 +5,14 @@ import { memo } from 'react';
import { EXECUTION_STATUS_VISUALS, type ExecutionStatusVisual } from '@/components/ExecutionStatus';
-type TopicRunStatus = 'canceled' | 'completed' | 'failed' | 'pending' | 'running' | 'timeout';
+type TopicRunStatus =
+ 'canceled' | 'completed' | 'device_offline' | 'failed' | 'pending' | 'running' | 'timeout';
const STATIC_META: Record<Exclude<TopicRunStatus, 'running'>, ExecutionStatusVisual> = {
canceled: EXECUTION_STATUS_VISUALS.canceled,
completed: EXECUTION_STATUS_VISUALS.completed,
+ // The run's device was unavailable; it is retried, not failed.
+ device_offline: { color: cssVar.colorWarning, icon: CircleAlert },
failed: EXECUTION_STATUS_VISUALS.failed,
// Not-yet-started run: same glyph as a backlog task.
pending: EXECUTION_STATUS_VISUALS.backlog,