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 settling a run whose output ingest discarded as success (#19658)

Arvin Xu230b8037f1cb
diff --git a/apps/cli/src/commands/hetero.ts b/apps/cli/src/commands/hetero.ts
index 413d3f5243f..6fa470b4e7e 100644
--- a/apps/cli/src/commands/hetero.ts
+++ b/apps/cli/src/commands/hetero.ts
@@ -1121,15 +1121,19 @@ const exec = async (options: ExecOptions): Promise<void> => {
const { code, signal, sessionId } = result;
+ // Why the run failed to upload, when it did. `sawTerminalError`/stderr stay
+ // ahead of it: those explain a failing agent, while this explains an agent
+ // that worked and lost its output β€” the least obvious of the three, and the
+ // only one with no other trace in the conversation.
+ let ingestErrorMessage: string | undefined;
+
if (serverIngester && sink) {
operationHeartbeat?.stop();
try {
await serverIngester.drain();
} catch (err) {
- log.error(
- 'Failed to flush events to server:',
- err instanceof Error ? err.message : String(err),
- );
+ ingestErrorMessage = err instanceof Error ? err.message : String(err);
+ log.error('Failed to flush events to server:', ingestErrorMessage);
result = { ...result, ingestError: true };
}
}
@@ -1146,11 +1150,12 @@ const exec = async (options: ExecOptions): Promise<void> => {
// When the run failed, pass an error detail so the server surfaces a useful
// message instead of the generic "Agent execution failed" fallback. Prefer
// the in-stream terminal error (CC relays API/rate-limit errors here while
- // exiting 0, so stderr is empty); otherwise fall back to the stderr tail.
+ // exiting 0, so stderr is empty), then the upload failure (a clean agent whose
+ // output never landed leaves nothing on stderr either), then the stderr tail.
// Trim to the last 1 KB β€” the tail is most informative and keeps the tRPC
// payload small.
const stderrTail = result.stderrContent.trim();
- const errorDetail = result.terminalErrorMessage || stderrTail;
+ const errorDetail = result.terminalErrorMessage || ingestErrorMessage || stderrTail;
// The adapter's in-stream classification (overloaded / rate_limit) already
// carries the structured status-guide body β€” forward it verbatim instead of
// re-deriving from the flattened message via the process-only classifier,
diff --git a/apps/cli/src/utils/BatchIngester.test.ts b/apps/cli/src/utils/BatchIngester.test.ts
index 7685accf46f..57754421bfa 100644
--- a/apps/cli/src/utils/BatchIngester.test.ts
+++ b/apps/cli/src/utils/BatchIngester.test.ts
@@ -40,6 +40,7 @@ describe('BatchIngester', () => {
ingest: vi.fn(async (events) => {
batches.push(numbers(events));
if (batches.length === 1) await firstAck; // slow first round-trip
+ return { accepted: true };
}),
};
const ingester = new BatchIngester(sink);
@@ -97,6 +98,7 @@ describe('BatchIngester', () => {
finish: vi.fn(async () => {}),
ingest: vi.fn(async (events) => {
batches.push(numbers(events));
+ return { accepted: true };
}),
};
const ingester = new BatchIngester(sink);
@@ -115,13 +117,47 @@ describe('BatchIngester', () => {
const failedDrain = expect(ingester.drain()).rejects.toThrow('offline');
await vi.advanceTimersByTimeAsync(20_000);
await failedDrain;
- ingest.mockResolvedValue(undefined);
+ ingest.mockResolvedValue({ accepted: true });
await ingester.drain();
expect(numbers(ingest.mock.calls.at(-1)![0])).toEqual([1]);
await ingester.drain();
expect(ingest).toHaveBeenCalledTimes(7);
});
+ it('fails the stream on a refused batch instead of retrying output the server threw away', async () => {
+ // Regression: a refusal arrives as a 200 (the operation is over server-side,
+ // so the batch is discarded), which the ingester read as "delivered". The
+ // agent kept working, every later batch was discarded the same way, and the
+ // run finished reporting success on output nobody ever stored.
+ const ingest = vi
+ .fn<IngestSink['ingest']>()
+ .mockResolvedValue({ accepted: false, reason: 'stale-operation' });
+ const ingester = new BatchIngester({ finish: vi.fn(), ingest });
+
+ ingester.push(makeEvent(1));
+ const drained = expect(ingester.drain()).rejects.toThrow('stale-operation');
+ await vi.advanceTimersByTimeAsync(20_000);
+ await drained;
+
+ expect(ingest).toHaveBeenCalledTimes(1); // refusal is permanent β€” no retries
+ expect(ingester.failed).toBe(true);
+
+ // And the stream stays failed: later events are dropped rather than queued
+ // for an upload that cannot succeed.
+ ingester.push(makeEvent(2));
+ await expect(ingester.drain()).rejects.toThrow('stale-operation');
+ expect(ingest).toHaveBeenCalledTimes(1);
+ });
+
+ it('treats an ack without a verdict as accepted so older servers keep working', async () => {
+ const ingest = vi.fn<IngestSink['ingest']>().mockResolvedValue(undefined as never);
+ const ingester = new BatchIngester({ finish: vi.fn(), ingest });
+
+ ingester.push(makeEvent(1));
+ await expect(ingester.drain()).resolves.toBeUndefined();
+ expect(ingester.failed).toBe(false);
+ });
+
it('fails closed on overflow instead of dropping a prefix then uploading a gapped stream', async () => {
const sink: IngestSink = { ingest: vi.fn(), finish: vi.fn() };
const maxBytes = Buffer.byteLength(JSON.stringify(makeEvent(1)));
diff --git a/apps/cli/src/utils/BatchIngester.ts b/apps/cli/src/utils/BatchIngester.ts
index 70f0b02f506..134b638f3ef 100644
--- a/apps/cli/src/utils/BatchIngester.ts
+++ b/apps/cli/src/utils/BatchIngester.ts
@@ -1,5 +1,15 @@
import type { AgentStreamEvent } from '@lobechat/heterogeneous-agents/spawn';
+/**
+ * Server verdict on one batch. `accepted: false` means the server took the
+ * batch and threw it away β€” the operation is over on its side β€” so the events
+ * are lost for good and retrying cannot help.
+ */
+export interface IngestAck {
+ accepted: boolean;
+ reason?: string;
+}
+
export interface IngestSink {
finish: (params: {
error?: {
@@ -16,18 +26,30 @@ export interface IngestSink {
result: 'cancelled' | 'error' | 'success';
sessionId?: string;
}) => Promise<void>;
- ingest: (events: AgentStreamEvent[]) => Promise<void>;
+ ingest: (events: AgentStreamEvent[]) => Promise<IngestAck>;
}
export class NoopIngestSink implements IngestSink {
async finish(_params: Parameters<IngestSink['finish']>[0]): Promise<void> {}
- async ingest(_events: AgentStreamEvent[]): Promise<void> {}
+ async ingest(_events: AgentStreamEvent[]): Promise<IngestAck> {
+ return { accepted: true };
+ }
}
const MAX_BATCH = 50;
const FLUSH_INTERVAL_MS = 250;
const MAX_RETRIES = 5;
+/** The server acknowledged a batch and discarded it β€” see {@link IngestAck}. */
+export class IngestRejectedError extends Error {
+ constructor(readonly reason?: string) {
+ super(
+ `Server discarded the agent's output${reason ? ` (${reason})` : ''}: this run is no longer the topic's active operation, so nothing it produced was saved`,
+ );
+ this.name = 'IngestRejectedError';
+ }
+}
+
const sleep = (ms: number) => new Promise<void>((r) => setTimeout(r, ms));
/**
@@ -121,9 +143,20 @@ export class BatchIngester {
for (let attempt = 0; attempt <= MAX_RETRIES; attempt++) {
if (this.fatalError) throw this.fatalError;
try {
- await this.sink.ingest(batch);
+ const ack = await this.sink.ingest(batch);
+ // A refusal is terminal, not transport noise: the server has closed the
+ // operation and will discard every later batch the same way. Fail the
+ // stream instead of retrying, so the run stops buffering and reports the
+ // loss at `drain()` rather than exiting 0 on output nobody stored.
+ if (ack && ack.accepted === false) {
+ throw new IngestRejectedError(ack.reason);
+ }
return;
} catch (error) {
+ if (error instanceof IngestRejectedError) {
+ this.fatalError = error;
+ throw error;
+ }
if (attempt === MAX_RETRIES) throw error;
await sleep(delay);
delay = Math.min(delay * 2, 8_000);
diff --git a/apps/cli/src/utils/TrpcIngestSink.test.ts b/apps/cli/src/utils/TrpcIngestSink.test.ts
index fd2b5c9ffb8..e2742157271 100644
--- a/apps/cli/src/utils/TrpcIngestSink.test.ts
+++ b/apps/cli/src/utils/TrpcIngestSink.test.ts
@@ -5,8 +5,15 @@ import { TrpcIngestSink } from './TrpcIngestSink';
const setup = () => {
const mutate = vi.fn();
- const client = { aiAgent: { heteroFinish: { mutate } } } as unknown as TrpcClient;
- return { mutate, sink: new TrpcIngestSink(client, 'kimi-code', 'owned-op', 'owned-topic') };
+ const ingestMutate = vi.fn();
+ const client = {
+ aiAgent: { heteroFinish: { mutate }, heteroIngest: { mutate: ingestMutate } },
+ } as unknown as TrpcClient;
+ return {
+ ingestMutate,
+ mutate,
+ sink: new TrpcIngestSink(client, 'kimi-code', 'owned-op', 'owned-topic'),
+ };
};
afterEach(() => vi.useRealTimers());
@@ -38,6 +45,20 @@ describe('heterogeneous completion delivery', () => {
expect(mutate).toHaveBeenCalledTimes(1);
});
+ it('reports the server verdict on an ingest batch, defaulting to accepted', async () => {
+ const { ingestMutate, sink } = setup();
+
+ // A server that predates the verdict answers `{ ack: true }` only.
+ ingestMutate.mockResolvedValueOnce({ ack: true });
+ await expect(sink.ingest([])).resolves.toEqual({ accepted: true, reason: undefined });
+
+ ingestMutate.mockResolvedValueOnce({ accepted: false, ack: true, reason: 'stale-operation' });
+ await expect(sink.ingest([])).resolves.toEqual({
+ accepted: false,
+ reason: 'stale-operation',
+ });
+ });
+
it('surfaces exhausted transport retries instead of acknowledging delivery', async () => {
vi.useFakeTimers();
const { mutate, sink } = setup();
diff --git a/apps/cli/src/utils/TrpcIngestSink.ts b/apps/cli/src/utils/TrpcIngestSink.ts
index 9428169026b..d3fb1c70f30 100644
--- a/apps/cli/src/utils/TrpcIngestSink.ts
+++ b/apps/cli/src/utils/TrpcIngestSink.ts
@@ -2,7 +2,7 @@ import type { LocalHeterogeneousAgentType } from '@lobechat/heterogeneous-agents
import type { AgentStreamEvent } from '@lobechat/heterogeneous-agents/spawn';
import type { TrpcClient } from '../api/client';
-import type { IngestSink } from './BatchIngester';
+import type { IngestAck, IngestSink } from './BatchIngester';
/**
* `IngestSink` implementation that forwards batches to the server via tRPC
@@ -49,13 +49,17 @@ export class TrpcIngestSink implements IngestSink {
}
}
- async ingest(events: AgentStreamEvent[]): Promise<void> {
- await this.client.aiAgent.heteroIngest.mutate({
+ async ingest(events: AgentStreamEvent[]): Promise<IngestAck> {
+ const ack = (await this.client.aiAgent.heteroIngest.mutate({
agentType: this.agentType,
assistantMessageId: this.assistantMessageId,
events: events as any,
operationId: this.operationId,
topicId: this.topicId,
- });
+ })) as { accepted?: boolean; reason?: string } | undefined;
+
+ // Servers older than the refusal contract answer `{ ack: true }` with no
+ // verdict; only an explicit `false` means the batch was discarded.
+ return { accepted: ack?.accepted !== false, reason: ack?.reason };
}
}
diff --git a/apps/server/src/routers/lambda/__tests__/aiAgent.heteroIngest.test.ts b/apps/server/src/routers/lambda/__tests__/aiAgent.heteroIngest.test.ts
index 8753e40c1dd..01364652b5c 100644
--- a/apps/server/src/routers/lambda/__tests__/aiAgent.heteroIngest.test.ts
+++ b/apps/server/src/routers/lambda/__tests__/aiAgent.heteroIngest.test.ts
@@ -1,7 +1,7 @@
// @vitest-environment node
import type { AgentStreamEvent } from '@lobechat/agent-gateway-client';
import { type LobeChatDatabase } from '@lobechat/database';
-import { topics, workspaceMembers, workspaces } from '@lobechat/database/schemas';
+import { agentOperations, topics, workspaceMembers, workspaces } from '@lobechat/database/schemas';
import { getTestDB } from '@lobechat/database/test-utils';
import { LOCAL_HETEROGENEOUS_AGENT_TYPES } from '@lobechat/types';
import { eq } from 'drizzle-orm';
@@ -265,6 +265,97 @@ describe('aiAgentRouter.heteroIngest / heteroFinish', () => {
});
});
+ /**
+ * Regression: an operation-token producer whose run had already been settled
+ * was turned away at the auth guard with CONFLICT. The ingester then burned
+ * its whole retry budget on a refusal that can never succeed, nothing recorded
+ * that the output had been dropped, and `heteroFinish` was rejected by the
+ * same guard β€” so the turn kept its unresolved assistant placeholder.
+ */
+ describe('callbacks on a terminal operation', () => {
+ const terminalOperationId = 'op-terminal';
+
+ const operationTokenCaller = (capabilities: string[]) =>
+ aiAgentRouter.createCaller({
+ jwtPayload: { userId },
+ oidcAuth: {
+ aud: 'urn:lobehub:hetero-operation',
+ capabilities,
+ exp: 2_000_000_000,
+ iat: 1_700_000_000,
+ iss: 'urn:lobehub:internal',
+ jti: 'jti-terminal',
+ operation_id: terminalOperationId,
+ purpose: 'hetero-operation',
+ sub: userId,
+ },
+ userId,
+ } as any);
+
+ beforeEach(async () => {
+ await serverDB.insert(agentOperations).values({
+ completionReason: 'done',
+ id: terminalOperationId,
+ status: 'done',
+ topicId: 'topic-1',
+ userId,
+ });
+ });
+
+ afterEach(async () => {
+ await serverDB.delete(agentOperations).where(eq(agentOperations.id, terminalOperationId));
+ });
+
+ it('reaches the service so the refusal and the outcome are reported', async () => {
+ mockHeteroIngest.mockResolvedValue({
+ accepted: false,
+ reason: 'operation-not-running',
+ });
+ const caller = operationTokenCaller(['hetero:ingest', 'hetero:finish']);
+
+ await expect(
+ caller.heteroIngest({
+ agentType: 'claude-code',
+ events: [buildEvent('stream_chunk', 0)],
+ operationId: terminalOperationId,
+ topicId: 'topic-1',
+ }),
+ ).resolves.toEqual({ accepted: false, ack: true, reason: 'operation-not-running' });
+
+ await expect(
+ caller.heteroFinish({
+ agentType: 'claude-code',
+ operationId: terminalOperationId,
+ result: 'success',
+ topicId: 'topic-1',
+ }),
+ ).resolves.toEqual({ ack: true });
+
+ expect(mockHeteroIngest).toHaveBeenCalledOnce();
+ expect(mockHeteroFinish).toHaveBeenCalledOnce();
+ });
+
+ it('does not extend the allowance to token renewal', async () => {
+ await expect(
+ operationTokenCaller(['hetero:ingest']).refreshHeteroOperationToken({
+ operationId: terminalOperationId,
+ }),
+ ).rejects.toMatchObject({ code: 'CONFLICT' });
+ });
+
+ it('still rejects a token scoped to a different operation', async () => {
+ await expect(
+ operationTokenCaller(['hetero:ingest']).heteroIngest({
+ agentType: 'claude-code',
+ events: [buildEvent('stream_chunk', 0)],
+ operationId: 'op-1',
+ topicId: 'topic-1',
+ }),
+ ).rejects.toMatchObject({ code: 'FORBIDDEN' });
+ expect(mockHeteroIngest).not.toHaveBeenCalled();
+ });
+ });
+
describe('heteroFinish', () => {
it('forwards finish payload to the service and acks', async () => {
const result = await createCaller().heteroFinish({
diff --git a/apps/server/src/routers/lambda/aiAgent.ts b/apps/server/src/routers/lambda/aiAgent.ts
index f3aaaf958f7..2064fa0e771 100644
--- a/apps/server/src/routers/lambda/aiAgent.ts
+++ b/apps/server/src/routers/lambda/aiAgent.ts
@@ -1617,11 +1617,13 @@ const authorizeOperationCallback = async (
},
operationId: string,
capability: 'hetero:finish' | 'hetero:ingest' | 'hetero:intervention:read',
+ options: { allowTerminalOperation?: boolean } = {},
) => {
if (ctx.heteroAuthKind !== 'operation') return;
if (!ctx.heteroOperation) throw new TRPCError({ code: 'UNAUTHORIZED' });
try {
await resolveActiveHeteroOperationPrincipal({
+ allowTerminalOperation: options.allowTerminalOperation,
capability,
claims: ctx.heteroOperation,
db: ctx.serverDB,
@@ -3105,7 +3107,14 @@ export const aiAgentRouter = router({
heteroIngest: heteroAgentProcedure.input(HeteroIngestSchema).mutation(async ({ input, ctx }) => {
const { agentType, assistantMessageId, events, operationId, topicId } = input;
- await authorizeOperationCallback(ctx, operationId, 'hetero:ingest');
+ // "The operation already ended" is one of the two refusals this procedure
+ // exists to report, so it has to survive the door check β€” rejecting it here
+ // would make the producer retry a permanent refusal through its whole
+ // budget and leave no record that its output was dropped. The batch still
+ // cannot be persisted: the service refuses it on the very same status.
+ await authorizeOperationCallback(ctx, operationId, 'hetero:ingest', {
+ allowTerminalOperation: true,
+ });
log(
'heteroIngest: topic=%s op=%s type=%s count=%d',
@@ -3129,14 +3138,20 @@ export const aiAgentRouter = router({
// Zod's z.any() infers `data?: any`, but the wire shape always includes
// a `data` field (may be null). Cast at the boundary instead of widening
// the shared `AgentStreamEvent` type or the service signature.
- await heteroService.heteroIngest({
+ const outcome = await heteroService.heteroIngest({
agentType,
assistantMessageId,
events: events as AgentStreamEvent[],
operationId,
topicId,
});
- return { ack: true as const };
+
+ // A refused batch is reported in the ack, not as a transport error: it is
+ // permanent (every later batch is refused too), so a producer must stop
+ // and fail the run rather than burn its retry budget on it. Returned
+ // alongside the original `ack` so producers that predate this field keep
+ // working β€” the row marker `heteroIngest` stamps is what covers them.
+ return { ack: true as const, ...outcome };
} catch (error: any) {
// Preserve deliberate auth errors (e.g. the ownership FORBIDDEN) instead
// of masking them as a generic 500.
@@ -3195,7 +3210,13 @@ export const aiAgentRouter = router({
heteroFinish: heteroAgentProcedure.input(HeteroFinishSchema).mutation(async ({ input, ctx }) => {
const { agentType, assistantMessageId, error, operationId, result, sessionId, topicId } = input;
- await authorizeOperationCallback(ctx, operationId, 'hetero:finish');
+ // A terminal row is the normal state for a finish that lost a race (gateway
+ // completion, a settle from another tab). The service already has the stale
+ // branches for it; turning it away here would drop the run's outcome instead
+ // β€” no error bubble, no lifecycle hooks, no bot callback.
+ await authorizeOperationCallback(ctx, operationId, 'hetero:finish', {
+ allowTerminalOperation: true,
+ });
log('heteroFinish: topic=%s op=%s type=%s result=%s', topicId, operationId, agentType, result);
diff --git a/apps/server/src/services/heterogeneousAgent/__tests__/index.test.ts b/apps/server/src/services/heterogeneousAgent/__tests__/index.test.ts
index d6042294947..1306578b48a 100644
--- a/apps/server/src/services/heterogeneousAgent/__tests__/index.test.ts
+++ b/apps/server/src/services/heterogeneousAgent/__tests__/index.test.ts
@@ -65,7 +65,8 @@ const createFakePersistenceHandler = () => {
};
const createFakeAgentOperationModel = () => ({
- findById: vi.fn(async () => null),
+ findById: vi.fn(async (): Promise<any> => null),
+ recordHeteroIngestRejection: vi.fn(async () => true),
settleRunning: vi.fn(async () => true),
touchRunning: vi.fn(async () => true),
});
@@ -161,21 +162,58 @@ describe('HeterogeneousAgentService', () => {
expect(agentOperationModel.touchRunning).toHaveBeenCalledWith('op-1');
expect(persistenceHandler.ingest).toHaveBeenCalledOnce();
+ expect(agentOperationModel.recordHeteroIngestRejection).not.toHaveBeenCalled();
});
- it('ignores delayed batches after the operation lost its lease', async () => {
+ it('acknowledges an accepted batch so the producer can tell it from a discarded one', async () => {
+ const { service } = createService();
+
+ await expect(
+ service.heteroIngest({
+ agentType: 'codex',
+ events: [buildEvent('stream_chunk', 0)],
+ operationId: 'op-1',
+ topicId: 'topic-1',
+ }),
+ ).resolves.toEqual({ accepted: true });
+ });
+
+ it('reports and records a refusal when the operation lost its lease', async () => {
const { agentOperationModel, manager, persistenceHandler, service } = createService();
agentOperationModel.touchRunning.mockResolvedValue(false);
- await service.heteroIngest({
- agentType: 'claude-code',
- events: [buildEvent('stream_chunk', 0)],
- operationId: 'op-reclaimed',
- topicId: 'topic-1',
- });
+ // Discarding the batch is right β€” the operation is over. Doing it behind a
+ // bare 200 was not: the producer read that as delivery and kept working.
+ await expect(
+ service.heteroIngest({
+ agentType: 'claude-code',
+ events: [buildEvent('stream_chunk', 0), buildEvent('stream_chunk', 1)],
+ operationId: 'op-reclaimed',
+ topicId: 'topic-1',
+ }),
+ ).resolves.toEqual({ accepted: false, reason: 'operation-not-running' });
expect(persistenceHandler.ingest).not.toHaveBeenCalled();
expect(manager.publishStreamEvent).not.toHaveBeenCalled();
+ expect(agentOperationModel.recordHeteroIngestRejection).toHaveBeenCalledWith(
+ 'op-reclaimed',
+ expect.objectContaining({ droppedEvents: 2, reason: 'operation-not-running' }),
+ );
+ });
+
+ it('still refuses the batch when the rejection marker cannot be written', async () => {
+ const { agentOperationModel, service } = createService();
+ agentOperationModel.touchRunning.mockResolvedValue(false);
+ agentOperationModel.recordHeteroIngestRejection.mockRejectedValue(new Error('db down'));
+
+ await expect(
+ service.heteroIngest({
+ agentType: 'claude-code',
+ events: [buildEvent('stream_chunk', 0)],
+ operationId: 'op-reclaimed',
+ topicId: 'topic-1',
+ }),
+ ).resolves.toEqual({ accepted: false, reason: 'operation-not-running' });
});
it('republishes every event through the stream manager preserving ordering', async () => {
@@ -407,7 +445,7 @@ describe('HeterogeneousAgentService', () => {
expect(manager.publishStreamEvent).not.toHaveBeenCalled();
});
- it('ignores stale operation batches without publishing or throwing', async () => {
+ it('refuses stale operation batches without publishing or throwing', async () => {
const manager: Partial<IStreamEventManager> = {
publishStreamEvent: vi.fn(),
};
@@ -417,8 +455,9 @@ describe('HeterogeneousAgentService', () => {
throw new StaleHeteroOperationError('stale old batch');
}),
} as unknown as HeterogeneousPersistenceHandler;
+ const agentOperationModel = createFakeAgentOperationModel();
const service = new HeterogeneousAgentService({} as any, 'user-test', {
- agentOperationModel: createFakeAgentOperationModel() as any,
+ agentOperationModel: agentOperationModel as any,
persistenceHandler,
streamEventManager: manager as IStreamEventManager,
});
@@ -430,8 +469,12 @@ describe('HeterogeneousAgentService', () => {
operationId: 'op-old',
topicId: 'topic-1',
}),
- ).resolves.toBeUndefined();
+ ).resolves.toEqual({ accepted: false, reason: 'stale-operation' });
expect(manager.publishStreamEvent).not.toHaveBeenCalled();
+ expect(agentOperationModel.recordHeteroIngestRejection).toHaveBeenCalledWith(
+ 'op-old',
+ expect.objectContaining({ reason: 'stale-operation' }),
+ );
});
});
@@ -458,6 +501,73 @@ describe('HeterogeneousAgentService', () => {
});
});
+ it('settles a success whose output ingest discarded as a failed turn', async () => {
+ // The producer's receipt is honest about its own process (the CLI did exit
+ // 0) and blind to the only thing that matters here: none of its output was
+ // persisted. Trusting it leaves the user on an assistant placeholder that
+ // never fills in, with the topic/task retired as answered.
+ const { agentOperationModel, persistenceHandler, published, service } = createService();
+ agentOperationModel.findById.mockResolvedValue({
+ metadata: {
+ heteroIngestRejection: {
+ at: '2026-09-18T04:44:38.923Z',
+ droppedEvents: 12,
+ reason: 'stale-operation',
+ },
+ },
+ });
+
+ await service.heteroFinish({
+ agentType: 'claude-code',
+ assistantMessageId: 'asst-1',
+ operationId: 'op-dropped',
+ result: 'success',
+ topicId: 'topic-1',
+ });
+
+ expect(persistenceHandler.finish).toHaveBeenCalledWith(
+ expect.objectContaining({
+ error: expect.objectContaining({
+ body: expect.objectContaining({ droppedEvents: 12, reason: 'stale-operation' }),
+ }),
+ result: 'error',
+ }),
+ );
+ expect(published[0].event.data.reason).toBe('error');
+ expect(published[0].event.data.error.message).toMatch(/not saved/);
+ });
+
+ it('leaves a clean success alone', async () => {
+ const { persistenceHandler, published, service } = createService();
+
+ await service.heteroFinish({
+ agentType: 'claude-code',
+ assistantMessageId: 'asst-1',
+ operationId: 'op-clean',
+ result: 'success',
+ topicId: 'topic-1',
+ });
+
+ expect(persistenceHandler.finish).toHaveBeenCalledWith(
+ expect.objectContaining({ error: undefined, result: 'success' }),
+ );
+ expect(published[0].event.data.reason).toBe('success');
+ });
+
+ it('keeps the producer verdict when the rejection marker cannot be read', async () => {
+ const { agentOperationModel, published, service } = createService();
+ agentOperationModel.findById.mockRejectedValue(new Error('db down'));
+
+ await service.heteroFinish({
+ agentType: 'claude-code',
+ operationId: 'op-unreadable',
+ result: 'success',
+ topicId: 'topic-1',
+ });
+
+ expect(published[0].event.data.reason).toBe('success');
+ });
+
it('forwards classified error details when the run failed', async () => {
const { published, service } = createService({ operationId: 'op-2' });
diff --git a/apps/server/src/services/heterogeneousAgent/index.ts b/apps/server/src/services/heterogeneousAgent/index.ts
index 45ba9f75621..0a45d5b80b9 100644
--- a/apps/server/src/services/heterogeneousAgent/index.ts
+++ b/apps/server/src/services/heterogeneousAgent/index.ts
@@ -9,7 +9,11 @@ import {
import { ThreadStatus } from '@lobechat/types';
import debug from 'debug';
-import { AgentOperationModel } from '@/database/models/agentOperation';
+import {
+ AgentOperationModel,
+ type HeteroIngestRejectionMarker,
+ type HeteroIngestRejectionReason,
+} from '@/database/models/agentOperation';
import { MessageModel } from '@/database/models/message';
import { ThreadModel } from '@/database/models/thread';
import { TopicModel } from '@/database/models/topic';
@@ -43,6 +47,20 @@ export interface HeterogeneousIngestParams {
topicId: string;
}
+/**
+ * Outcome of one ingest batch, reported back to the producer.
+ *
+ * A refused batch is NOT an error the producer should retry β€” the operation it
+ * belongs to is over as far as the server is concerned, and every later batch
+ * will be refused too. It IS, however, a failure of the run: the producer's
+ * output is not being persisted, so it must stop pushing and finish as failed
+ * rather than exit 0 on an empty turn.
+ */
+export interface HeterogeneousIngestResult {
+ accepted: boolean;
+ reason?: HeteroIngestRejectionReason;
+}
+
export interface HeterogeneousFinishParams {
agentType: HeterogeneousAgentType;
/** Initial assistant placeholder supplied by the producer. This remains
@@ -101,6 +119,26 @@ export const normalizeHeterogeneousFinishError = (
};
};
+/**
+ * User-facing failure for a run whose events ingest refused. Deliberately not a
+ * status-guide code: nothing is wrong with the user's machine, credentials or
+ * the CLI β€” the turn simply has to be re-sent.
+ */
+const buildIngestRejectionError = (
+ rejection: HeteroIngestRejectionMarker,
+): HeterogeneousFinishError => ({
+ body: {
+ droppedEvents: rejection.droppedEvents,
+ reason: rejection.reason,
+ rejectedAt: rejection.at,
+ },
+ message:
+ rejection.reason === 'stale-operation'
+ ? 'This run was replaced while it was still working, so its output was not saved. Send the message again.'
+ : 'This run had already been closed when its output arrived, so nothing was saved. Send the message again.',
+ type: 'AgentRuntimeError',
+});
+
export interface HeterogeneousAgentServiceOptions {
/** Inject a pre-built operation model (used by tests). */
agentOperationModel?: AgentOperationModel;
@@ -170,7 +208,7 @@ export class HeterogeneousAgentService {
});
}
- async heteroIngest(params: HeterogeneousIngestParams): Promise<void> {
+ async heteroIngest(params: HeterogeneousIngestParams): Promise<HeterogeneousIngestResult> {
const { agentType, assistantMessageId, events, operationId, topicId } = params;
log(
@@ -185,7 +223,7 @@ export class HeterogeneousAgentService {
const leaseRefreshed = await this.agentOperationModel.touchRunning(operationId);
if (!leaseRefreshed) {
log('heteroIngest: ignore terminal or missing operation op=%s', operationId);
- return;
+ return this.rejectIngest(operationId, 'operation-not-running', events.length);
}
// Persist FIRST, then publish β€” the renderer's gateway handler triggers
@@ -204,7 +242,7 @@ export class HeterogeneousAgentService {
operationId,
err.message,
);
- return;
+ return this.rejectIngest(operationId, 'stale-operation', events.length);
}
throw err;
}
@@ -246,6 +284,60 @@ export class HeterogeneousAgentService {
if (unpublished.length > 0) {
await this.traceRecorder.appendBatch(operationId, events);
}
+
+ return { accepted: true };
+ }
+
+ /**
+ * Turn a discarded batch into a durable, reportable refusal.
+ *
+ * Two consumers, because either can be missing: the return value lets a
+ * current producer stop and finish as failed, while the row marker covers the
+ * producers that predate that contract (and any that die before finishing) β€”
+ * `heteroFinish` reads it back and refuses to settle the run as a clean turn.
+ * Best-effort on the write: losing the marker must not turn a refusal into a
+ * silent acceptance for the producer that CAN act on it.
+ */
+ private async rejectIngest(
+ operationId: string,
+ reason: HeteroIngestRejectionReason,
+ droppedEvents: number,
+ ): Promise<HeterogeneousIngestResult> {
+ const marker: HeteroIngestRejectionMarker = {
+ at: new Date().toISOString(),
+ droppedEvents,
+ reason,
+ };
+
+ try {
+ await this.agentOperationModel.recordHeteroIngestRejection(operationId, marker);
+ } catch (err) {
+ log('heteroIngest: failed to record rejection op=%s (non-fatal): %O', operationId, err);
+ }
+
+ return { accepted: false, reason };
+ }
+
+ /**
+ * Read back the refusal {@link rejectIngest} stamped, if any. Never throws: a
+ * failed read must leave the producer's own verdict standing rather than
+ * fabricate a failure for a run that was fine.
+ */
+ private async readIngestRejection(
+ operationId: string,
+ ): Promise<HeteroIngestRejectionMarker | undefined> {
+ try {
+ const operation = await this.agentOperationModel.findById(operationId);
+ const marker = (operation?.metadata as Record<string, unknown> | null | undefined)
+ ?.heteroIngestRejection;
+
+ return marker && typeof marker === 'object'
+ ? (marker as HeteroIngestRejectionMarker)
+ : undefined;
+ } catch (err) {
+ log('heteroFinish: failed to read ingest rejection op=%s (non-fatal): %O', operationId, err);
+ return undefined;
+ }
}
async heteroFinish(params: HeterogeneousFinishParams): Promise<void> {
@@ -253,12 +345,35 @@ export class HeterogeneousAgentService {
agentType,
assistantMessageId: seedAssistantMessageId,
operationId,
- result,
+ result: reportedResult,
resumeSessionInvalidated,
sessionId,
topicId,
} = params;
- const error = normalizeHeterogeneousFinishError(agentType, params.error);
+
+ // A producer only sees HTTP acks, so it reports success for a run whose
+ // output ingest discarded β€” the CLI did exit 0, it just has no idea none of
+ // its work was persisted. That turn is a failure from the user's side: the
+ // assistant placeholder never fills in, and settling it as `done` retires
+ // the topic/task as if it had been answered. Downgrade it here, where the
+ // refusal was recorded, so every terminal consumer below (error bubble,
+ // operation row, completion hooks, bot callback) agrees it failed.
+ const rejection =
+ reportedResult === 'success' ? await this.readIngestRejection(operationId) : undefined;
+ const result: HeterogeneousFinishResult = rejection ? 'error' : reportedResult;
+ const error = rejection
+ ? buildIngestRejectionError(rejection)
+ : normalizeHeterogeneousFinishError(agentType, params.error);
+
+ if (rejection) {
+ log(
+ 'heteroFinish: downgrading success to error topic=%s op=%s reason=%s dropped=%d',
+ topicId,
+ operationId,
+ rejection.reason,
+ rejection.droppedEvents,
+ );
+ }
log(
'heteroFinish: user=%s topic=%s op=%s type=%s result=%s sessionId=%s',
diff --git a/apps/server/src/services/heterogeneousAgent/operationPrincipal.test.ts b/apps/server/src/services/heterogeneousAgent/operationPrincipal.test.ts
index ef32e8cc2ef..3783b8702c9 100644
--- a/apps/server/src/services/heterogeneousAgent/operationPrincipal.test.ts
+++ b/apps/server/src/services/heterogeneousAgent/operationPrincipal.test.ts
@@ -108,6 +108,47 @@ describe('resolveActiveHeteroOperationPrincipal', () => {
).rejects.toEqual(new HeteroOperationPrincipalError('Operation has already ended', 409));
});
+ it('lets a terminal-tolerant callback through a settled operation, checks intact', async () => {
+ // The reporting callbacks (ingest refusal / finish) have to reach their
+ // handlers on a settled row β€” that row IS what they report on. Everything
+ // else about the token is still re-authorized.
+ await expect(
+ resolveActiveHeteroOperationPrincipal({
+ allowTerminalOperation: true,
+ capability: 'hetero:ingest',
+ claims: { ...claims, capabilities: ['hetero:ingest'] },
+ db: dbWithOperation(activeOperation({ status: 'done' })),
+ operationId: 'op-1',
+ }),
+ ).resolves.toMatchObject({ operationId: 'op-1', userId: 'user-1' });
+ expect(hasPermission).toHaveBeenCalledOnce();
+
+ // The allowance is opt-in per call site, never implied by the capability:
+ // token renewal asks for `hetero:ingest` too and must stay strict.
+ await expect(
+ resolveActiveHeteroOperationPrincipal({
+ capability: 'hetero:ingest',
+ claims: { ...claims, capabilities: ['hetero:ingest'] },
+ db: dbWithOperation(activeOperation({ status: 'done' })),
+ operationId: 'op-1',
+ }),
+ ).rejects.toEqual(new HeteroOperationPrincipalError('Operation has already ended', 409));
+ });
+
+ it('still rejects a terminal-tolerant callback whose token is out of scope', async () => {
+ await expect(
+ resolveActiveHeteroOperationPrincipal({
+ allowTerminalOperation: true,
+ capability: 'hetero:finish',
+ claims: { ...claims, capabilities: ['hetero:finish'] },
+ db: dbWithOperation(activeOperation({ status: 'done', userId: 'someone-else' })),
+ operationId: 'op-1',
+ }),
+ ).rejects.toEqual(
+ new HeteroOperationPrincipalError('Operation is outside the token scope', 403),
+ );
+ });
+
it('rejects a model selection that no longer matches the operation', async () => {
await expect(
resolveActiveHeteroOperationPrincipal({
diff --git a/apps/server/src/services/heterogeneousAgent/operationPrincipal.ts b/apps/server/src/services/heterogeneousAgent/operationPrincipal.ts
index 30908b5ffb9..1c723137caa 100644
--- a/apps/server/src/services/heterogeneousAgent/operationPrincipal.ts
+++ b/apps/server/src/services/heterogeneousAgent/operationPrincipal.ts
@@ -32,12 +32,25 @@ export interface ActiveHeteroOperationPrincipal {
/** Resolve and re-authorize an operation token against current durable state. */
export const resolveActiveHeteroOperationPrincipal = async (params: {
+ /**
+ * Let the callback through when the operation row is already terminal.
+ *
+ * Only for the callbacks whose whole job is to report on a run that ended β€”
+ * `heteroIngest` answers "this batch was discarded", `heteroFinish` lands the
+ * turn's outcome. Rejecting those at the door leaves the producer retrying a
+ * permanent refusal and the user on an assistant bubble that never resolves.
+ * Every other check still runs, and neither callback can write anything to a
+ * terminal operation: the service refuses them on the same status, which is
+ * exactly the answer they exist to deliver. Live-work capabilities
+ * (`model:invoke`, token renewal, goal mutations) must never set this.
+ */
+ allowTerminalOperation?: boolean;
capability: HeteroOperationCapability;
claims: HeteroOperationJwtClaims;
db: LobeChatDatabase;
operationId: string;
}): Promise<ActiveHeteroOperationPrincipal> => {
- const { capability, claims, db, operationId } = params;
+ const { allowTerminalOperation, capability, claims, db, operationId } = params;
if (claims.operation_id !== operationId || !claims.capabilities.includes(capability)) {
throw new HeteroOperationPrincipalError('Operation token does not grant this request', 403);
}
@@ -69,7 +82,7 @@ export const resolveActiveHeteroOperationPrincipal = async (params: {
) {
throw new HeteroOperationPrincipalError('Operation is outside the token scope', 403);
}
- if (operation.status !== 'running') {
+ if (operation.status !== 'running' && !allowTerminalOperation) {
throw new HeteroOperationPrincipalError('Operation has already ended', 409);
}
diff --git a/packages/database/src/models/__tests__/agentOperation.test.ts b/packages/database/src/models/__tests__/agentOperation.test.ts
index a55160d38ec..f135c4291ee 100644
--- a/packages/database/src/models/__tests__/agentOperation.test.ts
+++ b/packages/database/src/models/__tests__/agentOperation.test.ts
@@ -494,6 +494,61 @@ describe('AgentOperationModel', () => {
});
});
+ describe('hetero ingest rejection marker', () => {
+ const marker = {
+ at: '2026-09-18T04:44:38.923Z',
+ droppedEvents: 12,
+ reason: 'stale-operation',
+ } as const;
+
+ it('keeps the first refusal, survives a terminal row, and stays owner-scoped', async () => {
+ const model = new AgentOperationModel(serverDB, userId);
+ const operationId = 'op-ingest-refused';
+ await model.recordStart({ operationId });
+
+ expect(await model.recordHeteroIngestRejection(operationId, marker)).toBe(true);
+ // Later batches of the same run are refused too β€” the first refusal is the
+ // one that explains where the output started disappearing.
+ expect(
+ await model.recordHeteroIngestRejection(operationId, {
+ ...marker,
+ at: '2026-09-18T04:46:00.000Z',
+ droppedEvents: 3,
+ }),
+ ).toBe(false);
+ expect((await model.findById(operationId))?.metadata).toMatchObject({
+ heteroIngestRejection: marker,
+ });
+
+ // "The row is already terminal" is itself a refusal reason, so unlike the
+ // lease writes this one must not be gated on status = running.
+ const terminalId = 'op-ingest-refused-terminal';
+ await model.recordStart({ operationId: terminalId });
+ await model.settleRunning(terminalId, 'done');
+ expect(await model.recordHeteroIngestRejection(terminalId, marker)).toBe(true);
+
+ expect(
+ await new AgentOperationModel(serverDB, otherUserId).recordHeteroIngestRejection(
+ 'op-ingest-refused-foreign',
+ marker,
+ ),
+ ).toBe(false);
+ });
+
+ it('merges into existing metadata instead of replacing it', async () => {
+ const model = new AgentOperationModel(serverDB, userId);
+ const operationId = 'op-ingest-refused-merge';
+ await model.recordStart({ operationId, metadata: { assistantMessageId: 'asst-1' } });
+
+ await model.recordHeteroIngestRejection(operationId, marker);
+
+ expect((await model.findById(operationId))?.metadata).toMatchObject({
+ assistantMessageId: 'asst-1',
+ heteroIngestRejection: marker,
+ });
+ });
+ });
+
describe('sumChildUsage', () => {
const seedChild = async (
model: AgentOperationModel,
diff --git a/packages/database/src/models/agentOperation.ts b/packages/database/src/models/agentOperation.ts
index a5fbe18d19e..0cf25f5dd7c 100644
--- a/packages/database/src/models/agentOperation.ts
+++ b/packages/database/src/models/agentOperation.ts
@@ -65,6 +65,26 @@ export interface AgentInterventionPreparationMarker {
stepIndex: number;
}
+/** Why `heteroIngest` refused a batch β€” see {@link HeteroIngestRejectionMarker}. */
+export type HeteroIngestRejectionReason = 'operation-not-running' | 'stale-operation';
+
+/**
+ * Stamped the first time `heteroIngest` refuses a batch for this operation.
+ *
+ * Both refusal paths (the op row is no longer `running`, or the topic's
+ * `runningOperation` marker no longer names this op) mean the producer's
+ * remaining output is being discarded while its CLI keeps running happily. The
+ * marker is what carries that fact across to `heteroFinish`, which would
+ * otherwise settle the producer's `success` receipt as a clean turn and leave
+ * the user staring at an assistant placeholder that never fills in.
+ */
+export interface HeteroIngestRejectionMarker {
+ at: string;
+ /** Events discarded with the refusal that stamped this marker. */
+ droppedEvents: number;
+ reason: HeteroIngestRejectionReason;
+}
+
const sameServerDefaultRelayInvocation = (
left: ServerDefaultHeterogeneousRelayInvocation,
right: ServerDefaultHeterogeneousRelayInvocation,
@@ -349,6 +369,33 @@ export class AgentOperationModel {
return Boolean(row);
}
+ /**
+ * Record that ingest discarded a batch for this operation, first refusal wins.
+ *
+ * Deliberately NOT gated on `status = 'running'`: a terminal row is itself one
+ * of the refusal reasons. The `?` guard keeps the first (and most informative)
+ * refusal instead of letting the run's remaining batches overwrite it.
+ */
+ async recordHeteroIngestRejection(
+ operationId: string,
+ marker: HeteroIngestRejectionMarker,
+ ): Promise<boolean> {
+ const [row] = await this.db
+ .update(agentOperations)
+ .set({
+ metadata: sql`coalesce(${agentOperations.metadata}, '{}'::jsonb) || ${JSON.stringify({ heteroIngestRejection: marker })}::jsonb`,
+ })
+ .where(
+ and(
+ eq(agentOperations.id, operationId),
+ this.ownership(),
+ sql`NOT (coalesce(${agentOperations.metadata}, '{}'::jsonb) ? 'heteroIngestRejection')`,
+ ),
+ )
+ .returning({ id: agentOperations.id });
+ return Boolean(row);
+ }
+
/** Refresh the durable liveness lease while an operation owns an execution step. */
async touchRunning(operationId: string): Promise<boolean> {
const [row] = await this.db