Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 4 additions & 1 deletion packages/llm/src/protocols/openai-responses.ts
Original file line number Diff line number Diff line change
Expand Up @@ -610,7 +610,10 @@ const NO_EVENTS: StepResult["1"] = []
// `finish` event; `response.failed` is a hard failure that emits a
// `provider-error`. All three end the stream — kept in one set so `step` and
// the protocol's `terminal` predicate stay in sync.
const TERMINAL_TYPES = new Set(["response.completed", "response.incomplete", "response.failed"])
// `error` is terminal too: the provider emits it as the last event before
// closing a failed stream, and treating EOF after it as truncation would mask
// the real provider error (#407).
const TERMINAL_TYPES = new Set(["response.completed", "response.incomplete", "response.failed", "error"])

const onOutputTextDelta = (state: ParserState, event: OpenAIResponsesEvent): StepResult => {
if (!event.delta) return [state, NO_EVENTS]
Expand Down
20 changes: 20 additions & 0 deletions packages/llm/src/route/client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -278,10 +278,19 @@ function makeFromTransport<Body, Prepared, Frame, Event, State>(
}),
streamPrepared: (prepared: Prepared, request: LLMRequest, runtime: TransportRuntime) => {
const route = `${request.model.provider}/${request.model.route.id}`
// Tracks whether a protocol-terminal event was seen, so a clean EOF
// without one (proxy/gateway truncation) fails into the retry pipeline
// instead of completing silently and looping generation (#407).
let sawTerminal = false
const events = routeInput.transport
.frames(prepared, request, runtime)
.pipe(
Stream.mapEffect(decodeEvent(route)),
Stream.tap((event) =>
Effect.sync(() => {
if (protocol.stream.terminal?.(event)) sawTerminal = true
}),
),
protocol.stream.terminal ? Stream.takeUntil(protocol.stream.terminal) : (stream) => stream,
)
return events.pipe(
Expand All @@ -291,6 +300,17 @@ function makeFromTransport<Body, Prepared, Frame, Event, State>(
protocol.stream.onHalt ? { onHalt: protocol.stream.onHalt } : undefined,
),
Stream.catchCause((cause) => Stream.fail(streamError(route, `Failed to read ${route} stream`, cause))),
(stream) =>
Stream.concat(
stream,
Stream.fromEffect(
Effect.suspend(() =>
protocol.stream.terminal === undefined || sawTerminal
? Effect.void
: ProviderShared.eventError(route, "Provider stream ended without a terminal finish event"),
),
).pipe(Stream.drain),
),
)
},
} satisfies Route<Body, Prepared>
Expand Down
30 changes: 30 additions & 0 deletions packages/llm/test/provider/openai-responses.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -754,6 +754,36 @@ describe("OpenAI Responses route", () => {
}),
)

it.effect("fails the stream when EOF arrives without a terminal event", () =>
Effect.gen(function* () {
const body = sseEvents(
{ type: "response.output_text.delta", item_id: "msg_1", delta: "Hello" },
{ type: "response.output_text.delta", item_id: "msg_1", delta: "!" },
)
const error = yield* LLMClient.stream(request).pipe(
Stream.runCollect,
Effect.flip,
Effect.provide(fixedResponse(body)),
)

expect(error.message).toContain("Provider stream ended without a terminal finish event")
}),
)

it.effect("streams cleanly when a terminal event closes the response", () =>
Effect.gen(function* () {
const body = sseEvents(
{ type: "response.output_text.delta", item_id: "msg_1", delta: "Hello" },
{ type: "response.completed", response: { id: "resp_1" } },
)
const events = Array.from(
yield* LLMClient.stream(request).pipe(Stream.runCollect, Effect.provide(fixedResponse(body))),
)

expect(events[events.length - 1]).toMatchObject({ type: "finish", reason: "stop" })
}),
)

it.effect("parses reasoning summary stream fixtures", () =>
Effect.gen(function* () {
const body = sseEvents(
Expand Down
10 changes: 9 additions & 1 deletion packages/opencode/src/util/rpc.ts
Original file line number Diff line number Diff line change
Expand Up @@ -110,7 +110,15 @@ export function client<T extends Definition>(target: {
const requestId = id++
return new Promise((resolve, reject) => {
pending.set(requestId, { resolve, reject })
target.postMessage(JSON.stringify({ type: "rpc.request", method, input, id: requestId }))
try {
target.postMessage(JSON.stringify({ type: "rpc.request", method, input, id: requestId }))
} catch (error) {
// postMessage throws synchronously when the worker is terminated or
// in its crash-restart window; settle the call instead of leaking
// the pending entry and hanging the caller forever (#397).
pending.delete(requestId)
reject(error instanceof Error ? error : new Error(String(error)))
}
})
},
on<Data>(event: string, handler: (data: Data) => void) {
Expand Down
22 changes: 22 additions & 0 deletions packages/opencode/test/util/rpc.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,28 @@ describe("Rpc client", () => {
await expect(pending).rejects.toThrow("worker crashed")
})

test("rejects the call when postMessage throws, without leaking it", async () => {
let down = true
const target = {
postMessage(message: string) {
if (down) throw new Error("Bun worker is not running")
queueMicrotask(() =>
target.onmessage?.({
data: JSON.stringify({ type: "rpc.result", id: JSON.parse(message).id, result: "recovered" }),
} as MessageEvent<string>),
)
},
onmessage: null as ((event: MessageEvent<string>) => void) | null,
onclose: null as ((error: Error) => void) | null,
}

const client = Rpc.client<{ work: (input: string) => Promise<string> }>(target)
await expect(client.call("work", "input")).rejects.toThrow("Bun worker is not running")

down = false
await expect(client.call("work", "again")).resolves.toBe("recovered")
})

test("rejects pending calls on rpc.error replies", async () => {
const target = {
postMessage() {},
Expand Down
Loading