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 discarding a live CLI run's output when its topic marker is settled (#19820)

Arvin Xuc8881a20a8ca
diff --git a/apps/cli/src/commands/hetero.test.ts b/apps/cli/src/commands/hetero.test.ts
index 3cb62bafc59..91ba9ad38ed 100644
--- a/apps/cli/src/commands/hetero.test.ts
+++ b/apps/cli/src/commands/hetero.test.ts
@@ -187,6 +187,93 @@ describe('hetero exec command', () => {
expect(exitSpy).toHaveBeenCalledWith(1);
});
+ // The inherited-group case is the desktop / connected-device dispatch: there
+ // an external signal already reaches the agent, so ordinary cancellation does
+ // not forward it β€” but an ingest-loss abort has no external signal behind it.
+ it.each([
+ { inheritsProcessGroup: false, name: 'its own process group' },
+ { inheritsProcessGroup: true, name: 'an inherited wrapper group' },
+ ])(
+ 'stops the agent as soon as the server starts discarding its output ($name)',
+ async ({ inheritsProcessGroup }) => {
+ if (inheritsProcessGroup) vi.stubEnv(HETERO_EXEC_INHERIT_PROCESS_GROUP_ENV, '1');
+
+ // A refusal is terminal for the whole run: the operation no longer owns the
+ // topic, so every later batch is discarded the same way. The verdict used
+ // to surface only at `drain()` β€” i.e. after the agent had finished β€” so a
+ // run whose output was already being thrown away kept working for as long
+ // as it had left (observed: 15 minutes of a CLI producing output nobody
+ // stored, then one error card).
+ mockHeteroIngestMutate.mockResolvedValue({ accepted: false, reason: 'stale-operation' });
+
+ let markKilled!: () => void;
+ const killed = new Promise<void>((resolve) => {
+ markKilled = resolve;
+ });
+ const kill = vi.fn(() => markKilled());
+ const stderr = new PassThrough();
+ stderr.end();
+
+ mockSpawnAgent.mockReturnValue(
+ Promise.resolve({
+ // A long-running agent: one event, then nothing until it is killed.
+ events: {
+ [Symbol.asyncIterator]() {
+ let sent = false;
+ return {
+ async next() {
+ if (!sent) {
+ sent = true;
+ return {
+ done: false,
+ value: {
+ data: { chunkType: 'text', content: 'working' },
+ operationId: 'op-1',
+ stepIndex: 0,
+ timestamp: Date.now(),
+ type: 'stream_chunk',
+ },
+ };
+ }
+ await killed;
+ return { done: true, value: undefined };
+ },
+ };
+ },
+ } as AsyncIterable<any>,
+ exit: killed.then(() => ({ code: null, signal: 'SIGTERM' as NodeJS.Signals })),
+ kill,
+ pid: 12_345,
+ stderr,
+ }),
+ );
+
+ await runCmd([
+ 'hetero',
+ 'exec',
+ '--type',
+ 'claude-code',
+ '--prompt',
+ 'hi',
+ '--topic',
+ 'topic-1',
+ '--operation-id',
+ 'op-1',
+ ]);
+
+ expect(kill).toHaveBeenCalledWith('SIGTERM');
+ // And it is reported as a failed run, not a cancellation: nobody stopped
+ // this agent, and `cancelled` would leave the server operation running with
+ // nothing left to drive it.
+ expect(mockHeteroFinishMutate).toHaveBeenCalledWith(
+ expect.objectContaining({
+ error: expect.objectContaining({ message: expect.stringContaining('stale-operation') }),
+ result: 'error',
+ }),
+ );
+ },
+ );
+
it('supports exactly the local agent descriptor types', () => {
expect([...SUPPORTED_AGENT_TYPES].toSorted()).toEqual(
HETEROGENEOUS_AGENT_CONFIGS.map(({ type }) => type).toSorted(),
@@ -1455,6 +1542,77 @@ describe('hetero exec command', () => {
);
});
+ it('does not fall back to a fresh run once the server has refused this run output', async () => {
+ // The ingester is shared across attempts and a refusal is permanent: a
+ // fallback run would stream into a dead pipe, and the one-shot abort that
+ // stopped attempt 1 could not stop it again.
+ mockHeteroIngestMutate.mockResolvedValue({ accepted: false, reason: 'stale-operation' });
+
+ let markKilled!: () => void;
+ const killed = new Promise<void>((resolve) => {
+ markKilled = resolve;
+ });
+ const stderr = new PassThrough();
+ stderr.end();
+ const events = [
+ {
+ data: { chunkType: 'text', content: 'working' },
+ operationId: 'op-refused',
+ stepIndex: 0,
+ timestamp: 1,
+ type: 'stream_chunk',
+ },
+ {
+ data: { message: 'No conversation found with session ID cc-stale' },
+ operationId: 'op-refused',
+ stepIndex: 0,
+ timestamp: 2,
+ type: 'error',
+ },
+ ];
+ mockSpawnAgent.mockReturnValueOnce(
+ Promise.resolve({
+ events: {
+ [Symbol.asyncIterator]() {
+ let i = 0;
+ return {
+ async next() {
+ if (i < events.length) return { done: false, value: events[i++] };
+ await killed;
+ return { done: true, value: undefined };
+ },
+ };
+ },
+ } as AsyncIterable<any>,
+ exit: killed.then(() => ({ code: null, signal: 'SIGTERM' as NodeJS.Signals })),
+ kill: vi.fn(() => markKilled()),
+ pid: 12_345,
+ stderr,
+ }),
+ );
+ mockSpawnAgent.mockReturnValue(createFakeHandle({ exitCode: 0 }));
+
+ await runCmd([
+ 'hetero',
+ 'exec',
+ '--type',
+ 'claude-code',
+ '--prompt',
+ 'continue',
+ '--resume',
+ 'cc-stale',
+ '--operation-id',
+ 'op-refused',
+ '--topic',
+ 'topic-refused',
+ ]);
+
+ expect(mockSpawnAgent).toHaveBeenCalledTimes(1);
+ expect(mockHeteroFinishMutate).toHaveBeenCalledWith(
+ expect.objectContaining({ result: 'error' }),
+ );
+ });
+
it('does not consume the recovery prompt when native resume succeeds', async () => {
const dir = await mkdtemp(`${tmpdir()}/hetero-resume-primary-`);
const file = path.join(dir, 'input.json');
diff --git a/apps/cli/src/commands/hetero.ts b/apps/cli/src/commands/hetero.ts
index 6fa470b4e7e..31082766db4 100644
--- a/apps/cli/src/commands/hetero.ts
+++ b/apps/cli/src/commands/hetero.ts
@@ -532,6 +532,9 @@ const exec = async (options: ExecOptions): Promise<void> => {
const agentType = options.type;
let sink: TrpcIngestSink | undefined;
let serverIngester: CoalescingBatchIngester | undefined;
+ // Set for the duration of each spawn attempt (see `runOneAgent`): stops the
+ // running agent when the server tells us its output is being discarded.
+ let abortForIngestLoss: ((error: Error) => void) | undefined;
// Uploader for tool_result images (CC `Read` on an image file). Reuses the
// CLI's authenticated lambda client so the persisted event carries a
// `{ fileId, url }` reference instead of heavy base64. Only wired in
@@ -548,7 +551,15 @@ const exec = async (options: ExecOptions): Promise<void> => {
options.topic!,
process.env.LOBEHUB_ASSISTANT_MESSAGE_ID,
);
- serverIngester = new CoalescingBatchIngester(sink);
+ serverIngester = new CoalescingBatchIngester(sink, undefined, (error) => {
+ // The server has stopped storing this run's events (its topic marker was
+ // settled underneath it, or the operation is already terminal) and every
+ // later batch would be discarded the same way. Waiting for `drain()` to
+ // report that means the agent keeps working β€” for minutes, on a long task
+ // β€” to produce output nobody will ever see. Stop it now; the drain below
+ // still raises the same error, so the finish leg reports a failed run.
+ abortForIngestLoss?.(error);
+ });
uploadImage = createFileStoreImageUploader(async () => {
const lambda = await getTrpcClient();
@@ -797,12 +808,26 @@ const exec = async (options: ExecOptions): Promise<void> => {
await Promise.all(cancellations);
if (cancellationError) throw cancellationError;
};
- const applyCancellation = (signal: NodeJS.Signals) => {
- cancellationSignal = signal;
- if (inheritsWrapperProcessGroup) return;
+ // Deliberately NOT `interrupted`: the user did not stop this run, so the
+ // finish leg must report `error` (with the ingest failure as its detail)
+ // rather than `cancelled`, which would leave the operation running on the
+ // server with nothing left to drive it.
+ let ingestLoss: Error | undefined;
+ // Inside an inherited wrapper group an external SIGINT/SIGTERM already
+ // reaches the agent, so forwarding it would signal twice. An ingest-loss
+ // abort has no OS signal behind it β€” the CLI decided on its own β€” so it
+ // must always deliver the signal itself, or the agent keeps running (the
+ // desktop and connected-device dispatches are exactly the inherited case).
+ const ownsSignalDelivery = () => !inheritsWrapperProcessGroup || ingestLoss !== undefined;
+ const signalAgent = (signal: NodeJS.Signals) => {
if (startupControl) cancelStartup(startupControl, signal);
else handle?.kill(signal);
};
+ const applyCancellation = (signal: NodeJS.Signals) => {
+ cancellationSignal = signal;
+ if (!ownsSignalDelivery()) return;
+ signalAgent(signal);
+ };
const onSigint = () => {
const signal = interrupted ? 'SIGKILL' : 'SIGINT';
interrupted = true;
@@ -815,10 +840,18 @@ const exec = async (options: ExecOptions): Promise<void> => {
const removeSignalListeners = () => {
process.off('SIGINT', onSigint);
process.off('SIGTERM', onSigterm);
+ abortForIngestLoss = undefined;
};
process.on('SIGINT', onSigint);
process.on('SIGTERM', onSigterm);
+ abortForIngestLoss = (error) => {
+ if (ingestLoss) return;
+ ingestLoss = error;
+ log.error('Server is discarding this run output, stopping the agent:', error.message);
+ applyCancellation('SIGTERM');
+ };
+
// One raw-dump file pair per spawn attempt (the resume retry is a second
// attempt). The stdout tee runs inside `spawnAgent` before the adapter.
const dumpAttempt = rawDump?.openAttempt(runLabel);
@@ -830,11 +863,11 @@ const exec = async (options: ExecOptions): Promise<void> => {
try {
handle = await spawnAgentOrRuntime(spawnOpts, dumpAttempt?.writeStdout, (control) => {
startupControl = control;
- if (cancellationSignal && !inheritsWrapperProcessGroup) {
+ if (cancellationSignal && ownsSignalDelivery()) {
cancelStartup(control, cancellationSignal);
}
});
- if (cancellationSignal && !startupControl && !inheritsWrapperProcessGroup) {
+ if (cancellationSignal && !startupControl && ownsSignalDelivery()) {
handle.kill(cancellationSignal);
}
} catch (err) {
@@ -846,9 +879,9 @@ const exec = async (options: ExecOptions): Promise<void> => {
}
if (cancellationSignal) {
return {
- cancelled: true,
+ cancelled: !ingestLoss,
code: null,
- ingestError: false,
+ ingestError: ingestLoss !== undefined,
resumeNotFound: false,
sawTerminalError: false,
sessionId: undefined,
@@ -912,7 +945,6 @@ const exec = async (options: ExecOptions): Promise<void> => {
let sawTerminalError = false;
let terminalErrorMessage: string | undefined;
let terminalErrorData: Record<string, unknown> | undefined;
- const ingestError = false;
try {
for await (const event of handle.events) {
if (interceptResumeErrors && event.type === 'error') {
@@ -1013,7 +1045,11 @@ const exec = async (options: ExecOptions): Promise<void> => {
return {
cancelled: interrupted,
code,
- ingestError,
+ // The shared ingester is permanently failed once the server refused a
+ // batch, so the caller must neither retry this run (every event of a
+ // retry would be dropped, with no second abort to stop it) nor report it
+ // as anything but failed.
+ ingestError: ingestLoss !== undefined,
resumeNotFound,
sawTerminalError,
sessionId: handle.sessionId,
@@ -1090,7 +1126,7 @@ const exec = async (options: ExecOptions): Promise<void> => {
// fresh session. The server's `heteroSessionId` is updated with the new id,
// breaking the stale-session loop.
let result = first;
- if (!first.cancelled && first.resumeNotFound) {
+ if (!first.cancelled && !first.ingestError && first.resumeNotFound) {
log.info('Resume failed (session not found or context overflow) β€” retrying without --resume');
result = await runOneAgent(
{
diff --git a/apps/cli/src/utils/BatchIngester.test.ts b/apps/cli/src/utils/BatchIngester.test.ts
index 57754421bfa..a2c698a5bda 100644
--- a/apps/cli/src/utils/BatchIngester.test.ts
+++ b/apps/cli/src/utils/BatchIngester.test.ts
@@ -149,6 +149,46 @@ describe('BatchIngester', () => {
expect(ingest).toHaveBeenCalledTimes(1);
});
+ it('reports a lost stream the moment it happens, not only at drain', async () => {
+ // The refusal above is terminal, but the caller only learned about it when
+ // it drained β€” i.e. after the agent had finished. A run whose output is
+ // already being discarded kept working until then (observed: 15 minutes of
+ // a CLI producing output nobody stored). The callback is what lets the
+ // caller stop the agent instead.
+ const ingest = vi
+ .fn<IngestSink['ingest']>()
+ .mockResolvedValue({ accepted: false, reason: 'stale-operation' });
+ const onFatal = vi.fn();
+ const ingester = new BatchIngester({ finish: vi.fn(), ingest }, undefined, onFatal);
+
+ ingester.push(makeEvent(1));
+ const drained = expect(ingester.drain()).rejects.toThrow('stale-operation');
+ await vi.advanceTimersByTimeAsync(20_000);
+ await drained;
+
+ expect(onFatal).toHaveBeenCalledTimes(1);
+ expect(onFatal.mock.calls[0][0]).toBeInstanceOf(Error);
+ expect(onFatal.mock.calls[0][0].message).toContain('stale-operation');
+
+ // Latched: a second failure (or a later push on a dead stream) must not
+ // re-fire it and abort a run twice.
+ ingester.push(makeEvent(2));
+ await expect(ingester.drain()).rejects.toThrow('stale-operation');
+ expect(onFatal).toHaveBeenCalledTimes(1);
+ });
+
+ it('reports an overflow through the same callback', () => {
+ const maxBytes = Buffer.byteLength(JSON.stringify(makeEvent(1)));
+ const onFatal = vi.fn();
+ const ingester = new BatchIngester({ finish: vi.fn(), ingest: vi.fn() }, maxBytes, onFatal);
+
+ ingester.push(makeEvent(1));
+ ingester.push(makeEvent(2));
+
+ expect(onFatal).toHaveBeenCalledTimes(1);
+ expect(onFatal.mock.calls[0][0].message).toContain('buffer limit exceeded');
+ });
+
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 });
diff --git a/apps/cli/src/utils/BatchIngester.ts b/apps/cli/src/utils/BatchIngester.ts
index 134b638f3ef..33ae81d5fec 100644
--- a/apps/cli/src/utils/BatchIngester.ts
+++ b/apps/cli/src/utils/BatchIngester.ts
@@ -70,6 +70,14 @@ export class BatchIngester {
constructor(
private readonly sink: IngestSink,
private readonly maxBufferedBytes = 16 * 1024 * 1024,
+ /**
+ * Called once, the moment the stream becomes unrecoverable (the server
+ * discarded a batch, or the buffer overflowed). Without it the verdict only
+ * surfaces at `drain()`, i.e. after the agent has finished β€” so a run whose
+ * output is already being thrown away keeps working for however long it had
+ * left. The caller uses this to stop the agent instead.
+ */
+ private readonly onFatal?: (error: Error) => void,
) {}
/** Only a lost/overflowed stream is permanent; a transport outage can recover. */
@@ -81,7 +89,7 @@ export class BatchIngester {
if (this.fatalError) return;
const size = Buffer.byteLength(JSON.stringify(event));
if (this.bufferedBytes + size > this.maxBufferedBytes) {
- this.fatalError = new Error('Agent event buffer limit exceeded while waiting for upload');
+ this.fail(new Error('Agent event buffer limit exceeded while waiting for upload'));
this.buffer = [];
this.bufferedBytes = 0;
if (this.timer) clearTimeout(this.timer);
@@ -113,6 +121,13 @@ export class BatchIngester {
if (this.lastSendError) throw this.lastSendError;
}
+ /** Latch the terminal state and tell the caller once, never twice. */
+ private fail(error: Error): void {
+ if (this.fatalError) return;
+ this.fatalError = error;
+ this.onFatal?.(error);
+ }
+
private startPump(): void {
if (this.pumping || this.fatalError || this.buffer.length === 0) return;
this.lastSendError = null;
@@ -154,7 +169,7 @@ export class BatchIngester {
return;
} catch (error) {
if (error instanceof IngestRejectedError) {
- this.fatalError = error;
+ this.fail(error);
throw error;
}
if (attempt === MAX_RETRIES) throw error;
diff --git a/apps/cli/src/utils/CoalescingBatchIngester.ts b/apps/cli/src/utils/CoalescingBatchIngester.ts
index 05dca84dbb5..9c5be3e6f38 100644
--- a/apps/cli/src/utils/CoalescingBatchIngester.ts
+++ b/apps/cli/src/utils/CoalescingBatchIngester.ts
@@ -38,8 +38,10 @@ export class CoalescingBatchIngester {
constructor(
sink: IngestSink,
private readonly snapshotFlushMs = 200,
+ /** Forwarded to {@link BatchIngester}: the stream is unrecoverable. */
+ onFatal?: (error: Error) => void,
) {
- this.batcher = new BatchIngester(sink);
+ this.batcher = new BatchIngester(sink, undefined, onFatal);
}
push(event: AgentStreamEvent): void {
diff --git a/apps/server/src/services/heterogeneousAgent/HeterogeneousPersistenceHandler.ts b/apps/server/src/services/heterogeneousAgent/HeterogeneousPersistenceHandler.ts
index 29502d476ae..bb222747dc6 100644
--- a/apps/server/src/services/heterogeneousAgent/HeterogeneousPersistenceHandler.ts
+++ b/apps/server/src/services/heterogeneousAgent/HeterogeneousPersistenceHandler.ts
@@ -185,6 +185,14 @@ export class StaleHeteroOperationError extends Error {
}
export interface HeterogeneousPersistenceHandlerDeps {
+ /**
+ * Liveness probe against the operation row, used only when the topic has lost
+ * its `runningOperation` marker: it answers whether this operation is still
+ * `running` and still owns this topic, i.e. whether the producer behind the
+ * batch is alive. Optional so standalone/test callers keep the marker-only
+ * behaviour.
+ */
+ isOperationLiveOnTopic?: (operationId: string, topicId: string) => Promise<boolean>;
messageModel: MessageModel;
threadModel: ThreadModel;
topicModel: TopicModel;
@@ -553,16 +561,35 @@ export class HeterogeneousPersistenceHandler {
? marker
: marker?.childOperations?.find((child) => child.operationId === operationId);
- if (!running && !(allowMissingRunningOperation && seedAssistantMessageId)) {
- throw new StaleHeteroOperationError(
- `Stale hetero operation ${operationId} on topic ${topicId}; no active runningOperation`,
- );
- }
-
- if (!running && !(allowMissingRunningOperation && seedAssistantMessageId)) {
- throw new StaleHeteroOperationError(
- `Stale hetero operation ${operationId} on topic ${topicId}; current operation is ${marker?.operationId ?? 'unknown'}`,
- );
+ if (!running) {
+ // Two different fates were collapsed into one refusal here.
+ //
+ // A marker naming ANOTHER operation means a newer run owns the topic:
+ // this batch is genuinely late and has to be dropped, or it would keep
+ // mutating a turn the conversation has already moved past.
+ //
+ // NO marker at all is a different story. The marker is a best-effort
+ // rendering pointer that a client can settle on nothing more than a
+ // transport signal β€” a raw `session_complete`, or one multiplexed socket
+ // failing auth for every operation on the tab β€” while the producer is
+ // still running and streaming. Refusing there throws away the whole
+ // remaining output of a live CLI, which then burns minutes of work
+ // nobody stores. The operation row is the authority on liveness, so ask
+ // it: still `running`, still bound to THIS topic β‡’ keep persisting
+ // without a marker. The turn's own pointers (`heteroCurrentMsgId`, the
+ // seeded assistant message) carry the rest.
+ const producerStillOwnsTopic =
+ !marker && (await this.deps.isOperationLiveOnTopic?.(operationId, topicId));
+
+ if (producerStillOwnsTopic) {
+ log('marker missing but operation still running op=%s topic=%s', operationId, topicId);
+ } else if (!(allowMissingRunningOperation && seedAssistantMessageId)) {
+ throw new StaleHeteroOperationError(
+ marker
+ ? `Stale hetero operation ${operationId} on topic ${topicId}; current operation is ${marker.operationId}`
+ : `Stale hetero operation ${operationId} on topic ${topicId}; no active runningOperation`,
+ );
+ }
}
// Prefer the assistantMessageId forwarded in the ingest payload (sandbox path).
@@ -572,7 +599,15 @@ export class HeterogeneousPersistenceHandler {
// runningOperation binding to match `operationId`, otherwise late/retried
// batches after finish could keep mutating a completed turn.
// Fall back to topic.metadata for desktop / old-CLI callers that lack the field.
- const baseAssistantMessageId = seedAssistantMessageId ?? running?.assistantMessageId;
+ // `heteroCurrentMsgId` is the last resort and is scoped to this operation:
+ // it is the only pointer left once a marker has been cleared out from under
+ // a still-running producer (see the liveness check above).
+ const currentMsgIdForOperation =
+ topic?.metadata?.heteroCurrentMsgId?.operationId === operationId
+ ? topic?.metadata?.heteroCurrentMsgId?.msgId
+ : undefined;
+ const baseAssistantMessageId =
+ seedAssistantMessageId ?? running?.assistantMessageId ?? currentMsgIdForOperation;
if (!baseAssistantMessageId) {
throw new Error(`runningOperation on topic ${topicId} is missing assistantMessageId`);
@@ -1003,7 +1038,16 @@ export class HeterogeneousPersistenceHandler {
? marker
: marker?.childOperations?.find((child) => child.operationId === state.operationId);
- if (!running) {
+ // Same split as `loadOrCreateState`: another operation on the marker means
+ // this run has been superseded and must stop writing, while a marker that
+ // is simply gone can be a live producer whose topic was settled by a
+ // transport signal. In the latter case `heteroCurrentMsgId` β€” repointed by
+ // this operation's own ingest β€” is a complete substitute for the pointer
+ // this sync would have read off the marker.
+ if (
+ !running &&
+ (marker || !(await this.deps.isOperationLiveOnTopic?.(state.operationId, state.topicId)))
+ ) {
throw new StaleHeteroOperationError(
`Stale hetero operation ${state.operationId} on topic ${state.topicId}; current operation is ${marker?.operationId ?? 'unknown'}`,
);
diff --git a/apps/server/src/services/heterogeneousAgent/__tests__/HeterogeneousPersistenceHandler.test.ts b/apps/server/src/services/heterogeneousAgent/__tests__/HeterogeneousPersistenceHandler.test.ts
index ed70d9cebb5..1cc7d3dcb18 100644
--- a/apps/server/src/services/heterogeneousAgent/__tests__/HeterogeneousPersistenceHandler.test.ts
+++ b/apps/server/src/services/heterogeneousAgent/__tests__/HeterogeneousPersistenceHandler.test.ts
@@ -56,6 +56,8 @@ interface FakeTopic {
const createHarness = (params: {
assistantAgentId?: string | null;
assistantMessageId: string;
+ /** Stands in for the operation row: is this run still live on this topic? */
+ isOperationLiveOnTopic?: (operationId: string, topicId: string) => Promise<boolean>;
operationId: string;
topicAgentId?: string | null;
topicId: string;
@@ -176,6 +178,7 @@ const createHarness = (params: {
};
const handler = new HeterogeneousPersistenceHandler({
+ isOperationLiveOnTopic: params.isOperationLiveOnTopic,
messageModel: messageModel as any,
threadModel: threadModel as any,
topicModel: topicModel as any,
@@ -277,6 +280,112 @@ describe('HeterogeneousPersistenceHandler', () => {
).rejects.toThrow(/no active runningOperation/);
});
+ it('keeps persisting when the marker is gone but the operation is still running', async () => {
+ // The marker is a rendering pointer any client can settle β€” a transport
+ // signal (a raw session_complete, or one multiplexed socket failing auth
+ // for every operation on the tab) clears it while the CLI keeps
+ // streaming. Refusing here discards the rest of a live run's output.
+ const isOperationLiveOnTopic = vi.fn(async () => true);
+ const h = createHarness({
+ assistantMessageId: 'asst-1',
+ isOperationLiveOnTopic,
+ operationId: 'op-1',
+ topicId: 'topic-1',
+ });
+ h.topicModel.findById.mockResolvedValueOnce({
+ agentId: null,
+ id: 'topic-1',
+ metadata: {} as any,
+ });
+
+ await h.handler.ingest({
+ assistantMessageId: 'asst-1',
+ events: [buildEvent('stream_chunk', 0, { chunkType: 'text', content: 'kept' })],
+ operationId: 'op-1',
+ topicId: 'topic-1',
+ });
+
+ expect(isOperationLiveOnTopic).toHaveBeenCalledWith('op-1', 'topic-1');
+ expect(h.messageModel.update).toHaveBeenCalledWith('asst-1', { content: 'kept' });
+ });
+
+ it('recovers the assistant pointer from heteroCurrentMsgId when the marker is gone', async () => {
+ // Desktop / old-CLI callers forward no assistantMessageId, so once the
+ // marker is gone the operation-scoped `heteroCurrentMsgId` is the only
+ // pointer left to the turn in flight.
+ const h = createHarness({
+ assistantMessageId: 'asst-1',
+ isOperationLiveOnTopic: async () => true,
+ operationId: 'op-1',
+ topicId: 'topic-1',
+ });
+ h.topicModel.findById.mockResolvedValueOnce({
+ agentId: null,
+ id: 'topic-1',
+ metadata: { heteroCurrentMsgId: { msgId: 'asst-1', operationId: 'op-1' } } as any,
+ });
+
+ await h.handler.ingest({
+ events: [buildEvent('stream_chunk', 0, { chunkType: 'text', content: 'kept' })],
+ operationId: 'op-1',
+ topicId: 'topic-1',
+ });
+
+ expect(h.messageModel.update).toHaveBeenCalledWith('asst-1', { content: 'kept' });
+ });
+
+ it('still refuses a marker-less batch once the operation row is terminal', async () => {
+ const h = createHarness({
+ assistantMessageId: 'asst-1',
+ isOperationLiveOnTopic: async () => false,
+ operationId: 'op-1',
+ topicId: 'topic-1',
+ });
+ h.topicModel.findById.mockResolvedValueOnce({
+ agentId: null,
+ id: 'topic-1',
+ metadata: {} as any,
+ });
+
+ await expect(
+ h.handler.ingest({
+ assistantMessageId: 'asst-1',
+ events: [buildEvent('stream_chunk', 0, { chunkType: 'text', content: 'x' })],
+ operationId: 'op-1',
+ topicId: 'topic-1',
+ }),
+ ).rejects.toThrow(/no active runningOperation/);
+ });
+
+ it('refuses a superseded batch even while its own operation row is alive', async () => {
+ // Liveness must NOT override ownership: a marker naming another run means
+ // the topic has moved on, and writing here would mutate a newer turn.
+ const isOperationLiveOnTopic = vi.fn(async () => true);
+ const h = createHarness({
+ assistantMessageId: 'asst-1',
+ isOperationLiveOnTopic,
+ operationId: 'op-1',
+ topicId: 'topic-1',
+ });
+ h.topicModel.findById.mockResolvedValueOnce({
+ agentId: null,
+ id: 'topic-1',
+ metadata: {
+ runningOperation: { assistantMessageId: 'asst-other', operationId: 'op-OTHER' },
+ },
+ });
+
+ await expect(
+ h.handler.ingest({
+ assistantMessageId: 'asst-1',
+ events: [buildEvent('stream_chunk', 0, { chunkType: 'text', content: 'x' })],
+ operationId: 'op-1',
+ topicId: 'topic-1',
+ }),
+ ).rejects.toThrow(/current operation is op-OTHER/);
+ expect(isOperationLiveOnTopic).not.toHaveBeenCalled();
+ });
+
it('validates seeded assistant ids belong to the current topic', async () => {
const h = createHarness({
assistantMessageId: 'asst-1',
diff --git a/apps/server/src/services/heterogeneousAgent/index.ts b/apps/server/src/services/heterogeneousAgent/index.ts
index 096d4f152bd..fb0071d2060 100644
--- a/apps/server/src/services/heterogeneousAgent/index.ts
+++ b/apps/server/src/services/heterogeneousAgent/index.ts
@@ -212,6 +212,8 @@ export class HeterogeneousAgentService {
this.persistenceHandler =
options.persistenceHandler ??
new HeterogeneousPersistenceHandler({
+ isOperationLiveOnTopic: (operationId, topicId) =>
+ this.agentOperationModel.isRunningOnTopic(operationId, topicId),
messageModel: this.messageModel,
threadModel: new ThreadModel(db, userId, workspaceId),
topicModel: this.topicModel,
diff --git a/packages/database/src/models/__tests__/agentOperation.test.ts b/packages/database/src/models/__tests__/agentOperation.test.ts
index f135c4291ee..739b8b33ccc 100644
--- a/packages/database/src/models/__tests__/agentOperation.test.ts
+++ b/packages/database/src/models/__tests__/agentOperation.test.ts
@@ -422,6 +422,34 @@ describe('AgentOperationModel', () => {
});
describe('operation lease', () => {
+ it('answers whether a run is still live on a given topic', async () => {
+ // The ingest path falls back to this when a topic loses its
+ // `runningOperation` marker: the row, not the marker, says whether the
+ // producer behind a batch is still alive β€” and the topic pairing keeps
+ // the answer from authorizing a write to someone else's topic.
+ await serverDB.insert(topics).values([
+ { id: 'live-topic', userId },
+ { id: 'other-topic', userId },
+ ]);
+ const model = new AgentOperationModel(serverDB, userId);
+ const operationId = 'op-live-on-topic';
+ await model.recordStart({ operationId, topicId: 'live-topic' });
+
+ expect(await model.isRunningOnTopic(operationId, 'live-topic')).toBe(true);
+ // Bound to another topic, so it cannot vouch for a write to this one.
+ expect(await model.isRunningOnTopic(operationId, 'other-topic')).toBe(false);
+ // Another user's row is out of scope entirely.
+ expect(
+ await new AgentOperationModel(serverDB, otherUserId).isRunningOnTopic(
+ operationId,
+ 'live-topic',
+ ),
+ ).toBe(false);
+
+ await model.recordCompletion(operationId, { status: 'done' });
+ expect(await model.isRunningOnTopic(operationId, 'live-topic')).toBe(false);
+ });
+
it('refreshes a running operation and only settles an expired lease', async () => {
const model = new AgentOperationModel(serverDB, userId);
const operationId = 'op-lease';
diff --git a/packages/database/src/models/agentOperation.ts b/packages/database/src/models/agentOperation.ts
index 0cf25f5dd7c..40f56cc2879 100644
--- a/packages/database/src/models/agentOperation.ts
+++ b/packages/database/src/models/agentOperation.ts
@@ -413,6 +413,34 @@ export class AgentOperationModel {
return Boolean(row);
}
+ /**
+ * Whether this operation is still running AND owns the given topic.
+ *
+ * The row β€” not `topic.metadata.runningOperation` β€” is the authority on
+ * liveness: the marker is a best-effort rendering pointer that any client can
+ * clear (a transport-level completion settles it while the producer keeps
+ * going), whereas the row only leaves `running` through a terminal path.
+ * Pairing it with `topicId` is what makes the answer safe to act on: it proves
+ * the caller is about to write to the topic this operation actually belongs
+ * to, not one it was handed.
+ */
+ async isRunningOnTopic(operationId: string, topicId: string): Promise<boolean> {
+ const [row] = await this.db
+ .select({ id: agentOperations.id })
+ .from(agentOperations)
+ .where(
+ and(
+ eq(agentOperations.id, operationId),
+ eq(agentOperations.status, 'running'),
+ eq(agentOperations.topicId, topicId),
+ this.ownership(),
+ ),
+ )
+ .limit(1);
+
+ 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.test.ts b/src/store/chat/slices/agentRun/actions/__tests__/gateway.test.ts
index da48383b0cc..0fea5d1eb45 100644
--- a/src/store/chat/slices/agentRun/actions/__tests__/gateway.test.ts
+++ b/src/store/chat/slices/agentRun/actions/__tests__/gateway.test.ts
@@ -1,4 +1,7 @@
-import type { AgentStreamEvent } from '@lobechat/agent-gateway-client';
+import type {
+ AgentStreamEvent,
+ AgentStreamSessionCompletion,
+} from '@lobechat/agent-gateway-client';
import { type ExecAgentResult, RequestTrigger } from '@lobechat/types';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
@@ -2129,18 +2132,19 @@ describe('GatewayActionImpl', () => {
expect(updateTopicStatus).not.toHaveBeenCalled();
});
- it('preserves only external-producer resume status without a terminal event', async () => {
+ it('preserves an external producer against every transport-only completion', async () => {
const runCompletion = async ({
activeTopicId = 'topic-1',
authFailed = false,
completion,
heteroType,
+ terminalReceived = false,
}: {
activeTopicId?: string | null;
authFailed?: boolean;
- completion:
- { source: 'raw_session_complete' } | { source: 'resume_status'; status: 'completed' };
+ completion: AgentStreamSessionCompletion;
heteroType: string | null | undefined;
+ terminalReceived?: boolean;
}) => {
const connectToGateway = vi.fn();
const completeOperation = vi.fn();
@@ -2216,7 +2220,7 @@ describe('GatewayActionImpl', () => {
internalDispatchTopic.mockClear();
vi.mocked(topicService.settleRunningOperation).mockClear();
- onSessionComplete({ authFailed, completion, succeeded: false, terminalReceived: false });
+ onSessionComplete({ authFailed, completion, succeeded: false, terminalReceived });
return { completeOperation, internalDispatchTopic };
};
@@ -2258,18 +2262,44 @@ describe('GatewayActionImpl', () => {
'unread',
);
- await runCompletion({
+ // A hetero CLI streams through `heteroIngest`, not this socket, so none of
+ // these prove it stopped. Settling on one clears the topic marker and the
+ // server then discards everything the still-running CLI produces.
+ const rawHeteroComplete = await runCompletion({
completion: { source: 'raw_session_complete' },
heteroType: 'claude-code',
});
- expect(topicService.settleRunningOperation).toHaveBeenCalled();
+ expect(topicService.settleRunningOperation).not.toHaveBeenCalled();
+ expect(rawHeteroComplete.internalDispatchTopic).not.toHaveBeenCalled();
+ // Protocol v2 only: a terminal `status_change` ends the subscription. v1
+ // ignored the message entirely.
+ await runCompletion({
+ completion: { source: 'status_change', status: 'error' },
+ heteroType: 'claude-code',
+ });
+ expect(topicService.settleRunningOperation).not.toHaveBeenCalled();
+
+ // On the multiplexed socket ONE auth failure is fanned out to every
+ // operation the tab is watching.
await runCompletion({
authFailed: true,
completion: { source: 'resume_status', status: 'completed' },
heteroType: 'claude-code',
});
- expect(topicService.settleRunningOperation).toHaveBeenCalled();
+ expect(topicService.settleRunningOperation).not.toHaveBeenCalled();
+
+ // The producer's own terminal event remains authoritative.
+ await runCompletion({
+ completion: { source: 'agent_event' },
+ heteroType: 'claude-code',
+ terminalReceived: true,
+ });
+ expect(topicService.settleRunningOperation).toHaveBeenCalledWith(
+ 'topic-1',
+ 'server-op-1',
+ 'active',
+ );
});
// Regression guard: a successful run the user is watching must reset the
@@ -3141,7 +3171,7 @@ describe('GatewayActionImpl', () => {
expect(topicService.settleRunningOperation).not.toHaveBeenCalled();
});
- it('settles normal runtime and raw heterogeneous session completions', async () => {
+ it('settles a normal runtime completion but never an external producer', async () => {
const normal = createOnSessionCompleteHarness();
await normal.action.reconnectToGatewayOperation({
assistantMessageId: 'ast-1',
@@ -3164,6 +3194,9 @@ describe('GatewayActionImpl', () => {
'active',
);
+ // The CLI behind a hetero run streams through `heteroIngest`, so a raw
+ // session_complete on this socket says nothing about whether it stopped β€”
+ // and settling here makes the server discard the rest of its output.
const rawHetero = createOnSessionCompleteHarness();
await rawHetero.action.reconnectToGatewayOperation({
assistantMessageId: 'ast-1',
@@ -3180,11 +3213,7 @@ describe('GatewayActionImpl', () => {
terminalReceived: false,
});
expect(rawHetero.completeOperation).toHaveBeenCalledWith('gw-op-reconnect');
- expect(topicService.settleRunningOperation).toHaveBeenCalledWith(
- 'topic-1',
- 'server-op-1',
- 'active',
- );
+ expect(topicService.settleRunningOperation).not.toHaveBeenCalled();
});
// A genuine terminal event (agent_runtime_end / error) still finalizes the
@@ -3215,15 +3244,16 @@ describe('GatewayActionImpl', () => {
);
});
- // auth_failed (or a failed token refresh) is authoritative that the op is
- // gone: clear the stale marker AND complete the local op, so reloads / drawer
- // opens stop reconnecting to a dead operation. Without this the persisted
- // runningOperation lingers forever.
+ // auth_failed (or a failed token refresh) is authoritative that a
+ // gateway-run op is gone: clear the stale marker AND complete the local op,
+ // so reloads / drawer opens stop reconnecting to a dead operation. Without
+ // this the persisted runningOperation lingers forever.
it('clears runningOperation and completes the local op on auth failure', async () => {
const { action, captured, completeOperation } = createOnSessionCompleteHarness();
await action.reconnectToGatewayOperation({
assistantMessageId: 'ast-1',
+ heteroType: null,
operationId: 'server-op-1',
topicId: 'topic-1',
});
@@ -3241,6 +3271,29 @@ describe('GatewayActionImpl', () => {
);
});
+ // ...but an auth failure is NOT authoritative for an external producer. On
+ // the multiplexed socket a single refused token fails every subscription on
+ // the tab at once, which would settle every hetero run the user has going
+ // and throw away everything they produce from then on.
+ it('keeps an external producer running when the socket fails auth', async () => {
+ const { action, captured, completeOperation } = createOnSessionCompleteHarness();
+
+ await action.reconnectToGatewayOperation({
+ assistantMessageId: 'ast-1',
+ heteroType: 'claude-code',
+ operationId: 'server-op-1',
+ topicId: 'topic-1',
+ });
+
+ vi.mocked(topicService.settleRunningOperation)
+ .mockClear()
+ .mockResolvedValue(undefined as never);
+ captured.onSessionComplete!({ authFailed: true, succeeded: false, terminalReceived: false });
+
+ expect(completeOperation).toHaveBeenCalledWith('gw-op-reconnect');
+ expect(topicService.settleRunningOperation).not.toHaveBeenCalled();
+ });
+
// The case that stranded 7 topics on a self-hosted deployment: a run that
// finishes cleanly while the user is on a DIFFERENT topic.
//
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 f50e3a1a418..5d16846f921 100644
--- a/src/store/chat/slices/agentRun/actions/transports/gateway/gateway.ts
+++ b/src/store/chat/slices/agentRun/actions/transports/gateway/gateway.ts
@@ -1413,17 +1413,22 @@ export class GatewayActionImpl {
// terminal-missing fallback so the op never sticks `running`.
if (!terminalReceived) this.#get().completeOperation(gatewayOpId);
- // A terminal resume status is ambiguous only for an external hetero
- // producer: an older or degraded Gateway may have no initialized DO
- // session while the CLI is still alive and streaming via heteroIngest.
- // Preserve unknown (`undefined`) during rolling deploys; new normal
- // runtimes explicitly return `heteroType: null`. A raw session_complete,
- // real terminal event, or auth failure remains authoritative.
- const preserveExternalProducer =
- !terminalReceived &&
- !authFailed &&
- completion?.source === 'resume_status' &&
- result.heteroType !== null;
+ // 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;
const effectiveSucceeded = isSuccessfulGatewayCompletion({
@@ -1698,17 +1703,15 @@ export class GatewayActionImpl {
// the preserved external producer case below) must close it here.
if (!terminalReceived) this.#get().completeOperation(gatewayOpId);
- // A reconnect is passive. Preserve only an external/rolling-unknown
- // producer whose terminal resume status may mean "Gateway session was
- // never initialized" rather than "producer ended". New normal runtime
- // markers carry `heteroType: null`; old markers omit the field, so the
- // rolling-deploy fallback is deliberately fail-safe. Raw session_complete,
- // terminal events and auth failures are authoritative and settle below.
- const preserveExternalProducer =
- !terminalReceived &&
- !authFailed &&
- completion?.source === 'resume_status' &&
- heteroType !== null;
+ // 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) {
return;
}