Skip to content

App-server still drops remote-control clients when outbound queue fills (128 messages) — #18203 fix missed the code path #37526

Open

Description

@joewolly

Summary

codex app-server still disconnects remote-control clients mid-turn with disconnecting slow connection after outbound queue filled on codex-cli 0.147.0 (and the same code exists on current main and rust-v0.148.0-alpha.5). This is the same symptom as #18203, which was closed as fixed by #19246 — but that PR only raised the WebSocket writer buffer. The per-connection outbound message channel that actually triggers the disconnect is still 128 messages, so the bug is unfixed.

Environment

  • codex-cli 0.147.0 (standalone package, Linux x86_64)
  • codex app-server with remote control enabled; phone + desktop apps connected through the chatgpt.com relay (wss://chatgpt.com/backend-api/wham/remote/control/server)
  • model routed through a local OpenAI-compatible proxy (opencode-go/deepseek-v4-flash, reasoning_effort=max)

Root cause

CHANNEL_CAPACITY is still 128 (verified identical on main, rust-v0.147.0, and rust-v0.148.0-alpha.5 as of 2026-08-07):

// codex-rs/app-server-transport/src/transport/mod.rs (line 25)
pub const CHANNEL_CAPACITY: usize = 128;

Disconnect path unchanged (codex-rs/app-server/src/transport.rs):

if connection_state.can_disconnect() {
    match writer.try_send(queued_message) {
        Ok(()) => false,
        Err(mpsc::error::TrySendError::Full(_)) => {
            warn!("disconnecting slow connection after outbound queue filled: {connection_id:?}");
            disconnect_connection(connections, connection_id)
        }
        ...

Reproduction

Run two threads concurrently so both stream reasoning deltas to one remote-control connection (each max-effort thread can emit hundreds of events/sec; relay latency lets the 128-slot queue fill). The app-server then kills the client:

20:23:28 WARN  transport | disconnecting slow connection after outbound queue filled: ConnectionId(25)
20:23:28 WARN  transport | dropping message for disconnected connection: ConnectionId(25)
20:23:28 INFO  client_tracker | forwarding remote control connection closed transport event connection_id=ConnectionId(25)

Both the phone and desktop apps show "connection lost"; the thread keeps running server-side but the client session is dropped.

Expected behavior

A slow-but-alive client should not be disconnected because of a burst. The outbound queue should be sized for streaming workloads, or the writer should apply backpressure (await send) and only disconnect after a timeout.

Suggested fix

References

Activity

  1. added
    bug
    CLI
    app-server
    connectivity
    on Aug 8, 2026
  2. niklassheth commented on Aug 9, 2026

    @niklassheth

    I'm experiencing this issue, it's incredibly frustrating because every time the connection drops my side chats expire.

  3. jdcodes1 commented on Aug 18, 2026

    @jdcodes1

    Verified on main (1f41cc5): both halves of the analysis hold. CHANNEL_CAPACITY is still 128 (app-server-transport/src/transport/mod.rs#L25, re-exported into the app-server), and the disconnect path is byte-identical — try_send → TrySendError::Full → immediate disconnect_connection (https://github.com/openai/codex/blob/1f41cc5d92/codex-rs/app-server/src/transport.rs#L156-L163). So #19246 enlarged the layer below the one that kills the connection; the mpsc hop above it still hard-drops at 128, and two max-effort reasoning streams through a relay can outrun that trivially.

    Beyond raising the constant, the structural issue is that disconnect is the only overflow policy. For a remote-control observer, the queue is full of deltas whose value decays instantly — the correct degradation is coalescing/shedding, not connection teardown: drop oldest delta messages (never lifecycle/completion events) when full, or collapse consecutive deltas for the same item into the latest one. That bounds memory identically while making slow relays lossy-but-alive — a phone missing some reasoning frames is fine; a phone being disconnected mid-turn (then re-syncing everything) is both worse UX and more total bandwidth. A capacity bump alone just moves the cliff; the reproduction with two concurrent threads will find any fixed constant.

  4. charles1w commented on Sep 7, 2026

    @charles1w

    Windows confirmation (desktop 26.901.4073, Sept 5–7): captured 17 disconnecting slow connection after outbound queue filled events, each followed by the same remote client's closure 0.1–1.4 ms later. RustDesk remained responsive during observed Codex Remote drops. In 16/17 incidents there was no host-relay reconnect within ±35 seconds; independently, both IPv4/IPv6 probes passed around 16/17.

    The confirmed immediate failure is per-client queue overflow triggering connection teardown. Likely trigger: streaming bursts outrunning relay/client consumption; writer or acknowledgement stalls remain possible but unmeasured. Queue occupancy, drain rate and ACK latency would distinguish these. This supports fixing backpressure/overflow handling rather than resetting host networking.

    These captures predate 26.901.6511; that build has not been revalidated.

  5. charles1w commented on Sep 10, 2026

    @charles1w

    Follow-up to my earlier Windows queue-overflow confirmation: the persistent inability to reconnect had an additional, separately reproduced cause: slow thread/list scanning. This does not establish what originally filled the outbound queue.

    On app-server 0.153.4, Android's list request omits useStateDbOnly, causing the host to parse huge subagent histories before excluding them. Controlled listing exceeded 25 seconds; early exclusion returned the same 50 tasks in 1.15 seconds (indexed: 27 ms).

    A live workaround preserves old histories via retained NTFS files and read-through links that the scanner skips. Task loading now takes 1.21 seconds and the phone connects; no app restart or manual network reset. The code-level remedy is indexed Remote bootstrap and source filtering before preview parsing.

    Sanitized reproduction and workaround details. The previously captured queue-full disconnects remain valid and require their own fix.

  6. arkycop commented on Oct 3, 2026

    @arkycop

    Fresh Windows-to-macOS confirmation on 0.159.0-alpha.12.1: command-output bursts coincide with queue-full disconnects

    Adding sanitized evidence from October 3, 2026 (UTC). This reproduces the queue-overflow disconnect mechanism described in this issue on a newer bundled app-server and a Windows Codex App host with macOS Codex remote projects.

    Environment and impact

    • Bundled CLI on both machines: codex-cli 0.159.0-alpha.12.1.
    • Windows Codex App package: 26.930.2377.0; Microsoft Windows NT 10.0.26300.0, x64.
    • macOS Codex App version: 26.930.21537; macOS 27.2, Darwin 27.2.0, ARM64.
    • The macOS app has multiple registered remote projects sharing one Windows remote-control connection. Drops affect the shared connection while native Windows agent work continues.
    • During normal active use, the connection repeatedly drops and reconnects quickly, often every 1–2 minutes; some retained-log intervals were approximately 31 seconds. No deterministic standalone reproduction has been constructed.

    Correlated failures

    All times are October 3, 2026, UTC.

    Windows outgoing queue-full disconnect Same 100-ms bucket macOS client close Delay
    03:20:04.6225218 231 outgoing notifications 03:20:17.913 13.29 s
    03:22:45.5807707 482 notifications, including 479 item/commandExecution/outputDelta 03:22:49.279 3.70 s
    03:38:48.7241326 591 item/commandExecution/outputDelta 03:39:01.757 13.03 s

    Representative Windows native messages:

    WARN codex_app_server::transport: disconnecting slow connection after outbound queue filled: ConnectionId(42)
    INFO codex_app_server_transport::transport::remote_control::client_tracker: forwarding remote control connection closed transport event connection_id=ConnectionId(42)
    

    The macOS desktop log then records close code 4000 with reason:

    remote control app-server stream became unknown
    

    The installed macOS app sends a logical stream heartbeat every 30 seconds. An unknown-stream pong causes this close and a scheduled reconnect, explaining why the visible Mac drop can lag the Windows queue-full event.

    Measurement and source boundary

    Windows native SQLite logs were read in read-only mode with short-interval polling. Outgoing notification records were classified by protocol method and grouped by native second/nanosecond timestamps. These are app-server notification counts, not console-line or byte counts. Counts cover the server's logged outgoing notifications; they do not independently prove every counted notification targeted the disconnected client. The transport warning separately establishes that the client's outbound queue filled.

    The official source tag matching the installed bundled CLI still has:

    This establishes the disconnect mechanism and strongly implicates command-output bursts. Live relay acknowledgments and sustained packet timing were not captured, so acknowledgment latency, network latency, or another drain-rate defect may also contribute. Matching the published version tag is not a byte-for-byte binary verification. Other historical sequence-gap and pong-timeout failures are not assigned this cause.

    Checks and mitigation

    • Windows desktop and app-server processes remained alive across the captured drops; native agent execution continued.
    • Thirty short TCP connection probes each to the remote SSH endpoint and ChatGPT port 443 succeeded. These do not establish sustained WebSocket health.
    • Capturing only verbose test/build output in local files did not prevent the third failure above: large command results still streamed.
    • Guidance was broadened to capture large file reads, searches, diffs, and worker output, returning small excerpts and preserving original exit status.
    • A fresh 03:43:25.565–03:45:25.584 UTC window after acknowledgment recorded 1,705 command-output notifications and 435 agent-message deltas, with no native transport warnings/closures or matching Mac closes. Subsequent Mac logs through 03:49:10 UTC also recorded no new closes. This is a short, uncontrolled observation, not proof of a permanent fix.
    • No app binaries, network policy, account settings, or transport constants were modified.

    Expected behavior and request

    A burst of command output should not repeatedly tear down an otherwise live remote project connection. Please investigate bounded backpressure/overflow handling that preserves required response and lifecycle events, along with queue occupancy, drain-rate, and relay-ACK diagnostics. The practical output-capture workaround is useful, but users should not have to control normal command verbosity to keep the desktop remote connection alive.

    This report intentionally excludes usernames, hostnames, internal addresses, account/enrollment identifiers, project names, conversation content, credentials, and full raw logs.

    Follow-up: October 3 morning recurrence

    The workflow mitigation has not eliminated the client symptom. Account-wide output-capture guidance remained installed on both macOS and Windows, and the app/CLI versions were unchanged. The Windows desktop app-server remained alive. Mac logs recorded two further code-4000 closes with reason remote control app-server stream became unknown at 2026-10-03T15:22:46.564Z and 15:27:17.882Z. A separate authenticated-workspace-change close preceded a Mac app restart around 15:21 UTC; it is not counted as a transport failure.

    No matching Windows queue-full warning was recovered for these two morning events, so they are not proven to have the earlier overflow cause. A subsequent 15:28:20.449–15:28:58.514 UTC sample recorded 1,051 command-output notifications, peaking at 228 in a 100-ms bucket, without a transport warning. A further 15:34:46.850–15:37:46.945 UTC capture recorded 146 agent-message deltas, no commandExecution/outputDelta notifications, and no transport warning or closure; the Mac also recorded no additional remote closes through 15:43:11 UTC.

    The earlier timestamp-correlated queue-overflow evidence remains valid. These later observations establish that output-capture guidance is only a partial workaround, while leaving the specific cause of the morning reconnects unclassified. A deterministic burst/slow-ACK reproduction and transport diagnostics are still needed.

  7. krotname commented on Oct 21, 2026

    @krotname

    Additional Windows evidence on the unmodified bundled codex-cli 0.163.0-alpha.10.2, collected on 2026-10-21. Source-side output capture greatly reduced notification load, but this does not establish that Remote disconnects are fixed.

    Two production queue-full events

    The following excerpts are from primary App Server logs. Hosts and connection identifiers have been anonymized; timestamps are UTC.

    Host A
    08:16:59.103487 WARN transport: disconnecting slow connection after outbound queue filled: ConnectionId(A)
    08:16:59.103582 INFO remote_control::client_tracker: forwarding remote control connection closed transport event connection_id=ConnectionId(A)
    
    Host B
    13:58:55.816225 WARN transport: disconnecting slow connection after outbound queue filled: ConnectionId(B)
    13:58:55.818115 INFO remote_control::client_tracker: forwarding remote control connection closed transport event connection_id=ConnectionId(B)
    

    The same connection was closed 95 microseconds and 1.890 milliseconds, respectively, after its queue-full warning. Both events came from the working desktop App Server, not the isolated test servers below.

    Around Host A's event, a 10-second window contained 454 outgoing notification trace entries, including 446 item/commandExecution/outputDelta; one 100 ms bucket contained 352 output deltas. The affected connection also submitted 100 filesystem/history RPCs before the warning: 59 fs/getMetadata, 32 fs/readDirectory, 9 thread/items/list. A contemporaneous command already had max_output_tokens=2500; its retained tool result was only 204 lines / 10,032 characters. A final-result token limit therefore did not prevent the observed output-notification burst.

    Around Host B's warning (±5 seconds), there were 451 output-delta trace entries, with a maximum of 178 in a 100 ms bucket. These are server-wide fan-out trace counts, not measured queue occupancy or proven per-recipient counts. The logs do not identify the recipient/item for each delta or establish why that connection's writer fell behind. Concurrent activity prevents assigning the overflow to one command with confidence.

    Controlled source-output mitigation test

    On the same unmodified bundled binary, I used an isolated loopback WebSocket App Server with an empty temporary CODEX_HOME, an ephemeral protocol fixture, and thread/shellCommand. This exercised the actual item/commandExecution/outputDelta notification, not just command/exec/outputDelta.

    Each run produced 8,781,824 bytes using 131,072 small stdout writes, while submitting 100 fs/getMetadata RPCs. The client paused application reads for one second; its receive buffer was reduced for the test. Three runs per variant:

    Variant Received output-delta notifications Output bytes delivered over WebSocket Outcome
    Direct stdout 7,763 / 5,198 / 7,841 8,781,824 each All completed, all 100 RPCs answered
    Capture before App Server 1 / 1 / 1 801 each Same successful outcome

    The capture helper drains stdout/stderr into separate files, caps each saved stream at 48 MiB, and emits one JSON summary of at most 6,144 UTF-8 bytes after completion. The controlled runs used a 256-byte excerpt budget per stream. It preserves the child's exit code and explicitly reports timeout, truncation and incomplete capture. All three captured runs retained the full synthetic stdout, exited 0, and passed a post-load RPC readback. No Codex executable, desktop bundle or running service was patched or restarted.

    Neither test variant disconnected. This demonstrates notification-load reduction, not reproduction of the production overflow or proof that the underlying defect is fixed. The loopback test also does not reproduce the hosted Remote relay.

    Live check and coverage limits

    A later wrapped command ran on the working desktop from 14:09:47.200 to 14:10:19.671 UTC, retained the same 8,781,824 bytes, and completed with exit 0 and complete capture. Native Remote reads of an existing chat succeeded during and after that command.

    Fresh primary-log capture on the second production host covered 14:09:49.886–14:10:56.057 UTC (33 polls, 21 matching new records, last matching source record at 14:10:44.531). It overlaps the first host's bounded capture, 13:57:13.558–14:12:14.688 UTC (447 polls, last matching source record at 14:12:09.866). Poll spacing was at most 2.372 seconds; the two clocks were compared before the tests, with the best sample estimating a +13 ms offset and ±18 ms round-trip uncertainty. No queue-full/pong-timeout/sequence-gap/stream-unknown event was found in the later overlapping live-check interval.

    However, Host B's 13:58:55 overflow occurred during the broader observation, before the final two-host deployment verification. The mitigation is an explicit command-execution wrapper/rule, not transparent interception of every existing agent or every notification type. An earlier remote sampler ended prematurely when its WinRM session closed; an isolated-test sampling interval had no fresh production records. Neither is counted as continuous healthy coverage. Long-term disappearance of the disconnects remains unproven.

  8. peetronicus commented on Oct 25, 2026

    @peetronicus

    FIX! - Deterministic Remote relay reproduction, two isolated causes, and an experimental byte-preserving fix (Windows, 0.164.0-alpha.11.1)

    Adding a self-contained reproducer to advance the earlier burst/flow-control reports. The unmodified bundled host disconnects with just a 51,800-byte synthetic file and 25 ms of simulated relay ACK delay. The same-version experimental build delivers the exact full output without disconnecting. A separate metadata-only case reproduces a closed logical client's retained replay window blocking the next client.

    This is an issue/evidence submission in accordance with the contribution policy, not an external PR. The experimental patch below documents the local change used to test the hypotheses; upstream may prefer a different implementation.

    Versions and scope

    • Windows 11 x64, OS version 10.0.26300.
    • Stock desktop package: OpenAI.Codex 26.1021.3705.0; unmodified bundled native host: codex-cli 0.164.0-alpha.11.1.
    • Experimental native host built from the exact public release tag rust-v0.164.0-alpha.11.1, commit 6905ecede7816e91373e9eabda3f6b0368fc747b, with the patch below. This is not a test of current main or a byte-for-byte reproduction of OpenAI's build process.
    • Python 3.14.0, aiohttp 3.13.2, PowerShell 7. Rust 1.99.1, MSVC x64, existing full release profile with thin LTO.
    • Each reproducer invocation uses a fresh temporary CODEX_HOME, file-backed synthetic credentials, an ephemeral loopback HTTP/WebSocket relay, and a deterministic local Responses SSE stub that requests one exec_command. No real account credentials or paid model inference are required. Mock HTTP requests to /v1/responses are local fixture traffic, not actual model calls.

    Controlled stock-versus-experimental results

    These five cases were run using the portable script included below, against the two native executables of the same reported version:

    Case Stock Experimental
    Fragmented Get-Content, relay ACKs delayed 25 ms Queue-full disconnect; 256 output notifications / 9,694 bytes reached the mock remote before loss of the logical client 7 output notifications / all 51,800 bytes; no queue-full warning; turn completes
    Closed-client replay window: 128 envelopes without ACKs, metadata requests only Second client cannot initialize until the first client's old ACKs are released Second client initializes before any old ACK is released
    Control: same file emitted in bulk, ACKs delayed 500 ms 8 notifications / all 51,800 bytes; completes Not needed for this control

    Both fragmented-output commands complete locally with exit code 0 and the full 51,800-byte captured result. On stock, the remote observer loses the result despite successful execution. The full-output SHA-256 is:

    0caaface4f99e8d2919b6b31766c5d8ee31d973e6c266097ad9819df5172f997

    The stock failure emits:

    WARN codex_app_server::transport: disconnecting slow connection after outbound queue filled: ConnectionId(1)
    

    The new client stall in the metadata-only case is not reported as another queue-full disconnect: it reproduces separately, without starting any agent turn or shell command.

    Reproduce without a real account or model

    1. Save the script in the first expandable section as remote_control_repro.py.
    2. Use Python with aiohttp installed (python -m pip install aiohttp==3.13.2) and PowerShell 7. Run this from an ordinary local shell. The fixture starts subprocesses and loopback servers; it is not intended to run inside another restrictive command sandbox.
    3. Point --codex at an unpacked executable directory with its matching helper executables, or the installed stock host. It never connects to the already-running desktop server or changes its real profile.
    $stock = 'C:\path\to\stock\codex.exe'
    $shell = (Get-Command pwsh).Source
    
    # A: Actual item/commandExecution/outputDelta path through an agent tool call.
    python .\remote_control_repro.py --codex $stock --shell $shell --case burst --ack-delay-ms 25
    
    # B: Same bytes, less fragmented producer; succeeds even with longer ACK delay.
    python .\remote_control_repro.py --codex $stock --shell $shell --case bulk --ack-delay-ms 500
    
    # C: No agent or command: fill replay window, close old client, initialize another.
    python .\remote_control_repro.py --codex $stock --shell $shell --case retired

    Expected distinguishing fields:

    • A on stock: nonempty queueWarnings, commandTimedOutWaitingForResponse: true, but localCompletion.exitCode: 0 and all 51,800 local bytes. Exact fragment counts/timing may vary with scheduling; the measured run is recorded below.
    • B: empty queueWarnings, full matching received SHA-256, completed turn.
    • C on stock: envelopesBeforeSecondClient: 128, secondInitBeforeOldAcksReleased: false, then secondInitAfterOldAcksReleased: true. The script intentionally releases old ACKs after measuring the stall.
    • With the experimental executable, A completes with full matching received bytes, and C has secondInitBeforeOldAcksReleased: true.

    The synthetic login and permissive command policy belong only to each disposable fixture profile. The command reads the generated fixture; it is not a production sandbox-policy recommendation. The mock's ACKs represent the relay's application ACKs, not TCP ACKs or user interaction on the phone.

    Source analysis and experimental change

    1. Read-fragment-to-notification amplification. Small stdout reads become output events. With the shared remote replay window at capacity, the WebSocket writer stops taking queued envelopes; the app-server's bounded try_send can then disconnect the logical connection. Permanently missing ACKs are not necessary: the controlled reproduction uses only 25 ms delay. The bulk-output control isolates message fragmentation from byte volume.

      The local experiment coalesces adjacent output into bounded 8 KiB batches with an absolute 10 ms deadline after the first byte, at the pipe/legacy reader and unified-exec watcher. The deadline is per stage, not an asserted 10 ms end-to-end bound. Idle readers do not spin on periodic timers. It preserves bytes, EOF flushing, pending bytes before later I/O errors, draining after receiver closure, and existing UTF-8 framing. It does not drop output or lifecycle messages, raise the 128-entry transport capacity, or require users to wrap/reduce their commands.

    2. Closed-stream ownership of replay capacity. Retiring a logical client stream did not release that stream's buffered unacknowledged envelopes. A new client on the same WebSocket can therefore wait for ACKs belonging to an already-closed stream, even with no agent running.

      The local experiment discards only the retired (client_id, stream_id) replay entries and adjusts window usage. Queued envelopes carry the logical stream's existing cancellation token; the writer checks it under the buffer lock before insertion, preventing already-retired queued work from refilling the window. Active streams retain their replay data. The legacy close path resolves its stream ID before removing the tracker entry. Late ACKs must not decrement released slots twice.

    Relevant upstream sources: pipe reader, legacy exec reader, unified watcher, overflow handling, remote replay window, client tracker.

    Other focused checks on the experimental build

    • Original loopback fixture: fragmented output with 500 ms ACK delay also completes in 7 notifications / 51,800 exact bytes.
    • Two logical clients: agent-tool output and direct command/exec output deliver 59,995 exact UTF-8 bytes each, including a multibyte character crossing an 8 KiB boundary; no queue-full warning. That original-fixture run received 9 and 8 output notifications respectively. SHA-256 for each: e5650c9f0e22c903680903bf0059cf25e23fa50a1bc298404c74d9a97a579825.
    • A queued-backlog variant with 280 metadata requests also permits new-client initialization before releasing old ACKs.
    • Three targeted reader tests pass: bounded coalescing with exact bytes, interactive flushing without EOF, and pending bytes delivered before an I/O error.
    • One targeted replay-slot test passes: retire one stream, preserve the other stream, and do not double-decrement on late ACK.
    • Full experimental ClientRequest, ServerNotification, ServerRequest, and combined v2 JSON schemas are identical to those generated by the installed stock host.
    • Windows read-only sandbox write-denial check passes with the desktop's code_mode_host and prefer_mxc flags and the matching unchanged stock helpers.

    For the patch experiment, save the second expandable section as experimental.patch, apply it at the release checkout's repository root, and build normally:

    git checkout rust-v0.164.0-alpha.11.1
    git apply .\experimental.patch
    cd codex-rs
    cargo +1.99.1 build --release -p codex-cli --bin codex
    cargo +1.99.1 test --release -p codex-utils-pty --lib output::tests
    cargo +1.99.1 test --release -p codex-app-server-transport --lib retiring_stream_releases_only_its_replay_slots

    The published release lockfile used 0.0.0 workspace package versions. Our build refreshed those workspace version entries only; no third-party dependency versions were changed relative to the release. That generated lockfile metadata diff is omitted from the experimental patch. The only test-dependency feature addition is tokio/test-util for deterministic reader-time tests.

    Live corroboration and limits

    Before patching, a controlled 700-line read on the actual Windows desktop host 0.163.0-alpha.11.2 produced 1,397 outgoing command-output trace records in a 284 ms command window, a native queue-full disconnect, and an observed Android reconnect. A bulk read of the same file produced 8 records without that failure. At a TCP sample 8 ms after the warning, the active burst socket had zero current application-write and retransmission queues; this is evidence against a permanently stuck TCP send buffer at that sampled instant, not a measurement of relay ACK latency.

    After selecting the same-version experimental 0.164.0-alpha.11.1 host and verifying its executable hash, repeating the live 51,800-byte check produced 8 output trace records including setup output, with zero queue-full warnings. Live trace records are server-wide notification logs, not proof of per-recipient queue occupancy. The isolated relay results above count messages actually received for the synthetic logical client.

    This supports the two reproduced mechanisms and the tested experimental correction. It does not establish that every idle reconnect, unknown-stream close, pong timeout, or network fault has these causes, or that the global active-client overflow policy is fully solved for every notification family. The 128-entry capacity and genuine-full disconnect policy remain unchanged in this experiment. Long-term production stability has not yet been established.

    The script, patch and compact measured receipts are included inline so this report does not depend on access to private logs, a personal repository, credentials, screenshots, or downloadable native binaries.

    Measured executable SHA-256 values:

    • Stock 1103e9e09c71fa2cd0afd6d8f3b9a2d63174fe8efd7cb5bd09f1cb14ef58a098
    • Experimental 2701b5d42d854e42bccd9fb72f1031c22fd5324ab785f8aa66ea0f09fc59c722
    Portable loopback reproducer: remote_control_repro.py
    """Exercise installed Remote Control against loopback only, with synthetic auth.
    
    Never reads the real profile/auth. Never calls a model. All endpoints are local.
    """
    import argparse
    import asyncio
    import shutil
    import tempfile
    import base64
    import collections
    import datetime
    import json
    import hashlib
    import os
    from pathlib import Path
    import sys
    import time
    from aiohttp import web
    
    ROOT = None  # Set to a fresh temporary directory by main().
    BINARY = None
    SHELL = None
    
    def fake_jwt():
        def encode(value):
            return base64.urlsafe_b64encode(json.dumps(value).encode()).decode().rstrip('=')
        return encode({'alg':'none','typ':'JWT'})+'.'+encode({'sub':'local-test-only','email':'[email protected]','exp':int(time.time())+3600,'https://api.openai.com/auth':{'chatgpt_account_id':'local-test-account','chatgpt_plan_type':'free'}})+'.synthetic-not-a-real-signature'
    
    async def run_case(label,ack_delay,agent=False,idle=False,backlog=False,bulk_output=False,backlog_requests=128,second_command=False,unicode_fixture=False):
        home=ROOT/('mock-relay-home-'+label)
        home.mkdir(exist_ok=True)
        fixture=ROOT/'mock-relay-fixture.txt'
        fixture_text=''.join('Line %04d: ordinary source text for a local remote-control reproduction.\n'%i for i in range(700))
        if unicode_fixture:fixture_text='x'*8189+'\U0001f680\n'+fixture_text
        fixture.write_text(fixture_text,encoding='utf-8')
        expected=fixture.read_bytes()
        result={'case':label,'ackDelaySeconds':ack_delay,'realCredentialsUsed':False,'externalModelCalls':0,'httpRequests':collections.Counter(),'receivedMethods':collections.Counter(),'serverEnvelopes':0,'outputNotifications':0,'outputBytes':0}
        ws_ready=asyncio.Event()
        remote_init=asyncio.Event()
        command_done=asyncio.Event()
        thread_started=asyncio.Event()
        second_init=asyncio.Event()
        second_command_done=asyncio.Event()
        rpc_futures={}
        metadata_futures={}
        pending_acks={}
        ack_enabled=ack_delay is not None
        ack_tasks=set()
        relay_socket=None
        seq=0
        model_requests=0
        started_at=time.monotonic()
        outstanding={}
        result['bulkOutput']=bulk_output
        result['peakReceivedBeforeMockAck']=0
        result['firstOutputElapsedMs']=None
        result['lastOutputElapsedMs']=None
        result['outputBytesByClient']=collections.Counter()
        result['outputMessagesByClient']=collections.Counter()
        result['expectedOutputBytes']=len(expected)
        result['expectedOutputSha256']=hashlib.sha256(expected).hexdigest()
        output_hashes={}
    
        async def send_client(message,client='synthetic-client',stream='synthetic-stream'):
            nonlocal seq
            seq+=1
            await relay_socket.send_json({'type':'client_message','client_id':client,'stream_id':stream,'seq_id':seq,'message':message})
    
        async def ack(value,delay):
            await asyncio.sleep(delay)
            if not relay_socket.closed:
                await relay_socket.send_json({'type':'ack','client_id':value['client_id'],'stream_id':value['stream_id'],'seq_id':value['seq_id']})
                stream_key=(value['client_id'],value['stream_id'])
                outstanding[stream_key]={seq for seq in outstanding.get(stream_key,set()) if seq>value['seq_id']}
    
        async def handle(request):
            nonlocal relay_socket,model_requests
            result['httpRequests'][request.method+' '+request.path]+=1
            if request.method=='POST' and request.path.endswith('/responses'):
                body=await request.json()
                model_requests+=1
                result['mockModelRequests']=model_requests
                tools=[]
                def collect(entries):
                    for entry in entries:
                        if entry.get('type')=='namespace':collect(entry.get('tools',[]))
                        elif entry.get('type')=='function':tools.append(entry)
                collect(body.get('tools',[]))
                result['advertisedToolNames']=[entry.get('name') for entry in tools]
                stream=web.StreamResponse(headers={'Content-Type':'text/event-stream','Cache-Control':'no-cache'})
                await stream.prepare(request)
                async def emit(name,**data):
                    await stream.write(('data: '+json.dumps({'type':name,**data})+'\n\n').encode())
                response_id='local-response-'+str(model_requests)
                await emit('response.created',response={'id':response_id,'status':'in_progress','output':[]})
                if model_requests==1:
                    tool=next((entry for entry in tools if entry.get('name')=='exec_command'),None)
                    if tool is None:
                        result['mockToolError']='exec_command was not advertised'
                        item={'id':'local-message','type':'message','role':'assistant','content':[{'type':'output_text','text':'No compatible local tool was advertised.'}]}
                    else:
                        command=("[Console]::Out.Write([IO.File]::ReadAllText('%s'))" if bulk_output else "Get-Content -LiteralPath '%s'")%fixture
                        args={'cmd':command,'workdir':str(ROOT),'yield_time_ms':1000,'max_output_tokens':20000,'shell':SHELL,'login':False}
                        item={'id':'local-function','type':'function_call','call_id':'local-tool-call','name':'exec_command','arguments':json.dumps(args)}
                    await emit('response.output_item.added',output_index=0,item=item)
                    await emit('response.output_item.done',output_index=0,item=item)
                else:
                    item={'id':'local-message','type':'message','role':'assistant','content':[{'type':'output_text','text':'Local diagnostic read completed.'}]}
                    await emit('response.output_item.added',output_index=0,item=item)
                    await emit('response.output_text.delta',item_id='local-message',output_index=0,content_index=0,delta='Local diagnostic read completed.')
                    await emit('response.output_item.done',output_index=0,item=item)
                await emit('response.completed',response={'id':response_id,'status':'completed','output':[item],'usage':{'input_tokens':1,'output_tokens':1,'total_tokens':2}})
                await stream.write_eof()
                return stream
            if request.headers.get('Upgrade','').lower()=='websocket':
                ws=web.WebSocketResponse(autoping=not idle)
                await ws.prepare(request)
                relay_socket=ws
                ws_ready.set()
                await send_client({'id':100,'method':'initialize','params':{'clientInfo':{'name':'local_mock_remote_client','version':'1'},'capabilities':{'experimentalApi':True}}})
                async for msg in ws:
                    if msg.type==web.WSMsgType.PING:
                        result['transportPings']=result.get('transportPings',0)+1
                        await ws.pong(msg.data)
                        continue
                    if msg.type!=web.WSMsgType.TEXT:continue
                    value=json.loads(msg.data)
                    if value.get('type')=='pong':result['logicalPongs']=result.get('logicalPongs',0)+1
                    result['serverEnvelopes']+=1
                    key=(value.get('client_id'),value.get('stream_id'))
                    if key[0] is not None:pending_acks[key]=value
                    if value.get('seq_id') is not None:
                        outstanding.setdefault(key,set()).add(value['seq_id'])
                        result['peakReceivedBeforeMockAck']=max(result['peakReceivedBeforeMockAck'],sum(len(v) for v in outstanding.values()))
                    if ack_enabled:
                        task=asyncio.create_task(ack(value,ack_delay or 0))
                        ack_tasks.add(task)
                        task.add_done_callback(ack_tasks.discard)
                    message=value.get('message',{})
                    response_id=message.get('id')
                    if isinstance(response_id,int) and response_id>=1000:
                        result['metadataResponses']=result.get('metadataResponses',0)+1
                        future=metadata_futures.get(response_id)
                        if future and not future.done():future.set_result(message)
                    method=message.get('method','')
                    if method:result['receivedMethods'][method]+=1
                    if method in ('command/exec/outputDelta','item/commandExecution/outputDelta'):
                        elapsed=round((time.monotonic()-started_at)*1000)
                        if result['firstOutputElapsedMs'] is None:result['firstOutputElapsedMs']=elapsed
                        result['lastOutputElapsedMs']=elapsed
                        result['outputNotifications']+=1
                        payload=base64.b64decode(message['params']['deltaBase64']) if method=='command/exec/outputDelta' else message['params']['delta'].encode()
                        size=len(payload)
                        result['outputBytes']+=size
                        result['outputBytesByClient'][value.get('client_id')]+=size
                        result['outputMessagesByClient'][value.get('client_id')]+=1
                        output_hashes.setdefault(value.get('client_id'),hashlib.sha256()).update(payload)
                    if method=='turn/completed':command_done.set()
                    if message.get('id')==100:
                        result['remoteInitializeError']=message.get('error')
                        remote_init.set()
                    elif message.get('id')==101:
                        result['commandResponse']=message
                        command_done.set()
                    elif message.get('id')==200:
                        result['secondInitializeError']=message.get('error')
                        second_init.set()
                    elif message.get('id')==201:
                        result['secondCommandResponse']=message
                        second_command_done.set()
                    elif message.get('id')==102:
                        result['threadStartError']=message.get('error')
                        if 'result' in message:result['threadId']=message['result']['thread']['id']
                        thread_started.set()
                return ws
            if request.path.endswith('/enroll') or request.path.endswith('/refresh'):
                await request.read()
                return web.json_response({'server_id':'local-test-server','environment_id':'local-test-environment','remote_control_token':'synthetic-local-relay-token','expires_at':(datetime.datetime.now(datetime.timezone.utc)+datetime.timedelta(hours=1)).isoformat()})
            if request.method=='GET':return web.json_response({'models':[],'data':[]})
            return web.json_response({'error':'unexpected local mock request'},status=404)
    
        app=web.Application()
        app.router.add_route('*','/{tail:.*}',handle)
        runner=web.AppRunner(app,access_log=None)
        await runner.setup()
        site=web.TCPSite(runner,'127.0.0.1',0)
        await site.start()
        port=site._server.sockets[0].getsockname()[1]
        env={k:v for k,v in os.environ.items() if k not in ('OPENAI_API_KEY','CODEX_API_KEY','CODEX_AUTH_JSON')}
        env.update(CODEX_HOME=str(home),RUST_LOG='warn',HTTP_PROXY='',HTTPS_PROXY='',ALL_PROXY='',NO_PROXY='127.0.0.1,localhost')
        config='chatgpt_base_url = "http://127.0.0.1:%d/backend-api"\ncli_auth_credentials_store = "file"\n'%port
        if agent:
            config+='model = "gpt-5.4"\nmodel_provider = "local_mock"\n[model_providers.local_mock]\nname = "Local diagnostic mock"\nbase_url = "http://127.0.0.1:%d/v1"\nwire_api = "responses"\nrequires_openai_auth = false\nsupports_websockets = false\n'%port
        (home/'config.toml').write_text(config)
        stderr_path=ROOT/('mock-relay-'+label+'.stderr.log')
        with stderr_path.open('w',encoding='utf-8') as err:
            proc=await asyncio.create_subprocess_exec(BINARY,'app-server','--listen','stdio://',cwd=ROOT,env=env,stdin=asyncio.subprocess.PIPE,stdout=asyncio.subprocess.PIPE,stderr=err)
            async def read_stdio():
                async for line in proc.stdout:
                    try:message=json.loads(line)
                    except json.JSONDecodeError:continue
                    future=rpc_futures.get(message.get('id'))
                    if future and not future.done():future.set_result(message)
            reader=asyncio.create_task(read_stdio())
            async def rpc(identity,method,params):
                future=asyncio.get_running_loop().create_future()
                rpc_futures[identity]=future
                proc.stdin.write((json.dumps({'id':identity,'method':method,'params':params})+'\n').encode())
                await proc.stdin.drain()
                response=await asyncio.wait_for(future,8)
                if 'error' in response:raise RuntimeError(method+': '+str(response['error']))
                return response
            try:
                await rpc(1,'initialize',{'clientInfo':{'name':'local_mock_relay_supervisor','version':'1'},'capabilities':{'experimentalApi':True}})
                await rpc(2,'account/login/start',{'type':'chatgptAuthTokens','accessToken':fake_jwt(),'chatgptAccountId':'local-test-account','chatgptPlanType':'free'})
                await rpc(3,'remoteControl/enable',{'ephemeral':True})
                await asyncio.wait_for(ws_ready.wait(),8)
                await asyncio.wait_for(remote_init.wait(),5)
                await send_client({'method':'initialized','params':{}})
                if second_command:
                    await send_client({'id':200,'method':'initialize','params':{'clientInfo':{'name':'local_mock_second_client','version':'1'},'capabilities':{'experimentalApi':True}}},'second-client','second-stream')
                    await asyncio.wait_for(second_init.wait(),5)
                    await send_client({'method':'initialized','params':{}},'second-client','second-stream')
                    await send_client({'id':201,'method':'command/exec','params':{'command':[SHELL,'-NoProfile','-NonInteractive','-Command',"[Console]::OutputEncoding = [System.Text.UTF8Encoding]::new(); Get-Content -LiteralPath '%s' -Encoding UTF8"%fixture],'cwd':str(ROOT),'sandboxPolicy':{'type':'dangerFullAccess'},'processId':'second-client-read','streamStdoutStderr':True,'outputBytesCap':100000,'timeoutMs':5000}},'second-client','second-stream')
                if backlog:
                    result['agentThreadsStarted']=0
                    result['shellCommandsStarted']=0
                    for i in range(backlog_requests):
                        if backlog_requests==128 and result['serverEnvelopes']>=128:break
                        identity=1000+i
                        future=asyncio.get_running_loop().create_future()
                        metadata_futures[identity]=future
                        await send_client({'id':identity,'method':'fs/getMetadata','params':{'path':str(fixture)}})
                        if backlog_requests==128:
                            try:await asyncio.wait_for(future,.5)
                            except asyncio.TimeoutError:break
                        elif i%16==0:await asyncio.sleep(.001)
                elif idle:
                    before=result['serverEnvelopes']
                    start=time.monotonic()
                    for _ in range(2):
                        await asyncio.sleep(30)
                        await relay_socket.send_json({'type':'ping','client_id':'synthetic-client','stream_id':'synthetic-stream'})
                    await asyncio.sleep(2)
                    result['idleSeconds']=round(time.monotonic()-start)
                    result['idleServerEnvelopes']=result['serverEnvelopes']-before
                    result['agentThreadsStarted']=0
                elif agent:
                    await send_client({'id':102,'method':'thread/start','params':{'cwd':str(ROOT),'approvalPolicy':'never','sandbox':'danger-full-access','model':'gpt-5.4','modelProvider':'local_mock'}})
                    await asyncio.wait_for(thread_started.wait(),5)
                    if result.get('threadStartError'):raise RuntimeError(str(result['threadStartError']))
                    await send_client({'id':103,'method':'turn/start','params':{'threadId':result['threadId'],'input':[{'type':'text','text':'Read the synthetic local diagnostic fixture only.'}]}})
                else:
                    await send_client({'id':101,'method':'command/exec','params':{'command':[SHELL,'-NoProfile','-NonInteractive','-Command',"Get-Content -LiteralPath '%s'"%fixture],'cwd':str(ROOT),'sandboxPolicy':{'type':'dangerFullAccess'},'processId':'mock-relay-read','streamStdoutStderr':True,'outputBytesCap':100000,'timeoutMs':5000}})
                if idle:
                    pass
                elif ack_delay is None:
                    await asyncio.sleep(2)
                    result['envelopesBeforeSecondClient']=result['serverEnvelopes']
                    await relay_socket.send_json({'type':'client_closed','client_id':'synthetic-client','stream_id':'synthetic-stream'})
                    await send_client({'id':200,'method':'initialize','params':{'clientInfo':{'name':'local_mock_second_client','version':'1'},'capabilities':{'experimentalApi':True}}},'second-client','second-stream')
                    await asyncio.sleep(1)
                    result['secondInitBeforeOldAcksReleased']=second_init.is_set()
                    ack_enabled=True
                    release=time.monotonic()
                    for value in list(pending_acks.values()):await ack(value,0)
                    try:
                        await asyncio.wait_for(second_init.wait(),3)
                        result['secondInitAfterOldAcksReleased']=True
                        result['secondInitAfterReleaseMs']=round((time.monotonic()-release)*1000)
                    except asyncio.TimeoutError:result['secondInitAfterOldAcksReleased']=False
                else:
                    try:await asyncio.wait_for(command_done.wait(),8 if agent else 4)
                    except asyncio.TimeoutError:result['commandTimedOutWaitingForResponse']=True
                if second_command:
                    try:await asyncio.wait_for(second_command_done.wait(),4)
                    except asyncio.TimeoutError:result['secondCommandTimedOut']=True
            except Exception as exc:
                result['error']=type(exc).__name__+': '+str(exc)[:500]
            finally:
                if relay_socket and not relay_socket.closed:await relay_socket.close()
                proc.terminate()
                await asyncio.wait_for(proc.wait(),5)
                reader.cancel()
                for task in list(ack_tasks):task.cancel()
        await runner.cleanup()
        result['queueWarnings']=[line.strip() for line in stderr_path.read_text(errors='replace').splitlines() if 'outbound queue filled' in line]
        result['httpRequests']=dict(result['httpRequests'])
        result['receivedMethods']=dict(result['receivedMethods'])
        result['outputSha256ByClient']={key:hasher.hexdigest() for key,hasher in output_hashes.items()}
        return result
    
    async def main():
        global ROOT, BINARY, SHELL
        parser = argparse.ArgumentParser(description=__doc__)
        parser.add_argument('--codex', required=True, help='Absolute path to the stock or experimental codex.exe')
        parser.add_argument('--shell', default=shutil.which('pwsh'), help='PowerShell 7 executable path')
        parser.add_argument('--case', choices=['burst', 'bulk', 'retired', 'two-clients'], default='burst')
        parser.add_argument('--ack-delay-ms', type=float, default=25)
        parser.add_argument('--backlog-requests', type=int, default=128)
        parser.add_argument('--out', type=Path, help='Write the JSON result to a new file')
        args = parser.parse_args()
        if not args.shell:
            parser.error('Install PowerShell 7 or pass --shell with its absolute executable path.')
        BINARY = str(Path(args.codex).resolve(strict=True))
        SHELL = str(Path(args.shell).resolve(strict=True))
        if args.ack_delay_ms < 0 or not 1 <= args.backlog_requests <= 1000:
            parser.error('ACK delay must be nonnegative; backlog requests must be in 1..1000.')
        if args.out and args.out.exists():
            parser.error('--out must name a new file.')
        with tempfile.TemporaryDirectory(prefix='codex-remote-loopback-') as directory:
            ROOT = Path(directory)
            result = await run_case(
                args.case,
                None if args.case == 'retired' else args.ack_delay_ms / 1000,
                agent=args.case != 'retired',
                backlog=args.case == 'retired',
                backlog_requests=args.backlog_requests,
                bulk_output=args.case == 'bulk',
                second_command=args.case == 'two-clients',
                unicode_fixture=args.case == 'two-clients',
            )
            # Include local command completion even if the remote client was dropped.
            # These are disposable histories created by this invocation, never the
            # caller's real Codex profile.
            if result.get('threadId'):
                import sqlite3
                database = ROOT/('mock-relay-home-'+args.case)/'thread_history_1.sqlite'
                with sqlite3.connect(database.as_uri()+'?mode=ro', uri=True, timeout=2) as conn:
                    row = conn.execute("select item_json from thread_items where thread_id=? and item_type='commandExecution' order by rollout_ordinal desc limit 1", (result['threadId'],)).fetchone()
                    command = json.loads(row[0]) if row else {}
                    payload = (command.get('aggregatedOutput') or '').encode()
                    result['localCompletion'] = {'status':command.get('status'), 'exitCode':command.get('exitCode'), 'bytes':len(payload), 'sha256':hashlib.sha256(payload).hexdigest()}
                conn.close()
            result.pop('threadId', None)
            text = json.dumps(result, indent=2) + '\n'
            if args.out:
                with args.out.open('x', encoding='utf-8') as output:
                    output.write(text)
            print(json.dumps(result), flush=True)
    
    if __name__ == '__main__':
        asyncio.run(main())
    Experimental patch used to verify the two mechanisms
    diff --git a/codex-rs/app-server-transport/src/transport/remote_control/client_tracker.rs b/codex-rs/app-server-transport/src/transport/remote_control/client_tracker.rs
    index 7c46632..3874455 100644
    --- a/codex-rs/app-server-transport/src/transport/remote_control/client_tracker.rs
    +++ b/codex-rs/app-server-transport/src/transport/remote_control/client_tracker.rs
    @@ -235,6 +235,7 @@ impl ClientTracker {
                             client_id,
                             stream_id,
                             write_complete_tx: None,
    +                        stream_token: None,
                         };
                         let _ = server_event_tx.send(server_envelope).await;
                     });
    @@ -283,6 +284,7 @@ impl ClientTracker {
                         client_id: client_id.clone(),
                         stream_id: stream_id.clone(),
                         write_complete_tx,
    +                    stream_token: Some(disconnect_token.clone()),
                     }) => send_result,
                 };
                 if send_result.is_err() {
    @@ -309,6 +311,10 @@ impl ClientTracker {
             Ok(expired_client_ids)
         }
     
    +    pub(super) fn legacy_stream_id(&self, client_id: &ClientId) -> Option<StreamId> {
    +        self.legacy_stream_ids.get(client_id).cloned()
    +    }
    +
         pub(super) async fn close_client(
             &mut self,
             client_key: &(ClientId, StreamId),
    @@ -569,6 +575,7 @@ mod tests {
                     client_id: ClientId("queued-client".to_string()),
                     stream_id: StreamId("queued-stream".to_string()),
                     write_complete_tx: None,
    +                stream_token: None,
                 })
                 .await
                 .expect("server event queue should accept prefill");
    diff --git a/codex-rs/app-server-transport/src/transport/remote_control/mod.rs b/codex-rs/app-server-transport/src/transport/remote_control/mod.rs
    index f08a694..1731615 100644
    --- a/codex-rs/app-server-transport/src/transport/remote_control/mod.rs
    +++ b/codex-rs/app-server-transport/src/transport/remote_control/mod.rs
    @@ -101,6 +101,7 @@ pub(super) struct QueuedServerEnvelope {
         pub(super) client_id: ClientId,
         pub(super) stream_id: StreamId,
         pub(super) write_complete_tx: Option<oneshot::Sender<()>>,
    +    pub(super) stream_token: Option<CancellationToken>,
     }
     
     #[derive(Clone)]
    diff --git a/codex-rs/app-server-transport/src/transport/remote_control/websocket.rs b/codex-rs/app-server-transport/src/transport/remote_control/websocket.rs
    index d74d3df..63431b6 100644
    --- a/codex-rs/app-server-transport/src/transport/remote_control/websocket.rs
    +++ b/codex-rs/app-server-transport/src/transport/remote_control/websocket.rs
    @@ -146,6 +146,15 @@ impl BoundedOutboundBuffer {
                 .values()
                 .flat_map(|buffer| buffer.iter())
         }
    +
    +    fn discard_stream(&mut self, client_id: &ClientId, stream_id: &StreamId) {
    +        if let Some(buffer) = self
    +            .buffer_by_stream
    +            .remove(&(client_id.clone(), stream_id.clone()))
    +        {
    +            self.used_tx.send_modify(|used| *used -= buffer.len());
    +        }
    +    }
     }
     
     struct WebsocketState {
    @@ -228,6 +237,7 @@ impl WebsocketState {
         }
     
         fn invalidate_client_message_stream(&mut self, client_id: &ClientId, stream_id: &StreamId) {
    +        self.outbound_buffer.discard_stream(client_id, stream_id);
             self.last_completed_client_chunk_seq_id_by_stream
                 .remove(&(client_id.clone(), Some(stream_id.clone())));
         }
    @@ -1052,6 +1062,15 @@ impl RemoteControlWebsocket {
                 };
                 let (payloads, write_complete_tx) = {
                     let mut state = state.lock().await;
    +                // Check under the same lock as retirement so a closed stream
    +                // cannot repopulate the replay window from the shared queue.
    +                if queued_server_envelope
    +                    .stream_token
    +                    .as_ref()
    +                    .is_some_and(CancellationToken::is_cancelled)
    +                {
    +                    continue;
    +                }
                     let seq_key = (
                         queued_server_envelope.client_id.clone(),
                         queued_server_envelope.stream_id.clone(),
    @@ -1248,7 +1267,9 @@ impl RemoteControlWebsocket {
                     matches!(&client_envelope.event, ClientEvent::ClientClosed).then(|| {
                         (
                             client_envelope.client_id.clone(),
    -                        client_envelope.stream_id.clone(),
    +                        client_envelope.stream_id.clone().or_else(|| {
    +                            client_tracker.legacy_stream_id(&client_envelope.client_id)
    +                        }),
                         )
                     });
                 let delivered_client_envelope = client_envelope.clone();
    @@ -1882,6 +1903,35 @@ mod tests {
         use tokio_tungstenite::WebSocketStream;
         use tokio_tungstenite::accept_async;
     
    +    #[test]
    +    fn retiring_stream_releases_only_its_replay_slots() {
    +        let (mut buffer, used) = BoundedOutboundBuffer::new();
    +        let client_id = ClientId("client".to_string());
    +        let retired = StreamId("retired".to_string());
    +        let active = StreamId("active".to_string());
    +        for seq_id in 1..=super::super::CHANNEL_CAPACITY as u64 {
    +            buffer.insert(&ServerEnvelope {
    +                event: ServerEvent::Pong {
    +                    status: super::super::protocol::PongStatus::Active,
    +                },
    +                client_id: client_id.clone(),
    +                seq_id,
    +                stream_id: if seq_id == 1 {
    +                    active.clone()
    +                } else {
    +                    retired.clone()
    +                },
    +            });
    +        }
    +        buffer.discard_stream(&client_id, &retired);
    +        assert_eq!(*used.borrow(), 1);
    +        assert_eq!(buffer.server_envelopes().next().unwrap().stream_id, active);
    +        buffer.ack(&client_id, &retired, u64::MAX, None);
    +        assert_eq!(*used.borrow(), 1);
    +        buffer.ack(&client_id, &active, 1, None);
    +        assert_eq!(*used.borrow(), 0);
    +    }
    +
         // State initialization can delay the first local connection on loaded Bazel workers.
         pub(super) const TEST_HTTP_ACCEPT_TIMEOUT: Duration = Duration::from_secs(30);
         pub(super) const TEST_INSTALLATION_ID: &str = "11111111-1111-4111-8111-111111111111";
    @@ -2801,6 +2851,7 @@ mod tests {
                         client_id: client_id.clone(),
                         stream_id: stream_id.clone(),
                         write_complete_tx: None,
    +                    stream_token: None,
                     })
                     .await
                     .expect("server event should queue");
    diff --git a/codex-rs/core/src/exec.rs b/codex-rs/core/src/exec.rs
    index f72396e..43513ab 100644
    --- a/codex-rs/core/src/exec.rs
    +++ b/codex-rs/core/src/exec.rs
    @@ -12,7 +12,6 @@ use std::time::Instant;
     
     use async_channel::Sender;
     use tokio::io::AsyncRead;
    -use tokio::io::AsyncReadExt;
     use tokio::io::BufReader;
     use tokio::process::Child;
     use tokio_util::sync::CancellationToken;
    @@ -71,7 +70,6 @@ const EXEC_TIMEOUT_EXIT_CODE: i32 = 124; // conventional timeout exit code
     const CANCELLATION_TERMINATION_GRACE_PERIOD: Duration = Duration::from_millis(50);
     
     // I/O buffer sizing
    -const READ_CHUNK_SIZE: usize = 8192; // bytes per read
     const AGGREGATE_BUFFER_INITIAL_CAPACITY: usize = 8 * 1024; // 8 KiB
     
     /// Hard cap on bytes retained from exec stdout/stderr/aggregated output.
    @@ -1192,7 +1190,7 @@ async fn consume_output(
     }
     
     async fn read_output<R: AsyncRead + Unpin + Send + 'static>(
    -    mut reader: R,
    +    reader: R,
         stream: Option<StdoutStream>,
         is_stderr: bool,
         max_bytes: Option<usize>,
    @@ -1202,19 +1200,18 @@ async fn read_output<R: AsyncRead + Unpin + Send + 'static>(
                 AGGREGATE_BUFFER_INITIAL_CAPACITY.min(max_bytes)
             }),
         );
    -    let mut tmp = [0u8; READ_CHUNK_SIZE];
    +    let mut reader = codex_utils_pty::BatchedOutputReader::new(reader);
         let mut emitted_deltas: usize = 0;
     
         loop {
    -        let n = reader.read(&mut tmp).await?;
    -        if n == 0 {
    +        let Some(chunk) = reader.next_chunk().await? else {
                 break;
    -        }
    +        };
     
             if let Some(stream) = &stream
                 && emitted_deltas < MAX_EXEC_OUTPUT_DELTAS_PER_CALL
             {
    -            let chunk = tmp[..n].to_vec();
    +            let chunk = chunk.clone();
                 let msg = EventMsg::ExecCommandOutputDelta(ExecCommandOutputDeltaEvent {
                     call_id: stream.call_id.clone(),
                     stream: if is_stderr {
    @@ -1234,9 +1231,9 @@ async fn read_output<R: AsyncRead + Unpin + Send + 'static>(
             }
     
             if let Some(max_bytes) = max_bytes {
    -            append_capped(&mut buf, &tmp[..n], max_bytes);
    +            append_capped(&mut buf, &chunk, max_bytes);
             } else {
    -            buf.extend_from_slice(&tmp[..n]);
    +            buf.extend_from_slice(&chunk);
             }
             // Continue reading to EOF to avoid back-pressure
         }
    diff --git a/codex-rs/core/src/unified_exec/async_watcher.rs b/codex-rs/core/src/unified_exec/async_watcher.rs
    index f30c750..7d934b2 100644
    --- a/codex-rs/core/src/unified_exec/async_watcher.rs
    +++ b/codex-rs/core/src/unified_exec/async_watcher.rs
    @@ -39,7 +39,7 @@ pub(crate) const TRAILING_OUTPUT_GRACE: Duration = Duration::from_millis(100);
     /// `UNIFIED_EXEC_OUTPUT_MAX_BYTES`), but we also cap per-event payload size so
     /// downstream event consumers (especially app-server JSON-RPC) don't have to
     /// process arbitrarily large delta payloads.
    -const UNIFIED_EXEC_OUTPUT_DELTA_MAX_BYTES: usize = 8192;
    +const UNIFIED_EXEC_OUTPUT_DELTA_MAX_BYTES: usize = codex_utils_pty::OUTPUT_BATCH_MAX_BYTES;
     
     struct Emitter {
         remaining_deltas: usize,
    @@ -112,7 +112,7 @@ pub(crate) fn start_streaming_output(process: &UnifiedExecProcess, context: &Uni
                     }
     
                     received = receiver.recv() => {
    -                    let chunk = match received {
    +                    let mut chunk = match received {
                             Ok(chunk) => chunk,
                             Err(RecvError::Lagged(_)) => {
                                 continue;
    @@ -123,6 +123,16 @@ pub(crate) fn start_streaming_output(process: &UnifiedExecProcess, context: &Uni
                             }
                         };
     
    +                    // A pipe read is not a network frame. Give adjacent small writes a
    +                    // bounded opportunity to accumulate before emitting a notification.
    +                    let deadline = Instant::now() + codex_utils_pty::OUTPUT_BATCH_DELAY;
    +                    while chunk.len() < UNIFIED_EXEC_OUTPUT_DELTA_MAX_BYTES && Instant::now() < deadline {
    +                        match tokio::time::timeout_at(deadline, receiver.recv()).await {
    +                            Ok(Ok(next)) => chunk.extend_from_slice(&next),
    +                            Ok(Err(RecvError::Lagged(_))) => continue,
    +                            Ok(Err(RecvError::Closed)) | Err(_) => break,
    +                        }
    +                    }
                         output.push(chunk).await;
                     }
                 }
    diff --git a/codex-rs/utils/pty/Cargo.toml b/codex-rs/utils/pty/Cargo.toml
    index f7cabb6..bba3571 100644
    --- a/codex-rs/utils/pty/Cargo.toml
    +++ b/codex-rs/utils/pty/Cargo.toml
    @@ -13,6 +13,7 @@ portable-pty = { workspace = true }
     tokio = { workspace = true, features = ["io-util", "macros", "net", "process", "rt-multi-thread", "signal", "sync", "time"] }
     
     [dev-dependencies]
    +tokio = { workspace = true, features = ["test-util"] }
     codex-utils-cargo-bin = { workspace = true }
     ctor = { workspace = true }
     tempfile = { workspace = true }
    diff --git a/codex-rs/utils/pty/src/lib.rs b/codex-rs/utils/pty/src/lib.rs
    index c2a0629..9462455 100644
    --- a/codex-rs/utils/pty/src/lib.rs
    +++ b/codex-rs/utils/pty/src/lib.rs
    @@ -8,8 +8,12 @@ pub use child_command::ProcessMode;
     pub use child_command::SpawnFallback;
     #[cfg(target_os = "linux")]
     mod linux_fds;
    +mod output;
     pub mod pipe;
     mod process;
    +pub use output::BatchedOutputReader;
    +pub use output::OUTPUT_BATCH_DELAY;
    +pub use output::OUTPUT_BATCH_MAX_BYTES;
     pub mod process_group;
     pub mod pty;
     pub use pty::ChildFds;
    diff --git a/codex-rs/utils/pty/src/output.rs b/codex-rs/utils/pty/src/output.rs
    new file mode 100644
    index 0000000..dae1a85
    --- /dev/null
    +++ b/codex-rs/utils/pty/src/output.rs
    @@ -0,0 +1,129 @@
    +use std::io;
    +use std::time::Duration;
    +
    +use tokio::io::AsyncRead;
    +use tokio::io::AsyncReadExt;
    +use tokio::time::Instant;
    +
    +/// Bound both notification size and the latency added to interactive output.
    +pub const OUTPUT_BATCH_MAX_BYTES: usize = 8192;
    +pub const OUTPUT_BATCH_DELAY: Duration = Duration::from_millis(10);
    +
    +/// Coalesce short pipe reads without waiting for EOF or an entire output buffer.
    +pub struct BatchedOutputReader<R> {
    +    reader: R,
    +    buffer: [u8; OUTPUT_BATCH_MAX_BYTES],
    +    pending_error: Option<io::Error>,
    +}
    +
    +impl<R: AsyncRead + Unpin> BatchedOutputReader<R> {
    +    pub fn new(reader: R) -> Self {
    +        Self {
    +            reader,
    +            buffer: [0; OUTPUT_BATCH_MAX_BYTES],
    +            pending_error: None,
    +        }
    +    }
    +
    +    pub async fn next_chunk(&mut self) -> io::Result<Option<Vec<u8>>> {
    +        if let Some(error) = self.pending_error.take() {
    +            return Err(error);
    +        }
    +        let mut len = self.reader.read(&mut self.buffer).await?;
    +        if len == 0 {
    +            return Ok(None);
    +        }
    +        let deadline = Instant::now() + OUTPUT_BATCH_DELAY;
    +        while len < self.buffer.len() && Instant::now() < deadline {
    +            match tokio::time::timeout_at(deadline, self.reader.read(&mut self.buffer[len..])).await
    +            {
    +                Ok(Ok(0)) | Err(_) => break,
    +                Ok(Ok(count)) => len += count,
    +                Ok(Err(error)) if error.kind() == io::ErrorKind::Interrupted => continue,
    +                Ok(Err(error)) => {
    +                    // Publish bytes already read before propagating a subsequent error.
    +                    self.pending_error = Some(error);
    +                    break;
    +                }
    +            }
    +        }
    +        Ok(Some(self.buffer[..len].to_vec()))
    +    }
    +}
    +
    +#[cfg(test)]
    +mod tests {
    +    use super::*;
    +    use std::collections::VecDeque;
    +    use std::pin::Pin;
    +    use std::task::Context;
    +    use std::task::Poll;
    +    use tokio::io::AsyncWriteExt;
    +    use tokio::io::ReadBuf;
    +
    +    struct Fragments(VecDeque<io::Result<Vec<u8>>>);
    +
    +    impl AsyncRead for Fragments {
    +        fn poll_read(
    +            mut self: Pin<&mut Self>,
    +            _: &mut Context<'_>,
    +            buffer: &mut ReadBuf<'_>,
    +        ) -> Poll<io::Result<()>> {
    +            match self.0.pop_front() {
    +                Some(Ok(bytes)) => {
    +                    let count = buffer.remaining().min(bytes.len());
    +                    buffer.put_slice(&bytes[..count]);
    +                    if count < bytes.len() {
    +                        self.0.push_front(Ok(bytes[count..].to_vec()));
    +                    }
    +                    Poll::Ready(Ok(()))
    +                }
    +                Some(Err(error)) => Poll::Ready(Err(error)),
    +                None => Poll::Ready(Ok(())),
    +            }
    +        }
    +    }
    +
    +    #[tokio::test(start_paused = true)]
    +    async fn coalesces_fragments_with_bounded_chunks_and_preserves_bytes() {
    +        let expected = vec![42; OUTPUT_BATCH_MAX_BYTES + 100];
    +        let fragments = expected.iter().map(|byte| Ok(vec![*byte])).collect();
    +        let mut reader = BatchedOutputReader::new(Fragments(fragments));
    +        let mut actual = Vec::new();
    +        let mut count = 0;
    +        while let Some(chunk) = reader.next_chunk().await.unwrap() {
    +            assert!(chunk.len() <= OUTPUT_BATCH_MAX_BYTES);
    +            actual.extend(chunk);
    +            count += 1;
    +        }
    +        assert_eq!(actual, expected);
    +        assert_eq!(count, 2);
    +    }
    +
    +    #[tokio::test(start_paused = true)]
    +    async fn flushes_interactive_output_without_waiting_for_eof() {
    +        let (mut writer, stream) = tokio::io::duplex(64);
    +        writer.write_all(b"prompt> ").await.unwrap();
    +        let mut reader = BatchedOutputReader::new(stream);
    +        let chunk = tokio::time::timeout(Duration::from_secs(1), reader.next_chunk())
    +            .await
    +            .unwrap()
    +            .unwrap()
    +            .unwrap();
    +        assert_eq!(chunk, b"prompt> ");
    +        drop(writer);
    +        assert!(reader.next_chunk().await.unwrap().is_none());
    +    }
    +
    +    #[tokio::test]
    +    async fn delivers_pending_bytes_before_a_read_error() {
    +        let fragments =
    +            VecDeque::from([Ok(b"tail".to_vec()), Err(io::Error::other("read failed"))]);
    +        let mut reader = BatchedOutputReader::new(Fragments(fragments));
    +        assert_eq!(reader.next_chunk().await.unwrap().unwrap(), b"tail");
    +        assert_eq!(
    +            reader.next_chunk().await.unwrap_err().to_string(),
    +            "read failed"
    +        );
    +    }
    +}
    diff --git a/codex-rs/utils/pty/src/pipe.rs b/codex-rs/utils/pty/src/pipe.rs
    index 802dfa5..6b5dde2 100644
    --- a/codex-rs/utils/pty/src/pipe.rs
    +++ b/codex-rs/utils/pty/src/pipe.rs
    @@ -18,7 +18,6 @@ use crate::ProcessMode;
     use crate::child_command::ChildDropPolicy;
     use anyhow::Result;
     use tokio::io::AsyncRead;
    -use tokio::io::AsyncReadExt;
     use tokio::io::AsyncWriteExt;
     use tokio::io::BufReader;
     use tokio::sync::mpsc;
    @@ -105,16 +104,16 @@ fn kill_process(pid: u32) -> io::Result<()> {
         }
     }
     
    -async fn read_output_stream<R>(mut reader: R, output_tx: mpsc::Sender<Vec<u8>>)
    +async fn read_output_stream<R>(reader: R, output_tx: mpsc::Sender<Vec<u8>>)
     where
         R: AsyncRead + Unpin,
     {
    -    let mut buf = vec![0u8; 8_192];
    +    let mut reader = crate::BatchedOutputReader::new(reader);
         loop {
    -        match reader.read(&mut buf).await {
    -            Ok(0) => break,
    -            Ok(n) => {
    -                let _ = output_tx.send(buf[..n].to_vec()).await;
    +        match reader.next_chunk().await {
    +            Ok(None) => break,
    +            Ok(Some(chunk)) => {
    +                let _ = output_tx.send(chunk).await;
                 }
                 Err(ref e) if e.kind() == ErrorKind::Interrupted => continue,
                 Err(_) => break,
    
    Compact measured stock / experimental receipts from the portable script
    [
      {
        "comparisonCase": "stock-burst-25ms",
        "ackDelaySeconds": 0.025,
        "outputNotifications": 256,
        "outputBytes": 9694,
        "expectedOutputBytes": 51800,
        "expectedOutputSha256": "0caaface4f99e8d2919b6b31766c5d8ee31d973e6c266097ad9819df5172f997",
        "outputSha256ByClient": {
          "synthetic-client": "344daf44ba81e34add63cc539f98bcc114783ace93b44cc85a55da7b11624eea"
        },
        "queueWarnings": [
          "{\"timestamp\":\"2026-10-25T02:06:05.872103Z\",\"level\":\"WARN\",\"fields\":{\"message\":\"disconnecting slow connection after outbound queue filled: ConnectionId(1)\"},\"target\":\"codex_app_server::transport\"}"
        ],
        "commandTimedOutWaitingForResponse": true,
        "localCompletion": {
          "status": "completed",
          "exitCode": 0,
          "bytes": 51800,
          "sha256": "0caaface4f99e8d2919b6b31766c5d8ee31d973e6c266097ad9819df5172f997"
        }
      },
      {
        "comparisonCase": "fixed-burst-25ms",
        "ackDelaySeconds": 0.025,
        "outputNotifications": 7,
        "outputBytes": 51800,
        "expectedOutputBytes": 51800,
        "expectedOutputSha256": "0caaface4f99e8d2919b6b31766c5d8ee31d973e6c266097ad9819df5172f997",
        "outputSha256ByClient": {
          "synthetic-client": "0caaface4f99e8d2919b6b31766c5d8ee31d973e6c266097ad9819df5172f997"
        },
        "queueWarnings": [],
        "localCompletion": {
          "status": "completed",
          "exitCode": 0,
          "bytes": 51800,
          "sha256": "0caaface4f99e8d2919b6b31766c5d8ee31d973e6c266097ad9819df5172f997"
        }
      },
      {
        "comparisonCase": "stock-retired-128",
        "ackDelaySeconds": null,
        "outputNotifications": 0,
        "outputBytes": 0,
        "expectedOutputBytes": 51800,
        "expectedOutputSha256": "0caaface4f99e8d2919b6b31766c5d8ee31d973e6c266097ad9819df5172f997",
        "outputSha256ByClient": {},
        "queueWarnings": [],
        "agentThreadsStarted": 0,
        "shellCommandsStarted": 0,
        "metadataResponses": 126,
        "envelopesBeforeSecondClient": 128,
        "secondInitBeforeOldAcksReleased": false,
        "secondInitAfterOldAcksReleased": true,
        "secondInitAfterReleaseMs": 1
      },
      {
        "comparisonCase": "fixed-retired-128",
        "ackDelaySeconds": null,
        "outputNotifications": 0,
        "outputBytes": 0,
        "expectedOutputBytes": 51800,
        "expectedOutputSha256": "0caaface4f99e8d2919b6b31766c5d8ee31d973e6c266097ad9819df5172f997",
        "outputSha256ByClient": {},
        "queueWarnings": [],
        "agentThreadsStarted": 0,
        "shellCommandsStarted": 0,
        "metadataResponses": 126,
        "envelopesBeforeSecondClient": 128,
        "secondInitBeforeOldAcksReleased": true,
        "secondInitAfterOldAcksReleased": true,
        "secondInitAfterReleaseMs": 0
      },
      {
        "comparisonCase": "stock-bulk-500ms",
        "ackDelaySeconds": 0.5,
        "outputNotifications": 8,
        "outputBytes": 51800,
        "expectedOutputBytes": 51800,
        "expectedOutputSha256": "0caaface4f99e8d2919b6b31766c5d8ee31d973e6c266097ad9819df5172f997",
        "outputSha256ByClient": {
          "synthetic-client": "0caaface4f99e8d2919b6b31766c5d8ee31d973e6c266097ad9819df5172f997"
        },
        "queueWarnings": [],
        "localCompletion": {
          "status": "completed",
          "exitCode": 0,
          "bytes": 51800,
          "sha256": "0caaface4f99e8d2919b6b31766c5d8ee31d973e6c266097ad9819df5172f997"
        }
      }
    ]
  9. timbuilt-db-tim commented on Oct 30, 2026

    @timbuilt-db-tim

    Retired-stream replay stall independently reproduced on stock Windows0.165.0-alpha.1.2

    Following the metadata-only reproduction in #37526 (comment), I independently tested the installed unmodified Windows desktop app-server0.165.0-alpha.1.2. This adds a newer-runtime confirmation of the retired-stream replay case, not a test of the experimental patch or a claim that all live Remote Control failures share this cause.

    Two isolated runs used fresh temporary CODEX_HOME profiles, file-backed synthetic login, and an ephemeral loopback-only mock backend/relay. No real credentials, paid inference, agent turns, shell commands, or production enrollment were used. The published harness was adapted for hidden Windows child launch, restricted inherited environment, retained fixtures, exception-safe cleanup, and per-stream/generation observations. Both diagnostic children exited normally.

    Case Old stream's unacknowledged envelopes at retirement Replacement initialize before old ACKs After old ACKs released
    Low-occupancy control 3, seq1–3 Succeeds Already initialized
    Saturated and explicitly closed old stream 128, seq1–128 No response during1.008s observation Succeeds1ms after release

    Each run used exactly one WebSocket generation. Both initialize responses were error-free. All retained entries at retirement belonged to the old synthetic client/stream. No outbound-queue-full warning occurred. The saturated case delivered126 metadata responses plus initialization/status envelopes before retirement; no command output or large history was involved.

    The timed observation alone does not establish an infinite stall. Together with the low-occupancy control, controlled ACK release, exact retired-stream occupancy and the source's global receive gate, it reproduces the retired replay-capacity coupling without a reconnect confound.

    The inspected websocket.rs blob is d74d3dfd8a4d5e19616bfac256f9e093e1ee7bc2, identical in current main and public rust-v0.166.0. This is a source comparison; the0.166 binary was not tested. No experimental build or live repair was installed.

    Please consider the narrow retired-stream cleanup described in the earlier comment: release the retired stream's replay slots, prevent canceled queued work from refilling them, preserve active-stream replay and byte delivery, and handle late ACKs without double accounting. Is there a planned vendor fix or supported diagnostic for correlating live stream retirement with retained replay occupancy? Active work must remain running during diagnosis.

    Private identifiers, transcripts, paths, addresses, account data and credentials are intentionally excluded.

  10. JeremiahG88 commented on Nov 22, 2026

    @JeremiahG88

    iOS voice session closes mid-sentence when the Windows host drops the phone for a full outbound queue (0.169.0-alpha.11.1)

    Fresh confirmation on a newer bundled runtime, with one user-visible consequence not yet described in this issue: an active realtime voice session on the iPhone ends with it. The voice screen closes mid-sentence and the user is returned to the text chat. Seen once in ordinary use with the log row captured, then reproduced twice on demand with a control. Identifiers are removed throughout; timestamps are UTC.

    Environment

    • Host: Windows Server 2025 (x64), Codex desktop package OpenAI.Codex 26.1111.2228.0, bundled runtime 0.169.0-alpha.11.1 (the cli_version recorded in the app's session files). Running since 16 November 2026.
    • Client: Codex for iOS (the host's Connections panel listed an iPhone on iOS 27.0.1 earlier the same day; the iOS app build was not recorded). Remote control through the hosted relay; voice started from the phone.
    • Shell on the host: Windows PowerShell 5.1 (powershell.exe -Command ..., as recorded for agent commands).

    What the user sees

    During a voice conversation the assistant stops mid-sentence, the whole voice screen closes and the phone shows the same chat as text. The app stays open. Voice has to be started again. The agent task itself keeps running on the host and completes.

    Host log, one event in ordinary use (21 November 2026)

    02:49:03.750  voice-triggered agent turn starts
    02:49:05.328  agent runs one shell command that prints several text files line by line
                  (result later recorded: 42,030 characters, 588 lines)
    02:49:07.844  WARN  app_server::transport: disconnecting slow connection after outbound queue filled: ConnectionId(N)
    02:49:07.844  INFO  remote_control::client_tracker: forwarding remote control connection closed transport event connection_id=ConnectionId(N)
    02:49:07.9 - 02:49:15.2  realtime conversation events still arrive on the host's sideband (call still up)
    02:49:17.860  ERROR realtime_websocket::methods: realtime websocket receive failed: WebSocket protocol error: Connection reset without closing handshake
    02:49:17.860  WARN  core::realtime_conversation::sideband: live sideband transport lost; reconnecting ... delay_ms=200
    02:49:18 / :23 / :29 / :35   four reconnect attempts to the same live session
    02:49:35.799  the agent turn completes normally (32.0 s)
    02:49:40.633  INFO  core::realtime_conversation::sideband: realtime sideband session ended while reconnecting
    02:49:40.687  INFO  core::realtime_conversation: realtime conversation transport closed   (session record: realtime_session_closed, outcome "ended")
    02:49:45.03   the phone is back as a new connection and resumes the thread
    

    So the order is: queue-full disconnect of the phone's logical connection (2.5 s into a line-by-line command output), the call torn down from the phone side about 10 s later, the host's sideband giving up about 23 s after that.

    Reproduced on demand, one factor varied (22 November 2026)

    One new voice chat started from the iPhone, the host log polled every two seconds for the whole test so that no row could be pruned unseen. The only thing varied was how the agent printed a text file.

    • Block output (a small program that writes the file to stdout in 32 KiB blocks): five voice requests in one unbroken voice session of 4 min 22 s. 14 commands printed 1,369 to 41,367 characters each, about 310,000 in total, plus four MCP calls. No queue-full row. At most 34 delta notifications in any second of those prints.
    • Get-Content <file> in Windows PowerShell 5.1 (41,194 characters, 369 lines), asked for twice:
    05:54:22.474  command starts
    05:54:24.775  WARN  app_server::transport: disconnecting slow connection after outbound queue filled: ConnectionId(N)
                  (388 delta notifications in that second)
    05:54:26.211  agent turn completes
    05:54:28.9 / 05:54:38.6  two more spoken segments recorded: the call is still up
    05:54:39.379  Submission operation="shutdown"; INFO core::session::handlers: Shutting down Codex instance; thread-state teardown
                  (no realtime_session_closed record is ever written for this voice session)
    05:54:47.940  the user starts voice again in the same chat
    05:55:04.634  the same command starts
    05:55:05.655  WARN  app_server::transport: disconnecting slow connection after outbound queue filled: ConnectionId(N+1)
                  WARN  app_server::transport: dropping message for disconnected connection (x3); 395 delta notifications in that second
    05:55:09.701  shutdown and teardown again, no close record
    

    2 of 2 with line-by-line output, 0 of 5 requests (14 prints) with block output, same chat, phone and network, minutes apart. Two shapes of the same failure follow from it: with an agent turn still running, the call is reset about 10 s after the disconnect and a close record follows (first event above); with the chat idle, the instance is shut down 4 to 15 s after the disconnect and the voice session gets no close record at all.

    For comparison, a voice session the user ended on the phone a minute later, with no command running and no queue-full row, shows on the host as the same Connection reset without closing handshake followed by a close record about 23 s later. So the session record of a dropped voice session and of one the user ended are the same.

    Log retention during this test: a normal read of logs_2.sqlite 60 and 100 seconds after the two WARN rows no longer contained either of them.

    Scope on the first day (the app's session records, which are not pruned)

    • 16 voice sessions. One drop is confirmed by the log lines above.
    • Eight further sessions ended within seconds of a shell command that printed 251 to 568 lines through PowerShell (Get-Content, a recursive listing, a search piped through a cmdlet). Their transport log rows were no longer retained when read (see "Log retention"), so they are consistent with the same cause, not confirmed.
    • Six sessions ended with no large output nearby (long idle, a command waiting for approval, or an ordinary close request); not attributed to this. One was still open when read.
    • Counting shell outputs of 250 lines or more printed while voice was live: 11 of 16 were followed by the end of the voice session within about a minute, 5 were not.
    • Not affected in the same session: about 15 seconds of continuous speech; MCP connector calls returning 8,552, 24,242 and 31,909 characters (connector results arrive as one item, not as output deltas).

    Fragmentation measured on the host (same 49,353-byte, 431-line file, 3 runs each, 8 KiB pipe reads)

    How it is printed Separate reads seen by a fast pipe reader
    Get-Content <file> (Windows PowerShell 5.1) 812 to 816
    Get-Content -Raw <file> 114 to 152
    Get-Content <file> | Out-String 156 to 171
    cmd /c type <file> 262 to 405
    raw bytes written to the stdout stream / a Python program printing the file once 7

    Windows PowerShell writes redirected output through a 256-character console writer and one write per line plus one per newline, so even a single string is split into more than a hundred writes. This is the "read-fragment-to-notification amplification" described in the 25 October comment above, on the stock shell of a Windows host.

    Source check

    At tag rust-v0.169.0-alpha.11.1: CHANNEL_CAPACITY is 128 (app-server-transport/src/transport/mod.rs), and send_message_to_connection (app-server/src/transport.rs) still does try_send and disconnects on TrySendError::Full. At the newest tag available on 22 November 2026 (rust-v0.173.0-alpha.4) the capacity and the disconnect path are unchanged and utils/pty/src/pipe.rs and core/src/unified_exec/async_watcher.rs are byte-identical to the installed tag. On main at cf3ff1530d (22 November) the capacity and the disconnect path are also unchanged. So no released build contains a fix.

    Log retention (makes this hard to report)

    logs_2.sqlite kept only about the last thousand process-level rows of the running app process: the 02:49:07 WARN row was present 25 minutes after the event and gone 5 minutes later, after one more voice session. The session .jsonl files keep realtime_session_closed with outcome: "ended" for every kind of ending, including this one, so nothing durable distinguishes a dropped voice session from one the user ended.

    Requests

    1. Do not disconnect a remote-control client for a burst of output deltas: coalesce command output before it becomes notifications, or apply backpressure with a timeout, as proposed in this issue.
    2. On iOS, do not end the realtime voice session when the host connection is re-established within a few seconds.
    3. Record a distinct close outcome in the session file when a voice session ends because the client connection was dropped, and keep WARN rows of app_server::transport longer than trace rows.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    CLIapp-serverbugconnectivityremote

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions