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(opencode): preserve completed replies after web search cancellation (#23733)

Mocha2d5beaa230e1
diff --git a/apps/desktop/src/main/controllers/HeterogeneousAgentImpl.ts b/apps/desktop/src/main/controllers/HeterogeneousAgentImpl.ts
index a4d3fd0933a..274ec66ea3d 100644
--- a/apps/desktop/src/main/controllers/HeterogeneousAgentImpl.ts
+++ b/apps/desktop/src/main/controllers/HeterogeneousAgentImpl.ts
@@ -2516,7 +2516,7 @@ export default class HeterogeneousAgentCtr {
session.liveInput = undefined;
if (code === 0) broadcastStreamEvents(pipeline.validateCompletion());
const liveEnd = endLiveCliRun(pipeline, liveInput, { code, sawError, signal });
- if (code === 0 || liveEnd.length > 0) {
+ if (pipeline.resolveExitCode(code) === 0 || liveEnd.length > 0) {
broadcastStreamEvents(liveEnd);
this.broadcast('heteroAgentSessionComplete', { sessionId: session.sessionId });
resolve();
diff --git a/packages/heterogeneous-agents/src/adapters/opencode.ts b/packages/heterogeneous-agents/src/adapters/opencode.ts
index e1722a3a7a8..fe7a56d22b4 100644
--- a/packages/heterogeneous-agents/src/adapters/opencode.ts
+++ b/packages/heterogeneous-agents/src/adapters/opencode.ts
@@ -12,6 +12,8 @@ import type {
const OPENCODE_IDENTIFIER = 'opencode';
const OPENCODE_TODO_WRITE_API = 'todowrite';
+const WEB_SEARCH_INPUT_CANCELLED =
+ 'Cancelled a request for input this run cannot answer: Web Search';
// OpenCode 2.x renamed `bash` to `shell` (same `command` input). Keep the 1.x
// name so command renders and git-effect recording apply to both majors.
const OPENCODE_TOOL_ALIASES: Record<string, string> = { shell: 'bash' };
@@ -94,6 +96,10 @@ export class OpenCodeAdapter implements AgentEventAdapter {
private stepIndex = 0;
private streamOpen = false;
private terminalErrorEmitted = false;
+ private cancelledWebSearchStep?: number;
+ private textStep?: number;
+ private completedReplyStep?: number;
+ private recoveredWebSearchStep?: number;
adapt(raw: any): HeterogeneousAgentEvent[] {
if (!raw || typeof raw !== 'object') return [];
@@ -128,6 +134,14 @@ export class OpenCodeAdapter implements AgentEventAdapter {
return [this.makeEvent('stream_end', {})];
}
+ resolveExitCode(code: number | null): number | null {
+ return code === 1 &&
+ this.recoveredWebSearchStep === this.stepIndex &&
+ !this.terminalErrorEmitted
+ ? 0
+ : code;
+ }
+
private handleStepStart(part: any): HeterogeneousAgentEvent[] {
if (!part || part.type !== 'step-start' || !part.id || this.completedPartIds.has(part.id)) {
return [];
@@ -155,6 +169,7 @@ export class OpenCodeAdapter implements AgentEventAdapter {
if (!part || part.type !== type || !part.id || this.completedPartIds.has(part.id)) return [];
this.completedPartIds.add(part.id);
if (typeof part.text !== 'string' || !part.text) return [];
+ if (type === 'text' && part.text.trim()) this.textStep = this.stepIndex;
return [
this.makeEvent(
@@ -171,6 +186,14 @@ export class OpenCodeAdapter implements AgentEventAdapter {
return [];
}
this.completedPartIds.add(part.id);
+ if (
+ part.reason === 'stop' &&
+ this.textStep === this.stepIndex &&
+ this.cancelledWebSearchStep !== undefined &&
+ this.cancelledWebSearchStep < this.stepIndex
+ ) {
+ this.completedReplyStep = this.stepIndex;
+ }
const data: StepCompleteData = {
costUsd: finiteNumber(part.cost),
phase: 'turn_metadata',
@@ -206,6 +229,9 @@ export class OpenCodeAdapter implements AgentEventAdapter {
type: 'default',
};
const isError = state.status === 'error';
+ if (part.tool === 'websearch' && isError && state.error === 'Web search cancelled') {
+ this.cancelledWebSearchStep = this.stepIndex;
+ }
const pluginState =
!isError && part.tool === OPENCODE_TODO_WRITE_API
? synthesizeTodoWritePluginState(state.metadata?.todos ?? state.input?.todos)
@@ -226,8 +252,18 @@ export class OpenCodeAdapter implements AgentEventAdapter {
private handleError(error: any): HeterogeneousAgentEvent[] {
if (this.terminalErrorEmitted) return [];
- this.terminalErrorEmitted = true;
const message = errorMessage(error);
+ // OpenCode 2 reports its headless form cancellation even after the model
+ // finishes a reply. The cancelled search already has its own tool error.
+ if (
+ error?.type === 'unknown' &&
+ message === WEB_SEARCH_INPUT_CANCELLED &&
+ this.completedReplyStep === this.stepIndex
+ ) {
+ this.recoveredWebSearchStep = this.stepIndex;
+ return [];
+ }
+ this.terminalErrorEmitted = true;
const authRequired = isAuthError(error, message);
const data: HeterogeneousTerminalErrorData = {
agentType: OPENCODE_IDENTIFIER,
diff --git a/packages/heterogeneous-agents/src/spawn/agentStreamPipeline.test.ts b/packages/heterogeneous-agents/src/spawn/agentStreamPipeline.test.ts
index 048adb68cb0..401606520c4 100644
--- a/packages/heterogeneous-agents/src/spawn/agentStreamPipeline.test.ts
+++ b/packages/heterogeneous-agents/src/spawn/agentStreamPipeline.test.ts
@@ -61,6 +61,96 @@ describe('AgentStreamPipeline', () => {
await Promise.all(tempDirs.splice(0).map((dir) => rm(dir, { force: true, recursive: true })));
});
+ it.each([
+ {
+ expectedCode: 0,
+ finishReason: 'stop',
+ message: 'Web Search',
+ reply: 'Search was unavailable.',
+ },
+ { expectedCode: 1, finishReason: 'stop', message: 'Web Search', reply: ' ' },
+ { expectedCode: 1, finishReason: 'length', message: 'Web Search', reply: 'Partial answer' },
+ {
+ expectedCode: 1,
+ finishReason: 'stop',
+ message: 'Other input',
+ reply: 'Search was unavailable.',
+ },
+ {
+ expectedCode: 1,
+ finishReason: 'stop',
+ message: 'Web Search',
+ providerError: true,
+ reply: 'Search was unavailable.',
+ },
+ ])(
+ 'settles an OpenCode cancellation ($finishReason, $message, "$reply", provider error: $providerError)',
+ async ({ expectedCode, finishReason, message, providerError, reply }) => {
+ const pipeline = new AgentStreamPipeline({ agentType: 'opencode', operationId: 'op-search' });
+ const nativeEvents = [
+ { part: { id: 'step-1', type: 'step-start' }, type: 'step_start' },
+ {
+ part: {
+ id: 'search-call',
+ partID: 'search-part',
+ state: { error: 'Web search cancelled', input: { query: 'example' }, status: 'error' },
+ tool: 'websearch',
+ type: 'tool',
+ },
+ type: 'tool_use',
+ },
+ {
+ part: { id: 'end-1', reason: 'tool-calls', type: 'step-finish' },
+ type: 'step_finish',
+ },
+ { part: { id: 'step-2', type: 'step-start' }, type: 'step_start' },
+ { part: { id: 'answer', text: reply, type: 'text' }, type: 'text' },
+ {
+ part: { id: 'end-2', reason: finishReason, type: 'step-finish' },
+ type: 'step_finish',
+ },
+ {
+ error: {
+ message: `Cancelled a request for input this run cannot answer: ${message}`,
+ type: 'unknown',
+ },
+ type: 'error',
+ },
+ ];
+ if (providerError) {
+ nativeEvents.push({
+ error: { message: 'Model unavailable', type: 'provider' },
+ type: 'error',
+ });
+ }
+ const events = [
+ ...(await pipeline.push(nativeEvents.map((event) => JSON.stringify(event)).join('\n'))),
+ ...(await pipeline.flush()),
+ ];
+
+ expect(events).toContainEqual(
+ expect.objectContaining({
+ data: expect.objectContaining({ content: 'Web search cancelled', isError: true }),
+ type: 'tool_result',
+ }),
+ );
+ expect(events).toContainEqual(
+ expect.objectContaining({
+ data: expect.objectContaining({ content: reply }),
+ type: 'stream_chunk',
+ }),
+ );
+ expect(events.some(({ type }) => type === 'error')).toBe(expectedCode !== 0);
+ if (providerError) {
+ expect(events.find(({ type }) => type === 'error')?.data?.message).toBe(
+ 'Model unavailable',
+ );
+ }
+ expect(pipeline.resolveExitCode(1)).toBe(expectedCode);
+ expect(pipeline.resolveExitCode(null)).toBeNull();
+ },
+ );
+
it.each(['uploaded', 'unavailable', 'failed'])(
'recovers only the current rollout images before stream end (%s)',
async (upload) => {
diff --git a/packages/heterogeneous-agents/src/spawn/agentStreamPipeline.ts b/packages/heterogeneous-agents/src/spawn/agentStreamPipeline.ts
index 331037ff17a..c98276fcbd7 100644
--- a/packages/heterogeneous-agents/src/spawn/agentStreamPipeline.ts
+++ b/packages/heterogeneous-agents/src/spawn/agentStreamPipeline.ts
@@ -184,6 +184,10 @@ export class AgentStreamPipeline {
return this.toStreamEvents(this.adapter.validateCompletion?.() ?? []);
}
+ resolveExitCode(code: number | null): number | null {
+ return this.adapter.resolveExitCode?.(code) ?? code;
+ }
+
private async processPayloads(payloads: unknown[]): Promise<AgentStreamEvent[]> {
const out: AgentStreamEvent[] = this.drainQueuedEvents();
diff --git a/packages/heterogeneous-agents/src/spawn/spawnAgent.ts b/packages/heterogeneous-agents/src/spawn/spawnAgent.ts
index d4a0dff7ea1..711e2489623 100644
--- a/packages/heterogeneous-agents/src/spawn/spawnAgent.ts
+++ b/packages/heterogeneous-agents/src/spawn/spawnAgent.ts
@@ -1,5 +1,6 @@
import type { ChildProcess } from 'node:child_process';
import { platform } from 'node:os';
+import { finished } from 'node:stream/promises';
import type { AgentStreamEvent } from '@lobechat/agent-gateway-client';
import type { CodexCollaborationMode, HeteroPermissionMode } from '@lobechat/types';
@@ -150,11 +151,9 @@ export interface SpawnAgentHandle {
*/
events: AsyncIterable<AgentStreamEvent>;
/**
- * Resolves once the child process exits. Note: this resolves on the
- * underlying `'exit'` event, which Node may fire before stdio is fully
- * closed — `events` already gates on `stdout` end internally, so consumers
- * should iterate `events` to completion BEFORE awaiting `exit` if they
- * care about ordering.
+ * Resolves after process exit, which can precede stdio closure. OpenCode
+ * exit 1 also waits for stdout to determine the outcome. Drain `events`
+ * before awaiting `exit` when event ordering matters.
*/
exit: Promise<{ code: number | null; signal: NodeJS.Signals | null }>;
/**
@@ -846,7 +845,22 @@ const spawnCliAgent = async (
return {
events,
- exit,
+ exit:
+ options.agentType === 'opencode'
+ ? exit.then(async (status) => {
+ if (status.code !== 1 || status.signal || killedByUs) return status;
+ try {
+ await finished(stdout, { cleanup: true, writable: false });
+ await pipelineQueue;
+ if (!streamError && !killedByUs) {
+ return { ...status, code: pipeline.resolveExitCode(status.code) };
+ }
+ } catch {
+ // A broken stdout stream cannot establish a completed reply.
+ }
+ return status;
+ })
+ : exit,
...(claudeLive && {
interruptTurn: () => claudeLive.interrupt(),
sendControlRequest: (request: ClaudeCodeControlRequest) =>
diff --git a/packages/heterogeneous-agents/src/types.ts b/packages/heterogeneous-agents/src/types.ts
index d70f7a26a7c..30a17090d34 100644
--- a/packages/heterogeneous-agents/src/types.ts
+++ b/packages/heterogeneous-agents/src/types.ts
@@ -491,6 +491,9 @@ export interface AgentEventAdapter {
*/
flush: () => HeterogeneousAgentEvent[];
+ /** Interpret the native CLI exit code after stdout has fully drained. */
+ resolveExitCode?: (code: number | null) => number | null;
+
/** The session ID extracted from the agent's init event (for multi-turn resume). */
sessionId?: string;