π€― 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): recover tasks whose device run was abandoned or lost its device (#19943)
Arvin Xu8f7d0b0702ab
diff --git a/apps/server/src/services/agentRuntime/AbandonOperationService.ts b/apps/server/src/services/agentRuntime/AbandonOperationService.tsindex c44a90ef950..f460cd3c1b1 100644--- a/apps/server/src/services/agentRuntime/AbandonOperationService.ts+++ b/apps/server/src/services/agentRuntime/AbandonOperationService.ts@@ -1,5 +1,6 @@import type { ISnapshotStore } from '@lobechat/agent-tracing';import { LOADING_FLAT } from '@lobechat/const';+import { ABANDONED_OPERATION_ERROR_PREFIX } from '@lobechat/const/goal';import type { ChatMessageError } from '@lobechat/types';import { AgentRuntimeErrorType } from '@lobechat/types';import debug from 'debug';@@ -16,6 +17,7 @@ import type { LobeChatDatabase } from '@/database/type';import { AgentRuntimeCoordinator } from '@/server/modules/AgentRuntime/AgentRuntimeCoordinator';import { CompletionLifecycle } from './CompletionLifecycle';+import type { SerializedHook } from './hooks/types';import { OperationTraceRecorder } from './OperationTraceRecorder';import { createDefaultSnapshotStore } from './snapshotStore';@@ -121,7 +123,7 @@ export class AbandonOperationService {state.status === 'running' ||state.status === 'waiting_for_human' ||state.status === 'waiting_for_async_tool';- const message = `Operation abandoned: ${reason}`;+ const message = `${ABANDONED_OPERATION_ERROR_PREFIX} ${reason}`;const error: ChatMessageError = {body: { message },message,@@ -285,7 +287,7 @@ export class AbandonOperationService {result.abandoned = true;- const message = `Operation abandoned: ${reason}`;+ const message = `${ABANDONED_OPERATION_ERROR_PREFIX} ${reason}`;const error: ChatMessageError = {body: { message },message,@@ -312,27 +314,63 @@ export class AbandonOperationService {log('[%s] no-state abandon: recordCompletion failed (non-fatal): %O', operationId, e);}- const assistantMessageId = await this.resolveAssistantMessageIdForOperation(op, operationId);- if (!assistantMessageId) return;+ const settled = await this.settleOperationTopic(op, operationId);+ if (settled.assistantMessageId) {+ try {+ // No-state cleanup path: this is a system-side finalize keyed on ids+ // read from the persisted `agentOperations` row (no user input), and the+ // op may belong to a shared-agent visitor conversation whose rows the+ // default MessageModel gate would hide. Opt in unconditionally so the+ // placeholder can still be marked errored when the coordinator state has+ // already evaporated.+ const messageModel = new MessageModel(+ this.db,+ op.userId,+ op.workspaceId ?? undefined,+ undefined,+ { includeShareVisitor: true },+ );+ await messageModel.update(settled.assistantMessageId, { content: '', error });+ result.assistantMessageUpdated = true;+ } catch (e) {+ log(+ '[%s] no-state abandon: assistant message update failed (non-fatal): %O',+ operationId,+ e,+ );+ }+ }++ // Heterogeneous and device runs never have coordinator state, so this is+ // the only terminal they get when the process dies silently. Their hooks+ // (task lifecycle, bot callbacks) must still hear about it β otherwise the+ // Task keeps a `running` topic forever and a Goal waits on it indefinitely.+ // A newer operation owning the topic means this callback cannot prove which+ // run the hooks belong to, the same rule `heteroFinish` applies.+ if (settled.ownershipUnproven) return;+ const serializedHooks = settled.hooks ?? readDurableHooks(op.metadata);+ if (!serializedHooks?.length) return;try {- // No-state cleanup path: this is a system-side finalize keyed on ids- // read from the persisted `agentOperations` row (no user input), and the- // op may belong to a shared-agent visitor conversation whose rows the- // default MessageModel gate would hide. Opt in unconditionally so the- // placeholder can still be marked errored when the coordinator state has- // already evaporated.- const messageModel = new MessageModel(- this.db,- op.userId,- op.workspaceId ?? undefined,- undefined,- { includeShareVisitor: true },+ await new CompletionLifecycle(this.db, op.userId, op.workspaceId ?? undefined, {+ includeShareVisitor: true,+ }).completeOperation(+ {+ agentId: op.agentId ?? undefined,+ assistantMessageId: settled.assistantMessageId,+ error,+ operationId,+ orchestrationRole: settled.orchestrationRole,+ serializedHooks,+ startedAt: op.startedAt ?? undefined,+ topicId: op.topicId ?? undefined,+ userId: op.userId,+ },+ 'error',+ { skipErrorMessageWrite: true },);- await messageModel.update(assistantMessageId, { content: '', error });- result.assistantMessageUpdated = true;} catch (e) {- log('[%s] no-state abandon: assistant message update failed (non-fatal): %O', operationId, e);+ log('[%s] no-state abandon: lifecycle dispatch failed (non-fatal): %O', operationId, e);}}@@ -347,10 +385,10 @@ export class AbandonOperationService {}}- private async resolveAssistantMessageIdForOperation(+ private async settleOperationTopic(op: typeof agentOperations.$inferSelect,operationId: string,- ): Promise<string | undefined> {+ ): Promise<SettledOperationTopic> {let topicModel: TopicModel | undefined;if (op.topicId) {@@ -363,13 +401,31 @@ export class AbandonOperationService {includeShareVisitor: true,});const settled = await topicModel.settleRunningOperation(op.topicId, operationId);- if (settled.status !== 'settled') return undefined;- if (settled.assistantMessageId) return settled.assistantMessageId;+ if (settled.status === 'conflict') return { ownershipUnproven: true };+ if (settled.status !== 'settled') return {};+ const topicHooks = {+ hooks: settled.hooks as SerializedHook[] | undefined,+ orchestrationRole: settled.orchestrationRole,+ };+ if (settled.assistantMessageId) {+ return { ...topicHooks, assistantMessageId: settled.assistantMessageId };+ }+ return { ...topicHooks, ...(await this.findPlaceholderMessage(op, operationId)) };} catch (e) {log('[%s] no-state abandon: topic lookup failed (non-fatal): %O', operationId, e);+ // A failed settle cannot rule out a newer operation on the topic, and+ // firing this run's task hook would then pause the replacement's Task.+ return { ...(await this.findPlaceholderMessage(op, operationId)), ownershipUnproven: true };}}+ return this.findPlaceholderMessage(op, operationId);+ }++ private async findPlaceholderMessage(+ op: typeof agentOperations.$inferSelect,+ operationId: string,+ ): Promise<{ assistantMessageId?: string }> {try {const startedAt = op.startedAt ? new Date(op.startedAt) : undefined;const lowerBound = startedAt ? new Date(startedAt.getTime() - 5000) : undefined;@@ -388,10 +444,27 @@ export class AbandonOperationService {),});- return assistant?.id;+ return { assistantMessageId: assistant?.id };} catch (e) {log('[%s] no-state abandon: assistant lookup failed (non-fatal): %O', operationId, e);- return undefined;+ return {};}}}++interface SettledOperationTopic {+ assistantMessageId?: string;+ hooks?: SerializedHook[];+ orchestrationRole?: 'member' | 'supervisor';+ /**+ * The topic could not prove this run still owns it β a newer operation holds+ * it, or the settle itself failed β so this run's hooks must not fire.+ */+ ownershipUnproven?: boolean;+}++/** Queue-mode dispatch serializes the run's hooks onto the operation row. */+const readDurableHooks = (metadata: unknown): SerializedHook[] | undefined => {+ const hooks = (metadata as { _hooks?: unknown } | null | undefined)?._hooks;+ return Array.isArray(hooks) ? (hooks as SerializedHook[]) : undefined;+};diff --git a/apps/server/src/services/agentRuntime/CompletionLifecycle.ts b/apps/server/src/services/agentRuntime/CompletionLifecycle.tsindex 400decdce9a..ccfe455d480 100644--- a/apps/server/src/services/agentRuntime/CompletionLifecycle.ts+++ b/apps/server/src/services/agentRuntime/CompletionLifecycle.ts@@ -141,6 +141,8 @@ export interface OperationCompletionInput {provider?: string | null;/** Serialized webhook hooks (queue mode); ignored in local in-memory mode. */serializedHooks?: SerializedHook[];+ /** When the run started, so the terminal row keeps its processing time. */+ startedAt?: Date | string;stepCount?: number | null;topicId?: string;/** Trace / usage aggregates (llm calls, tokens, tool calls). */@@ -684,6 +686,7 @@ export class CompletionLifecycle {private buildStateFromInput(input: OperationCompletionInput) {return {cost: input.cost ?? { total: null },+ createdAt: input.startedAt,error: input.error ?? undefined,messages: [{ content: input.goal ?? '', role: 'user' },diff --git a/apps/server/src/services/agentRuntime/__tests__/AbandonOperationService.test.ts b/apps/server/src/services/agentRuntime/__tests__/AbandonOperationService.test.tsindex 02edd90dc44..e6a13257cca 100644--- a/apps/server/src/services/agentRuntime/__tests__/AbandonOperationService.test.ts+++ b/apps/server/src/services/agentRuntime/__tests__/AbandonOperationService.test.ts@@ -48,9 +48,11 @@ vi.mock('@/database/models/agentOperation', () => ({}));const dispatchHooksMock = vi.fn().mockResolvedValue(undefined);+const completeOperationMock = vi.fn().mockResolvedValue(undefined);vi.mock('../CompletionLifecycle', () => ({CompletionLifecycle: vi.fn().mockImplementation(function () {return {+ completeOperation: completeOperationMock,dispatchHooks: dispatchHooksMock,};}),@@ -106,6 +108,7 @@ describe('AbandonOperationService', () => {beforeEach(() => {messageUpdateMock.mockClear();dispatchHooksMock.mockClear();+ completeOperationMock.mockClear();findOperationMock.mockReset().mockResolvedValue(null);recordCompletionMock.mockClear();findThreadMock.mockReset().mockResolvedValue(null);@@ -185,6 +188,94 @@ describe('AbandonOperationService', () => {});});+ describe('no-state lifecycle hooks', () => {+ const taskHook = {+ id: 'task-on-complete',+ type: 'onComplete',+ webhook: { url: '/api/workflows/task/on-topic-complete' },+ };+ const runningRow = (metadata?: Record<string, unknown>) => ({+ agentId: 'agt_x',+ id: 'op_x',+ metadata,+ startedAt: new Date('2026-09-24T17:30:02.000Z'),+ status: 'running',+ topicId: 'tpc_x',+ userId: 'user_x',+ workspaceId: 'ws_x',+ });+ const abandon = (operationRow: any) =>+ new AbandonOperationService(buildDb({ operationRow }), {+ coordinator: buildCoordinator({ loadAgentState: vi.fn().mockResolvedValue(null) }) as any,+ snapshotStore: buildStore() as any,+ }).finalizeAbandoned('op_x', 'inactivity_watchdog');++ it('fires the run hooks so a task topic does not stay running forever', async () => {+ topicSettleRunningOperationMock.mockResolvedValue({+ assistantMessageId: 'msg_assist_1',+ hooks: [taskHook],+ orchestrationRole: undefined,+ status: 'settled',+ });++ await abandon(runningRow());++ expect(completeOperationMock).toHaveBeenCalledTimes(1);+ expect(completeOperationMock).toHaveBeenCalledWith(+ expect.objectContaining({+ agentId: 'agt_x',+ assistantMessageId: 'msg_assist_1',+ error: expect.objectContaining({+ message: expect.stringContaining('inactivity_watchdog'),+ }),+ operationId: 'op_x',+ serializedHooks: [taskHook],+ startedAt: new Date('2026-09-24T17:30:02.000Z'),+ topicId: 'tpc_x',+ userId: 'user_x',+ }),+ 'error',+ { skipErrorMessageWrite: true },+ );+ });++ it('falls back to the hooks serialized on the operation row', async () => {+ await abandon(runningRow({ _hooks: [taskHook] }));++ expect(completeOperationMock).toHaveBeenCalledWith(+ expect.objectContaining({ serializedHooks: [taskHook] }),+ 'error',+ { skipErrorMessageWrite: true },+ );+ });++ it('does not fire hooks when a newer operation owns the topic', async () => {+ topicSettleRunningOperationMock.mockResolvedValue({+ activeOperationId: 'op_newer',+ status: 'conflict',+ });++ await abandon(runningRow({ _hooks: [taskHook] }));++ expect(completeOperationMock).not.toHaveBeenCalled();+ });++ it('does not fire hooks when settling the topic fails', async () => {+ // A failed settle cannot rule out a newer operation on the topic.+ topicSettleRunningOperationMock.mockRejectedValue(new Error('db unavailable'));++ await abandon(runningRow({ _hooks: [taskHook] }));++ expect(completeOperationMock).not.toHaveBeenCalled();+ });++ it('does not run the lifecycle for a run without hooks', async () => {+ await abandon(runningRow());++ expect(completeOperationMock).not.toHaveBeenCalled();+ });+ });+it('keeps no-state terminal operations classified as completed phantom timeouts', async () => {const coord = buildCoordinator({ loadAgentState: vi.fn().mockResolvedValue(null) });const store = buildStore();diff --git a/apps/server/src/services/aiAgent/__tests__/execAgent.heteroFiles.test.ts b/apps/server/src/services/aiAgent/__tests__/execAgent.heteroFiles.test.tsindex b729193062d..f2e154f2bf7 100644--- a/apps/server/src/services/aiAgent/__tests__/execAgent.heteroFiles.test.ts+++ b/apps/server/src/services/aiAgent/__tests__/execAgent.heteroFiles.test.ts@@ -598,6 +598,35 @@ describe('AiAgentService.execAgent - hetero early-exit file attachments', () =>);});+ it('records the device a failed dispatch was routed to on the operation error', async () => {+ heteroAgentConfig.model = 'amp';+ heteroAgentConfig.provider = 'amp';+ heteroAgentConfig.agencyConfig = {+ boundDeviceId: 'device-1',+ executionTarget: 'device',+ heterogeneousProvider: { type: 'amp' },+ } as any;+ mockDispatchAgentRun.mockResolvedValueOnce({ error: 'DEVICE_OFFLINE', success: false });+ const completeOperationSpy = vi+ .spyOn(CompletionLifecycle.prototype, 'completeOperation')+ .mockResolvedValue(undefined);++ await service.execAgent({ agentId: 'agent-1', prompt: 'Use Amp on my device' });++ // A Goal waiting for this device to come back reads the route from here+ // instead of re-deriving which device and pool the dispatch picked.+ expect(completeOperationSpy).toHaveBeenCalledWith(+ expect.objectContaining({+ error: expect.objectContaining({+ deviceRoute: { deviceId: 'device-1', userId },+ }),+ }),+ 'error',+ { skipErrorMessageWrite: true },+ );+ completeOperationSpy.mockRestore();+ });+it('resumes Amp natively without loading or injecting fallback history', async () => {mockGetHeterogeneousResumeSessionId.mockResolvedValue('amp-thread-existing');heteroAgentConfig.model = 'amp';diff --git a/apps/server/src/services/aiAgent/helpers/heteroErrors.ts b/apps/server/src/services/aiAgent/helpers/heteroErrors.tsindex 4c2d34bd5e9..bec885b09fc 100644--- a/apps/server/src/services/aiAgent/helpers/heteroErrors.ts+++ b/apps/server/src/services/aiAgent/helpers/heteroErrors.ts@@ -60,6 +60,31 @@ const toDispatchErrorCode = (raw?: string): string | undefined => {return text?.match(/^([A-Z][\dA-Z_]*)/)?.[1];};+/**+ * The device a failed dispatch was aimed at, recorded on the operation's error so+ * a later reader can ask whether *that* device is back β the routing that picked+ * it (topic override, member binding, personal vs workspace pool) is not+ * something a consumer should re-derive.+ */+export interface DeviceDispatchRoute {+ deviceId: string;+ /** The principal whose device pool the gateway was asked to route through. */+ userId: string;+ /** Set when the device belongs to a workspace pool rather than the personal one. */+ workspaceId?: string;+}++export const readDeviceDispatchRoute = (error: unknown): DeviceDispatchRoute | undefined => {+ const route = (error as { deviceRoute?: Partial<DeviceDispatchRoute> } | null | undefined)+ ?.deviceRoute;+ if (typeof route?.deviceId !== 'string' || typeof route.userId !== 'string') return undefined;+ return {+ deviceId: route.deviceId,+ userId: route.userId,+ ...(typeof route.workspaceId === 'string' ? { workspaceId: route.workspaceId } : {}),+ };+};+export const humanizeHeteroDispatchError = (raw?: string): string => {const code = toDispatchErrorCode(raw);diff --git a/apps/server/src/services/aiAgent/pipeline/heteroDispatch.ts b/apps/server/src/services/aiAgent/pipeline/heteroDispatch.tsindex 8406084e138..c461226b57e 100644--- a/apps/server/src/services/aiAgent/pipeline/heteroDispatch.ts+++ b/apps/server/src/services/aiAgent/pipeline/heteroDispatch.ts@@ -47,6 +47,7 @@ import { buildRemoteDeviceHeteroContext } from '@/server/services/heterogeneousAimport type { MarketService } from '@/server/services/market';import {+ type DeviceDispatchRoute,getHeterogeneousAgentTitle,humanizeHeteroDispatchError,resolveHeteroDispatchErrorType,@@ -104,6 +105,8 @@ const finalizeHeteroDispatchError = async (agentId?: string;assistantMessageId: string;detail: string;+ /** The device this dispatch was routed to, when it was a device dispatch. */+ deviceRoute?: DeviceDispatchRoute;errorData?: DeviceUnavailableErrorData;/*** Client error type. Defaults to the generic `ServerAgentRuntimeError`; pass a@@ -120,6 +123,7 @@ const finalizeHeteroDispatchError = async (agentId,assistantMessageId,detail,+ deviceRoute,errorData,errorType = ChatErrorType.ServerAgentRuntimeError,message,@@ -150,7 +154,7 @@ const finalizeHeteroDispatchError = async ({agentId,assistantMessageId,- error: { message, type: errorType },+ error: { message, type: errorType, ...(deviceRoute && { deviceRoute }) },operationId,serializedHooks: hookDispatcher.getSerializedHooks(operationId),topicId,@@ -855,6 +859,13 @@ export const dispatchHeteroAgent = async (agentId: resolvedAgentId,assistantMessageId,detail: result.error ?? 'Device dispatch failed',+ deviceRoute: remoteDeviceId+ ? {+ deviceId: remoteDeviceId,+ userId: remoteDeviceUserId,+ ...(remoteDeviceWorkspaceId ? { workspaceId: remoteDeviceWorkspaceId } : {}),+ }+ : undefined,errorData: result.errorData,errorType: resolveHeteroDispatchErrorType(result.error),message: humanizeHeteroDispatchError(result.error),@@ -1035,6 +1046,11 @@ export const dispatchHeteroAgent = async (agentId: resolvedAgentId,assistantMessageId,detail: result.error ?? 'Device dispatch failed',+ deviceRoute: {+ deviceId: dispatchDeviceId,+ userId: deps.userId,+ ...(dispatchWorkspaceId ? { workspaceId: dispatchWorkspaceId } : {}),+ },errorData: result.errorData,errorType: resolveHeteroDispatchErrorType(result.error),message: humanizeHeteroDispatchError(result.error),diff --git a/apps/server/src/services/goal/decideNextMove.test.ts b/apps/server/src/services/goal/decideNextMove.test.tsindex 9f0478d643a..68414b1f193 100644--- a/apps/server/src/services/goal/decideNextMove.test.ts+++ b/apps/server/src/services/goal/decideNextMove.test.ts@@ -176,6 +176,17 @@ describe('decideNextMove', () => {}).branch,).toBe('recover_lease');+ // The gateway watchdog abandoning a silent run loses it the same way an+ // expired lease does; nothing judged the work, so it must not wait on a person.+ expect(+ decide(snapshot, {+ frontierTask: task({+ error: 'Operation abandoned: inactivity_watchdog',+ status: 'paused',+ }),+ }).branch,+ ).toBe('recover_lease');+expect(decide(snapshot, {frontierTask: task({ error: VERIFICATION_FAILED_ERROR, status: 'paused' }),diff --git a/apps/server/src/services/goal/decideNextMove.ts b/apps/server/src/services/goal/decideNextMove.tsindex e293f90a21f..aae1d60f7d9 100644--- a/apps/server/src/services/goal/decideNextMove.ts+++ b/apps/server/src/services/goal/decideNextMove.ts@@ -6,6 +6,7 @@ import type {GoalTickOutcome,} from '@lobechat/agent-tracing';import {+ ABANDONED_OPERATION_ERROR_PREFIX,GOAL_ACCEPTANCE_TASK_TITLE,LEASE_EXPIRED_ERROR,VERIFICATION_ERRORED_ERROR,@@ -26,6 +27,14 @@ export { LEASE_EXPIRED_ERROR, VERIFICATION_ERRORED_ERROR, VERIFICATION_FAILED_ERexport const TERMINAL_NODE_STATUSES = new Set(['resolved', 'rejected', 'retired']);+/**+ * Whether a paused Task lost its run rather than failed it: the coordinator+ * reclaimed an expired lease, or the gateway watchdog abandoned a silent run.+ * Either way nothing judged the work, so another attempt is the recovery.+ */+export const isLostRunError = (error?: string | null): boolean =>+ error === LEASE_EXPIRED_ERROR || !!error?.startsWith(ABANDONED_OPERATION_ERROR_PREFIX);+export interface FrontierSelection {/** Every eligible task node, best first β the trace-shaped view. */candidates: FrontierCandidate[];@@ -94,7 +103,7 @@ export const needsBudget = (task?: TaskItem | null): boolean => {// A failure the coordinator can retry spends money too.if (task.status === 'paused') {return (- task.error === LEASE_EXPIRED_ERROR ||+ isLostRunError(task.error) ||task.error === VERIFICATION_FAILED_ERROR ||task.error === VERIFICATION_ERRORED_ERROR);@@ -516,7 +525,7 @@ const decideForTask = (if (budget?.deadlinePassed &&task.status === 'paused' &&- (task.error === LEASE_EXPIRED_ERROR ||+ (isLostRunError(task.error) ||task.error === VERIFICATION_FAILED_ERROR ||task.error === VERIFICATION_ERRORED_ERROR)) {@@ -527,7 +536,7 @@ const decideForTask = (outcome: 'no_progress',};}- if (task.status === 'paused' && task.error === LEASE_EXPIRED_ERROR) {+ if (task.status === 'paused' && isLostRunError(task.error)) {if (!capacity) return 'needs-capacity';return {...base,diff --git a/apps/server/src/services/goal/index.test.ts b/apps/server/src/services/goal/index.test.tsindex 2e99ccd1549..ae5a14a9117 100644--- a/apps/server/src/services/goal/index.test.ts+++ b/apps/server/src/services/goal/index.test.ts@@ -32,6 +32,7 @@ import {import type { LobeChatDatabase } from '@/database/type';import { AgentRuntimeCoordinator } from '@/server/modules/AgentRuntime/AgentRuntimeCoordinator';+import { deviceGateway } from '../deviceGateway';import { TaskService } from '../task';import { TaskRunnerService } from '../taskRunner';import { VerifyPlanGeneratorService } from '../verify/planGenerator';@@ -2379,6 +2380,81 @@ describe('GoalService', () => {);});+ describe('a running topic whose run already ended', () => {+ const setup = async (title: string, operationId: string, completedAt: Date) => {+ const runSpy = vi+ .spyOn(TaskRunnerService.prototype, 'runTask')+ .mockResolvedValue({ operationId: 'op-next', success: true } as never);+ vi.spyOn(TaskTopicModel.prototype, 'findRunningByTaskIds').mockResolvedValue([+ {+ createdAt: new Date('2026-01-01T00:00:00.000Z'),+ operationId,+ topicId: `topic-${operationId}`,+ } as never,+ ]);+ const timeoutSpy = vi+ .spyOn(TaskTopicModel.prototype, 'updateStatus')+ .mockResolvedValue(undefined);++ const service = new GoalService(serverDB, userId);+ const taskModel = new TaskModel(serverDB, userId);+ const graph = await service.create({+ config: { recovery: { maxAttemptsPerTask: 3, operationLeaseTimeoutMs: 60_000 } },+ title,+ tasks: ['Run a device experiment'],+ });+ const created = await service.tick(graph.goal.id);+ await taskModel.update(created.taskId!, { totalTopics: 1 });+ await taskModel.updateStatus(created.taskId!, 'running');++ // The gateway watchdog already settled the run as an error, but the task+ // lifecycle never heard about it, so the topic still reads `running`.+ const operationModel = new AgentOperationModel(serverDB, userId);+ await operationModel.recordStart({ operationId, taskId: created.taskId });+ await operationModel.recordCompletion(operationId, {+ completedAt,+ completionReason: 'error',+ status: 'error',+ });++ return { created, graph, runSpy, service, timeoutSpy };+ };++ it('reclaims it once the run has been over for longer than the lease', async () => {+ const { created, graph, runSpy, service, timeoutSpy } = await setup(+ 'Recover a watchdog-abandoned run',+ 'op-abandoned',+ new Date('2026-01-01T00:10:00.000Z'),+ );++ const recovered = await service.tick(graph.goal.id);++ expect(timeoutSpy).toHaveBeenCalledWith(created.taskId, 'topic-op-abandoned', 'timeout');+ expect(runSpy).toHaveBeenCalledWith(+ expect.objectContaining({ taskId: created.taskId, trigger: 'goal' }),+ );+ expect(recovered).toMatchObject({+ message: expect.stringContaining('Recovered abandoned task'),+ outcome: 'waiting_external',+ taskId: created.taskId,+ });+ });++ it('leaves a run that just ended to its own completion hook', async () => {+ const { created, graph, runSpy, service, timeoutSpy } = await setup(+ 'Wait for the completion hook',+ 'op-just-ended',+ new Date(),+ );++ const waiting = await service.tick(graph.goal.id);++ expect(timeoutSpy).not.toHaveBeenCalled();+ expect(runSpy).not.toHaveBeenCalled();+ expect(waiting).toMatchObject({ outcome: 'waiting_external', taskId: created.taskId });+ });+ });+it('does not reclaim a running Task operation without a persisted topic id', async () => {vi.spyOn(TaskTopicModel.prototype, 'findRunningByTaskIds').mockResolvedValue([{ operationId: 'op-without-topic', topicId: null } as never,@@ -2554,6 +2630,135 @@ describe('GoalService', () => {expect((await service.graph(graph.goal.id)).decisions).toHaveLength(0);});+ describe('a Task that could not reach its device', () => {+ const DEVICE_NOT_FOUND_HEADLINE =+ 'The device this agent is bound to is no longer registered with the connection service. Reconnect the device, or bind this agent to another online device.';+ // A workspace goal whose agent runs on its owner's personal device: the+ // route the dispatch recorded names the personal pool, not the goal's.+ const route = { deviceId: 'device-laptop', userId: 'device-owner' };++ const setup = async (title: string) => {+ vi.spyOn(deviceGateway, 'isConfigured', 'get').mockReturnValue(true);+ const service = new GoalService(serverDB, userId);+ const taskModel = new TaskModel(serverDB, userId);+ const graph = await service.create({+ config: { recovery: { maxAttemptsPerTask: 3 } },+ title,+ tasks: ['Reproduce on the bound device'],+ });+ const created = await service.tick(graph.goal.id);+ await taskModel.update(created.taskId!, { totalTopics: 1 });++ const operationModel = new AgentOperationModel(serverDB, userId);+ await operationModel.recordStart({ operationId: 'op-dispatch', taskId: created.taskId });+ await operationModel.recordCompletion('op-dispatch', {+ completedAt: new Date(),+ completionReason: 'error',+ error: { deviceRoute: route, message: DEVICE_NOT_FOUND_HEADLINE },+ status: 'error',+ });+ vi.spyOn(TaskTopicModel.prototype, 'findWithHandoff').mockResolvedValue([+ { operationId: 'op-dispatch' } as never,+ ]);++ await taskModel.updateStatus(created.taskId!, 'paused', {+ error: DEVICE_NOT_FOUND_HEADLINE,+ });+ return { created, graph, service, taskModel };+ };++ it('waits for the device instead of asking a person', async () => {+ const listSpy = vi.spyOn(deviceGateway, 'queryDeviceList').mockResolvedValue([]);+ const runSpy = vi.spyOn(TaskRunnerService.prototype, 'runTask');+ const { created, graph, service } = await setup('Device went to sleep');++ const waiting = await service.tick(graph.goal.id);++ expect(listSpy).toHaveBeenCalledWith('device-owner', undefined);+ expect(waiting).toMatchObject({+ message: expect.stringContaining('waiting for its device to reconnect'),+ outcome: 'waiting_external',+ taskId: created.taskId,+ });+ expect(runSpy).not.toHaveBeenCalled();+ expect((await service.graph(graph.goal.id)).decisions).toHaveLength(0);+ });++ it('keeps waiting while only some other device is online', async () => {+ vi.spyOn(deviceGateway, 'queryDeviceList').mockResolvedValue([+ { deviceId: 'device-desktop' } as never,+ ]);+ const runSpy = vi.spyOn(TaskRunnerService.prototype, 'runTask');+ const { graph, service } = await setup('Another device is online');++ const waiting = await service.tick(graph.goal.id);++ expect(waiting).toMatchObject({ outcome: 'waiting_external' });+ expect(runSpy).not.toHaveBeenCalled();+ });++ it('retries on its own once its device is back online', async () => {+ vi.spyOn(deviceGateway, 'queryDeviceList').mockResolvedValue([+ { deviceId: 'device-laptop' } as never,+ ]);+ const runSpy = vi+ .spyOn(TaskRunnerService.prototype, 'runTask')+ .mockResolvedValue({ operationId: 'op-after-reconnect', success: true } as never);+ const { created, graph, service } = await setup('Device reconnected');++ const retried = await service.tick(graph.goal.id);++ 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('keeps waiting when the retry itself cannot reach the device', async () => {+ vi.spyOn(deviceGateway, 'queryDeviceList').mockResolvedValue([+ { deviceId: 'device-laptop' } as never,+ ]);+ vi.spyOn(TaskRunnerService.prototype, 'runTask').mockRejectedValue(+ new Error('DEVICE_OFFLINE (HTTP 503)'),+ );+ const { created, graph, service, taskModel } = await setup('Device flapping');++ const waiting = await service.tick(graph.goal.id);++ expect(waiting).toMatchObject({ outcome: 'waiting_external', taskId: created.taskId });+ expect(await taskModel.findById(created.taskId!)).toMatchObject({+ error: 'DEVICE_OFFLINE (HTTP 503)',+ status: 'paused',+ });+ 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 () => {+ vi.spyOn(deviceGateway, 'queryDeviceList').mockResolvedValue([]);+ const { created, graph, service } = await setup('Device gone for good');+ await serverDB+ .update(tasks)+ .set({ updatedAt: new Date(Date.now() - 13 * 60 * 60 * 1000) })+ .where(eq(tasks.id, created.taskId!));++ const gated = await service.tick(graph.goal.id);++ expect(gated).toMatchObject({ outcome: 'waiting_human', taskId: created.taskId });+ });++ it('does not wait on a deployment without a device gateway', async () => {+ const listSpy = vi.spyOn(deviceGateway, 'queryDeviceList');+ 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);++ expect(listSpy).not.toHaveBeenCalled();+ expect(gated).toMatchObject({ outcome: 'waiting_human', taskId: created.taskId });+ });+ });+it('only selects Tasks whose explicit dependencies are resolved', async () => {const service = new GoalService(serverDB, userId);const graph = await service.create({ title: 'Dependency-aware goal' });diff --git a/apps/server/src/services/goal/index.ts b/apps/server/src/services/goal/index.tsindex 62a581282ba..a04d49ea8f9 100644--- a/apps/server/src/services/goal/index.ts+++ b/apps/server/src/services/goal/index.ts@@ -38,6 +38,8 @@ import type { LobeChatDatabase } from '@/database/type';import { assertAgentUsableBy } from '@/database/utils/agent-access';import { AgentRuntimeCoordinator } from '@/server/modules/AgentRuntime/AgentRuntimeCoordinator';+import { readDeviceDispatchRoute } from '../aiAgent/helpers/heteroErrors';+import { deviceGateway } from '../deviceGateway';import { TaskService } from '../task';import { TaskRunnerService } from '../taskRunner';import { AcceptanceService } from '../verify/acceptanceService';@@ -58,6 +60,8 @@ import {import { experimentResults, exploreGraph } from './exploreGraph';import { answeredProblem, GoalManagerService, problemKey } from './manager';import {+ DEVICE_RECONNECT_WAIT_MS,+ isDeviceUnavailableFailure,resolveMaxConcurrentTasks,resolveOperationLeaseTimeout,resolveTaskMaxSteps,@@ -1618,6 +1622,8 @@ export class GoalService {}case 'failure_decision': {+ const waiting = await this.waitForDevice(graph, acting!.id, task, effects);+ if (waiting) return observe(waiting);const supervision = await new GoalSupervisorService(this.db,this.userId,@@ -1944,6 +1950,18 @@ export class GoalService {};}+ // The retry never reached a device. The Task keeps that reason, and the next+ // advance waits for the device to come back rather than asking a person.+ if (recovery.outcome === 'spawn-failed' && recovery.deviceUnavailable) {+ return {+ goalId: graph.goal.id,+ message: `Task ${task.identifier} is waiting for its device to reconnect`,+ nodeId,+ outcome: 'waiting_external',+ taskId: task.id,+ };+ }+// Nothing failed: somebody settled the Task while this advance was deciding.// Opening a gate would ask them to judge their own decision.if (recovery.outcome === 'settled') {@@ -2175,12 +2193,14 @@ export class GoalService {const latestUsage = await new AgentRuntimeCoordinator().getOperationMetadata(operationId);const reclaimed = await this.db.transaction(async (tx) => {- const settled = await new AgentOperationModel(- tx,- this.userId,- this.workspaceId,- ).settleStaleRunning(operationId, staleBefore, latestUsage?.totalCost);- if (!settled) return false;+ const operationModel = new AgentOperationModel(tx, this.userId, this.workspaceId);+ const settled = await operationModel.settleStaleRunning(+ operationId,+ staleBefore,+ latestUsage?.totalCost,+ );+ if (!settled && !(await isOrphanedRun(operationModel, operationId, staleBefore)))+ return false;await new TaskTopicModel(tx, this.userId, this.workspaceId).updateStatus(task.id,@@ -2234,6 +2254,18 @@ export class GoalService {};}+ // The retry never reached a device. The Task keeps that reason, and the next+ // advance waits for the device to come back rather than asking a person.+ if (recovery.outcome === 'spawn-failed' && recovery.deviceUnavailable) {+ return {+ goalId: graph.goal.id,+ message: `Task ${task.identifier} is waiting for its device to reconnect`,+ nodeId,+ outcome: 'waiting_external',+ taskId: task.id,+ };+ }+// Nothing failed: somebody settled the Task while this advance was deciding.// Opening a gate would ask them to judge their own decision.if (recovery.outcome === 'settled') {@@ -2254,6 +2286,56 @@ export class GoalService {return this.gateOrTakeOver(graph, nodeId, task.id, reason, effects);};+ /**+ * Hold a Task whose run could not reach its device until a device is back.+ *+ * 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.+ */+ private waitForDevice = async (+ graph: GoalGraphSnapshot,+ nodeId: string,+ task: TaskItem,+ 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 [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;++ const devices = await deviceGateway.queryDeviceList(route.userId, route.workspaceId);+ if (devices.some((device) => device.deviceId === route.deviceId))+ return this.resumeAbandonedTaskRecovery(graph, nodeId, task, effects);++ return {+ goalId: graph.goal.id,+ message: `Task ${task.identifier} is waiting for its device to reconnect`,+ nodeId,+ outcome: 'waiting_external',+ taskId: task.id,+ };+ };+private buildTaskInstruction = (graph: GoalGraphSnapshot,title: string,@@ -2731,3 +2813,35 @@ export class GoalService {};};}++/** Operation states that still own their run; the lease path reclaims them, not this. */+const IN_FLIGHT_OPERATION_STATUSES = new Set([+ 'idle',+ 'running',+ 'waiting_for_async_tool',+ 'waiting_for_human',+]);++/**+ * Whether a Task topic is still `running` although its run has already ended.+ *+ * The run's terminal normally moves the topic through the task lifecycle hook,+ * but that delivery can be lost β a watchdog-abandoned device run had none at+ * all, and a dropped webhook has no retry. The lease reclaim cannot see these:+ * it only settles an operation that is itself still `running`, so the Task+ * stays in flight forever and its goal with it. Once the run has been over for+ * longer than the lease, nothing is left to report it and the topic is lost.+ *+ * A missing operation row proves nothing β a run executed on the client never+ * writes one β so only a row that says the run ended counts.+ */+const isOrphanedRun = async (+ operationModel: AgentOperationModel,+ operationId: string,+ staleBefore: Date,+): Promise<boolean> => {+ const operation = await operationModel.findById(operationId);+ if (!operation || IN_FLIGHT_OPERATION_STATUSES.has(operation.status)) return false;+ const endedAt = operation.completedAt ?? operation.updatedAt;+ return new Date(endedAt) < staleBefore;+};diff --git a/apps/server/src/services/goal/recoveryPolicy.ts b/apps/server/src/services/goal/recoveryPolicy.tsindex 71eb3357ae1..a48a7bff8ce 100644--- a/apps/server/src/services/goal/recoveryPolicy.ts+++ b/apps/server/src/services/goal/recoveryPolicy.ts@@ -1,5 +1,7 @@import type { GoalItem } from '@lobechat/types';+import { HETERO_DISPATCH_ERROR_HEADLINES } from '@/server/services/aiAgent/helpers/heteroErrors';+/*** Attempts a Task gets before the coordinator opens a decision gate, when the* goal does not set its own.@@ -59,3 +61,32 @@ export const resolveOperationLeaseTimeout = (goal: GoalItem): number => {? Math.max(configured, MIN_OPERATION_LEASE_TIMEOUT_MS): DEFAULT_OPERATION_LEASE_TIMEOUT_MS;};++/**+ * 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.+ */+export const DEVICE_RECONNECT_WAIT_MS = 12 * 60 * 60 * 1000;++/**+ * Dispatch failures that only say the device is not reachable right now. A+ * reconnect is what fixes each of them β including a lost registration, which the+ * device renews itself when it connects again β so the goal waits for it instead+ * of opening a decision nobody can act on until the device is back.+ */+const DEVICE_UNAVAILABLE_CODES = [+ 'DEVICE_OFFLINE',+ 'DEVICE_CHANNEL_UNAVAILABLE',+ 'DEVICE_NOT_FOUND',+];++/**+ * The same failure reaches `task.error` as a raw gateway code on one path and as+ * its humanized headline on another, so match both off the one map.+ */+export const isDeviceUnavailableFailure = (error?: string | null): boolean =>+ !!error &&+ DEVICE_UNAVAILABLE_CODES.some(+ (code) => error.includes(code) || error.includes(HETERO_DISPATCH_ERROR_HEADLINES[code]),+ );diff --git a/apps/server/src/services/goal/taskRecoveryCoordinator.ts b/apps/server/src/services/goal/taskRecoveryCoordinator.tsindex 4affd3ea6d6..6e3857b64cb 100644--- a/apps/server/src/services/goal/taskRecoveryCoordinator.ts+++ b/apps/server/src/services/goal/taskRecoveryCoordinator.ts@@ -6,7 +6,11 @@ import { TaskModel } from '@/database/models/task';import type { LobeChatDatabase } from '@/database/type';import { TaskRunnerService } from '@/server/services/taskRunner';-import { resolveTaskAttemptBudget, resolveTaskMaxSteps } from './recoveryPolicy';+import {+ isDeviceUnavailableFailure,+ resolveTaskAttemptBudget,+ resolveTaskMaxSteps,+} from './recoveryPolicy';import { statusAuthoredByActor } from './supervisor/policy';import { claimGoalTask } from './taskClaim';@@ -30,6 +34,8 @@ export type TaskRecoveryOutcome =* and drop the operation id of the one it had.*/export interface TaskRecoveryResult {+ /** Present only on `spawn-failed` when the retry could not reach its device. */+ deviceUnavailable?: boolean;/** Present only on `started`. The drill-down link into `agent_operations`. */operationId?: string;outcome: TaskRecoveryOutcome;@@ -115,13 +121,19 @@ export class TaskRecoveryCoordinator {return { operationId: run.operationId, outcome: 'started' };} catch (error) {log('task %s recovery spawn failed (non-fatal): %O', task.identifier, error);+ // A retry that could not reach its device keeps that reason, so the next+ // advance waits for the device instead of retrying into the same failure.+ const message = error instanceof Error ? error.message : String(error);+ const deviceUnavailable = isDeviceUnavailableFailure(message);// We own the claim, so nothing else will put the task back.await taskModel- .updateStatusIfCurrent(task.id, 'running', 'paused', { error: current.error })+ .updateStatusIfCurrent(task.id, 'running', 'paused', {+ error: deviceUnavailable ? message : current.error,+ }).catch((releaseError) => {log('task %s failed to release the recovery claim: %O', task.identifier, releaseError);});- return { outcome: 'spawn-failed' };+ return { deviceUnavailable, outcome: 'spawn-failed' };}};}diff --git a/packages/const/src/goal.ts b/packages/const/src/goal.tsindex cbc442d4d8d..82271d77e04 100644--- a/packages/const/src/goal.ts+++ b/packages/const/src/goal.ts@@ -59,6 +59,13 @@ export const GOAL_ACCEPTANCE_TASK_TITLE = 'Complete full Goal acceptance';* stops a long-horizon goal until a person clicks retry.*/export const LEASE_EXPIRED_ERROR = 'Goal Task operation lease expired.';+/**+ * Prefix of the error the runtime writes when the gateway's inactivity watchdog+ * abandons a run whose worker went silent (a device that slept or restarted, a+ * CLI that died). The run is lost exactly the way an expired lease is, so the+ * coordinator recovers it the same way instead of asking a person.+ */+export const ABANDONED_OPERATION_ERROR_PREFIX = 'Operation abandoned:';/** 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. */