π€― 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(agent-runtime): retire silent heterogeneous runs from the stale-operation sweep (#20855)
Arvin Xu666ca691a9f3
diff --git a/apps/server/src/routers/lambda/__tests__/agentNotify.test.ts b/apps/server/src/routers/lambda/__tests__/agentNotify.test.tsindex 59f29fe3454..39dba080fe7 100644--- a/apps/server/src/routers/lambda/__tests__/agentNotify.test.ts+++ b/apps/server/src/routers/lambda/__tests__/agentNotify.test.ts@@ -34,11 +34,12 @@ const mockMessageUpdate = vi.fn();const mockMessageCreate = vi.fn();const mockExecAgent = vi.fn();const mockOpFindById = vi.fn();+const mockOpTouchRunning = vi.fn();const mockInstantiateVerifyPlan = vi.fn();vi.mock('@/database/models/agentOperation', () => ({AgentOperationModel: vi.fn(function () {- return { findById: mockOpFindById };+ return { findById: mockOpFindById, touchRunning: mockOpTouchRunning };}),}));// Partial mock: keep the real runVerifyOnCompletion (CompletionLifecycle's gate@@ -140,6 +141,7 @@ describe('agentNotifyRouter.notify β remote hetero terminal signal', () => {// Default: a non-task op so the plan-instantiation guard no-ops unless a// test opts into a task-bound op.mockOpFindById.mockResolvedValue({ parentOperationId: null, taskId: null });+ mockOpTouchRunning.mockResolvedValue(true);mockInstantiateVerifyPlan.mockResolvedValue(undefined);});@@ -561,4 +563,26 @@ describe('agentNotifyRouter.notify β remote hetero terminal signal', () => {expect.objectContaining({ type: 'notify_update' }),);});++ it('refreshes the run lease on a nonterminal remote progress callback', async () => {+ await createCaller().notify({+ content: 'progress',+ operationId: OP,+ role: 'assistant',+ topicId: TOPIC,+ });++ // The stale-operation sweep retires a stateless run whose lease went silent+ // for the hetero window; a remote provider never calls `heteroIngest`, so+ // this path is the only thing keeping an active remote run's lease fresh.+ expect(mockOpTouchRunning).toHaveBeenCalledWith(OP);+ expect(mockOpTouchRunning).toHaveBeenCalledTimes(1);+ expect(mockMessageUpdate).toHaveBeenCalledWith(FINAL_MSG_ID, { content: 'progress' });+ });++ it('does not touch the lease on a terminal signal', async () => {+ await createCaller().notify({ content: '', done: true, role: 'assistant', topicId: TOPIC });++ expect(mockOpTouchRunning).not.toHaveBeenCalled();+ });});diff --git a/apps/server/src/routers/lambda/agentNotify.ts b/apps/server/src/routers/lambda/agentNotify.tsindex 18c26bb5695..d77b458028e 100644--- a/apps/server/src/routers/lambda/agentNotify.ts+++ b/apps/server/src/routers/lambda/agentNotify.ts@@ -347,6 +347,27 @@ export const agentNotifyRouter = router({stepIndex: 0,});} else {+ // Refresh the durable liveness lease before publishing progress.+ // Remote hetero providers (openclaw / hermes) report through+ // `agentNotify.notify` rather than `heteroIngest`, so nothing else on+ // this path bumps `agent_operations.updated_at` β the column the+ // stale-operation sweep compares against the hetero window before it+ // retires a *stateless* heterogeneous run (a remote run carries no+ // coordinator state either). Without this refresh a remote agent that+ // is actively streaming progress for over an hour is+ // indistinguishable from a dead one: an unrelated opportunistic sweep+ // retires it mid-run and every later callback is rejected as stale.+ // Terminal notifications are excluded β they settle the row through+ // CompletionLifecycle instead.+ try {+ await new AgentOperationModel(+ ctx.serverDB,+ ctx.userId,+ ctx.workspaceId ?? undefined,+ ).touchRunning(remoteOperationId);+ } catch (err) {+ log('notify: failed to refresh lease for operationId=%s: %O', remoteOperationId, err);+ }// Lightweight invalidation β frontend calls fetchAndReplaceMessages.await stream.publishStreamEvent(remoteOperationId, {data: { messageId: writtenMessageId },diff --git a/apps/server/src/services/agentRuntime/StaleOperationReaper.ts b/apps/server/src/services/agentRuntime/StaleOperationReaper.tsindex 18c6dcb1fc4..3022d522206 100644--- a/apps/server/src/services/agentRuntime/StaleOperationReaper.ts+++ b/apps/server/src/services/agentRuntime/StaleOperationReaper.ts@@ -1,6 +1,11 @@import type { AgentRuntimeContext, AgentState } from '@lobechat/agent-runtime';+import {+ isLocalHeterogeneousType,+ isLocalRuntimeHeterogeneousType,+ isRemoteHeterogeneousType,+} from '@lobechat/heterogeneous-agents';import debug from 'debug';-import { and, asc, eq, isNotNull, isNull, lt, notInArray, or, sql } from 'drizzle-orm';+import { and, asc, eq, gte, isNotNull, isNull, lt, notInArray, or, sql } from 'drizzle-orm';import urlJoin from 'url-join';import { AgentOperationModel } from '@/database/models/agentOperation';@@ -38,11 +43,49 @@ const DEFAULT_MAX_REDRIVE_ATTEMPTS = 3;/** Bound the work of a single cron tick so one sweep cannot run long. */const DEFAULT_LIMIT = 50;+/**+ * How far back the sweep looks for candidates.+ *+ * Without a floor the oldest-first scan never gets past rows nobody will ever+ * recover: production carries ~21k `running` rows whose lease froze more than a+ * day ago (the oldest from May), every one of them without coordinator state+ * and therefore `skipped`. The 50-row window was the same 50 dead rows on every+ * tick, so a run that died five minutes ago was never examined. Coordinator+ * state lives for two hours (`AgentStateManager` TTL), so nothing older than a+ * day can be redriven anyway, and a stateless heterogeneous run is retired well+ * inside it (see `HETERO_SILENCE_MS`).+ */+const DEFAULT_LOOKBACK_MS = 24 * 60 * 60_000;++/**+ * How long a heterogeneous run (Claude Code, Codex, β¦) may go without any+ * `heteroIngest` batch before this sweep retires it.+ *+ * Deliberately the same window as the agent-gateway inactivity watchdog uses+ * for hetero runs (`INACTIVITY_WATCHDOG_TIMEOUT_HETERO`, 60 min): a long shell+ * command inside the CLI reaches the server as silence, and this must not be+ * stricter than the path it backs up. The two read the same clock β every+ * ingest batch both refreshes this lease and pushes the events that reset the+ * gateway's β so whichever runs first wins and the other finds the row+ * terminal.+ */+const HETERO_SILENCE_MS = 60 * 60_000;++const isHeterogeneousProvider = (provider: string | null | undefined): boolean =>+ !!provider &&+ (isLocalHeterogeneousType(provider) ||+ isRemoteHeterogeneousType(provider) ||+ isLocalRuntimeHeterogeneousType(provider));+/** Bound how many overlapping topics one sweep reports. */const CONCURRENT_FOREGROUND_REPORT_LIMIT = 20;export interface ReapStaleOperationsParams {+ /** Silence after which a stateless heterogeneous run is retired. */+ heteroSilenceMs?: number;limit?: number;+ /** Ignore rows whose lease froze longer ago than this. */+ lookbackMs?: number;maxRedriveAttempts?: number;staleAfterMs?: number;}@@ -122,9 +165,12 @@ export class StaleOperationReaper {const staleAfterMs = params?.staleAfterMs ?? DEFAULT_STALE_AFTER_MS;const maxRedriveAttempts = params?.maxRedriveAttempts ?? DEFAULT_MAX_REDRIVE_ATTEMPTS;const limit = params?.limit ?? DEFAULT_LIMIT;- const staleBefore = new Date(Date.now() - staleAfterMs);+ const now = Date.now();+ const staleBefore = new Date(now - staleAfterMs);+ const heteroStaleBefore = new Date(now - (params?.heteroSilenceMs ?? HETERO_SILENCE_MS));+ const notBefore = new Date(now - (params?.lookbackMs ?? DEFAULT_LOOKBACK_MS));- const candidates = await this.listStaleRunning(staleBefore, limit);+ const candidates = await this.listStaleRunning(staleBefore, notBefore, limit);const result: ReapStaleOperationsResult = {abandoned: 0,alive: 0,@@ -137,7 +183,12 @@ export class StaleOperationReaper {for (const candidate of candidates) {try {- const outcome = await this.recover(candidate, staleBefore, maxRedriveAttempts);+ const outcome = await this.recover(+ candidate,+ staleBefore,+ heteroStaleBefore,+ maxRedriveAttempts,+ );result[outcome] += 1;} catch (e) {// One poisoned row must not abort the rest of the sweep.@@ -213,13 +264,15 @@ export class StaleOperationReaper {* model with the row's own owner so ownership is still enforced where it* matters.*/- private async listStaleRunning(staleBefore: Date, limit: number) {+ private async listStaleRunning(staleBefore: Date, notBefore: Date, limit: number) {return (this.db// Only what recovery needs: everything else about the run is read from// the coordinator state, and the abandon path re-reads the row itself..select({id: agentOperations.id,+ provider: agentOperations.provider,+ updatedAt: agentOperations.updatedAt,userId: agentOperations.userId,workspaceId: agentOperations.workspaceId,})@@ -228,6 +281,9 @@ export class StaleOperationReaper {and(eq(agentOperations.status, 'running'),lt(agentOperations.updatedAt, staleBefore),+ // See DEFAULT_LOOKBACK_MS: without this floor the oldest-first+ // window is permanently filled by long-dead rows.+ gte(agentOperations.updatedAt, notBefore),// A never-heartbeated row is only meaningful once it is older than// the window too; `startedAt` is the lease's initial value.or(isNull(agentOperations.startedAt), lt(agentOperations.startedAt, staleBefore)),@@ -241,8 +297,15 @@ export class StaleOperationReaper {}private async recover(- candidate: { id: string; userId: string; workspaceId: string | null },+ candidate: {+ id: string;+ provider: string | null;+ updatedAt: Date;+ userId: string;+ workspaceId: string | null;+ },staleBefore: Date,+ heteroStaleBefore: Date,maxRedriveAttempts: number,): Promise<'abandoned' | 'alive' | 'redriven' | 'skipped'> {const operationId = candidate.id;@@ -268,11 +331,35 @@ export class StaleOperationReaper {// `heteroIngest` bails out on `touchRunning` returning false, so every// subsequent batch of a live session would be dropped before persistence.//- // Stateless-but-genuinely-dead operations are the inactivity watchdog's- // job (it reaches them through `finalize-abandoned`), and it has the- // gateway-side evidence to tell the two apart. This sweep deliberately- // limits itself to runs it can actually resume.- if (!state || !this.queueService) return 'skipped';+ // So a stateless heterogeneous run is only retired once it has been silent+ // for the full hetero window β the same window the agent-gateway inactivity+ // watchdog uses. That watchdog used to be the only thing that ever ended+ // such a run, and it does not always fire: on 2026-10-12 two Codex runs on+ // one desktop went silent in the same minute; one was abandoned after an+ // hour, the other stayed `running` (its Task refusing every new message as+ // "Topic is already running") until the user paused it, and dozens more+ // hetero rows have sat `running` for days. This is the server-side backstop.+ // `abandonIfStillStale` re-checks the lease inside its UPDATE, so a batch+ // that lands meanwhile keeps the run alive.+ if (!state) {+ if (+ isHeterogeneousProvider(candidate.provider) &&+ new Date(candidate.updatedAt).getTime() < heteroStaleBefore.getTime()+ ) {+ return this.abandonIfStillStale(+ operationModel,+ operationId,+ heteroStaleBefore,+ 'hetero_silent',+ );+ }++ return 'skipped';+ }++ // Any other stateless operation is left alone: this sweep only acts on+ // runs it can resume or can prove dead.+ if (!this.queueService) return 'skipped';// Parked operations have their own resume paths; a plain step would run// past whatever they are waiting on.diff --git a/apps/server/src/services/agentRuntime/__tests__/StaleOperationReaper.test.ts b/apps/server/src/services/agentRuntime/__tests__/StaleOperationReaper.test.tsindex 56c948aa41b..a225188593a 100644--- a/apps/server/src/services/agentRuntime/__tests__/StaleOperationReaper.test.ts+++ b/apps/server/src/services/agentRuntime/__tests__/StaleOperationReaper.test.ts@@ -1,4 +1,6 @@// @vitest-environment node+import type { SQL } from 'drizzle-orm';+import { PgDialect } from 'drizzle-orm/pg-core';import { beforeEach, describe, expect, it, vi } from 'vitest';import { StaleOperationReaper } from '../StaleOperationReaper';@@ -26,27 +28,35 @@ vi.mock('../AbandonOperationService', () => ({/*** Minimal drizzle select chains: the stale-candidate query (`orderBy`) returns* `rows`, the concurrent-foreground patrol (`groupBy`) returns `overlapRows`.+ * Every WHERE condition is kept so a test can read the SQL it compiles to.*/+const whereConditions: SQL[] = [];const buildDb = (rows: any[], overlapRows: any[] = []) =>({select: () => ({from: () => ({- where: () => ({- groupBy: () => ({- having: () => ({ limit: vi.fn().mockResolvedValue(overlapRows) }),- }),- orderBy: () => ({ limit: vi.fn().mockResolvedValue(rows) }),- }),+ where: (condition: SQL) => {+ whereConditions.push(condition);+ return {+ groupBy: () => ({+ having: () => ({ limit: vi.fn().mockResolvedValue(overlapRows) }),+ }),+ orderBy: () => ({ limit: vi.fn().mockResolvedValue(rows) }),+ };+ },}),}),}) as any;-const candidate = (id = 'op_x') => ({+const candidate = (id = 'op_x', overrides: Record<string, any> = {}) => ({id,+ provider: 'openai',threadId: null,+ updatedAt: new Date(Date.now() - 10 * 60_000),topicId: 'tpc_x',userId: 'user_x',workspaceId: null,+ ...overrides,});const buildCoordinator = (@@ -90,6 +100,7 @@ describe('StaleOperationReaper', () => {settleStaleRunningMock.mockReset().mockResolvedValue(true);releaseStaleRedriveMock.mockReset().mockResolvedValue(true);finalizeAbandonedMock.mockClear();+ whereConditions.length = 0;process.env.APP_URL = 'https://app.lobehub.test';});@@ -155,14 +166,18 @@ describe('StaleOperationReaper', () => {expect(result).toMatchObject({ abandoned: 0, redriven: 0, skipped: 1 });});- it('never touches an operation with no coordinator state', async () => {- // This is the shape of a HEALTHY heterogeneous run: an external Claude+ it('never redrives an operation with no coordinator state', async () => {+ // This is also the shape of a HEALTHY heterogeneous run: an external Claude// Code / Codex CLI drives it, it never creates coordinator state, and it// only refreshes its lease on `heteroIngest` batches β so one long tool- // call reads as stale here. Retiring it would make `heteroIngest` drop- // every subsequent batch of a live session.+ // call reads as stale here. Retiring it early would make `heteroIngest`+ // drop every subsequent batch of a live session.const queue = buildQueue();- const result = await buildReaper([candidate()], null, queue).sweep();+ const result = await buildReaper(+ [candidate('op_x', { provider: 'codex' })],+ null,+ queue,+ ).sweep();expect(queue.scheduleMessage).not.toHaveBeenCalled();expect(claimStaleRedriveMock).not.toHaveBeenCalled();@@ -170,6 +185,97 @@ describe('StaleOperationReaper', () => {expect(result).toMatchObject({ abandoned: 0, redriven: 0, skipped: 1 });});+ it('only scans rows whose lease froze within the lookback window', async () => {+ // Production carries ~21k `running` rows dead for days, none with+ // coordinator state. Unbounded, the oldest-first window was those same 50+ // skipped rows on every tick and never reached a run that just died.+ const before = Date.now();+ await buildReaper([], runningState()).sweep();++ const { params, sql } = new PgDialect().sqlToQuery(whereConditions[0]);+ expect(sql).toMatch(/"updated_at" >= \$\d+/);+ const floor = params.find(+ (p) => typeof p === 'string' && new Date(p).getTime() <= before - 23 * 60 * 60_000,+ );+ expect(floor).toBeDefined();+ expect(new Date(floor as string).getTime()).toBeGreaterThanOrEqual(+ before - 24 * 60 * 60_000 - 1000,+ );+ });++ it('abandons a stateless heterogeneous run silent past the hetero window', async () => {+ // 2026-10-12: a device-dispatched Codex run went silent when its desktop+ // dropped off, the gateway inactivity watchdog never fired for it, and it+ // stayed `running` β its Task refusing every new message β until a human+ // paused it. Hetero runs never have coordinator state, so the reaper used+ // to skip them unconditionally.+ const queue = buildQueue();+ const before = Date.now();+ const result = await buildReaper(+ [candidate('op_x', { provider: 'codex', updatedAt: new Date(before - 61 * 60_000) })],+ null,+ queue,+ ).sweep();++ const [, staleBefore] = settleStaleRunningMock.mock.calls[0];+ // The CAS re-checks the lease against the hetero window, not the 5-min one,+ // so an ingest batch that lands meanwhile keeps the run alive.+ expect(staleBefore.getTime()).toBeLessThanOrEqual(before - 60 * 60_000 + 5);+ expect(staleBefore.getTime()).toBeGreaterThan(before - 61 * 60_000);+ expect(finalizeAbandonedMock).toHaveBeenCalledWith('op_x', 'stale_lease_hetero_silent', {+ settledAsAbandoned: true,+ });+ expect(queue.scheduleMessage).not.toHaveBeenCalled();+ expect(claimStaleRedriveMock).not.toHaveBeenCalled();+ expect(result).toMatchObject({ abandoned: 1, skipped: 0 });+ });++ it('keeps a heterogeneous run that is quiet but inside the hetero window', async () => {+ // A long shell command inside the CLI reaches the server as silence; the+ // backstop must not be stricter than the gateway's 60-min hetero window.+ const result = await buildReaper(+ [+ candidate('op_x', {+ provider: 'claude-code',+ updatedAt: new Date(Date.now() - 30 * 60_000),+ }),+ ],+ null,+ ).sweep();++ expect(settleStaleRunningMock).not.toHaveBeenCalled();+ expect(finalizeAbandonedMock).not.toHaveBeenCalled();+ expect(result).toMatchObject({ abandoned: 0, skipped: 1 });+ });++ it('leaves a silent heterogeneous run alone when an ingest batch wins the CAS', async () => {+ settleStaleRunningMock.mockResolvedValue(false);++ const result = await buildReaper(+ [candidate('op_x', { provider: 'codex', updatedAt: new Date(Date.now() - 90 * 60_000) })],+ null,+ ).sweep();++ expect(finalizeAbandonedMock).not.toHaveBeenCalled();+ expect(result).toMatchObject({ abandoned: 0, alive: 1 });+ });++ it('still skips a stateless non-heterogeneous run however long it has been quiet', async () => {+ const result = await buildReaper(+ [+ candidate('op_x', {+ provider: 'openai',+ updatedAt: new Date(Date.now() - 3 * 60 * 60_000),+ }),+ ],+ null,+ ).sweep();++ expect(settleStaleRunningMock).not.toHaveBeenCalled();+ expect(finalizeAbandonedMock).not.toHaveBeenCalled();+ expect(result).toMatchObject({ skipped: 1 });+ });+it.each(['waiting_for_human', 'waiting_for_async_tool'])('never redrives a deliberately parked operation (%s)',async (status) => {