fix(opencode): surface v2 scheduled retries (#2300)

This commit is contained in:
Junmo Kim
2026-11-07 08:15:41 +08:00
committed by GitHub
parent 3caa3f9e84
commit df96b3b8fb
3 changed files with 282 additions and 46 deletions
@@ -2834,6 +2834,100 @@ describe('opencodeRemoteLauncher mid-turn steer', () => {
}
});
it('keeps inbox receipts and retry progress live while v2 cancellation drains, then closes the stream', async () => {
harness.detectedVersion = 'v2';
harness.discoveredPort = 48274;
harness.discoveredPassword = 'synthetic-password';
const actual = await vi.importActual<typeof import('./utils/opencodeEventStream')>('./utils/opencodeEventStream');
const eventStreamModule = await import('./utils/opencodeEventStream');
let controller!: ReadableStreamDefaultController<Uint8Array>;
let streamCancelled = false;
const stream = new ReadableStream<Uint8Array>({
start(value) { controller = value; },
cancel() { streamCancelled = true; }
});
const push = (type: string, data: Record<string, unknown>) => {
controller.enqueue(new TextEncoder().encode(`data: ${JSON.stringify({ type, data })}\n\n`));
};
const retry = (attempt: number) => push('session.retry.scheduled', {
sessionID: 'acp-session-1', attempt, error: { message: 'Fixture rate limit' }
});
let subscriptionClosed = false;
vi.mocked(eventStreamModule.subscribeToOpencodeEvents).mockImplementationOnce(options => {
expect(options).toMatchObject({ mode: 'v2', sessionId: 'acp-session-1' });
const subscription = actual.subscribeToOpencodeEvents({
...options,
fetchImpl: async () => new Response(stream, { headers: { 'content-type': 'text/event-stream' } })
});
return { close() { subscriptionClosed = true; subscription.close(); } };
});
let inputId = '';
let deleteStarted = false;
let delivered = false;
let releaseDelete!: () => void;
const deleting = new Promise<void>(resolve => { releaseDelete = resolve; });
const nativeFetch = vi.spyOn(globalThis, 'fetch').mockImplementation(async (url, init) => {
if (init?.method === 'POST') inputId = JSON.parse(String(init.body)).id;
if (init?.method === 'DELETE') {
deleteStarted = true;
await deleting;
return new Response(null, { status: 204 });
}
const item = { id: inputId, sessionID: 'acp-session-1', type: 'user', delivery: 'steer', payload: { text: 'correction' } };
if (init?.method === 'POST') return Response.json({ data: item });
return Response.json({ data: String(url).endsWith('/inbox') ? delivered ? [] : [item]
: { id: inputId, sessionID: 'acp-session-1', type: 'user', text: 'correction' } });
});
const { stub, releasePrompt, runPromise } = await startTurn();
let switching: Promise<void> | undefined;
try {
stub.session.queue.push('correction', createMode(), 'v2-steer');
await expect(steerHandlerOf(stub)({ localId: 'v2-steer' })).resolves.toEqual({ steered: true });
retry(2);
push('session.inbox.enqueued', { sessionID: 'acp-session-1', inboxID: inputId,
item: { type: 'user', payload: { text: 'correction' } } });
retry(2);
await vi.waitFor(() => expect(stub.claudeSessionMessages).toHaveLength(1));
expect(stub.emitMessagesConsumedCalls).toEqual([]);
switching = (stub.rpcHandlers.get('switch') as () => Promise<void>)();
await vi.waitFor(() => expect(deleteStarted).toBe(true));
releasePrompt();
stub.session.queue.close();
await vi.waitFor(() => expect(harness.events).toContain('prompt:end'));
expect(subscriptionClosed).toBe(false);
expect(harness.cleanupEvents).not.toContain('cleanup:disconnect');
// The real parser still feeds both launcher consumers while the
// native DELETE and foreground drain await the delivery outcome.
retry(3);
push('session.step.started', { sessionID: 'acp-session-1' });
retry(2);
await vi.waitFor(() => expect(stub.claudeSessionMessages).toHaveLength(3));
expect(stub.claudeSessionMessages.map(message => (message as { retryAttempt: number }).retryAttempt)).toEqual([1, 2, 1]);
delivered = true;
push('session.inbox.delivered', { sessionID: 'acp-session-1', inboxID: inputId });
push('session.inbox.delivered', { sessionID: 'acp-session-1', inboxID: inputId });
await vi.waitFor(() => expect(stub.emitMessagesConsumedCalls).toEqual([
{ localIds: ['v2-steer'], options: { steered: true } }
]));
releaseDelete();
await Promise.all([switching, runPromise]);
expect(subscriptionClosed).toBe(true);
expect(streamCancelled).toBe(true);
expect(harness.cleanupEvents).toContain('cleanup:disconnect');
expect(stub.emitMessagesConsumedCalls).toHaveLength(1);
expect(harness.softSteerCalls).toEqual([]);
} finally {
delivered = true;
releaseDelete();
releasePrompt();
stub.session.queue.close();
await Promise.all([switching, runPromise]);
nativeFetch.mockRestore();
}
});
it('v2 recovers a missing delivered event by exact native projection readback', async () => {
harness.detectedVersion = 'v2'; harness.discoveredPort = 48274; harness.discoveredPassword = 'test-only';
let id = '';
@@ -68,6 +68,20 @@ function retryEvent(attempt: number, sessionId = 'ses_ours') {
};
}
function scheduledRetryEvent(attempt: number, sessionId = 'ses_ours') {
return {
id: `evt_retry_${attempt}`,
type: 'session.retry.scheduled',
data: {
sessionID: sessionId,
assistantMessageID: 'msg_assistant',
attempt,
at: NOW + 30_000,
error: { message: 'Rate limit exceeded.' }
}
};
}
function statusEvent(type: 'busy' | 'idle', sessionId = 'ses_ours') {
return {
id: `evt_${type}`,
@@ -79,6 +93,7 @@ function statusEvent(type: 'busy' | 'idle', sessionId = 'ses_ours') {
function subscribe(options: {
fetchImpl: (url: string, init?: RequestInit) => Promise<Response>;
onRetry?: (retry: { attempt: number; message: string }) => void;
onEvent?: (type: string, properties: Record<string, unknown>, eventId?: string) => void;
/** Records the backoff schedule instead of waiting it out. */
delays?: number[];
/**
@@ -96,6 +111,7 @@ function subscribe(options: {
directory: SESSION_CWD,
sessionId: 'ses_ours',
onRetry: options.onRetry ?? (() => {}),
onEvent: options.onEvent,
headers: options.headers,
mode: options.mode,
fetchImpl: options.fetchImpl,
@@ -192,6 +208,121 @@ describe('subscribeToOpencodeEvents', () => {
sse.close();
});
it('reports v2 scheduled retries with HAPI numbering, sampling and step dedupe boundaries', async () => {
const sse = createSseStream();
const fetchImpl = vi.fn(async () => new Response(sse.stream));
const retries: number[] = [];
const onEvent = vi.fn();
const subscription = subscribe({ fetchImpl, mode: 'v2', onEvent, onRetry: (retry) => retries.push(retry.attempt) });
try {
sse.push(scheduledRetryEvent(2));
sse.push(scheduledRetryEvent(2));
sse.push(scheduledRetryEvent(3));
sse.push(scheduledRetryEvent(4));
sse.push(scheduledRetryEvent(5));
sse.push(scheduledRetryEvent(6));
sse.push(scheduledRetryEvent(9));
sse.push(scheduledRetryEvent(2));
sse.push({ type: 'session.step.started', data: { sessionID: 'ses_ours' } });
sse.push(scheduledRetryEvent(2));
await vi.waitFor(() => expect(retries).toEqual([1, 2, 3, 4, 8, 1, 1]));
expect(onEvent).toHaveBeenCalledWith('session.retry.scheduled', scheduledRetryEvent(2).data, 'evt_retry_2');
} finally {
subscription.close();
}
});
it.each([
'session.step.started',
'session.execution.started',
'session.execution.succeeded',
'session.execution.failed',
'session.execution.interrupted'
])('resets v2 dedupe only for the subscribed session on %s', async (type) => {
const sse = createSseStream();
const fetchImpl = vi.fn(async () => new Response(sse.stream));
const retries: number[] = [];
const onEvent = vi.fn();
const subscription = subscribe({ fetchImpl, mode: 'v2', onEvent, onRetry: (retry) => retries.push(retry.attempt) });
try {
sse.push(scheduledRetryEvent(2));
sse.push({ type, data: { sessionID: 'ses_other' } });
sse.push(scheduledRetryEvent(2));
sse.push(scheduledRetryEvent(3, 'ses_other'));
sse.push(scheduledRetryEvent(2));
sse.push({ type, data: {} });
sse.push(scheduledRetryEvent(2));
sse.push({ type, data: { sessionID: 'ses_ours' } });
sse.push(scheduledRetryEvent(2));
await vi.waitFor(() => expect(retries).toEqual([1, 1]));
expect(onEvent.mock.calls.every(([, properties]) => properties.sessionID === 'ses_ours')).toBe(true);
} finally {
subscription.close();
}
});
it('validates v2 attempts and message text without resetting dedupe on unreadable retries', async () => {
const sse = createSseStream();
const fetchImpl = vi.fn(async () => new Response(sse.stream));
const retries: Array<{ attempt: number; message: string }> = [];
const subscription = subscribe({ fetchImpl, mode: 'v2', onRetry: (retry) => retries.push(retry) });
try {
sse.push(scheduledRetryEvent(2));
for (const attempt of [1, 0, -2, 2.5, '2', null, undefined]) {
const event = scheduledRetryEvent(2);
sse.push({ ...event, data: { ...event.data, attempt } });
}
// JSON.stringify turns Infinity into null; send the overflowing literal on the wire.
sse.pushRaw('data: {"type":"session.retry.scheduled","data":{"sessionID":"ses_ours","attempt":1e400,"error":{"message":"bad"}}}\n\n');
for (const error of [null, {}, { message: '' }, { message: ' \n \t ' }, { message: 42 }]) {
const event = scheduledRetryEvent(3);
sse.push({ ...event, data: { ...event.data, error } });
}
sse.push(scheduledRetryEvent(2));
const event = scheduledRetryEvent(3);
const message = ' Rate\n limit\t ' + 'x'.repeat(OPENCODE_PROVIDER_TEXT_MAX_LENGTH * 2);
sse.push({ ...event, data: { ...event.data, error: { message } } });
await vi.waitFor(() => expect(retries).toEqual([
{ attempt: 1, message: 'Rate limit exceeded.' },
{ attempt: 2, message: truncateOpencodeProviderText('Rate limit ' + 'x'.repeat(OPENCODE_PROVIDER_TEXT_MAX_LENGTH * 2)) }
]));
expect(retries[1].message).toHaveLength(OPENCODE_PROVIDER_TEXT_MAX_LENGTH);
} finally {
subscription.close();
}
});
it('never relays v2 error details or malformed payloads into retry callbacks or logs', async () => {
const marker = 'synthetic-do-not-relay';
const sse = createSseStream();
const fetchImpl = vi.fn(async () => new Response(sse.stream));
const onRetry = vi.fn();
vi.mocked(logger.debug).mockClear();
vi.mocked(logger.warn).mockClear();
const subscription = subscribe({ fetchImpl, mode: 'v2', onRetry });
try {
const event = scheduledRetryEvent(2);
const details = { response: { body: marker, headers: { authorization: marker } }, status: marker, type: marker };
sse.push({ ...event, data: { ...event.data, error: { ...details, message: 'Safe provider message' } } });
sse.push({ ...event, data: { ...event.data, attempt: 3, error: { ...details, message: '' } } });
sse.pushRaw(`data: {"${marker}": invalid}\n\n`);
// Exercise the preserved v1-shaped event path on this same v2 stream as well.
sse.push({ type: 'session.status', data: { sessionID: 'ses_ours', status: { type: 'retry', attempt: 3, message: '', response: marker } } });
sse.push(scheduledRetryEvent(3));
await vi.waitFor(() => expect(onRetry).toHaveBeenCalledTimes(2));
expect(onRetry.mock.calls).toEqual([
[{ attempt: 1, message: 'Safe provider message' }],
[{ attempt: 2, message: 'Rate limit exceeded.' }]
]);
const logged = [...vi.mocked(logger.debug).mock.calls, ...vi.mocked(logger.warn).mock.calls];
// Include Error.message: JSON.stringify(Error) alone would hide parse-error leakage.
expect(JSON.stringify(logged, (_key, value) => value instanceof Error ? value.message : value)).not.toContain(marker);
expect(logged.some(([message]) => String(message).includes('retry reporting is live'))).toBe(true);
} finally {
subscription.close();
}
});
it('merges caller headers into every connect attempt (v2 Basic auth)', async () => {
const sse = createSseStream();
const fetchImpl = vi.fn(async (_url: string, _init?: RequestInit) => new Response(sse.stream, { status: 200 }));
+57 -46
View File
@@ -4,11 +4,12 @@ import type { FetchLike } from './opencodeCompactBridge';
import { collapseWhitespace, truncateOpencodeProviderText } from './opencodeErrorText';
/**
* `session.status` with `type: "retry"` — OpenCode announcing that it hit an
* upstream failure and will try again.
* An OpenCode retry announcement, normalized from v1 `session.status` or
* v2 `session.retry.scheduled` into a one-based retry count.
*
* The payload also carries `next` (the absolute timestamp of the following
* The v1 payload also carries `next` (the absolute timestamp of the following
* attempt) and an optional `action` (a title/message/label/link hint).
* v2 carries its timestamp as `at`; neither timestamp is rendered.
* Neither is modelled. `next` would only invite a countdown, which must not
* be rendered — see formatOpencodeRetryStatus. `action` has never been
* observed on a live retry, and rendering it meant concatenating four more
@@ -82,10 +83,11 @@ const UNPRODUCTIVE_ATTEMPTS_BEFORE_WARNING = 5;
* over SSE to every connected client, and it is kept in session exports.
* `foldApiErrorEvents` collapses a run of them when a client renders, but
* that is a view concern — the rows, the traffic and the export are not
* folded. OpenCode never gives up and its backoff tops out at 30 seconds,
* so an unfiltered subscription writes about two rows a minute for as long
* as the provider keeps refusing: the measured 40-minute stall alone would
* have been 85 of them, and a session left overnight is four figures.
* folded. The measured OpenCode 1.18.15 retry loop kept going for a
* 40-minute stall (85 retries), with backoff capped at 30 seconds. An
* unfiltered subscription would persist each of those reports. Newer
* versions may bound retries, but retaining this sampling policy keeps
* long runs legible across versions.
*
* Sampling on the attempt number rather than on elapsed time keeps this a
* pure function of what the agent itself published — so it is decidable the
@@ -116,7 +118,7 @@ function isReportableRetryAttempt(attempt: number): boolean {
* like a clean end of stream forever, reconnecting twice a second without
* even logging it.
*
* There is no attempt ceiling on purpose. This is the only channel carrying
* There is no connection-attempt ceiling on purpose. This subscription carries
* upstream retry reports, a reconnect costs a loopback request, and a
* session can outlive a transient outage by hours — giving up for good
* would silently leave the user back where this feature started. (Only a
@@ -154,7 +156,7 @@ export function formatOpencodeRetryStatus(status: OpencodeRetryStatus): string {
}
/**
* Reads one `session.status` retry payload.
* Validates the count and message from either retry event dialect.
*
* Every string here is provider-authored and unbounded, exactly like the
* `session/prompt` error message, so it is capped at the parse boundary —
@@ -162,8 +164,7 @@ export function formatOpencodeRetryStatus(status: OpencodeRetryStatus): string {
* rendered. See OPENCODE_PROVIDER_TEXT_MAX_LENGTH for the measurement
* behind that.
*/
function parseRetryStatus(status: unknown): OpencodeRetryStatus | null {
if (!isObject(status) || status.type !== 'retry') return null;
function parseRetryStatus(attemptValue: unknown, messageValue: unknown): OpencodeRetryStatus | null {
// A counting number or nothing. `typeof === 'number'` would let
// JSON.parse's Infinity (from an overflowing literal) through, and
// asNumber alone still admits 0, -1 and 0.5 — all of which satisfy the
@@ -171,12 +172,12 @@ function parseRetryStatus(status: unknown): OpencodeRetryStatus | null {
// "(attempt 0.5)". Zero is worse than cosmetic: it is the same value
// the turn-boundary reset uses as its sentinel, so accepting it merges
// "saw a retry" with "this turn has had none".
const attempt = asNumber(status.attempt);
const attempt = asNumber(attemptValue);
// Collapsed before it is judged, not after: a provider message of " \n "
// is truthy but says nothing, and embedded newlines would survive into a
// status line this module promises to keep to one line. Truncating alone
// does neither.
const message = collapseWhitespace(asString(status.message) ?? '');
const message = collapseWhitespace(asString(messageValue) ?? '');
// Only what is actually rendered is required: dropping a retry because a
// field we never show is missing or malformed would hide the very report
// this exists to deliver.
@@ -187,17 +188,19 @@ function parseRetryStatus(status: unknown): OpencodeRetryStatus | null {
/**
* Subscribes to an `opencode acp` subprocess's server event stream
* (`GET {baseUrl}/event`, Server-Sent Events) and reports this session's
* (`/event` for v1, `/api/event` for v2, Server-Sent Events) and reports this session's
* upstream retries.
*
* This exists because that is the *only* channel that carries them.
* Measured against opencode 1.18.15 with a provider stubbed to always answer
* This was the only observed retry channel in opencode 1.18.15.
* Measured against that version with a provider stubbed to always answer
* 429: over 40 minutes and 85 retries the ACP channel produced zero
* `session/update` notifications and zero stderr output while
* `session/prompt` stayed pending, yet this stream emitted a
* `session.status` retry event — carrying the provider's own message and
* attempt number — throughout. Without it the user sees a session that
* appears to be thinking and never learns that it is rate limited.
* OpenCode 2.2.5 publishes `session.retry.scheduled` here; its ACP notices
* are a separate format and are not parsed by this subscription.
*
* **The `directory` query parameter is not optional.** Subscribing to the
* same server with and without it from one process and comparing: the
@@ -294,42 +297,50 @@ export function subscribeToOpencodeEvents(options: OpencodeEventStreamOptions):
const record = isObject(properties.info) ? properties.info : isObject(properties.part) ? properties.part : properties;
if (record.sessionID === sessionId) options.onEvent?.(event.type, properties, typeof event.id === 'string' ? event.id : undefined);
}
if (event.type !== 'session.status') return;
if (!properties) return;
// Status is per-session bookkeeping and drives the dedupe state
// below, so an event that cannot be attributed must not touch it.
// Retry bookkeeping must be attributed before it changes dedupe state.
if (asString(properties.sessionID) !== sessionId) return;
switch (event.type) {
case 'session.step.started':
case 'session.execution.started':
case 'session.execution.succeeded':
case 'session.execution.failed':
case 'session.execution.interrupted':
lastSeenAttempt = 0;
return;
}
if (event.type !== 'session.status' && event.type !== 'session.retry.scheduled') return;
if (!sawAttributedStatus) {
sawAttributedStatus = true;
// The one positive confirmation that this subscription is wired
// to the right session and directory. Without it, a wrong
// baseUrl and a session that simply never retried look
// identical in the logs — and this whole feature exists
// because silence was the bug.
// Constant text only: provider events may contain response credentials.
logger.debug('[opencode-events] receiving status for this session; retry reporting is live');
}
const isRetry = isObject(properties.status) && properties.status.type === 'retry';
if (!isRetry) {
// idle or busy: a turn boundary. Deliberately not surfaced —
// turn state already has its own channel, and the hub layers
// its own queue rules on top of what this session reports —
// but it does mean the next turn's attempt 1 is new
// information again. Both are honoured rather than just idle:
// a reconnect that lands between the two would otherwise leave
// the following turn's retries suppressed as duplicates.
lastSeenAttempt = 0;
return;
let retry: OpencodeRetryStatus | null;
if (event.type === 'session.retry.scheduled') {
// OpenCode 2.2.5 counts the initial request as attempt 1, then
// increments before scheduling a retry. HAPI counts retries from 1.
const attempt = asNumber(properties.attempt);
retry = parseRetryStatus(
attempt === null ? null : attempt - 1,
isObject(properties.error) ? properties.error.message : null
);
} else {
const status = properties.status;
if (!isObject(status) || status.type !== 'retry') {
// v1 idle/busy marks a turn boundary; turn state itself is
// reported through its existing channel.
lastSeenAttempt = 0;
return;
}
retry = parseRetryStatus(status.attempt, status.message);
}
const retry = parseRetryStatus(properties.status);
if (!retry) {
// A retry we could not read (empty message, schema drift) is
// still a retry: treating it as a turn boundary would reset
// the dedupe state and let the agent's next repeat of the
// same attempt through as if it were new.
logger.debug('[opencode-events] ignoring unreadable retry status', properties.status);
// Unreadable retries are still retries, not dedupe boundaries.
// Never log the payload: it may contain raw provider responses.
logger.debug('[opencode-events] ignoring unreadable retry status');
return;
}
@@ -366,8 +377,8 @@ export function subscribeToOpencodeEvents(options: OpencodeEventStreamOptions):
let payload: unknown;
try {
payload = JSON.parse(data);
} catch (error) {
logger.debug('[opencode-events] ignoring unparsable event payload', error);
} catch {
logger.debug('[opencode-events] ignoring unparsable event payload');
return;
}
// v2 wraps the v1-shaped body in an envelope: { id, type, data },
@@ -389,8 +400,8 @@ export function subscribeToOpencodeEvents(options: OpencodeEventStreamOptions):
// "unparsable payload" would file it as the latter and lose it.
try {
handleEvent(payload);
} catch (error) {
logger.debug('[opencode-events] reporting a retry threw; continuing to read the stream', error);
} catch {
logger.debug('[opencode-events] reporting a retry threw; continuing to read the stream');
}
};