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: Fix remote agent dispatch failures (#16527)

Arvin Xu0eed5cd9e37d
diff --git a/apps/server/src/services/agentRuntime/AbandonOperationService.ts b/apps/server/src/services/agentRuntime/AbandonOperationService.ts
index 326ef0209f7..5cc3402ddf8 100644
--- a/apps/server/src/services/agentRuntime/AbandonOperationService.ts
+++ b/apps/server/src/services/agentRuntime/AbandonOperationService.ts
@@ -1,11 +1,15 @@
import type { ISnapshotStore } from '@lobechat/agent-tracing';
+import { LOADING_FLAT } from '@lobechat/const';
import type { ChatMessageError } from '@lobechat/types';
import { AgentRuntimeErrorType } from '@lobechat/types';
import debug from 'debug';
+import { and, desc, eq, gte, lte, or } from 'drizzle-orm';
import { AgentOperationModel } from '@/database/models/agentOperation';
import { MessageModel } from '@/database/models/message';
import { ThreadModel } from '@/database/models/thread';
+import { TopicModel } from '@/database/models/topic';
+import { agentOperations, messages } from '@/database/schemas';
import type { LobeChatDatabase } from '@/database/type';
// Direct file import (not the barrel) to avoid pulling in RuntimeExecutors and
// its workspace-package transitive deps in the unit-test environment.
@@ -37,6 +41,12 @@ export interface AbandonedSubAgentResume {
}
export interface FinalizeAbandonedResult {
+ /**
+ * Whether this watchdog firing represents a real abandoned run. `found=false`
+ * alone is ambiguous: normal runtime ops may already be cleaned up, while
+ * device/hetero runs can have no coordinator state but still be stuck in DB.
+ */
+ abandoned?: boolean;
/** Whether the assistant message was successfully marked as errored. */
assistantMessageUpdated: boolean;
/** Whether the operation was finalized into a snapshot (false if no partial existed). */
@@ -88,6 +98,7 @@ export class AbandonOperationService {
const state = await this.coordinator.loadAgentState(operationId);
if (!state) {
log('[%s] no agent state in coordinator — already cleaned up', operationId);
+ await this.finalizeRunningOperationWithoutState(operationId, reason, result);
return result;
}
result.found = true;
@@ -208,4 +219,116 @@ export class AbandonOperationService {
log('[%s] abandoned op finalized (reason=%s): %O', operationId, reason, result);
return result;
}
+
+ private async finalizeRunningOperationWithoutState(
+ operationId: string,
+ reason: string,
+ result: FinalizeAbandonedResult,
+ ): Promise<void> {
+ const op = await this.findOperationRow(operationId);
+ if (!op || !['running', 'waiting_for_human', 'waiting_for_async_tool'].includes(op.status)) {
+ return;
+ }
+
+ result.abandoned = true;
+
+ const message = `Operation abandoned: ${reason}`;
+ const error: ChatMessageError = {
+ body: { message },
+ message,
+ type: AgentRuntimeErrorType.AgentRuntimeError,
+ };
+
+ try {
+ await new AgentOperationModel(
+ this.db,
+ op.userId,
+ op.workspaceId ?? undefined,
+ ).recordCompletion(operationId, {
+ completedAt: new Date(),
+ completionReason: 'error',
+ error: { message, type: String(error.type) },
+ llmCalls: 0,
+ processingTimeMs: op.startedAt ? Date.now() - new Date(op.startedAt).getTime() : null,
+ status: 'error',
+ stepCount: 0,
+ toolCalls: 0,
+ totalTokens: 0,
+ });
+ } catch (e) {
+ log('[%s] no-state abandon: recordCompletion failed (non-fatal): %O', operationId, e);
+ }
+
+ const assistantMessageId = await this.resolveAssistantMessageIdForOperation(op, operationId);
+ if (!assistantMessageId) return;
+
+ try {
+ const messageModel = new MessageModel(this.db, op.userId, op.workspaceId ?? undefined);
+ 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);
+ }
+ }
+
+ private async findOperationRow(operationId: string) {
+ try {
+ return await (this.db as any).query?.agentOperations?.findFirst({
+ where: eq(agentOperations.id, operationId),
+ });
+ } catch (e) {
+ log('[%s] no-state abandon: operation lookup failed (non-fatal): %O', operationId, e);
+ return null;
+ }
+ }
+
+ private async resolveAssistantMessageIdForOperation(
+ op: typeof agentOperations.$inferSelect,
+ operationId: string,
+ ): Promise<string | undefined> {
+ let topicModel: TopicModel | undefined;
+
+ if (op.topicId) {
+ try {
+ topicModel = new TopicModel(this.db, op.userId, op.workspaceId ?? undefined);
+ const topic = await topicModel.findById(op.topicId);
+ const running = topic?.metadata?.runningOperation as
+ | { assistantMessageId?: string; operationId?: string }
+ | undefined;
+
+ if (running?.operationId && running.operationId !== operationId) return undefined;
+
+ if (running?.operationId === operationId) {
+ await topicModel.updateMetadata(op.topicId, { runningOperation: null }).catch(() => {});
+ if (running.assistantMessageId) return running.assistantMessageId;
+ }
+ } catch (e) {
+ log('[%s] no-state abandon: topic lookup failed (non-fatal): %O', operationId, e);
+ }
+ }
+
+ try {
+ const startedAt = op.startedAt ? new Date(op.startedAt) : undefined;
+ const lowerBound = startedAt ? new Date(startedAt.getTime() - 5000) : undefined;
+ const upperBound = startedAt ? new Date(startedAt.getTime() + 5000) : undefined;
+ const assistant = await (this.db as any).query?.messages?.findFirst({
+ orderBy: [desc(messages.createdAt)],
+ where: and(
+ eq(messages.userId, op.userId),
+ eq(messages.role, 'assistant'),
+ op.topicId ? eq(messages.topicId, op.topicId) : undefined,
+ op.agentId ? eq(messages.agentId, op.agentId) : undefined,
+ op.provider ? eq(messages.provider, op.provider) : undefined,
+ lowerBound ? gte(messages.createdAt, lowerBound) : undefined,
+ upperBound ? lte(messages.createdAt, upperBound) : undefined,
+ or(eq(messages.content, LOADING_FLAT), eq(messages.content, '')),
+ ),
+ });
+
+ return assistant?.id;
+ } catch (e) {
+ log('[%s] no-state abandon: assistant lookup failed (non-fatal): %O', operationId, e);
+ return undefined;
+ }
+ }
}
diff --git a/apps/server/src/services/agentRuntime/__tests__/AbandonOperationService.test.ts b/apps/server/src/services/agentRuntime/__tests__/AbandonOperationService.test.ts
index 760853506ac..612ecec092a 100644
--- a/apps/server/src/services/agentRuntime/__tests__/AbandonOperationService.test.ts
+++ b/apps/server/src/services/agentRuntime/__tests__/AbandonOperationService.test.ts
@@ -31,8 +31,12 @@ vi.mock('@/database/models/message', () => ({
}));
const findOperationMock = vi.fn().mockResolvedValue(null);
+const recordCompletionMock = vi.fn().mockResolvedValue(undefined);
vi.mock('@/database/models/agentOperation', () => ({
- AgentOperationModel: vi.fn().mockImplementation(() => ({ findById: findOperationMock })),
+ AgentOperationModel: vi.fn().mockImplementation(() => ({
+ findById: findOperationMock,
+ recordCompletion: recordCompletionMock,
+ })),
}));
const findThreadMock = vi.fn().mockResolvedValue(null);
@@ -40,6 +44,15 @@ vi.mock('@/database/models/thread', () => ({
ThreadModel: vi.fn().mockImplementation(() => ({ findById: findThreadMock })),
}));
+const topicFindByIdMock = vi.fn().mockResolvedValue(null);
+const topicUpdateMetadataMock = vi.fn().mockResolvedValue(undefined);
+vi.mock('@/database/models/topic', () => ({
+ TopicModel: vi.fn().mockImplementation(() => ({
+ findById: topicFindByIdMock,
+ updateMetadata: topicUpdateMetadataMock,
+ })),
+}));
+
const stateWith = (overrides: Record<string, any> = {}) => ({
cost: { total: 0.1 },
metadata: {
@@ -54,11 +67,26 @@ const stateWith = (overrides: Record<string, any> = {}) => ({
...overrides,
});
+const buildDb = (overrides: { assistantRow?: any; operationRow?: any } = {}) =>
+ ({
+ query: {
+ agentOperations: {
+ findFirst: vi.fn().mockResolvedValue(overrides.operationRow ?? null),
+ },
+ messages: {
+ findFirst: vi.fn().mockResolvedValue(overrides.assistantRow ?? null),
+ },
+ },
+ }) as any;
+
describe('AbandonOperationService', () => {
beforeEach(() => {
messageUpdateMock.mockClear();
findOperationMock.mockReset().mockResolvedValue(null);
+ recordCompletionMock.mockClear();
findThreadMock.mockReset().mockResolvedValue(null);
+ topicFindByIdMock.mockReset().mockResolvedValue(null);
+ topicUpdateMetadataMock.mockReset().mockResolvedValue(undefined);
});
it('returns found:false when coordinator has no state', async () => {
@@ -80,6 +108,122 @@ describe('AbandonOperationService', () => {
expect(messageUpdateMock).not.toHaveBeenCalled();
});
+ it('marks a no-state running operation as abandoned and errors the placeholder', async () => {
+ const coord = buildCoordinator({ loadAgentState: vi.fn().mockResolvedValue(null) });
+ const store = buildStore();
+ const db = buildDb({
+ operationRow: {
+ agentId: 'agt_x',
+ id: 'op_x',
+ provider: 'claude-code',
+ startedAt: new Date('2026-06-30T11:51:14.745Z'),
+ status: 'running',
+ topicId: 'tpc_x',
+ userId: 'user_x',
+ workspaceId: 'ws_x',
+ },
+ });
+ topicFindByIdMock.mockResolvedValue({
+ metadata: {
+ runningOperation: {
+ assistantMessageId: 'msg_assist_1',
+ operationId: 'op_x',
+ },
+ },
+ });
+
+ const svc = new AbandonOperationService(db, {
+ coordinator: coord as any,
+ snapshotStore: store as any,
+ });
+
+ const result = await svc.finalizeAbandoned('op_x', 'inactivity_watchdog');
+
+ expect(result).toMatchObject({
+ abandoned: true,
+ assistantMessageUpdated: true,
+ finalized: false,
+ found: false,
+ });
+ expect(recordCompletionMock).toHaveBeenCalledWith(
+ 'op_x',
+ expect.objectContaining({
+ completionReason: 'error',
+ status: 'error',
+ stepCount: 0,
+ toolCalls: 0,
+ }),
+ );
+ expect(topicUpdateMetadataMock).toHaveBeenCalledWith('tpc_x', { runningOperation: null });
+ expect(messageUpdateMock).toHaveBeenCalledWith('msg_assist_1', {
+ content: '',
+ error: expect.objectContaining({
+ message: expect.stringContaining('inactivity_watchdog'),
+ type: 'AgentRuntimeError',
+ }),
+ });
+ });
+
+ it('keeps no-state terminal operations classified as completed phantom timeouts', async () => {
+ const coord = buildCoordinator({ loadAgentState: vi.fn().mockResolvedValue(null) });
+ const store = buildStore();
+ const db = buildDb({
+ operationRow: {
+ id: 'op_done',
+ status: 'done',
+ userId: 'user_x',
+ },
+ });
+
+ const svc = new AbandonOperationService(db, {
+ coordinator: coord as any,
+ snapshotStore: store as any,
+ });
+
+ const result = await svc.finalizeAbandoned('op_done', 'inactivity_watchdog');
+
+ expect(result.abandoned).toBeUndefined();
+ expect(recordCompletionMock).not.toHaveBeenCalled();
+ expect(messageUpdateMock).not.toHaveBeenCalled();
+ });
+
+ it('does not touch a newer runningOperation when abandoning an old no-state op', async () => {
+ const coord = buildCoordinator({ loadAgentState: vi.fn().mockResolvedValue(null) });
+ const store = buildStore();
+ const db = buildDb({
+ assistantRow: { id: 'msg_old_placeholder' },
+ operationRow: {
+ agentId: 'agt_x',
+ id: 'op_old',
+ provider: 'claude-code',
+ startedAt: new Date('2026-06-30T11:51:14.745Z'),
+ status: 'running',
+ topicId: 'tpc_x',
+ userId: 'user_x',
+ },
+ });
+ topicFindByIdMock.mockResolvedValue({
+ metadata: {
+ runningOperation: {
+ assistantMessageId: 'msg_new_placeholder',
+ operationId: 'op_new',
+ },
+ },
+ });
+
+ const svc = new AbandonOperationService(db, {
+ coordinator: coord as any,
+ snapshotStore: store as any,
+ });
+
+ const result = await svc.finalizeAbandoned('op_old', 'inactivity_watchdog');
+
+ expect(result.abandoned).toBe(true);
+ expect(recordCompletionMock).toHaveBeenCalled();
+ expect(topicUpdateMetadataMock).not.toHaveBeenCalled();
+ expect(messageUpdateMock).not.toHaveBeenCalled();
+ });
+
it('finalizes snapshot and marks assistant message errored when state + partial exist', async () => {
const coord = buildCoordinator({
loadAgentState: vi.fn().mockResolvedValue(stateWith()),
diff --git a/packages/device-gateway-client/src/http.test.ts b/packages/device-gateway-client/src/http.test.ts
index b227020a6c2..c489f430437 100644
--- a/packages/device-gateway-client/src/http.test.ts
+++ b/packages/device-gateway-client/src/http.test.ts
@@ -311,6 +311,108 @@ describe('GatewayHttpClient', () => {
});
});
+ describe('dispatchAgentRun', () => {
+ it('should return success for accepted agent runs', async () => {
+ mockFetch({
+ json: vi.fn().mockResolvedValue({ success: true }),
+ ok: true,
+ });
+
+ const result = await client.dispatchAgentRun({
+ agentType: 'claude-code',
+ jwt: 'jwt',
+ operationId: 'op-1',
+ prompt: 'run',
+ topicId: 'tpc-1',
+ userId: 'user-1',
+ });
+
+ expect(result).toEqual({ success: true });
+ expect(fetch).toHaveBeenCalledWith(
+ 'https://gateway.test.com/api/device/agent/run',
+ expect.objectContaining({
+ body: expect.stringContaining('"operationId":"op-1"'),
+ }),
+ );
+ });
+
+ it('should preserve backward compatibility when accepted response has no JSON body', async () => {
+ mockFetch({
+ json: vi.fn().mockRejectedValue(new Error('empty body')),
+ ok: true,
+ });
+
+ const result = await client.dispatchAgentRun({
+ agentType: 'claude-code',
+ jwt: 'jwt',
+ operationId: 'op-1',
+ prompt: 'run',
+ topicId: 'tpc-1',
+ userId: 'user-1',
+ });
+
+ expect(result).toEqual({ success: true });
+ });
+
+ it('should surface rejected agent-run acks returned with HTTP 200', async () => {
+ mockFetch({
+ json: vi.fn().mockResolvedValue({
+ reason: 'spawn failed',
+ status: 'rejected',
+ }),
+ ok: true,
+ });
+
+ const result = await client.dispatchAgentRun({
+ agentType: 'claude-code',
+ jwt: 'jwt',
+ operationId: 'op-1',
+ prompt: 'run',
+ topicId: 'tpc-1',
+ userId: 'user-1',
+ });
+
+ expect(result).toEqual({ error: 'spawn failed', success: false });
+ });
+
+ it('should surface success false returned with HTTP 200', async () => {
+ mockFetch({
+ json: vi.fn().mockResolvedValue({ error: 'DEVICE_OFFLINE', success: false }),
+ ok: true,
+ });
+
+ const result = await client.dispatchAgentRun({
+ agentType: 'claude-code',
+ jwt: 'jwt',
+ operationId: 'op-1',
+ prompt: 'run',
+ topicId: 'tpc-1',
+ userId: 'user-1',
+ });
+
+ expect(result).toEqual({ error: 'DEVICE_OFFLINE', success: false });
+ });
+
+ it('should surface non-ok agent-run responses', async () => {
+ mockFetch({
+ ok: false,
+ status: 503,
+ text: vi.fn().mockResolvedValue('DEVICE_OFFLINE'),
+ });
+
+ const result = await client.dispatchAgentRun({
+ agentType: 'claude-code',
+ jwt: 'jwt',
+ operationId: 'op-1',
+ prompt: 'run',
+ topicId: 'tpc-1',
+ userId: 'user-1',
+ });
+
+ expect(result).toEqual({ error: 'DEVICE_OFFLINE', success: false });
+ });
+ });
+
describe('executeMcpCall', () => {
it('should tunnel the call over the tool-call relay with stdio params', async () => {
mockFetch({
diff --git a/packages/device-gateway-client/src/http.ts b/packages/device-gateway-client/src/http.ts
index 917885d50b2..09238a9e625 100644
--- a/packages/device-gateway-client/src/http.ts
+++ b/packages/device-gateway-client/src/http.ts
@@ -221,6 +221,14 @@ export class GatewayHttpClient {
const text = await res.text().catch(() => '');
return { error: text || `HTTP ${res.status}`, success: false };
}
+ const data = await res.json().catch(() => null);
+ if (data && (data.success === false || data.status === 'rejected')) {
+ return {
+ error: data.error ?? data.reason ?? 'DEVICE_REJECTED',
+ success: false,
+ };
+ }
+
return { success: true };
}