🤯 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): park a first dispatch that cannot reach its device instead of re-dispatching it (#21180)
Arvin Xua8e7075c8b18
diff --git a/apps/server/src/services/goal/GoalService/__tests__/batchBreak.test.ts b/apps/server/src/services/goal/GoalService/__tests__/batchBreak.test.tsindex 0b2b2598197..2ff7d4c4b2f 100644--- a/apps/server/src/services/goal/GoalService/__tests__/batchBreak.test.ts+++ b/apps/server/src/services/goal/GoalService/__tests__/batchBreak.test.ts@@ -364,6 +364,49 @@ describe('GoalService', () => {});});+ it('waits for the device of a batch unit instead of breaking the batch', async () => {+ // A sleeping laptop is not the recipe's fault. Routed to the batch gate first,+ // one device the probe could not reach paused the whole rollout and asked the+ // owner to revise or fork the recipe.+ vi.spyOn(GoalCriteriaGeneratorService.prototype, 'decompose').mockResolvedValue({+ problemStatement: '把 50 个同构的 store 迁移到 replica',+ rollout: {+ recipeOutline: '把 store 换成 replica 支撑的实现',+ repeatable: true,+ unitCount: 50,+ units: Array.from({ length: 50 }, (_, i) => `Unit ${i + 1}`),+ variants: [],+ },+ tasks: Array.from({ length: 5 }, (_, i) => ({+ dependsOn: [],+ instruction: `把 src/store/store${i + 1}.ts 换成 replica 实现`,+ title: `Unit ${i + 1}`,+ })),+ });+ const runSpy = vi+ .spyOn(TaskRunnerService.prototype, 'runTask')+ .mockRejectedValueOnce(new Error('DEVICE_NOT_FOUND'))+ .mockResolvedValue({} as never);+ const service = new GoalService(serverDB, userId);+ const graph = await service.create({ title: 'Migrate stores on a sleeping laptop' });+ let parked = await service.tick(graph.goal.id);+ for (let i = 0; i < 10 && runSpy.mock.calls.length === 0; i++)+ parked = await service.tick(graph.goal.id);+ expect(parked.message).toContain('waiting for its device to reconnect');++ // The other probes dispatch; the parked unit's turn comes round again.+ for (let i = 0; i < 8; i++) await service.tick(graph.goal.id);++ const current = await service.graph(graph.goal.id);+ expect(current.goal.config!.rolloutState!.phase).toBe('probe');+ expect(current.decisions.filter((item) => item.status === 'pending')).toHaveLength(0);+ expect(await new TaskModel(serverDB, userId).findById(parked.taskId!)).toMatchObject({+ error: 'DEVICE_NOT_FOUND',+ status: 'paused',+ });+ expect(runSpy.mock.calls.filter(([params]) => params.taskId === parked.taskId)).toHaveLength(1);+ });+it('stops the running Tasks of the members a restart retires', async () => {vi.spyOn(GoalCriteriaGeneratorService.prototype, 'decompose').mockResolvedValue({problemStatement: '把 50 个同构的 store 迁移到 replica',diff --git a/apps/server/src/services/goal/GoalService/__tests__/device.test.ts b/apps/server/src/services/goal/GoalService/__tests__/device.test.tsindex b2038249a9b..8bafdc8b9e7 100644--- a/apps/server/src/services/goal/GoalService/__tests__/device.test.ts+++ b/apps/server/src/services/goal/GoalService/__tests__/device.test.ts@@ -18,7 +18,7 @@ import type { LobeChatDatabase } from '@/database/type';import { deviceGateway } from '../../../deviceGateway';import { TaskRunnerService } from '../../../taskRunner';import { MAX_QUOTA_RETRIES } from '../../machineRecovery';-import { DEVICE_OFFLINE_GATE_REASON } from '../../recoveryPolicy';+import { DEVICE_OFFLINE_GATE_REASON, MAX_DEVICE_OFFLINE_RETRIES } from '../../recoveryPolicy';import * as scheduler from '../../scheduler';import { LocalGoalScheduler } from '../../scheduler/impls';import { registerGoalServiceTestCleanup } from '../../testUtils';@@ -29,6 +29,27 @@ const userId = 'goal-service-test-user';registerGoalServiceTestCleanup(serverDB, userId);+/** The run-less device failures a Task carries on `context.deviceDispatch`. */+const dispatchFailures = async (taskId: string) => {+ const task = await new TaskModel(serverDB, userId).findById(taskId);+ return ((task?.context as { deviceDispatch?: { failedAt?: string[] } } | null)?.deviceDispatch+ ?.failedAt ?? []) as string[];+};++/** Rewrite those failures, e.g. to put them in the past. */+const setDispatchFailures = async (taskId: string, failedAt: Date[]) => {+ const task = await new TaskModel(serverDB, userId).findById(taskId);+ await serverDB+ .update(tasks)+ .set({+ context: {+ ...(task?.context as object),+ deviceDispatch: { failedAt: failedAt.map((time) => time.toISOString()) },+ },+ })+ .where(eq(tasks.id, taskId));+};+describe('GoalService', () => {describe('a Task that could not reach its device', () => {const DEVICE_NOT_FOUND_HEADLINE =@@ -166,6 +187,216 @@ describe('GoalService', () => {expect(runSpy).not.toHaveBeenCalled();expect(waiting).toMatchObject({ outcome: 'waiting_external', taskId: created.taskId });});++ it('parks a first dispatch that cannot reach its device instead of re-dispatching it', async () => {+ // A first dispatch handed its claim back to `backlog` with no error and threw.+ // Every sweep then dispatched again, the queue redelivered each throw twice,+ // and a sleeping laptop became 27 uncharged runs in 40 minutes.+ const runSpy = vi+ .spyOn(TaskRunnerService.prototype, 'runTask')+ .mockRejectedValue(new Error('DEVICE_NOT_FOUND'));+ const service = new GoalService(serverDB, userId);+ const taskModel = new TaskModel(serverDB, userId);+ const graph = await service.create({+ title: 'First dispatch to a sleeping device',+ tasks: ['Run on the bound device'],+ });+ const created = await service.tick(graph.goal.id);++ const parked = await service.tick(graph.goal.id);++ expect(parked).toMatchObject({+ message: expect.stringContaining('waiting for its device to reconnect'),+ outcome: 'waiting_external',+ taskId: created.taskId,+ });+ expect(await taskModel.findById(created.taskId!)).toMatchObject({+ error: 'DEVICE_NOT_FOUND',+ status: 'paused',+ });++ const waiting = await service.tick(graph.goal.id);++ expect(waiting).toMatchObject({+ message: expect.stringContaining('next retry at'),+ outcome: 'waiting_external',+ });+ expect(runSpy).toHaveBeenCalledTimes(1);+ expect((await service.graph(graph.goal.id)).decisions).toHaveLength(0);+ });++ it('gates a device that stays gone even when no dispatch leaves a run behind', async () => {+ // Counted from runs alone, a dispatch that failed before `runTask` recorded+ // a run never advanced the schedule: each failure refreshed `updatedAt`,+ // so the Task waited 30 minutes and retried, forever, without a gate.+ const runSpy = vi+ .spyOn(TaskRunnerService.prototype, 'runTask')+ .mockRejectedValue(new Error('DEVICE_NOT_FOUND'));+ const service = new GoalService(serverDB, userId);+ const graph = await service.create({+ title: 'Device never registers again',+ tasks: ['Run on the bound device'],+ });+ const created = await service.tick(graph.goal.id);+ const backdateLastFailure = async () => {+ const failures = await dispatchFailures(created.taskId!);+ await setDispatchFailures(+ created.taskId!,+ failures.map(() => new Date(Date.now() - 24 * 60 * 60 * 1000)),+ );+ };++ // The first dispatch, then each retry the schedule allows once it is due.+ await service.tick(graph.goal.id);+ for (let retry = 1; retry <= MAX_DEVICE_OFFLINE_RETRIES; retry++) {+ await backdateLastFailure();+ await service.tick(graph.goal.id);+ }++ expect(runSpy).toHaveBeenCalledTimes(MAX_DEVICE_OFFLINE_RETRIES + 1);+ expect(await serverDB.select().from(taskTopics)).toHaveLength(0);+ expect(await dispatchFailures(created.taskId!)).toHaveLength(MAX_DEVICE_OFFLINE_RETRIES + 1);++ await backdateLastFailure();+ await service.tick(graph.goal.id);++ expect(runSpy).toHaveBeenCalledTimes(MAX_DEVICE_OFFLINE_RETRIES + 1);+ const gate = (await service.graph(graph.goal.id)).nodes.find(+ (node) => node.kind === 'decision',+ );+ expect(gate).toMatchObject({+ description: DEVICE_OFFLINE_GATE_REASON,+ title: GOAL_MACHINE_GATE_TITLE,+ });+ });++ it('adds a run lost offline and a retry that left no run as two failures', async () => {+ // Read as the larger count, the pair was one failure dated by the old run,+ // so the schedule found it due and dispatched again at once.+ const runSpy = vi+ .spyOn(TaskRunnerService.prototype, 'runTask')+ .mockRejectedValue(new Error('DEVICE_NOT_FOUND'));+ const service = new GoalService(serverDB, userId);+ const taskModel = new TaskModel(serverDB, userId);+ const graph = await service.create({+ title: 'Run lost, then the retry finds no device',+ tasks: ['Run on the bound device'],+ });+ const created = await service.tick(graph.goal.id);+ const topicId = 'tpc_lost_offline_run';+ await serverDB.insert(topics).values({ id: topicId, userId });+ await serverDB.insert(taskTopics).values({+ seq: 1,+ status: DEVICE_OFFLINE_RUN_STATUS,+ taskId: created.taskId!,+ topicId,+ updatedAt: new Date(Date.now() - 31 * 60_000),+ userId,+ });+ await taskModel.update(created.taskId!, { totalTopics: 1 });+ await taskModel.updateStatus(created.taskId!, 'paused', { error: 'DEVICE_OFFLINE' });++ // The lost run's first retry is due; it fails before recording a run.+ await service.tick(graph.goal.id);+ expect(runSpy).toHaveBeenCalledTimes(1);+ expect(await dispatchFailures(created.taskId!)).toHaveLength(1);++ const waiting = await service.tick(graph.goal.id);++ expect(runSpy).toHaveBeenCalledTimes(1);+ expect(waiting).toMatchObject({+ message: expect.stringContaining('next retry at'),+ outcome: 'waiting_external',+ });+ // Two failures: the second retry waits 60 minutes from the newer one.+ const retryAt = Date.parse(waiting.message.split('next retry at ')[1]);+ expect(retryAt - Date.now()).toBeGreaterThan(55 * 60_000);+ });++ it('does not count a failed dispatch that left a run on the streak too', async () => {+ // `runTask` records the failed run before it throws: that run is the count.+ const service = new GoalService(serverDB, userId);+ const taskModel = new TaskModel(serverDB, userId);+ const graph = await service.create({+ title: 'Dispatch failure with a recorded run',+ tasks: ['Run on the bound device'],+ });+ const created = await service.tick(graph.goal.id);+ vi.spyOn(TaskRunnerService.prototype, 'runTask').mockImplementation(async () => {+ await taskModel.update(created.taskId!, { totalTopics: 1 });+ throw new Error('DEVICE_NOT_FOUND');+ });++ await service.tick(graph.goal.id);++ expect(await taskModel.findById(created.taskId!)).toMatchObject({+ error: 'DEVICE_NOT_FOUND',+ status: 'paused',+ });+ expect(+ (await taskModel.findById(created.taskId!))?.context as Record<string, unknown> | null,+ ).not.toHaveProperty('deviceDispatch');+ });++ it('drops run-less failures from before a run that was not offline', async () => {+ // A run that reached the device and failed for another reason ends the+ // offline streak, even though no dispatch succeeded to clear it. Counted+ // anyway, the stale failure doubled the next wait and hastened the gate.+ const runSpy = vi.spyOn(TaskRunnerService.prototype, 'runTask');+ const service = new GoalService(serverDB, userId);+ const taskModel = new TaskModel(serverDB, userId);+ const graph = await service.create({+ title: 'Device failure, other failure, device failure',+ tasks: ['Run on the bound device'],+ });+ const created = await service.tick(graph.goal.id);+ const topicId = 'tpc_failed_startup_run';+ await serverDB.insert(topics).values({ id: topicId, userId });+ await serverDB.insert(taskTopics).values({+ createdAt: new Date(Date.now() - 60 * 60_000),+ seq: 1,+ status: 'failed',+ taskId: created.taskId!,+ topicId,+ updatedAt: new Date(Date.now() - 60 * 60_000),+ userId,+ });+ await taskModel.update(created.taskId!, { totalTopics: 1 });+ await setDispatchFailures(created.taskId!, [+ new Date(Date.now() - 2 * 60 * 60_000),+ new Date(Date.now() - 5 * 60_000),+ ]);+ await taskModel.updateStatus(created.taskId!, 'paused', { error: 'DEVICE_NOT_FOUND' });++ const waiting = await service.tick(graph.goal.id);++ expect(runSpy).not.toHaveBeenCalled();+ // One failure counts: the first retry is 30 minutes after it, not 60.+ const retryAt = Date.parse(waiting.message.split('next retry at ')[1]);+ expect(retryAt - Date.now()).toBeGreaterThan(20 * 60_000);+ expect(retryAt - Date.now()).toBeLessThan(30 * 60_000);+ });++ it('starts a new streak once a dispatch gets through', async () => {+ const runSpy = vi+ .spyOn(TaskRunnerService.prototype, 'runTask')+ .mockRejectedValueOnce(new Error('DEVICE_NOT_FOUND'))+ .mockResolvedValue({ operationId: 'op-reached-device', success: true } as never);+ const service = new GoalService(serverDB, userId);+ const graph = await service.create({+ title: 'Device comes back',+ tasks: ['Run on the bound device'],+ });+ const created = await service.tick(graph.goal.id);+ await service.tick(graph.goal.id);+ expect(await dispatchFailures(created.taskId!)).toHaveLength(1);+ await setDispatchFailures(created.taskId!, [new Date(Date.now() - 31 * 60 * 1000)]);++ await service.tick(graph.goal.id);++ expect(runSpy).toHaveBeenCalledTimes(2);+ expect(await dispatchFailures(created.taskId!)).toHaveLength(0);+ });});describe('a Task its usage window refused', () => {diff --git a/apps/server/src/services/goal/GoalService/dispatch.ts b/apps/server/src/services/goal/GoalService/dispatch.tsindex f46e794027e..84b41e9eb45 100644--- a/apps/server/src/services/goal/GoalService/dispatch.ts+++ b/apps/server/src/services/goal/GoalService/dispatch.ts@@ -10,8 +10,13 @@ import { TaskModel } from '@/database/models/task';import { TaskRunnerService } from '../../taskRunner';import { learnedRulesClause, planSkillIdentifier } from '../batchPlanSkill';import { GOAL_ACCEPTANCE_TASK_TITLE } from '../decideNextMove';+import { clearDeviceDispatchStreak, parkDeviceUnavailableDispatch } from '../deviceDispatchStreak';import { experimentResults } from '../exploreGraph';-import { resolveMaxConcurrentTasks, resolveTaskMaxSteps } from '../recoveryPolicy';+import {+ isDeviceUnavailableFailure,+ resolveMaxConcurrentTasks,+ resolveTaskMaxSteps,+} from '../recoveryPolicy';import { GoalSupervisorService } from '../supervisor';import { claimGoalTask } from '../taskClaim';import type { GoalServiceContext } from './types';@@ -252,6 +257,9 @@ export const dispatchWork = async (taskId: task.id,trigger: 'goal',});+ await clearDeviceDispatchStreak(ctx.taskModel, task.id).catch((clearError) => {+ console.error('[GoalService.tick] failed to clear the device dispatch streak:', clearError);+ });await new GoalSupervisorService(ctx.db, ctx.userId, ctx.workspaceId).recordDispatch(graph,task.id,@@ -271,6 +279,24 @@ export const dispatchWork = async (taskId: run.taskId,};} catch (error) {+ // A run that could not reach its device parks on that reason, the same as a+ // retry that could not (`TaskRecoveryCoordinator`), so the next advance takes+ // the offline schedule. Handed back to `backlog` with no error, every advance+ // dispatched again and threw, the queue redelivered each throw, and one+ // sleeping laptop became three uncharged runs per sweep with no bound.+ const message = error instanceof Error ? error.message : String(error);+ if (isDeviceUnavailableFailure(message)) {+ await parkDeviceUnavailableDispatch(ctx.taskModel, task, message).catch((releaseError) => {+ console.error('[GoalService.tick] failed to park claimed task:', releaseError);+ });+ return {+ goalId,+ message: `Task ${task.identifier} is waiting for its device to reconnect`,+ nodeId,+ outcome: 'waiting_external',+ taskId: task.id,+ };+ }// We claimed the task, so nothing else will put it back. Release it or the// Task stays 'running' with no run behind it and only the lease reclaims it.await ctx.taskModeldiff --git a/apps/server/src/services/goal/GoalService/recovery.ts b/apps/server/src/services/goal/GoalService/recovery.tsindex edd10b2433c..be9f548ded6 100644--- a/apps/server/src/services/goal/GoalService/recovery.ts+++ b/apps/server/src/services/goal/GoalService/recovery.ts@@ -18,6 +18,7 @@ import { deviceGateway } from '../../deviceGateway';import { isOrphanedRun, readRunTopicMetadata, stopStaleRun } from '../abandonedRun';import { LEASE_EXPIRED_ERROR } from '../decideNextMove';import { isDeliverySettling } from '../deliverySettle';+import { readDeviceDispatchStreak } from '../deviceDispatchStreak';import { classifyGoalFailure } from '../failureClass';import { lastAnsweredGateAt, planMachineRecovery } from '../machineRecovery';import {@@ -438,11 +439,21 @@ export const holdForOfflineDevice = async (): Promise<GoalTickResult | undefined> => {const runs = await ctx.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;+ // A dispatch failure is an offline run even when it left no run behind. Those+ // are kept on the dispatch streak, which holds only failures without a run,+ // so the two counts add up and the latest of either dates the schedule. The+ // newest run that was not offline ends the streak for both.+ const dispatch = readDeviceDispatchStreak(task, runs[offlineRuns]?.createdAt);+ if (!offlineRuns && !dispatch.failures && !isDeviceUnavailableFailure(task.error)) return;- const lastFailureAt = new Date(offlineRuns ? runs[0].updatedAt : task.updatedAt);- const retryAt = nextDeviceOfflineRetryAt(offlineRuns, lastFailureAt);+ const failureTimes = [+ ...(offlineRuns ? [new Date(runs[0].updatedAt).getTime()] : []),+ ...(dispatch.failures && dispatch.lastFailedAt ? [dispatch.lastFailedAt.getTime()] : []),+ ];+ const lastFailureAt = new Date(+ failureTimes.length ? Math.max(...failureTimes) : new Date(task.updatedAt).getTime(),+ );+ const retryAt = nextDeviceOfflineRetryAt(offlineRuns + dispatch.failures, lastFailureAt);if (!retryAt)return ctx.gateOrTakeOver(graph, nodeId, task.id, DEVICE_OFFLINE_GATE_REASON, effects, {machine: true,diff --git a/apps/server/src/services/goal/GoalService/tick.ts b/apps/server/src/services/goal/GoalService/tick.tsindex 2dca788c447..8cdd5598f06 100644--- a/apps/server/src/services/goal/GoalService/tick.ts+++ b/apps/server/src/services/goal/GoalService/tick.ts@@ -303,6 +303,14 @@ export const tickOnce = async (}case 'failure_decision': {+ // A device that went to sleep or a usage window that closed says+ // nothing about the recipe, for a batch member as for any Task: wait it+ // out first. Checked after the batch gate, one sleeping laptop paused+ // the whole rollout and asked the owner to revise or fork the recipe.+ const waiting =+ (await ctx.waitForDevice(graph, acting!.id, task, effects)) ??+ (await ctx.waitForQuotaReset(graph, acting!.id, task, effects));+ if (waiting) return observe(waiting);// R6: a batch member that did not pass its own check IS the same// intervention as a blocked gate. Route it through the batch gate so// the class rolls back to canary, instead of parking on a standalone@@ -314,10 +322,6 @@ export const tickOnce = async (}),);}- const waiting =- (await ctx.waitForDevice(graph, acting!.id, task, effects)) ??- (await ctx.waitForQuotaReset(graph, acting!.id, task, effects));- if (waiting) return observe(waiting);const held = await ctx.holdForMachineFailure(graph, acting!.id, task, effects);if (held) return observe(held);const supervision = await new GoalSupervisorService(diff --git a/apps/server/src/services/goal/deviceDispatchStreak.ts b/apps/server/src/services/goal/deviceDispatchStreak.tsnew file mode 100644index 00000000000..e931493fa0a--- /dev/null+++ b/apps/server/src/services/goal/deviceDispatchStreak.ts@@ -0,0 +1,98 @@+import type { TaskItem } from '@lobechat/types';++import type { TaskModel } from '@/database/models/task';++import { MAX_DEVICE_OFFLINE_RETRIES } from './recoveryPolicy';++/**+ * Dispatches of a Task that could not reach its device and left no run behind,+ * kept on `task.context` as the times they failed.+ *+ * The offline schedule (`holdForOfflineDevice`) counts offline runs, but a+ * dispatch can fail before `runTask` records a run. Counted from runs alone,+ * such a Task stayed at the first retry forever: every failure refreshed+ * `task.updatedAt`, so the schedule restarted at 30 minutes and never reached+ * its retry cap or the gate.+ *+ * Only failures without a run are kept here, so they never overlap the offline+ * runs and the schedule adds the two. Taking the larger one instead undercounted+ * a mix: a run lost offline plus a retry that left no run read as one failure,+ * dated by the old run, and was retried at once.+ *+ * The times, not a counter, decide what is still consecutive: any run that is+ * not offline breaks the streak, and the reader drops failures from before it.+ * A counter cleared by each writer missed the paths that record such a run+ * without a successful kickoff (a startup error after the run row, a lifecycle+ * hook), and a stale failure doubled the next backoff.+ */+const CONTEXT_KEY = 'deviceDispatch';++/** Enough to reach the offline gate; older failures can no longer change it. */+const MAX_KEPT_FAILURES = MAX_DEVICE_OFFLINE_RETRIES + 1;++interface DeviceDispatchStreak {+ failedAt: string[];+}++const readFailedAt = (task: Pick<TaskItem, 'context'>): string[] => {+ const streak = (task.context as Record<string, unknown> | null)?.[CONTEXT_KEY] as+ Partial<DeviceDispatchStreak> | undefined;+ return Array.isArray(streak?.failedAt)+ ? streak.failedAt.filter((value) => !Number.isNaN(Date.parse(value)))+ : [];+};++/**+ * Run-less device failures since `since` (the newest run that was not offline),+ * and when the latest of them happened.+ */+export const readDeviceDispatchStreak = (+ task: Pick<TaskItem, 'context'>,+ since?: Date | string,+): { failures: number; lastFailedAt?: Date } => {+ const after = since ? new Date(since).getTime() : -Infinity;+ const times = readFailedAt(task)+ .map((value) => Date.parse(value))+ .filter((time) => time > after);+ return {+ failures: times.length,+ lastFailedAt: times.length ? new Date(Math.max(...times)) : undefined,+ };+};++const writeFailedAt = async (+ taskModel: TaskModel,+ task: Pick<TaskItem, 'context' | 'id'>,+ failedAt: string[],+) => {+ // Replace the key outright: the context merge would keep a longer old array.+ const context = {+ ...(task.context as Record<string, unknown> | null),+ [CONTEXT_KEY]: { failedAt } satisfies DeviceDispatchStreak,+ };+ await taskModel.update(task.id, { context });+};++/**+ * Park a claimed Task whose dispatch could not reach its device: `paused` with+ * the device error, so the next advance takes the offline schedule. A dispatch+ * that recorded no run (`totalTopics` unchanged since `task` was read) is one+ * more failure on the streak; one that did is already counted as an offline run.+ */+export const parkDeviceUnavailableDispatch = async (+ taskModel: TaskModel,+ task: Pick<TaskItem, 'id' | 'totalTopics'>,+ error: string,+) => {+ const parked = await taskModel.updateStatusIfCurrent(task.id, 'running', 'paused', { error });+ if (!parked || (parked.totalTopics ?? 0) > (task.totalTopics ?? 0)) return;+ const failedAt = [...readFailedAt(parked), new Date().toISOString()].slice(-MAX_KEPT_FAILURES);+ await writeFailedAt(taskModel, parked, failedAt);+};++/** A dispatch got through: the next device failure starts a new streak. */+export const clearDeviceDispatchStreak = async (taskModel: TaskModel, taskId: string) => {+ const task = await taskModel.findById(taskId);+ if (!task || readFailedAt(task).length === 0) return;+ await writeFailedAt(taskModel, task, []);+};diff --git a/apps/server/src/services/goal/taskRecoveryCoordinator.ts b/apps/server/src/services/goal/taskRecoveryCoordinator.tsindex 68cc42b514e..1d2fed70a39 100644--- a/apps/server/src/services/goal/taskRecoveryCoordinator.ts+++ b/apps/server/src/services/goal/taskRecoveryCoordinator.ts@@ -8,6 +8,7 @@ import { TaskTopicModel } from '@/database/models/taskTopic';import type { LobeChatDatabase } from '@/database/type';import { TaskRunnerService } from '@/server/services/taskRunner';+import { clearDeviceDispatchStreak, parkDeviceUnavailableDispatch } from './deviceDispatchStreak';import {countChargedTaskAttempts,countUnchargedRuns,@@ -151,6 +152,9 @@ export class TaskRecoveryCoordinator {trigger: 'goal',});log('task %s → recovery attempt %d spawned', task.identifier, attempts + 1);+ await clearDeviceDispatchStreak(taskModel, current.id).catch((clearError) => {+ log('task %s failed to clear the device dispatch streak: %O', task.identifier, clearError);+ });return { operationId: run.operationId, outcome: 'started' };} catch (error) {log('task %s recovery spawn failed (non-fatal): %O', task.identifier, error);@@ -159,13 +163,13 @@ export class TaskRecoveryCoordinator {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: deviceUnavailable ? message : current.error,- })- .catch((releaseError) => {- log('task %s failed to release the recovery claim: %O', task.identifier, releaseError);- });+ await (+ deviceUnavailable+ ? parkDeviceUnavailableDispatch(taskModel, current, message)+ : taskModel.updateStatusIfCurrent(task.id, 'running', 'paused', { error: current.error })+ ).catch((releaseError) => {+ log('task %s failed to release the recovery claim: %O', task.identifier, releaseError);+ });return { deviceUnavailable, outcome: 'spawn-failed' };}};