Skip to content

fix: finish passthrough SSE after terminal events - #1055

Closed
itling wants to merge 1 commit into
lidge-jun:devfrom
itling:agent/passthrough-done-tail
Closed

fix: finish passthrough SSE after terminal events#1055
itling wants to merge 1 commit into
lidge-jun:devfrom
itling:agent/passthrough-done-tail

Conversation

@itling

@itling itling commented Aug 5, 2026

Copy link
Copy Markdown

Problem

When a provider (e.g. DeepSeek Flash v4) ends a Responses passthrough stream with a terminal event such as response.completed / response.failed / response.incomplete but does not send data: [DONE], the relay keeps the client SSE stream open indefinitely. The client shows the assistant "thinking" forever and never receives the final response.

Fix

In src/server/relay.ts, after forwarding a terminal event, emit [DONE] and close the client stream so the client can finalize the turn.

Tests

  • Added tests/passthrough-abort.test.ts coverage for a stream that ends with response.completed and no [DONE].
  • bun test tests/passthrough-abort.test.ts passes.
  • Related relay tests and bun run typecheck pass.

Review readiness checklist

This PR stays in draft until every box below is ticked. Tick all four boxes once the requirements are met:

  • All CI tests are green on my local testing.

  • I pushed my PR to the latest dev commit.

  • I fixed all correct Codex and CodeRabbit findings.

  • My PR is ready for review.

Summary by CodeRabbit

  • Bug Fixes

    • Improved streaming response handling when terminal events omit the expected completion marker.
    • Ensured clients receive a consistent completion signal and connection closure after a response finishes.
  • Tests

    • Added coverage confirming terminal events are preserved and the completion marker is appended when missing.

@github-actions

github-actions Bot commented Aug 5, 2026

Copy link
Copy Markdown

Deterministic PR hygiene checks passed.

@github-actions

github-actions Bot commented Aug 5, 2026

Copy link
Copy Markdown

Review readiness checklist

This PR is kept in draft until every requirement below is fulfilled. The tickable checklist has been added to your PR description — tick all four boxes there.

  • ✅ All CI tests are green on my local testing.
  • ✅ I pushed my PR to the latest dev commit.
  • ✅ I fixed all correct Codex and CodeRabbit findings.
  • ✅ My PR is ready for review.

4/4 boxes ticked.

All four boxes are ticked.
Completed against head 5a69355; new commits after this will reset the checklist.
This pull request is already Ready for Review.
Maintainers: @lidge-jun @Ingwannu @Wibias

@github-actions

github-actions Bot commented Aug 5, 2026

Copy link
Copy Markdown

PR quality gates passed

This pull request now targets dev with acceptable ancestry, description, and UI screenshot coverage. The review readiness checklist is complete.

The title was left unchanged. Its existing draft status has been preserved.

@github-actions github-actions Bot changed the title fix: finish passthrough SSE after terminal events [WRONG BRANCH] fix: finish passthrough SSE after terminal events Aug 5, 2026
@github-actions
github-actions Bot marked this pull request as draft August 5, 2026 08:57
@github-actions github-actions Bot added the bug Something isn't working label Aug 5, 2026
@coderabbitai

coderabbitai Bot commented Aug 5, 2026

Copy link
Copy Markdown
Contributor

Review Change Stack

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: ASSERTIVE

Plan: Pro Plus

Run ID: 11929061-73c6-43ae-b928-ca9ee3bb9abc

📥 Commits

Reviewing files that changed from the base of the PR and between 410db97 and 5a69355.

📒 Files selected for processing (2)
  • src/server/relay.ts
  • tests/passthrough-abort.test.ts

📝 Walkthrough

Walkthrough

The SSE relay now tracks upstream [DONE] frames, appends a missing sentinel after terminal completion or clean EOF, closes the client stream, and cancels upstream reading. A passthrough test covers this behavior.

Changes

SSE completion handling

Layer / File(s) Summary
Relay completion and cleanup
src/server/relay.ts
relaySseWithHeartbeat reuses encoded frames, tracks [DONE], ignores [DONE] during terminal-status parsing, appends missing sentinels, closes the client stream, and cancels upstream reading after terminal completion.
Completion sentinel coverage
tests/passthrough-abort.test.ts
The test verifies terminal event forwarding, [DONE] insertion, and single terminal status reporting.

Estimated code review effort: 2 (Simple) | ~10 minutes

Sequence Diagram(s)

sequenceDiagram
  participant UpstreamSSE
  participant relaySseWithHeartbeat
  participant ClientStream
  UpstreamSSE->>relaySseWithHeartbeat: Send response.completed
  relaySseWithHeartbeat->>ClientStream: Forward terminal event
  relaySseWithHeartbeat->>ClientStream: Append data: [DONE] if missing
  relaySseWithHeartbeat->>UpstreamSSE: Cancel upstream reading
  relaySseWithHeartbeat->>ClientStream: Close stream
Loading

Possibly related PRs

  • lidge-jun/opencodex#942: Both changes update src/server/relay.ts to handle terminal SSE events, append [DONE], and stop upstream processing.
  • lidge-jun/opencodex#953: Both changes update src/server/relay.ts for terminal [DONE] handling and stream cleanup.

Suggested reviewers: l14ny1wang, lidge-jun, wibias

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title clearly and concisely describes the main change: completing passthrough SSE streams after terminal events.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
✨ Finishing Touches 💡 1
🛠️ Fix failing CI checks 💡
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests

Comment @coderabbitai help to get the list of available commands.

@itling
itling force-pushed the agent/passthrough-done-tail branch from 58f0307 to 5a69355 Compare August 5, 2026 09:00

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@src/server/relay.ts`:
- Around line 590-598: The relay stream handling around inspectChunk must return
the byte boundary of the terminal SSE block, then enqueue only the input through
that boundary and discard any following bytes before emitting the synthetic
doneSentinel. Update terminal detection so doneSeen reflects the inspected
terminal block even when a later [DONE] block is split across the same read, and
add a split-chunk regression covering this case in passthrough-abort.test.ts.
🪄 Autofix

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: ASSERTIVE

Plan: Pro Plus

Run ID: 67b81ed9-0aac-459c-9b7c-9974f87fa702

📥 Commits

Reviewing files that changed from the base of the PR and between 80be427 and 58f0307.

📒 Files selected for processing (2)
  • src/server/relay.ts
  • tests/passthrough-abort.test.ts

Comment thread src/server/relay.ts
Comment on lines 590 to +598
inspectChunk(value);
controller.enqueue(value);
if (terminalReported && !doneSeen) {
controller.enqueue(doneSentinel);
doneSeen = true;
cleanup();
controller.close();
reader.cancel("Responses terminal event received").catch(() => {});
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🎯 Functional Correctness | 🟠 Major | 🏗️ Heavy lift

Do not forward bytes after the terminal SSE block.

Line 590 can leave an incomplete later block in buffer, but Line 591 forwards the entire value. If one upstream read contains a complete response.completed block followed by the first bytes of a real data: [DONE] block, doneSeen remains false. Lines 592-598 then append a second sentinel and cancel before the next read can complete the original block. The client receives adjacent data: [DONE] lines, which an SSE parser reads as one payload instead of [DONE].

Return the terminal block boundary from the inspector and enqueue only bytes through that boundary. Discard post-terminal bytes before emitting the synthetic sentinel. Add a split-chunk regression in tests/passthrough-abort.test.ts around Lines 224-238.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@src/server/relay.ts` around lines 590 - 598, The relay stream handling around
inspectChunk must return the byte boundary of the terminal SSE block, then
enqueue only the input through that boundary and discard any following bytes
before emitting the synthetic doneSentinel. Update terminal detection so
doneSeen reflects the inspected terminal block even when a later [DONE] block is
split across the same read, and add a split-chunk regression covering this case
in passthrough-abort.test.ts.

@itling
itling changed the base branch from main to dev August 5, 2026 09:04
@itling itling changed the title [WRONG BRANCH] fix: finish passthrough SSE after terminal events fix: finish passthrough SSE after terminal events Aug 5, 2026

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 58f0307ca1

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread src/server/relay.ts
}
inspectChunk(value);
controller.enqueue(value);
if (terminalReported && !doneSeen) {

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Close the relay even when DONE is already present

When an upstream batches a Responses terminal event and data: [DONE] in the same chunk but keeps the HTTP connection open, inspectChunk() sets both terminalReported and doneSeen, so this new branch is skipped and the relay never runs cleanup() or controller.close(). That leaves the heartbeat timer active and onDone uncalled despite the terminal event already being forwarded; only the synthetic DONE enqueue should be guarded by !doneSeen, while close/cleanup should still happen whenever a terminal was reported.

Useful? React with 👍 / 👎.

Comment thread src/server/relay.ts
Comment on lines +581 to +582
if (terminalReported && !doneSeen) {
controller.enqueue(doneSentinel);

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Separate synthetic DONE from unterminated terminal frames

If the upstream closes after a terminal frame that lacks the final blank SSE delimiter, the relay already forwarded those raw bytes during the previous pull and this EOF path then appends data: [DONE]\n\n directly after them. That turns the terminal payload and [DONE] into one malformed SSE block (data: <json>\ndata: [DONE]) instead of dispatching the terminal event followed by a separate DONE sentinel; insert a delimiter before the synthetic sentinel or use the frame-aware terminal boundary for this path.

Useful? React with 👍 / 👎.

Comment on lines +228 to +230
const relayed = relaySseWithHeartbeat(streamFromChunks([
enc.encode('event: response.completed\ndata: {"type":"response.completed","response":{"id":"r1","status":"completed"}}\n\n'),
]), ac, 15_000, status => terminals.push(status))!;

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Exercise the relay used by native passthrough

This regression constructs relaySseWithHeartbeat() directly, but this same test file asserts that the real native Responses passthrough branch does not call relaySseWithHeartbeat() and production now routes through relaySseWithFailedTail() instead. As a result, the new test can pass while the described passthrough path still hangs or formats DONE incorrectly; cover relaySseWithFailedTail() or a server-level passthrough stream so the focused regression protects the changed behavior.

AGENTS.md reference: AGENTS.md:L228-L230

Useful? React with 👍 / 👎.

Comment thread src/server/relay.ts
doneSeen = true;
cleanup();
controller.close();
reader.cancel("Responses terminal event received").catch(() => {});

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Drop coalesced frames after the terminal event

If a gateway writes response.completed and another SSE block in the same upstream chunk, this branch closes only after controller.enqueue(value) has already forwarded the whole chunk, so post-terminal deltas or metadata can reach the client before the synthetic [DONE]. The terminal-aware relays elsewhere use an SSE frame boundary to forward through the terminal block and drop later blocks; this path should do the same before cancelling the reader.

Useful? React with 👍 / 👎.

@github-actions
github-actions Bot marked this pull request as ready for review August 5, 2026 09:13
@coderabbitai

coderabbitai Bot commented Aug 5, 2026

Copy link
Copy Markdown
Contributor

Note

GitHub couldn't provide a complete incremental comparison for this pull request, so CodeRabbit is performing a full review instead. This review may take a little longer.

@itling

itling commented Aug 5, 2026

Copy link
Copy Markdown
Author

Closing this as superseded: upstream dev (and main) already contain 02ca79a fix(responses): close passthrough streams at terminal events, which implements this behavior in the production relay. Since that commit, native Responses passthrough routes through relaySseWithFailedTail + createSseTerminalOutputBoundary, which already closes the client stream at a Responses terminal event even when the upstream keeps the connection open, appends data: [DONE] when the upstream omits it, forwards only through the terminal SSE block boundary (dropping post-terminal frames), and handles split chunks and partial terminal blocks. relaySseWithHeartbeat (the function this PR modified) has no remaining production call sites, so this change would duplicate an existing fix in dead code. The scenarios are already covered in tests/sse-failed-tail.test.ts (terminal-without-DONE close, coalesced post-terminal frames, real-DONE detection). Recommendation: update the running OpenCodex build to a version containing 02ca79a.

@itling itling closed this Aug 5, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

bug Something isn't working

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant