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(hetero): keep timed-out device runs alive and stop stuck sidebar spinners (#21765)

Arvin Xua95aea31f6d9
diff --git a/apps/server/src/services/aiAgent/helpers/heteroErrors.ts b/apps/server/src/services/aiAgent/helpers/heteroErrors.ts
index b375cd58f8a..70a93229077 100644
--- a/apps/server/src/services/aiAgent/helpers/heteroErrors.ts
+++ b/apps/server/src/services/aiAgent/helpers/heteroErrors.ts
@@ -104,6 +104,14 @@ export const readDeviceDispatchRoute = (error: unknown): DeviceDispatchRoute | u
};
};
+/**
+ * Whether a dispatch failed only because the device's ack never arrived. Unlike
+ * every other dispatch failure this does not prove nothing ran β€” see
+ * {@link GATEWAY_CODE_ALIASES}.
+ */
+export const isDeviceResponseTimeout = (raw?: string): boolean =>
+ toDispatchErrorCode(raw) === 'DEVICE_RESPONSE_TIMEOUT';
+
export const humanizeHeteroDispatchError = (raw?: string): string => {
const code = toDispatchErrorCode(raw);
diff --git a/apps/server/src/services/aiAgent/pipeline/heteroDispatch/device.ts b/apps/server/src/services/aiAgent/pipeline/heteroDispatch/device.ts
index 767b7c4cc89..dc63d639e28 100644
--- a/apps/server/src/services/aiAgent/pipeline/heteroDispatch/device.ts
+++ b/apps/server/src/services/aiAgent/pipeline/heteroDispatch/device.ts
@@ -12,6 +12,7 @@ import { buildRemoteDeviceHeteroContext } from '@/server/services/heterogeneousA
import {
humanizeHeteroDispatchError,
+ isDeviceResponseTimeout,
resolveHeteroDispatchErrorType,
supportsCloudHeterogeneousSandbox,
} from '../../helpers/heteroErrors';
@@ -19,6 +20,7 @@ import { resolveDeviceWorkingDirectoryConfig } from '../../resolveDeviceWorkingD
import type { ExecRunContext } from '../../types';
import { selectCodexDeviceDispatch } from '../codexDeviceRuntime';
import type { PreparedHeteroRun } from './prepare';
+import { scheduleTimedOutDispatchConfirmation } from './timeoutConfirmation';
import type { HeteroDispatchDeps, HeteroDispatchInput, HeteroRun } from './types';
import { failHeteroDispatch } from './utils';
@@ -62,7 +64,7 @@ const resolveClaudeAccountRouting = async (
* request reaches the process.
*
* Returns the terminal error result when the run cannot start, `undefined`
- * once the device accepted it.
+ * once the device accepted it β€” or may have, when only its ack timed out.
*/
export const dispatchToCliDevice = async (
deps: HeteroDispatchDeps,
@@ -214,6 +216,8 @@ export const dispatchToCliDevice = async (
dispatchDeviceId,
dispatchWorkspaceId,
);
+ // Anything that touches the run after this instant proves it started.
+ const dispatchedAt = new Date();
const result = authorizationError
? { error: 'DEVICE_NOT_FOUND', errorData: authorizationError, success: false }
: await deviceGateway.dispatchAgentRun({
@@ -236,31 +240,37 @@ export const dispatchToCliDevice = async (
ingestWorkspaceId: deps.workspaceId,
});
if (!result.success) {
- log('execAgent: hetero device dispatch failed: %s', result.error);
- return failHeteroDispatch(
- deps,
- run,
- {
- 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),
- },
- {
- error: result.error,
- errorData: result.errorData,
- message: 'Hetero agent device dispatch failed',
+ const finalize = {
+ 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),
+ };
+ const failure = {
+ error: result.error,
+ errorData: result.errorData,
+ message: 'Hetero agent device dispatch failed',
+ };
+
+ // A lost ack is not proof the run never started β€” the device may already
+ // be spawning it. Keep the run alive and fail it only if nothing shows up.
+ if (!isDeviceResponseTimeout(result.error)) {
+ log('execAgent: hetero device dispatch failed: %s', result.error);
+ return failHeteroDispatch(deps, run, finalize, failure);
+ }
+
+ log('execAgent: hetero device dispatch unconfirmed, awaiting first ingest op=%s', operationId);
+ scheduleTimedOutDispatchConfirmation(deps, run, { dispatchedAt, finalize, result: failure });
}
// Local CLI hetero agents dispatch to a device just like remote platform
- // agents, so persist the device route after the dispatch is accepted.
+ // agents, so persist the device route once the dispatch is accepted (or may
+ // have been, after a timeout).
// interruptTask uses these fields to find and stop the native process.
try {
const patched = await deps.topicModel.patchRunningOperation(topicId, operationId, {
diff --git a/apps/server/src/services/aiAgent/pipeline/heteroDispatch/index.branches.test.ts b/apps/server/src/services/aiAgent/pipeline/heteroDispatch/index.branches.test.ts
index 3231517e1e7..2982c272fce 100644
--- a/apps/server/src/services/aiAgent/pipeline/heteroDispatch/index.branches.test.ts
+++ b/apps/server/src/services/aiAgent/pipeline/heteroDispatch/index.branches.test.ts
@@ -22,6 +22,7 @@ const mocks = vi.hoisted(() => ({
recordStart: vi.fn(),
resolveDeviceDispatchAuthorizationFailure: vi.fn(),
resolveSandboxSessionConfig: vi.fn(),
+ scheduleTimedOutDispatchConfirmation: vi.fn(),
selectCodexDeviceDispatch: vi.fn(),
signHeteroOperationJWT: vi.fn(),
signUserJWT: vi.fn(),
@@ -98,6 +99,10 @@ vi.mock('../finalizeHeteroDispatchError', () => ({
finalizeHeteroDispatchError: mocks.finalizeHeteroDispatchError,
}));
+vi.mock('./timeoutConfirmation', () => ({
+ scheduleTimedOutDispatchConfirmation: mocks.scheduleTimedOutDispatchConfirmation,
+}));
+
vi.mock('../codexDeviceRuntime', () => ({
selectCodexDeviceDispatch: mocks.selectCodexDeviceDispatch,
}));
@@ -612,16 +617,17 @@ describe('dispatchHeteroAgent β€” local CLI agents', () => {
);
});
- it('settles a dispatch timeout as a device timeout, even when the device is now offline', async () => {
+ it('keeps a timed-out dispatch alive and settles it later as a device timeout', async () => {
// Whether the run started is unknowable after a timeout: the device may
- // have received it before dropping. Asking the device now must not turn
- // "may still be starting" into "never started".
+ // have received it before the ack was lost, and its CLI may already be
+ // starting. Failing it now would refuse that CLI's first batch as
+ // `operation-not-running`; asking the device now must not decide it either.
const raw = JSON.stringify({ error: 'TIMEOUT', success: false, timeSinceHeartbeatMs: 70_000 });
mocks.dispatchAgentRun.mockResolvedValueOnce({ error: raw, success: false });
mocks.readDeviceSystemInfo.mockResolvedValue({ ok: false, reason: 'DEVICE_OFFLINE' });
- const { deps } = createDeps();
+ const { deps, topicModel } = createDeps();
- await dispatchHeteroAgent(
+ const result = await dispatchHeteroAgent(
deps,
createCtx({
boundDeviceId: 'dev-1',
@@ -631,14 +637,27 @@ describe('dispatchHeteroAgent β€” local CLI agents', () => {
createInput('claude-code'),
);
- expect(mocks.finalizeHeteroDispatchError).toHaveBeenCalledWith(
+ expect(mocks.finalizeHeteroDispatchError).not.toHaveBeenCalled();
+ expect(mocks.scheduleTimedOutDispatchConfirmation).toHaveBeenCalledWith(
deps,
- expect.objectContaining({
- detail: raw,
- errorType: ChatErrorType.DeviceResponseTimeout,
- message: humanizeHeteroDispatchError('DEVICE_RESPONSE_TIMEOUT'),
- }),
+ expect.objectContaining({ operationId: result.operationId }),
+ {
+ dispatchedAt: expect.any(Date),
+ finalize: expect.objectContaining({
+ detail: raw,
+ errorType: ChatErrorType.DeviceResponseTimeout,
+ message: humanizeHeteroDispatchError('DEVICE_RESPONSE_TIMEOUT'),
+ }),
+ result: expect.objectContaining({ error: raw }),
+ },
+ );
+ // Stop must still reach a run that may be live on the device.
+ expect(topicModel.patchRunningOperation).toHaveBeenCalledWith(
+ 'topic-1',
+ result.operationId,
+ expect.objectContaining({ deviceId: 'dev-1' }),
);
+ expect(result).toMatchObject({ status: 'created', success: true });
expect(mocks.readDeviceSystemInfo).not.toHaveBeenCalled();
});
diff --git a/apps/server/src/services/aiAgent/pipeline/heteroDispatch/timeoutConfirmation.test.ts b/apps/server/src/services/aiAgent/pipeline/heteroDispatch/timeoutConfirmation.test.ts
new file mode 100644
index 00000000000..89336435710
--- /dev/null
+++ b/apps/server/src/services/aiAgent/pipeline/heteroDispatch/timeoutConfirmation.test.ts
@@ -0,0 +1,68 @@
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { confirmTimedOutDispatch, HETERO_DISPATCH_CONFIRM_WINDOW_MS } from './timeoutConfirmation';
+import type { HeteroDispatchDeps, HeteroRun } from './types';
+
+const mocks = vi.hoisted(() => ({
+ failHeteroDispatch: vi.fn(),
+ settleUnconfirmedRunning: vi.fn(),
+}));
+
+vi.mock('@/database/models/agentOperation', () => ({
+ AgentOperationModel: vi.fn().mockImplementation(function () {
+ return { settleUnconfirmedRunning: mocks.settleUnconfirmedRunning };
+ }),
+}));
+
+vi.mock('./utils', () => ({ failHeteroDispatch: mocks.failHeteroDispatch }));
+
+const deps = { db: {}, userId: 'user-1' } as unknown as HeteroDispatchDeps;
+const run = { operationId: 'op-1', topicId: 'topic-1' } as HeteroRun;
+const dispatchedAt = new Date('2026-10-28T02:43:56.000Z');
+const finalize = { detail: '{"error":"TIMEOUT"}', message: 'timeout' };
+const result = { error: '{"error":"TIMEOUT"}', message: 'Hetero agent device dispatch failed' };
+
+beforeEach(() => {
+ vi.clearAllMocks();
+});
+
+describe('confirmTimedOutDispatch', () => {
+ it('keeps a run whose CLI started after the ack timed out', async () => {
+ // The device spawned the CLI and its first batch refreshed the row.
+ mocks.settleUnconfirmedRunning.mockResolvedValue(false);
+ const wait = vi.fn().mockResolvedValue(undefined);
+
+ await expect(
+ confirmTimedOutDispatch(deps, run, { dispatchedAt, finalize, result, wait }),
+ ).resolves.toBe('confirmed');
+
+ expect(wait).toHaveBeenCalledWith(HETERO_DISPATCH_CONFIRM_WINDOW_MS);
+ expect(mocks.settleUnconfirmedRunning).toHaveBeenCalledWith('op-1', dispatchedAt);
+ expect(mocks.failHeteroDispatch).not.toHaveBeenCalled();
+ });
+
+ it('fails a run that never showed up with the original timeout', async () => {
+ mocks.settleUnconfirmedRunning.mockResolvedValue(true);
+ const wait = vi.fn().mockResolvedValue(undefined);
+
+ await expect(
+ confirmTimedOutDispatch(deps, run, { dispatchedAt, finalize, result, wait }),
+ ).resolves.toBe('failed');
+
+ expect(mocks.failHeteroDispatch).toHaveBeenCalledWith(deps, run, finalize, result);
+ });
+
+ it('claims the run only after the confirmation window', async () => {
+ let release!: () => void;
+ const wait = vi.fn(() => new Promise<void>((resolve) => (release = resolve)));
+ mocks.settleUnconfirmedRunning.mockResolvedValue(true);
+
+ const pending = confirmTimedOutDispatch(deps, run, { dispatchedAt, finalize, result, wait });
+ await Promise.resolve();
+ expect(mocks.settleUnconfirmedRunning).not.toHaveBeenCalled();
+
+ release();
+ await pending;
+ expect(mocks.settleUnconfirmedRunning).toHaveBeenCalledTimes(1);
+ });
+});
diff --git a/apps/server/src/services/aiAgent/pipeline/heteroDispatch/timeoutConfirmation.ts b/apps/server/src/services/aiAgent/pipeline/heteroDispatch/timeoutConfirmation.ts
new file mode 100644
index 00000000000..3f164a458ea
--- /dev/null
+++ b/apps/server/src/services/aiAgent/pipeline/heteroDispatch/timeoutConfirmation.ts
@@ -0,0 +1,69 @@
+import debug from 'debug';
+
+import { AgentOperationModel } from '@/database/models/agentOperation';
+import { afterUnscoped } from '@/server/utils/scheduleAfterResponse';
+
+import type { HeteroDispatchDeps, HeteroRun } from './types';
+import { failHeteroDispatch } from './utils';
+
+const log = debug('lobe-server:ai-agent-service');
+
+/**
+ * How long a run whose device ack timed out may stay unconfirmed before it is
+ * settled as the timeout. A device that did receive the request spawns the CLI
+ * and lands its first `heteroIngest` well inside this window.
+ */
+export const HETERO_DISPATCH_CONFIRM_WINDOW_MS = 60_000;
+
+type FailParams = Parameters<typeof failHeteroDispatch>;
+
+const sleep = (ms: number) => new Promise<void>((resolve) => setTimeout(resolve, ms));
+
+/**
+ * Settle a timed-out dispatch only if the run never showed up.
+ *
+ * A device ack timeout does not mean nothing ran: the request may have reached
+ * the device over a slow socket, with the ack lost behind it. Failing the run
+ * right away settles a CLI that is already starting β€” its first batch is then
+ * refused as `operation-not-running` and the whole turn is thrown away. So the
+ * run stays `running` and this waits for the first ingest; only a run nothing
+ * touched since dispatch is failed, through the same funnel an immediate
+ * dispatch failure uses.
+ */
+export const confirmTimedOutDispatch = async (
+ deps: HeteroDispatchDeps,
+ run: HeteroRun,
+ params: {
+ dispatchedAt: Date;
+ finalize: FailParams[2];
+ result: FailParams[3];
+ wait?: (ms: number) => Promise<void>;
+ },
+): Promise<'confirmed' | 'failed'> => {
+ const { dispatchedAt, finalize, result, wait = sleep } = params;
+
+ await wait(HETERO_DISPATCH_CONFIRM_WINDOW_MS);
+
+ const settled = await new AgentOperationModel(
+ deps.db,
+ deps.userId,
+ deps.workspaceId,
+ ).settleUnconfirmedRunning(run.operationId, dispatchedAt);
+ if (!settled) {
+ log('confirmTimedOutDispatch: op=%s started or settled, keeping it', run.operationId);
+ return 'confirmed';
+ }
+
+ log('confirmTimedOutDispatch: op=%s never started, failing as timeout', run.operationId);
+ await failHeteroDispatch(deps, run, finalize, result);
+ return 'failed';
+};
+
+/** Run {@link confirmTimedOutDispatch} after the response, off any step's clock. */
+export const scheduleTimedOutDispatchConfirmation = (
+ deps: HeteroDispatchDeps,
+ run: HeteroRun,
+ params: Parameters<typeof confirmTimedOutDispatch>[2],
+): void => {
+ afterUnscoped(() => confirmTimedOutDispatch(deps, run, params));
+};
diff --git a/packages/database/src/models/__tests__/agentOperation.recovery.test.ts b/packages/database/src/models/__tests__/agentOperation.recovery.test.ts
index 46ee1ce6f59..911485c97b0 100644
--- a/packages/database/src/models/__tests__/agentOperation.recovery.test.ts
+++ b/packages/database/src/models/__tests__/agentOperation.recovery.test.ts
@@ -271,4 +271,56 @@ describe('AgentOperationModel recovery lookups', () => {
});
});
});
+
+ describe('settleUnconfirmedRunning', () => {
+ const startBefore = async (operationId: string, dispatchedAt: Date) => {
+ await model().recordStart({ operationId });
+ await serverDB
+ .update(agentOperations)
+ .set({ updatedAt: new Date(dispatchedAt.getTime() - 1000) })
+ .where(eq(agentOperations.id, operationId));
+ };
+
+ it('fails a run nothing has touched since dispatch', async () => {
+ const dispatchedAt = new Date(Date.now() - 60_000);
+ await startBefore('op-unconfirmed', dispatchedAt);
+
+ expect(
+ await model(otherUserId).settleUnconfirmedRunning('op-unconfirmed', dispatchedAt),
+ ).toBe(false);
+ expect(await model().settleUnconfirmedRunning('op-unconfirmed', dispatchedAt)).toBe(true);
+ expect(await model().findById('op-unconfirmed')).toMatchObject({
+ completionReason: 'error',
+ status: 'error',
+ });
+ // The completion lifecycle then persists onto the same status.
+ expect(
+ await model().recordCompletion('op-unconfirmed', {
+ completionReason: 'error',
+ status: 'error',
+ }),
+ ).toBe(true);
+ });
+
+ it('leaves a run alone once an ingest refreshed it after dispatch', async () => {
+ const dispatchedAt = new Date(Date.now() - 60_000);
+ await startBefore('op-confirmed', dispatchedAt);
+ await model().touchRunning('op-confirmed');
+
+ expect(await model().settleUnconfirmedRunning('op-confirmed', dispatchedAt)).toBe(false);
+ expect((await model().findById('op-confirmed'))?.status).toBe('running');
+ });
+
+ it('never rewrites a settled run', async () => {
+ const dispatchedAt = new Date(Date.now() - 60_000);
+ await startBefore('op-finished', dispatchedAt);
+ await serverDB
+ .update(agentOperations)
+ .set({ status: 'done', updatedAt: new Date(dispatchedAt.getTime() - 1000) })
+ .where(eq(agentOperations.id, 'op-finished'));
+
+ expect(await model().settleUnconfirmedRunning('op-finished', dispatchedAt)).toBe(false);
+ expect((await model().findById('op-finished'))?.status).toBe('done');
+ });
+ });
});
diff --git a/packages/database/src/models/agentOperation.ts b/packages/database/src/models/agentOperation.ts
index c555570c082..59fda41bf79 100644
--- a/packages/database/src/models/agentOperation.ts
+++ b/packages/database/src/models/agentOperation.ts
@@ -519,6 +519,29 @@ export class AgentOperationModel {
return Boolean(row);
}
+ /**
+ * Fail a run whose dispatch was never confirmed: nothing has touched the row
+ * since `dispatchedAt`. The first `heteroIngest` refreshes `updatedAt`, so a run
+ * that did start wins the race and this returns false. Settles to `error` so the
+ * caller's completion lifecycle persists onto the same status.
+ */
+ async settleUnconfirmedRunning(operationId: string, dispatchedAt: Date): Promise<boolean> {
+ const [row] = await this.db
+ .update(agentOperations)
+ .set({ completedAt: new Date(), completionReason: 'error', status: 'error' })
+ .where(
+ and(
+ eq(agentOperations.id, operationId),
+ eq(agentOperations.status, 'running'),
+ sql`${agentOperations.updatedAt} <= ${dispatchedAt}`,
+ this.ownership(),
+ ),
+ )
+ .returning({ id: agentOperations.id });
+
+ return Boolean(row);
+ }
+
/**
* Atomically retire an operation whose liveness lease has expired. A concurrent
* heartbeat wins by moving updatedAt past staleBefore, preventing false recovery.
diff --git a/src/store/chat/slices/agentRun/actions/__tests__/gateway.externalProducerSettle.test.ts b/src/store/chat/slices/agentRun/actions/__tests__/gateway.externalProducerSettle.test.ts
new file mode 100644
index 00000000000..e26cb6464bd
--- /dev/null
+++ b/src/store/chat/slices/agentRun/actions/__tests__/gateway.externalProducerSettle.test.ts
@@ -0,0 +1,386 @@
+import { afterEach, describe, expect, it, vi } from 'vitest';
+
+import type * as ConstVersion from '@/const/version';
+import { aiAgentService, type ExecAgentResult } from '@/services/aiAgent';
+import { topicService } from '@/services/topic';
+
+import type { GatewayConnection } from '../transports/gateway/gateway';
+import { GatewayActionImpl } from '../transports/gateway/gateway';
+
+const reclaimServerQueuedMessages = vi.hoisted(() => vi.fn().mockResolvedValue(undefined));
+vi.mock('../transports/gateway/serverSteerQueue', () => ({
+ restoreServerQueuedMessages: vi.fn(),
+ reclaimServerQueuedMessages,
+ withdrawQueuedMessage: vi.fn(),
+}));
+
+vi.mock('@/services/aiAgent', () => ({
+ aiAgentService: {
+ execAgentTask: vi.fn(),
+ interruptTask: vi.fn(),
+ refreshGatewayToken: vi.fn(),
+ },
+}));
+
+vi.mock('@/services/shareChat', () => ({
+ shareChatService: {
+ execAgentTask: vi.fn(),
+ getTopics: vi.fn().mockResolvedValue([]),
+ interruptTask: vi.fn(),
+ refreshGatewayToken: vi.fn(),
+ },
+}));
+
+vi.mock('@/services/message', () => ({
+ messageService: {
+ getMessages: vi.fn().mockResolvedValue([]),
+ },
+}));
+
+vi.mock('@/services/topic', () => ({
+ topicService: {
+ // Defaults to "no detail readable" so the silent-end reconcile stays
+ // fail-safe unless a test opts in by returning a row.
+ getTopicDetail: vi.fn().mockResolvedValue(null),
+ settleRunningOperation: vi.fn().mockResolvedValue(undefined),
+ updateTopicMetadata: vi.fn().mockResolvedValue(undefined),
+ },
+}));
+
+const moveChatContextSelections = vi.hoisted(() => vi.fn());
+vi.mock('@/store/file/store', () => ({
+ getFileStoreState: () => ({ moveChatContextSelections }),
+}));
+
+const mockUserDefaultConfig = vi.hoisted(() => ({
+ disableGatewayMode: undefined as boolean | undefined,
+}));
+const mockToolInterventionConfig = vi.hoisted(() => ({
+ allowList: [] as string[],
+ approvalMode: 'manual' as 'allow-list' | 'auto-run' | 'manual',
+}));
+const mockUserState = vi.hoisted(() => ({
+ profile: { id: 'user-1' },
+ workspaceUserPreference: { agentDeviceOverrides: {} as Record<string, any> },
+}));
+
+vi.mock('@/store/user', () => ({
+ useUserStore: {
+ getState: vi.fn(() => mockUserState),
+ },
+}));
+
+vi.mock('@/store/user/selectors', () => ({
+ // Lab flag off: this suite pins the v1 per-operation socket path.
+ labPreferSelectors: { enableGatewayMux: () => false },
+ settingsSelectors: {
+ defaultAgentConfig: () => ({
+ chatConfig: { disableGatewayMode: mockUserDefaultConfig.disableGatewayMode },
+ }),
+ },
+ toolInterventionSelectors: {
+ allowList: () => mockToolInterventionConfig.allowList,
+ approvalMode: () => mockToolInterventionConfig.approvalMode,
+ },
+ userProfileSelectors: {
+ userId: (state: typeof mockUserState) => state.profile.id,
+ },
+}));
+
+// ─── Local-device activation (本机) test seams ───
+// Controlled per-test; default off so the rest of the suite runs as web (no
+// device resolution, no electron IPC).
+const mockEnv = vi.hoisted(() => ({ isDesktop: false }));
+const mockGateway = vi.hoisted(() => ({ getDeviceInfo: vi.fn() }));
+// Effective runtime mode === 'local' (what isLocalSystemEnabledById returns)
+// and chat mode (what isChatModeById returns).
+const mockRuntime = vi.hoisted(() => ({ isChatMode: false, isLocal: false }));
+const mockAgentStore = vi.hoisted(() => ({
+ state: { activeAgentId: undefined, agentMap: {} } as any,
+}));
+
+vi.mock('@/const/version', async (importOriginal) => {
+ const actual = await importOriginal<typeof ConstVersion>();
+ return {
+ ...actual,
+ get isDesktop() {
+ return mockEnv.isDesktop;
+ },
+ };
+});
+
+vi.mock('@/services/electron/gatewayConnection', () => ({
+ gatewayConnectionService: { getDeviceInfo: mockGateway.getDeviceInfo },
+}));
+
+vi.mock('@/store/agent', () => ({ getAgentStoreState: () => mockAgentStore.state }));
+
+vi.mock('@/store/agent/selectors', () => ({
+ agentByIdSelectors: {
+ getAgencyConfigById: (agentId: string) => (state: any) =>
+ state.agentMap?.[agentId]?.agencyConfig,
+ getAgentById: (agentId: string) => (state: any) => state.agentMap?.[agentId],
+ },
+ agentSelectors: { currentAgentWorkingDirectory: () => () => undefined },
+ chatConfigByIdSelectors: {
+ getChatConfigById: (agentId: string) => (state: any) =>
+ state.agentMap?.[agentId]?.chatConfig ?? {},
+ isChatModeById: () => () => mockRuntime.isChatMode,
+ isLocalSystemEnabledById: () => () => mockRuntime.isLocal,
+ },
+}));
+
+function createMockClient(): GatewayConnection['client'] & {
+ emitEvent: (event: string, ...args: any[]) => void;
+} {
+ const listeners = new Map<string, Set<(...args: any[]) => void>>();
+
+ return {
+ connect: vi.fn(),
+ disconnect: vi.fn(),
+ emitEvent(event: string, ...args: any[]) {
+ listeners.get(event)?.forEach((listener) => listener(...args));
+ },
+ on: vi.fn((event: string, listener: (...args: any[]) => void) => {
+ let set = listeners.get(event);
+ if (!set) {
+ set = new Set();
+ listeners.set(event, set);
+ }
+ set.add(listener);
+ }),
+ reconnect: vi.fn(async () => {}),
+ sendToolResult: vi.fn(() => true),
+ updateToken: vi.fn(),
+ };
+}
+
+afterEach(() => {
+ vi.clearAllMocks();
+ delete (globalThis as any).window;
+});
+
+/**
+ * Start a Claude Code run whose topic row is optimistically `running`, then end
+ * its session without the run's own terminal frame β€” the shape a run takes when
+ * the server failed its device dispatch before the CLI wrote anything.
+ */
+const endExternalRunWithoutTerminal = async (activeTopicId = 'topic-1') => {
+ const connectToGateway = vi.fn();
+ const completeOperation = vi.fn();
+ const internalDispatchTopic = vi.fn();
+ const internalPinTopicStatus = vi.fn();
+ const state: Record<string, any> = {
+ activeAgentId: 'agent-1',
+ activeTopicId,
+ gatewayConnections: {},
+ operations: {},
+ topicDataMap: {
+ 'agent_agent-1': {
+ items: [
+ {
+ id: 'topic-1',
+ metadata: {
+ runningOperation: { assistantMessageId: 'ast-1', operationId: 'server-op' },
+ },
+ status: 'running',
+ },
+ ],
+ },
+ },
+ };
+ const set = vi.fn((updater: any) => {
+ Object.assign(state, typeof updater === 'function' ? updater(state) : updater);
+ });
+ const get = vi.fn(() => ({
+ ...state,
+ associateMessageWithOperation: vi.fn(),
+ completeOperation,
+ connectToGateway,
+ internal_dispatchTopic: internalDispatchTopic,
+ internal_pinTopicStatus: internalPinTopicStatus,
+ moveQueuedMessages: vi.fn(),
+ moveVoiceMessages: vi.fn(),
+ onOperationCancel: vi.fn(),
+ refreshTopicDetail: vi.fn().mockResolvedValue(undefined),
+ startOperation: vi.fn(() => ({ operationId: 'gw-op' })),
+ updateTopicStatus: vi.fn(),
+ })) as any;
+
+ (globalThis as any).window = {
+ global_serverConfigStore: {
+ getState: () => ({ serverConfig: { agentGatewayUrl: 'https://gateway.test.com' } }),
+ },
+ };
+
+ const action = new GatewayActionImpl(set as any, get, undefined);
+ action.createClient = vi.fn(() => createMockClient());
+ vi.mocked(aiAgentService.execAgentTask).mockResolvedValue({
+ ...serverResult,
+ heteroType: 'claude-code',
+ });
+
+ await action.executeGatewayAgent({ context, message: 'Hello' });
+
+ const { onSessionComplete } = connectToGateway.mock.calls[0][0];
+ internalDispatchTopic.mockClear();
+ internalPinTopicStatus.mockClear();
+ onSessionComplete({
+ authFailed: false,
+ completion: { source: 'resume_status', status: 'error' },
+ succeeded: false,
+ terminalReceived: false,
+ });
+ // Let the server read and the local retire settle.
+ await new Promise((resolve) => setTimeout(resolve, 0));
+
+ return { completeOperation, internalDispatchTopic, internalPinTopicStatus };
+};
+
+const context = { agentId: 'agent-1', scope: 'main' as const, threadId: null, topicId: 'topic-1' };
+
+const serverResult: ExecAgentResult = {
+ agentId: 'agent-1',
+ assistantMessageId: 'ast-1',
+ autoStarted: true,
+ createdAt: new Date().toISOString(),
+ message: 'ok',
+ operationId: 'server-op',
+ status: 'created',
+ success: true,
+ timestamp: new Date().toISOString(),
+ token: 'test-token',
+ topicId: 'topic-1',
+ userMessageId: 'usr-1',
+};
+
+describe('external producer session ending without its terminal', () => {
+ it('retires the local running row once the server no longer backs the run', async () => {
+ vi.mocked(topicService.getTopicDetail).mockResolvedValue({
+ id: 'topic-1',
+ metadata: { lastSettledOperationId: 'server-op', runningOperation: null },
+ status: 'active',
+ } as any);
+
+ const run = await endExternalRunWithoutTerminal();
+
+ expect(run.completeOperation).toHaveBeenCalledWith('gw-op');
+ // The row stops spinning…
+ expect(run.internalPinTopicStatus).toHaveBeenCalledWith(
+ expect.objectContaining({ status: 'active', topicId: 'topic-1' }),
+ );
+ expect(run.internalDispatchTopic).toHaveBeenCalledWith(
+ expect.objectContaining({
+ id: 'topic-1',
+ value: { metadata: expect.objectContaining({ runningOperation: null }) },
+ }),
+ );
+ // …without the transport settling a producer it cannot see.
+ expect(topicService.settleRunningOperation).not.toHaveBeenCalled();
+ });
+
+ it("mirrors the server's terminal status for a topic the user is not watching", async () => {
+ vi.mocked(topicService.getTopicDetail).mockResolvedValue({
+ id: 'topic-1',
+ metadata: {},
+ status: 'unread',
+ } as any);
+
+ const run = await endExternalRunWithoutTerminal('another-topic');
+
+ expect(run.internalPinTopicStatus).toHaveBeenCalledWith(
+ expect.objectContaining({ status: 'unread', topicId: 'topic-1' }),
+ );
+ });
+
+ it('keeps the row running while the server still backs the CLI', async () => {
+ vi.mocked(topicService.getTopicDetail).mockResolvedValue({
+ id: 'topic-1',
+ metadata: { runningOperation: { operationId: 'server-op' } },
+ status: 'running',
+ } as any);
+
+ const run = await endExternalRunWithoutTerminal();
+
+ expect(run.internalPinTopicStatus).not.toHaveBeenCalled();
+ expect(run.internalDispatchTopic).not.toHaveBeenCalled();
+ expect(topicService.settleRunningOperation).not.toHaveBeenCalled();
+ });
+
+ it('keeps the row running when the server row cannot be read', async () => {
+ vi.mocked(topicService.getTopicDetail).mockRejectedValue(new Error('offline'));
+ vi.spyOn(console, 'error').mockImplementation(() => {});
+
+ const run = await endExternalRunWithoutTerminal();
+
+ expect(run.internalPinTopicStatus).not.toHaveBeenCalled();
+ expect(run.internalDispatchTopic).not.toHaveBeenCalled();
+ });
+});
+
+describe('a run the server failed at dispatch', () => {
+ it('never marks the topic running or opens a gateway socket', async () => {
+ const connectToGateway = vi.fn();
+ const completeOperation = vi.fn();
+ const updateTopicStatus = vi.fn();
+ const replaceMessages = vi.fn();
+ const state: Record<string, any> = {
+ activeAgentId: 'agent-1',
+ activeTopicId: 'topic-1',
+ gatewayConnections: {},
+ operations: {},
+ topicDataMap: {},
+ };
+ const set = vi.fn((updater: any) => {
+ Object.assign(state, typeof updater === 'function' ? updater(state) : updater);
+ });
+ const get = vi.fn(() => ({
+ ...state,
+ associateMessageWithOperation: vi.fn(),
+ completeOperation,
+ connectToGateway,
+ getOperationAbortSignal: vi.fn(() => new AbortController().signal),
+ internal_dispatchTopic: vi.fn(),
+ internal_pinTopicStatus: vi.fn(),
+ moveQueuedMessages: vi.fn(),
+ moveVoiceMessages: vi.fn(),
+ onOperationCancel: vi.fn(),
+ replaceMessages,
+ startOperation: vi.fn(() => ({ operationId: 'gw-op' })),
+ updateTopicStatus,
+ })) as any;
+ (globalThis as any).window = {
+ global_serverConfigStore: {
+ getState: () => ({ serverConfig: { agentGatewayUrl: 'https://gateway.test.com' } }),
+ },
+ };
+
+ const action = new GatewayActionImpl(set as any, get, undefined);
+ action.createClient = vi.fn(() => createMockClient());
+ // A device dispatch the server refused: it already wrote the error bubble and
+ // settled the topic before answering, and there is no gateway token.
+ vi.mocked(aiAgentService.execAgentTask).mockResolvedValue({
+ ...serverResult,
+ autoStarted: false,
+ error: 'DEVICE_OFFLINE',
+ heteroType: 'claude-code',
+ status: 'error',
+ success: false,
+ token: undefined,
+ } as any);
+
+ await action.executeGatewayAgent({
+ context,
+ message: 'Hello',
+ parentOperationId: 'send-op',
+ } as any);
+
+ expect(updateTopicStatus).not.toHaveBeenCalledWith(
+ expect.objectContaining({ status: 'running' }),
+ );
+ expect(connectToGateway).not.toHaveBeenCalled();
+ expect(completeOperation).toHaveBeenCalledWith('send-op');
+ // The server's error bubble is pulled in, since no stream will deliver it.
+ expect(replaceMessages).toHaveBeenCalled();
+ });
+});
diff --git a/src/store/chat/slices/agentRun/actions/transports/gateway/externalProducerSettle.ts b/src/store/chat/slices/agentRun/actions/transports/gateway/externalProducerSettle.ts
new file mode 100644
index 00000000000..f702a400c3d
--- /dev/null
+++ b/src/store/chat/slices/agentRun/actions/transports/gateway/externalProducerSettle.ts
@@ -0,0 +1,41 @@
+import type { ChatTopic, ChatTopicStatus } from '@lobechat/types';
+
+import { isInterventionRunActive } from '@/store/chat/utils/interventionSync';
+
+/**
+ * Retire the local `running` row of an external hetero run whose session ended
+ * without its terminal frame β€” but only once the server no longer backs any run
+ * on the topic.
+ *
+ * The gateway transport never settles such a run itself (the CLI may still be
+ * producing), and it completes the local operation, so nothing else is left to
+ * retire the row: the stale-run sweep only considers topics that still have a
+ * running local operation. A run whose dispatch the server failed before the
+ * CLI ever wrote ends exactly like this, and kept the sidebar spinning over a
+ * failed turn until a topic-list refetch.
+ *
+ * Never settles anything server-side, and an unreadable row is not evidence the
+ * run ended. Mirrors the server's own terminal status unless the user is
+ * watching, which pins `active` like the terminal-frame path.
+ *
+ * Returns whether the local row was retired.
+ */
+export const retireLocalRowIfServerSettled = async (params: {
+ clear: (status: ChatTopicStatus) => void;
+ isViewing: () => boolean;
+ readTopic: () => Promise<ChatTopic | null | undefined>;
+}): Promise<boolean> => {
+ const { clear, isViewing, readTopic } = params;
+
+ let topic: ChatTopic | null | undefined;
+ try {
+ topic = await readTopic();
+ } catch (error) {
+ console.error('[Gateway] External producer topic read failed:', error);
+ return false;
+ }
+ if (!topic || isInterventionRunActive(topic)) return false;
+
+ clear(isViewing() ? 'active' : (topic.status ?? 'active'));
+ return true;
+};
diff --git a/src/store/chat/slices/agentRun/actions/transports/gateway/gateway.ts b/src/store/chat/slices/agentRun/actions/transports/gateway/gateway.ts
index 67d210e1fe7..683b0ab2670 100644
--- a/src/store/chat/slices/agentRun/actions/transports/gateway/gateway.ts
+++ b/src/store/chat/slices/agentRun/actions/transports/gateway/gateway.ts
@@ -71,6 +71,7 @@ import {
resolveDesktopDeviceHints,
resolveUserInterventionConfig,
} from './execRequest';
+import { retireLocalRowIfServerSettled } from './externalProducerSettle';
import { createGatewayEventBuffer } from './gatewayEventBuffer';
import { createGatewayEventHandler } from './gatewayEventHandler';
import { createGatewayEventRouter } from './gatewayEventRouter';
@@ -1336,7 +1337,10 @@ export class GatewayActionImpl {
}
}
- if (!isCreateNewTopic && cancelledAfterPersistence) {
+ // A run the server failed at dispatch is already settled and has no token;
+ // treating it as started wrote `running` back over that settlement.
+ const failedBeforeStart = result.success === false && result.status === 'error';
+ if (!isCreateNewTopic && (cancelledAfterPersistence || failedBeforeStart)) {
try {
const messages = await messageService.getMessages(resolvedMessageContext);
this.#get().replaceMessages(messages, { context: resolvedMessageContext });
@@ -1421,11 +1425,10 @@ export class GatewayActionImpl {
);
cancelledAfterPersistence = interruptIfCancelledAfterPersistence() || cancelledAfterPersistence;
- if (cancelledAfterPersistence) {
- // This path never opens a socket, so no terminal frame will ever retire
- // the topic row. Settle it once the stop is confirmed AND the sidebar
- // refetch has landed: settling first would find no marker to clear, and
- // the refetch would then install a `running` row nobody retires.
+ if (cancelledAfterPersistence || failedBeforeStart) {
+ // No socket opens here, so no terminal frame retires the row. A stop settles
+ // once confirmed AND the sidebar refetch landed: settling first finds no
+ // marker, and the refetch would reinstall a `running` row nobody retires.
const { topicId } = result;
if (lateInterruptConfirmed && topicId) {
void Promise.all([lateInterruptConfirmed, topicRefresh]).then(([confirmed]) => {
@@ -1442,10 +1445,9 @@ export class GatewayActionImpl {
return result;
}
- // `updateTopicStatus` persists through the owner-scoped `topic.updateTopic`
- // procedure, which a share visitor is never authorized to call β€” firing it
- // would only produce a rejected request (and a pinned optimistic write that
- // no owner topic list ever consumes).
+ // `updateTopicStatus` persists through the owner-scoped `topic.updateTopic`,
+ // which a share visitor may never call β€” it would only be rejected (and pin
+ // an optimistic write that no owner topic list ever consumes).
if (result.topicId && !agentShareId) {
void this.#get().updateTopicStatus?.({
agentId: messageContext.agentId,
@@ -1624,22 +1626,22 @@ export class GatewayActionImpl {
if (!terminalReceived) this.#get().completeOperation(gatewayOpId);
// An external hetero producer does not run on this socket: the CLI
- // streams through `heteroIngest` and ends the run through
- // `heteroFinish`, so nothing the transport observes proves it stopped.
- // A terminal resume status can mean the Gateway simply has no
- // initialized DO session; a raw `session_complete` or a terminal
- // `status_change` can arrive for a run that is still producing; and on
- // the multiplexed socket ONE auth failure is fanned out to every
- // operation on the tab. Settling on any of those clears
- // `topic.metadata.runningOperation`, after which the server discards
- // every later batch as stale β€” the CLI keeps burning tokens and its
- // whole output is thrown away. Only an in-band terminal for THIS op
- // (`terminalReceived`) is authoritative; otherwise leave the settle to
- // the server, which owns `heteroFinish` and the liveness lease behind
- // it. Preserve unknown (`undefined`) during rolling deploys too; new
- // normal runtimes explicitly return `heteroType: null`.
- const preserveExternalProducer = !terminalReceived && result.heteroType !== null;
- if (preserveExternalProducer) return;
+ // streams through `heteroIngest` and ends through `heteroFinish`, so no
+ // transport signal proves it stopped β€” a terminal resume status (no DO
+ // session yet), a raw `session_complete` / terminal `status_change` for
+ // a run still producing, or ONE auth failure fanned out across the mux.
+ // Settling on those clears `runningOperation`, and the server then
+ // discards every later batch as stale. Only an in-band terminal for THIS
+ // op is authoritative; otherwise the server owns the settle, and the
+ // local row only follows once the server proves the run over. Unknown
+ // (`undefined`, rolling deploys) is preserved; normal runs send `null`.
+ if (!terminalReceived && result.heteroType !== null) {
+ const { agentId, groupId } = resolvedMessageContext;
+ const { operationId, topicId } = result;
+ if (topicId && !agentShareId)
+ this.#retireExternalRow({ agentId, groupId, operationId, topicId });
+ return;
+ }
const effectiveSucceeded = isSuccessfulGatewayCompletion({
authFailed,
@@ -1996,16 +1998,11 @@ export class GatewayActionImpl {
// the preserved external producer case below) must close it here.
if (!terminalReceived) this.#get().completeOperation(gatewayOpId);
- // A reconnect is passive, and an external producer's output never
- // travelled over this socket in the first place β€” see the same guard in
- // `executeGatewayAgent`. No transport signal (terminal resume status,
- // raw `session_complete`, terminal `status_change`, or an auth failure
- // fanned out across the multiplexed socket) proves such a run ended, and
- // settling on one discards everything it produces afterwards. New normal
- // runtime markers carry `heteroType: null`; old markers omit the field,
- // so the rolling-deploy fallback is deliberately fail-safe.
- const preserveExternalProducer = !terminalReceived && heteroType !== null;
- if (preserveExternalProducer) {
+ // An external producer never streamed over this socket: no transport
+ // signal proves it ended β€” see the same guard in `executeGatewayAgent`.
+ if (!terminalReceived && heteroType !== null) {
+ const { agentId } = context;
+ if (!agentShareId) this.#retireExternalRow({ agentId, operationId, topicId });
return;
}
@@ -2020,21 +2017,11 @@ export class GatewayActionImpl {
// terminal status inside the topic row lock, comparing the operation id
// so a late close from another tab cannot settle a newer run.
//
- // This was hand-rolled here as two independent fire-and-forget writes: an
- // UNCONDITIONAL `updateTopicMetadata({ runningOperation: null })` plus an
- // `updateTopicStatus('active')` that was SKIPPED whenever the run finished
- // cleanly while the user was on another topic. That case delegated the
- // status write to `markTopicUnread` β€” a separate call, on a separate
- // guard β€” and when it did not land the topic stayed `running` forever:
- // the marker was already gone, so every later `settleRunningOperation`
- // returned `missing` and nothing on the server could repair it. Observed
- // on a self-hosted deployment as 7 topics stuck `running` whose
- // `metadata.runningOperation` was present-and-JSON-null (the signature of
- // that unconditional clear) with their operation rows already terminal.
- //
- // Reconnect is the path a page refresh takes, which is why the symptom
- // was always "still spinning after a reload" β€” refreshing is what moved
- // the run off the primary path and onto this one.
+ // It used to be two independent writes: an unconditional marker clear
+ // plus an `active` status write skipped for an unwatched clean finish,
+ // left to `markTopicUnread`. When that did not land the topic stayed
+ // `running` forever with no marker left for any settle to match (seen
+ // self-hosted: 7 topics stuck after a reload, the path this one serves).
const viewing = this.#get().activeTopicId === topicId;
// Share visitors cannot settle the creator-owned topic row (the topic
// router is owner-scoped) β€” the local clear below still runs. Same
@@ -2578,6 +2565,19 @@ export class GatewayActionImpl {
.catch(console.error);
};
+ /** See {@link retireLocalRowIfServerSettled}. */
+ #retireExternalRow = (params: {
+ agentId?: string;
+ groupId?: string;
+ operationId: string;
+ topicId: string;
+ }) =>
+ void retireLocalRowIfServerSettled({
+ clear: (status) => this.clearLocalRunningOperation({ ...params, status }),
+ isViewing: () => this.#get().activeTopicId === params.topicId,
+ readTopic: () => topicService.getTopicDetail(params.topicId),
+ });
+
/**
* @returns Whether a terminal status was written without a local marker β€” the
* only case whose ownership still needs the server's confirmation (see