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): stop a sandbox spawn 504 from killing a live or finished run (#19443)

Arvin Xue1d9a716adc8
diff --git a/apps/server/src/services/aiAgent/__tests__/execAgent.heteroFiles.test.ts b/apps/server/src/services/aiAgent/__tests__/execAgent.heteroFiles.test.ts
index 42ebf732ddb..b729193062d 100644
--- a/apps/server/src/services/aiAgent/__tests__/execAgent.heteroFiles.test.ts
+++ b/apps/server/src/services/aiAgent/__tests__/execAgent.heteroFiles.test.ts
@@ -1906,4 +1906,107 @@ describe('AiAgentService.execAgent - hetero early-exit file attachments', () =>
expect(findRunningOpSeed()).toBeDefined();
});
});
+ /**
+ * A cloud-sandbox `runCommand` rejection is the ONLY dispatch failure that can
+ * land after the agent already started β€” it is issued with `background: true`
+ * but the sandbox gateway can answer `Gateway Timeout` a minute later, long
+ * after the sandbox booted and started streaming through `heteroIngest`.
+ */
+ describe('cloud sandbox spawn failure vs. a live run', () => {
+ let completeOperationSpy: MockInstance<CompletionLifecycle['completeOperation']>;
+ let findOperationSpy: MockInstance<AgentOperationModel['findById']>;
+
+ beforeEach(() => {
+ completeOperationSpy = vi
+ .spyOn(CompletionLifecycle.prototype, 'completeOperation')
+ .mockResolvedValue(undefined as any);
+ findOperationSpy = vi
+ .spyOn(AgentOperationModel.prototype, 'findById')
+ .mockResolvedValue({ status: 'running' } as any);
+ });
+
+ afterEach(() => {
+ completeOperationSpy.mockRestore();
+ findOperationSpy.mockRestore();
+ });
+
+ const errorBubbleUpdates = () => mockMessageUpdate.mock.calls.filter((call) => call[1]?.error);
+
+ it('finalizes the run when the sandbox never came up', async () => {
+ mockSpawnHeteroSandbox.mockRejectedValueOnce(new Error('Gateway Timeout'));
+
+ await service.execAgent({ agentId: 'agent-1', prompt: 'clean the worktrees' });
+
+ await vi.waitFor(() => expect(errorBubbleUpdates()).toHaveLength(1));
+ expect(errorBubbleUpdates()[0][1]).toEqual(
+ expect.objectContaining({
+ error: expect.objectContaining({
+ body: { detail: 'Gateway Timeout' },
+ message: 'Hetero sandbox spawn failed',
+ }),
+ }),
+ );
+ expect(completeOperationSpy).toHaveBeenCalledWith(
+ expect.anything(),
+ 'error',
+ expect.anything(),
+ );
+ expect(mockPublishAgentRuntimeEnd).toHaveBeenCalled();
+ });
+
+ /**
+ * ROOT CAUSE:
+ *
+ * The catch finalized on every rejection, so a gateway 504 arriving after a
+ * successful run blanked the assistant message and stamped an error bubble
+ * on a turn the user had already read.
+ */
+ it('leaves a run that already finished alone', async () => {
+ findOperationSpy.mockResolvedValue({ status: 'done' } as any);
+ mockSpawnHeteroSandbox.mockRejectedValueOnce(new Error('Gateway Timeout'));
+
+ await service.execAgent({ agentId: 'agent-1', prompt: 'clean the worktrees' });
+
+ await vi.waitFor(() => expect(findOperationSpy).toHaveBeenCalled());
+ expect(errorBubbleUpdates()).toHaveLength(0);
+ expect(completeOperationSpy).not.toHaveBeenCalled();
+ expect(mockPublishAgentRuntimeEnd).not.toHaveBeenCalled();
+ });
+
+ /**
+ * ROOT CAUSE:
+ *
+ * Same 504, but arriving mid-run: finalizing closed the UI stream and marked
+ * the op failed while the sandbox was still producing output, so the
+ * conversation stopped dead at the moment the 504 landed.
+ */
+ it('leaves a run that is still ingesting turns alone', async () => {
+ mockSpawnHeteroSandbox.mockImplementationOnce(async ({ operationId }: any) => {
+ // The sandbox is alive and has already persisted an assistant turn.
+ topicMock.findById.mockResolvedValue({
+ metadata: { heteroCurrentMsgId: { msgId: 'msg-live', operationId } },
+ });
+ throw new Error('Gateway Timeout');
+ });
+
+ await service.execAgent({ agentId: 'agent-1', prompt: 'clean the worktrees' });
+
+ await vi.waitFor(() => expect(topicMock.findById).toHaveBeenCalled());
+ expect(errorBubbleUpdates()).toHaveLength(0);
+ expect(completeOperationSpy).not.toHaveBeenCalled();
+ expect(mockPublishAgentRuntimeEnd).not.toHaveBeenCalled();
+ });
+
+ it('still finalizes when the topic pointer names a different operation', async () => {
+ topicMock.findById.mockResolvedValue({
+ metadata: { heteroCurrentMsgId: { msgId: 'msg-old', operationId: 'op-previous-turn' } },
+ });
+ mockSpawnHeteroSandbox.mockRejectedValueOnce(new Error('Gateway Timeout'));
+
+ await service.execAgent({ agentId: 'agent-1', prompt: 'clean the worktrees' });
+
+ await vi.waitFor(() => expect(errorBubbleUpdates()).toHaveLength(1));
+ expect(completeOperationSpy).toHaveBeenCalled();
+ });
+ });
});
diff --git a/apps/server/src/services/aiAgent/pipeline/heteroDispatch.ts b/apps/server/src/services/aiAgent/pipeline/heteroDispatch.ts
index 9dca4f82375..c6ae43f1a89 100644
--- a/apps/server/src/services/aiAgent/pipeline/heteroDispatch.ts
+++ b/apps/server/src/services/aiAgent/pipeline/heteroDispatch.ts
@@ -24,6 +24,7 @@ import {
import { nanoid } from '@lobechat/utils';
import debug from 'debug';
+import { AgentOperationModel } from '@/database/models/agentOperation';
import { DeviceModel } from '@/database/models/device';
import type { MessageModel } from '@/database/models/message';
import type { TopicModel } from '@/database/models/topic';
@@ -174,6 +175,78 @@ const finalizeHeteroDispatchError = async (
}
};
+/**
+ * Liveness probe for the ONE dispatch failure that races a live run: the cloud
+ * sandbox `runCommand` call (see the `spawnHeteroSandbox` catch below). Every
+ * other `finalizeHeteroDispatchError` caller rejects synchronously, before any
+ * agent process can exist, so none of them needs this.
+ *
+ * `runCommand` is issued with `background: true` and is supposed to return as
+ * soon as the command is handed to the sandbox β€” but the sandbox gateway can
+ * sit on the connection and answer `Gateway Timeout` a minute or more later,
+ * long after the sandbox actually booted and started streaming events back
+ * through `heteroIngest`. Finalizing on that rejection blindly treats a
+ * transient gateway 504 as "the run never started": it blanks the assistant
+ * message, stamps an error bubble on a turn the user already read, marks the
+ * op row + its task failed, and closes the UI stream out from under a run that
+ * is still producing output.
+ *
+ * Two cheap reads tell a stranded dispatch apart from a live one:
+ *
+ * 1. `agent_operations.status` β€” anything other than `running` means the run
+ * reached `heteroFinish` (or a park) on its own. Nothing left to finalize.
+ * 2. `topics.metadata.heteroCurrentMsgId` β€” the ingest path repoints this at
+ * every assistant turn it persists, scoped by `operationId`. It naming THIS
+ * operation is proof the sandbox is alive and writing.
+ *
+ * When neither fires the sandbox really never came up and the caller finalizes
+ * as before. A run that passes this probe and then dies is not stranded: the
+ * agent-gateway inactivity watchdog still reaps it through `finalizeAbandoned`.
+ */
+const hasHeteroRunStarted = async (
+ deps: HeteroDispatchDeps,
+ params: { operationId: string; topicId: string },
+): Promise<boolean> => {
+ const { operationId, topicId } = params;
+
+ try {
+ const operation = await new AgentOperationModel(
+ deps.db,
+ deps.userId,
+ deps.workspaceId,
+ ).findById(operationId);
+
+ if (operation && operation.status !== 'running') {
+ log(
+ 'hasHeteroRunStarted: op=%s already settled (status=%s) β€” skipping spawn-failure finalize',
+ operationId,
+ operation.status,
+ );
+ return true;
+ }
+
+ const topic = await deps.topicModel.findById(topicId);
+ if (topic?.metadata?.heteroCurrentMsgId?.operationId === operationId) {
+ log(
+ 'hasHeteroRunStarted: op=%s has ingested turns β€” skipping spawn-failure finalize',
+ operationId,
+ );
+ return true;
+ }
+
+ return false;
+ } catch (err) {
+ // A probe that cannot read must not swallow a real spawn failure: fall
+ // back to the pre-existing behaviour and finalize.
+ log(
+ 'hasHeteroRunStarted: probe failed for op=%s (treating as not started): %O',
+ operationId,
+ err,
+ );
+ return false;
+ }
+};
+
export interface HeteroDispatchInput {
canManageAgent: boolean;
effectiveRequestedDeviceId?: string;
@@ -1028,6 +1101,13 @@ export const dispatchHeteroAgent = async (
// the same terminal funnel so the stranded run surfaces an error and
// its task is marked failed instead of hanging in `running`.
log('execAgent: hetero sandbox spawn failed: %O', err);
+
+ // ...unless the run is demonstrably alive or already finished. This
+ // call is the only dispatch failure that can land AFTER the agent
+ // started, so a rejection here is not by itself evidence that nothing
+ // ran β€” see `hasHeteroRunStarted`.
+ if (await hasHeteroRunStarted(deps, { operationId, topicId })) return;
+
await finalizeHeteroDispatchError(deps, {
agentId: resolvedAgentId,
assistantMessageId,