codex icon indicating copy to clipboard operation
codex copied to clipboard

TUI can show duplicated interleaved text after mid-stream disconnects on third-party Responses providers (repro scaffold)

Open olympum opened this issue 2 months ago • 7 comments

What we observed

A user of a third-party OpenAI-Responses-compatible gateway saw assistant text rendered twice in the same visual flow — two complete copies of each sentence, interleaved, with different chunk boundaries:

ThisThis is a is a native native mac macOS session, not the LinOS session,
not the Linux/ux/ABK tABK tier —ier —

Both copies reassemble into the same clean sentence, so the model output itself is single; the duplication happens between the SSE event stream and the terminal.

What we verified on codex-cli 0.156.1 (macOS, arm64)

  • codex exec --json against a local fake gateway that closes the stream mid-turn: codex prints Reconnecting... 1/5 (stream disconnected before completion: stream closed before response.completed), retries, and ends the turn with ONE clean agent_message item. No duplication at the item layer.
  • The interactive TUI driven under a PTY with the same truncating server: the final screen shows the message once, clean.
  • A variant that also streams response.reasoning_summary_text.delta events while the model catalog declares supports_reasoning_summaries: false: rendered clean; the summary text was not displayed.

So we could not reproduce the visual duplication on 0.156.1 with these triggers. The affected user's client version is unknown.

Suspect

The live-render path across a mid-stream disconnect: whether the TUI rolls back the partial live text of a failed attempt before painting the retry's stream, and how it renders reasoning-summary events for a model whose metadata says summaries are unsupported. Related: #15758 (fixed duplicate live reasoning summaries), #29755 and #30072 (open: third-party Responses backends emitting snapshot-shaped streams render repeatedly).

Repro scaffold

A local HTTP server answers POST /v1/responses with a real-shaped SSE stream. Attempt 1 serves response.created plus a few response.output_text.delta frames, then closes the socket without response.completed. Attempt 2 serves the full stream to completion. Point a custom model_providers.<id>.base_url at it and run codex. The artifact above came from a user session on such a gateway.

Ask

Which client versions or stream shapes reproduce the duplicated live text? Does the TUI roll back partial live text on Reconnecting?

olympum avatar Sep 23 '26 11:09 olympum

could you format this in spanish too ? hard to understand

glook9001 avatar Sep 23 '26 11:09 glook9001

@olympum Do you , thank , this is , something interduced?

glook9001 avatar Sep 23 '26 11:09 glook9001

Direct answer to the ask: no — the TUI has no rollback of the live text of a failed attempt.

Traced on main (78245b47af, 2026-09-19), with lines:

  1. Deltas are emitted per attempt, live: core/src/session/turn.rs:2151-2158 emits AgentMessageContentDeltaEvent { thread_id, turn_id, item_id, delta }. Note the event does carry item_id.
  2. The retry boundary has a signal: core/src/responses_retry.rs:125-133 calls sess.notify_stream_error(turn_context, "Reconnecting... {n}/{max}", err) before sleeping and retrying (same for the unbounded-connection-retry branch at :84). That reaches app-server bespoke_event_handling.rs:1057-1070 and is published as ServerNotification::Error { will_retry: true, .. }.
  3. TUI: tui/src/chatwidget/protocol.rs:178-185 routes will_retry == true to on_stream_error, and on_stream_error (tui/src/chatwidget/streaming.rs:379-388) only does remember_retry_status_header() + set_status(...). It never touches self.stream_controller, and nothing else in the TUI consumes will_retry: stream_controller.take() appears only in flush_answer_stream (streaming.rs:86-88) and on turn teardown.
  4. Answer deltas are accumulated into one unbucketed controller: protocol.rs:96-105 passes only notification.delta into on_agent_message_delta — the wire item_id is used solely for realtime-delegated filtering, never for bucketing — and handle_streaming_delta (streaming.rs:553-580) lazily creates the controller on the first delta, then push()es every later delta into it. Contrast ReasoningSummaryTextDelta immediately below (protocol.rs:111-119), which is bucketed by status_state.reasoning_item_id == item_id. The answer path has no such check.

So attempt 2's deltas (a new item_id) are appended to the controller that already holds attempt 1's partial text; structurally, nothing distinguishes them at render time. That is the duplicate live text.

Why your PTY run came out clean — expected, not a contradiction

Item completion is authoritative and consolidates: finalize_completed_assistant_message (streaming.rs:187-198, comment: "Item completion is authoritative. Use it for consolidation so any deltas dropped by a saturated transport cannot truncate the transcript.") calls flush_answer_stream(Some(visible_markdown)), where source = completed_message.or(streamed_source) (streaming.rs:86-148) and the run of streaming cells is collapsed into one AgentMarkdownCell via AppEvent::ConsolidateAgentMessage. A retry that reaches completion therefore erases the transient duplicate. Your PTY capture was after completion, so it could not see it. codex exec behaves the same way for the same reason: the exec renderers publish the item, not the live delta stream. Capture the screen during the "Reconnecting..." window and the duplication should be visible; that is the minimum change to the scaffold.

Where it does not self-heal — the shape that matches "the user saw it persist"

If the turn ends with no item completion for that answer (retry budget exhausted → failed turn, or any termination path), finalize_turn (turn_runtime.rs:311-341) calls flush_answer_and_plan_streams (streaming.rs:64-65) → flush_answer_stream(completed_message = None) → source = streamed_source, i.e. attempt 1 concatenated with attempt 2, and that text becomes the consolidated transcript cell. "Preserve received answer ... before ordinary turn termination" is the intent there, but what is preserved is both attempts.

Concrete variant of your scaffold worth testing: attempt 1 streams a few deltas then closes without response.completed, and attempt 2 also closes early, enough times to exhaust the retry budget (or let attempt 2 hang past the client timeout). Prediction: the final screen shows the sentence twice, and it stays.

The artifact you pasted is probably a second, different mechanism

ThisThis is a is a native native mac macOS session, not the LinOS session,
not the Linux/ux/ABK tABK tier —ier —

Sub-sentence interleaving with different chunk boundaries is not what sequential appends produce: two attempts appended into one controller yield copy 1 followed by copy 2 (a screenshot of the live tail can look interleaved, since the tail cell renders only its last lines, but the halves are not woven together). Woven output is the signature of the #29755/#30072 family — a backend whose response.output_text.delta delta field carries cumulative/snapshot text rather than a true delta, or two attempts arriving concurrently. Discriminators, cheapest first:

  • Count the copies. Exactly two, stable: the retry accumulation above. Three or more, or growing frame by frame: snapshot-shaped deltas / #29755 / #30072.
  • Log the raw SSE frames. If frame N's delta already contains text from frame N-1, the gateway is sending snapshots, and appending them duplicates by construction.
  • The user's client version matters for rendering; the gateway matters for the stream shape. They are separable tests.

Fix direction (small, and consistent with the existing design)

  • TUI: make will_retry mean "drop this attempt's speculative live text" — in on_stream_error, take the controller and discard the tail (the same two steps flush_answer_stream performs, stream_controller.take() + clear_active_stream_tail(), but without consolidating). No new semantics are invented: the partial stream is explicitly speculative and item completion is already declared authoritative.
  • Protocol: will_retry (app-server notification.rs) is documented as an intermediate retry state but never states that deltas already received for that turn are void. Third-party clients that consume AgentMessageDelta directly have no consolidation step to fall back on, so that gap is exactly where their persistent duplication comes from.

I can draft the TUI-side patch plus a regression test if that direction looks right. What I have not done here is run your scaffold (no build in my environment) or verify client-side whether a partially streamed item can later complete with the same id — happy to trace that next if it matters for the fix.

argszero avatar Sep 23 '26 14:09 argszero

Direct answer to the ask: no — the TUI has no rollback of the live text of a failed attempt.

Traced on main (78245b47af, 2026-09-19), with lines:

  1. Deltas are emitted per attempt, live: core/src/session/turn.rs:2151-2158 emits AgentMessageContentDeltaEvent { thread_id, turn_id, item_id, delta }. Note the event does carry item_id.
  2. The retry boundary has a signal: core/src/responses_retry.rs:125-133 calls sess.notify_stream_error(turn_context, "Reconnecting... {n}/{max}", err) before sleeping and retrying (same for the unbounded-connection-retry branch at :84). That reaches app-server bespoke_event_handling.rs:1057-1070 and is published as ServerNotification::Error { will_retry: true, .. }.
  3. TUI: tui/src/chatwidget/protocol.rs:178-185 routes will_retry == true to on_stream_error, and on_stream_error (tui/src/chatwidget/streaming.rs:379-388) only does remember_retry_status_header() + set_status(...). It never touches self.stream_controller, and nothing else in the TUI consumes will_retry: stream_controller.take() appears only in flush_answer_stream (streaming.rs:86-88) and on turn teardown.
  4. Answer deltas are accumulated into one unbucketed controller: protocol.rs:96-105 passes only notification.delta into on_agent_message_delta — the wire item_id is used solely for realtime-delegated filtering, never for bucketing — and handle_streaming_delta (streaming.rs:553-580) lazily creates the controller on the first delta, then push()es every later delta into it. Contrast ReasoningSummaryTextDelta immediately below (protocol.rs:111-119), which is bucketed by status_state.reasoning_item_id == item_id. The answer path has no such check.

So attempt 2's deltas (a new item_id) are appended to the controller that already holds attempt 1's partial text; structurally, nothing distinguishes them at render time. That is the duplicate live text.

Why your PTY run came out clean — expected, not a contradiction

Item completion is authoritative and consolidates: finalize_completed_assistant_message (streaming.rs:187-198, comment: "Item completion is authoritative. Use it for consolidation so any deltas dropped by a saturated transport cannot truncate the transcript.") calls flush_answer_stream(Some(visible_markdown)), where source = completed_message.or(streamed_source) (streaming.rs:86-148) and the run of streaming cells is collapsed into one AgentMarkdownCell via AppEvent::ConsolidateAgentMessage. A retry that reaches completion therefore erases the transient duplicate. Your PTY capture was after completion, so it could not see it. codex exec behaves the same way for the same reason: the exec renderers publish the item, not the live delta stream. Capture the screen during the "Reconnecting..." window and the duplication should be visible; that is the minimum change to the scaffold.

Where it does not self-heal — the shape that matches "the user saw it persist"

If the turn ends with no item completion for that answer (retry budget exhausted → failed turn, or any termination path), finalize_turn (turn_runtime.rs:311-341) calls flush_answer_and_plan_streams (streaming.rs:64-65) → flush_answer_stream(completed_message = None) → source = streamed_source, i.e. attempt 1 concatenated with attempt 2, and that text becomes the consolidated transcript cell. "Preserve received answer ... before ordinary turn termination" is the intent there, but what is preserved is both attempts.

Concrete variant of your scaffold worth testing: attempt 1 streams a few deltas then closes without response.completed, and attempt 2 also closes early, enough times to exhaust the retry budget (or let attempt 2 hang past the client timeout). Prediction: the final screen shows the sentence twice, and it stays.

The artifact you pasted is probably a second, different mechanism

ThisThis is a is a native native mac macOS session, not the LinOS session,
not the Linux/ux/ABK tABK tier —ier —

Sub-sentence interleaving with different chunk boundaries is not what sequential appends produce: two attempts appended into one controller yield copy 1 followed by copy 2 (a screenshot of the live tail can look interleaved, since the tail cell renders only its last lines, but the halves are not woven together). Woven output is the signature of the #29755/#30072 family — a backend whose response.output_text.delta delta field carries cumulative/snapshot text rather than a true delta, or two attempts arriving concurrently. Discriminators, cheapest first:

Fix direction (small, and consistent with the existing design)

  • TUI: make will_retry mean "drop this attempt's speculative live text" — in on_stream_error, take the controller and discard the tail (the same two steps flush_answer_stream performs, stream_controller.take() + clear_active_stream_tail(), but without consolidating). No new semantics are invented: the partial stream is explicitly speculative and item completion is already declared authoritative.
  • Protocol: will_retry (app-server notification.rs) is documented as an intermediate retry state but never states that deltas already received for that turn are void. Third-party clients that consume AgentMessageDelta directly have no consolidation step to fall back on, so that gap is exactly where their persistent duplication comes from.

I can draft the TUI-side patch plus a regression test if that direction looks right. What I have not done here is run your scaffold (no build in my environment) or verify client-side whether a partially streamed item can later complete with the same id — happy to trace that next if it matters for the fix.

@argszero try again - ? is this still a thing ?

glook9001 avatar Sep 28 '26 10:09 glook9001

dude. slop

glook9001 avatar Oct 09 '26 07:10 glook9001

Reproduced on codex-cli 0.169.0 (macOS arm64, interactive TUI), with a custom Responses provider pointing at a local mock. On the two questions above: the TUI does not roll back the failed attempt's live text on Reconnecting..., and the stream shape is just "attempt 1 stops before response.completed, the retry starts the answer over". You can see it if you look during the retry, and it stays if the retries run out.

When the retry succeeds (9/9 runs, 3 each: socket closed mid-chunk, clean HTTP end without response.completed, and a 200-line answer cut at line 160)

  • While the retry streams, attempt 1's text stays in the message, and attempt 2 starts again from line 1 directly below it, in the same cell, with no separator.
  • When the retry completes, the message collapses to one copy. The saved session and the next request contain one copy.
  • Both copies are on screen for as long as the retry takes to stream: about half a second for a short answer, about 30 s for the 200-line one (200 lines at 150 ms per delta).

When the retries run out (6/6 runs: 3 with the socket closed mid-chunk, 3 with a clean end without response.completed)

  • Every attempt streams the same first half and is cut. The turn ends with ■ stream disconnected before completion: …, and the final screen keeps all six attempts concatenated in one message (the original plus Reconnecting... 1/5 to 5/5).
  • The saved session has no assistant message for that turn, so this is display-only, but it does not go away.

The copies are sequential, never interleaved, so the woven text in the original report probably has another cause (#30072).

Code (rust-v0.169.0; on_stream_error is unchanged on main today)

  • An error with will_retry: true goes to on_stream_error (protocol.rs:223), which only updates the status row (streaming.rs:517). stream_controller keeps attempt 1's text, and handle_streaming_delta appends attempt 2's deltas to it (streaming.rs:728).
  • On success, finalize_completed_assistant_message consolidates from the completed item (streaming.rs:289), so the final screen is clean.
  • When the turn fails, finalize_turn (turn_runtime.rs:349) calls flush_answer_and_plan_streams (streaming.rs:71) with no completed message, so the concatenated stream becomes the transcript cell.

That matches the analysis earlier in this thread.

Expected: the message shows one attempt at a time. When Reconnecting... starts a retry, the failed attempt's text is cleared or visibly marked as discarded.

Repro

retry_dup_mock.py (Python 3, stdlib only)
#!/usr/bin/env python3
"""Minimal OpenAI Responses mock for openai/codex#47538.

Attempt 1 streams the first half of the answer and closes the connection
without response.completed; later attempts stream the whole answer.
With --always every attempt is cut, so the retry budget runs out.

    python3 retry_dup_mock.py [--port 8765] [--always]
"""
import argparse
import json
import time
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer

LINES = [f"[{i:02d}] line {i:02d} of the answer" for i in range(1, 41)]
CUT = 20      # lines sent before the connection is cut
DELAY = 0.15  # seconds per delta, so the retry window is long enough to see


class Handler(BaseHTTPRequestHandler):
    protocol_version = "HTTP/1.1"
    attempts = 0

    def log_message(self, fmt, *args):
        pass

    def do_GET(self):  # model list
        body = json.dumps({"object": "list", "data": [
            {"id": "mock-model", "object": "model", "created": 0, "owned_by": "mock"}]}).encode()
        self.send_response(200)
        self.send_header("content-type", "application/json")
        self.send_header("content-length", str(len(body)))
        self.end_headers()
        self.wfile.write(body)

    def do_POST(self):
        req = json.loads(self.rfile.read(int(self.headers.get("content-length", 0))) or b"{}")
        if "json_schema" in json.dumps(req.get("text", {})):  # thread-title side request
            return self.stream(['{"title": "retry test"}'], complete=True, delay=0)
        Handler.attempts += 1
        cut = ARGS.always or Handler.attempts == 1
        print(f"attempt {Handler.attempts}: {'cut after ' + str(CUT) + ' lines' if cut else 'complete'}", flush=True)
        self.stream(LINES[:CUT] if cut else LINES, complete=not cut, delay=DELAY)

    def stream(self, lines, complete, delay):
        n = Handler.attempts
        msg = {"id": f"msg_{n}", "type": "message", "role": "assistant"}
        resp = {"id": f"resp_{n}", "object": "response", "created_at": int(time.time()), "model": "mock-model"}
        text = "".join(f"{line}\n" for line in lines)
        self.send_response(200)
        self.send_header("content-type", "text/event-stream")
        self.send_header("connection", "close")  # body ends when the socket closes
        self.end_headers()

        def send(kind, **data):
            self.wfile.write(f"event: {kind}\ndata: {json.dumps({'type': kind, **data})}\n\n".encode())
            self.wfile.flush()

        send("response.created", response={**resp, "status": "in_progress", "output": []})
        send("response.output_item.added", output_index=0, item={**msg, "status": "in_progress", "content": []})
        send("response.content_part.added", item_id=msg["id"], output_index=0, content_index=0,
             part={"type": "output_text", "text": ""})
        for line in lines:
            send("response.output_text.delta", item_id=msg["id"], output_index=0, content_index=0, delta=f"{line}\n")
            time.sleep(delay)
        if complete:
            done = {**msg, "status": "completed", "content": [{"type": "output_text", "text": text, "annotations": []}]}
            send("response.output_text.done", item_id=msg["id"], output_index=0, content_index=0, text=text)
            send("response.output_item.done", output_index=0, item=done)
            send("response.completed", response={**resp, "status": "completed", "output": [done],
                                                 "usage": {"input_tokens": 1, "output_tokens": 1, "total_tokens": 2}})
        self.close_connection = True


if __name__ == "__main__":
    p = argparse.ArgumentParser()
    p.add_argument("--port", type=int, default=8765)
    p.add_argument("--always", action="store_true", help="cut every attempt")
    ARGS = p.parse_args()
    ThreadingHTTPServer(("127.0.0.1", ARGS.port), Handler).serve_forever()
python3 retry_dup_mock.py          # add --always to cut every attempt
MOCK_API_KEY=x codex \
  -c model_provider=mock \
  -c 'model_providers.mock.name="Mock"' \
  -c 'model_providers.mock.base_url="http://127.0.0.1:8765/v1"' \
  -c 'model_providers.mock.wire_api="responses"' \
  -c 'model_providers.mock.env_key="MOCK_API_KEY"' \
  -c 'model="mock-model"'

Send any prompt. Lines [01]–[20] stream, Reconnecting... 1/5 flashes in the status row, and [01] starts again under [20] in the same message. Both copies stay for about 6 s; when [40] arrives, the message collapses to one copy. With --always, every retry adds another copy, and the turn ends with the error and all six copies on screen.

How I looked: the screen was captured every 30 ms in a 110×400 tmux window. Attempt 1's text carries a marker that only the failed attempt emits, so the copies can be told apart. Network access was limited to localhost.

BiBoyang avatar Nov 16 '26 01:11 BiBoyang

(response from codex)

If you’re running an older gateway version, please try the latest stable release and see whether the word-by-word duplication persists. If it’s a hosted gateway, ask the provider whether they’ve fixed any duplicate streaming events.

On Codex CLI 0.172.0, I reproduced ThisThis by having a mock gateway send two overlapping copies of the sentence under different message IDs. Codex mixed them together (#60938).

etraut-openai avatar Nov 26 '26 00:11 etraut-openai