Skip to content

Detect dead websocket connections faster after network changes instead of showing Working for up to 5 minutes #17003

Open

Description

@0xdeafbeef

What version of Codex CLI is running?

codex-cli 0.118.0

What subscription do you have?

pro

Which model were you using?

No response

What platform is your computer?

it is platform independent

What terminal emulator and version are you using (if applicable)?

No response

What issue are you seeing?

When the network changes underneath an active Codex session, for example switching VPNs or after resuming from sleep, the TUI can keep showing Working for 5 minutes even though the underlying websocket is effectively dead.

The websocket response stream is considered dead only after stream_idle_timeout_ms, which defaults to 300000 ms (5 minutes).

Relevant code:

  • codex-rs/model-provider-info/src/lib.rs
    • DEFAULT_STREAM_IDLE_TIMEOUT_MS = 300_000
    • DEFAULT_STREAM_MAX_RETRIES = 5
    • DEFAULT_WEBSOCKET_CONNECT_TIMEOUT_MS = 15_000
  • codex-rs/codex-api/src/endpoint/responses_websocket.rs
    • run_websocket_response_stream() waits with tokio::time::timeout(idle_timeout, ws_stream.next())
  • codex-rs/core/src/codex.rs
    • retry UI for websocket reconnects is partially hidden in release builds on the first retry

Because of that, a silent network break can look like a healthy in-progress turn until the 5-minute idle timeout expires.

What steps can reproduce the bug?

Switch vpn, turn wifi on/off/put laptop to sleep and resume.

What is the expected behavior?

Codex should detect dead websocket connections promptly after network changes and either:

  • reconnect within seconds, or
  • clearly show a reconnecting / waiting-for-network state instead of Working

Additional information

Any of these would be an improvement:

  • add proactive websocket heartbeat ping/pong from the client and fail the connection if pong is not received within a short deadline
  • lower the effective websocket idle detection timeout during active turns
  • surface the first websocket reconnect attempt in the TUI instead of hiding it in release builds
  • distinguish between “model is working” and “connection is stalled / reconnecting”

Activity

  1. added
    bug
    on Apr 7, 2026
  2. added
    CLI
    TUI
    on Apr 7, 2026
  3. added
    agent
    and removed
    TUI
    CLI
    on Apr 7, 2026
  4. added
    connectivity
    and removed
    agent
    on Apr 11, 2026
  5. Ragnoroct commented on Jul 29, 2026

    @Ragnoroct

    I traced my Linux suspend/resume stalls to IPv6 address rotation.

    After resume, NetworkManager has removed the WebSocket's source address, but
    Linux still reports the TCP socket as established (SO_ERROR=0, no EOF). Codex
    reuses it and waits for the 300-second timeout.

    Ragnoroct/codex@082a5fc is a diagnostic-only commit. It checks the socket's local IP before each send with a temporary UDP bind (no traffic):

    before suspend: assigned
    after resume:   stale (EADDRNOTAVAIL)
    
  6. argothiel commented on Sep 13, 2026

    @argothiel

    Same issue after simple sleep/resume on codex-cli 0.154.0.

  7. mib00038 commented on Sep 27, 2026

    @mib00038

    Linux, codex-cli 0.157.1: same stall after suspend/resume. Tracing at 18344a9:

    • ResponsesWebsocket::is_closed() only checks whether the pump task has finished (codex-api/src/endpoint/responses_websocket.rs:225-231), so a half-open socket passes the reuse check in core/src/client.rs:1562-1571.
    • The client never sends pings, and incoming pongs are dropped (responses_websocket.rs:91-97).
    • connect_resolved_tcp sets only TCP_NODELAY (websocket-client/src/dialer.rs:209-217).
    • Detection falls to stream_idle_timeout (300 s) on tokio's monotonic clock, which stops during suspend, so the full 300 s runs after wake. Allow idle threads to prewarm and repair WebSocket connections #47701's idle repair also relies on is_closed().

    Proposed fix, two layers:

    1. Probe before reusing an idle socket (gives recovery in seconds).

    • Add WsCommand::Ping { tx_pong: oneshot::Sender<()> } to the pump. The pump sends Message::Ping and completes tx_pong on the next Message::Pong, instead of dropping it.
    • Add ResponsesWebsocketConnection::probe(deadline) -> bool, false if no pong arrives within about 2 s.
    • In the reuse check, when the connection has been idle more than about 15 s, measured on a clock that advances during suspend (CLOCK_BOOTTIME on Linux, SystemTime elsewhere), call probe. On false, reset with reason "probe_failed" and reconnect.
    • The first turn after wake then reconnects within about 2 s instead of 300 s, and turns on a recently used connection pay nothing.

    2. Kernel backstop in connect_resolved_tcp:

    let sock = socket2::SockRef::from(&stream);
    sock.set_tcp_keepalive(&socket2::TcpKeepalive::new()
        .with_time(Duration::from_secs(30))
        .with_interval(Duration::from_secs(10)))?;
    #[cfg(any(target_os = "linux", target_os = "android"))]
    sock.set_tcp_user_timeout(Some(Duration::from_secs(20)))?;

    This bounds a send over a dead path to about 20 s and lets keepalive reap idle dead sockets. On its own it doesn't give seconds-level recovery, hence layer 1. socket2 0.6 is already a workspace dependency.

    We haven't tested a patch.

  8. Ragnoroct commented on Sep 27, 2026

    @Ragnoroct

    On linux it can be a lot simpler.

    // Linux psuedocode: RTMGRP_IPV6_IFADDR + RTM_DELADDR
    let ip = conn.local_addr()?.ip();
    
    listen(RTMGRP_IPV6_IFADDR, |event| {
        if event.kind == RTM_DELADDR && event.ip == ip {
            reconnect(conn);
        }
    });
    
  9. ninja- commented on Oct 4, 2026

    @ninja-

    I hope this gets fixed. my workflow involves re-connecting various devices posing as network adapters etc. even though I have a seperate one for stable internet connection. a single, irrelevant to internet access, netlink event moves the Codex websocket into a zombie state every single time.

  10. Morritse commented on Oct 21, 2026

    @Morritse

    Additional reproduction on Linux with Codex app-server 0.163.0, plus a locally tested candidate fix based on main at 07cc649c658be7018b6913299f12f843b24679f8.

    After suspend/resume, sending a one-word test through the CLI took 303.853 seconds. Exiting and resuming the conversation has consistently been my workaround.

    Observed behavior

    Sanitized timeline from the unpatched installation (UTC, 2026-10-21):

    21:30:12 system resumed from suspend
    21:30:48 test turn started; auth_connection_reused=true
    21:35:48 stream disconnected before completion: idle timeout waiting for websocket
    21:35:49 new WebSocket successfully connected; auth_connection_reused=false
    21:35:52 nine-token final answer completed
    

    The test executed no tools and used zero reasoning output tokens. This was a direct CLI prompt. The 300-second stream idle timeout accounts for essentially the entire delay.

    Source observations

    These observations are from the main commit above, not a tag-level comparison to 0.163.0:

    • ResponsesWebsocketConnection::is_closed only tests whether its pump task finished.
    • A half-open TCP connection can pass that check and buffer writes locally.
    • The pump answers server pings but previously discarded all pongs; it did not probe before reuse.
    • The response stream waits for the normal model stream idle timeout before reconnecting.

    Candidate fix, implemented locally

    • Before reusing a connection idle for at least 15 seconds, send a nonce-bearing WebSocket ping and require the matching pong within 2 seconds (including write time).
    • Measure the idle gate with SystemTime so Linux suspend counts; a backward wall-clock adjustment also triggers a probe.
    • Retire the connection on failed or canceled probe, before response.create is sent. Use the existing reconnect path to clear connection-specific previous_response_id and send full history on the replacement connection.
    • Keep recently used connections on the fast path and leave model response timeouts unchanged.

    Scope: pre-request idle connection recovery. It does not promise detection of network loss during an active response, or a new failure inside the 15-second idle gate. No claim of detecting the underlying network/suspend cause.

    This follows the idle-probe approach already discussed in this issue.

    Validation

    • 22 transport tests passed, including 10 new liveness cases (missing/wrong pong, cancellation, queued data, server ping, timestamp refresh, backward clock).
    • All 51 client WebSocket tests passed, including healthy idle continuation and an old connection whose server stops reading, while the kernel still acknowledges TCP traffic. This simulates an unresponsive peer; the client reconnects without sending response.create on that socket. The replacement request has full history and no previous_response_id.
    • Used the repository CI test stack setting, RUST_MIN_STACK=8388608.
    • cargo clippy -p codex-api --lib --tests -- -D warnings passed; formatting and patch application checks passed.

    After activating the patched managed backend, I completed a physical laptop sleep/wake cycle and sent a test prompt; it returned without the previously observed five-minute stall. This is one successful smoke test, not repeated controlled validation. A healthy connection taking more than two seconds to answer a ping will also be replaced. A separate authenticated transport-only check against the real Responses endpoint received matching pongs in 66.3 ms initially and 39.0 ms after 16 seconds idle, with no response.create or model request sent. This confirms ping support on that connection; repeated sleep/wake and network-change testing remain useful follow-up checks.

  11. vitek commented on Nov 10, 2026

    @vitek

    Confirmed still reproducible with Codex CLI 0.167.0 on Linux. A reused Responses WebSocket can remain half-open after suspend/resume and accept a local write without delivering a response.

    Observed unpatched behavior:

    • system resumed at 16:56:49
    • network was globally connected at 16:56:56
    • turn started at 16:57:02 with auth_connection_reused=true
    • no response events arrived; the turn was manually interrupted at 16:57:38
    • the following turn opened a new WebSocket and completed normally

    I tested a client-side idle probe based on the approach discussed above:

    • before reusing a WebSocket idle for at least 5 seconds, send a WebSocket Ping
    • require the matching Pong within 3 seconds
    • on timeout, retire the socket and use the existing retry/reconnect path
    • track idle time using SystemTime, so suspend time is included

    Physical suspend/resume validation:

    • resumed: 18:54:56
    • NetworkManager reached CONNECTED_GLOBAL: 18:55:02
    • idle-socket probe started: 18:55:03.543
    • Pong timeout: 18:55:06.545
    • replacement WebSocket connected: 18:55:07.349
    • first response item arrived: 18:55:08.515

    This reduced the observed post-resume stall to about 5 seconds. On a healthy idle connection, the same probe received a Pong in approximately 49 ms.

    Validation: all 225 codex-api tests passed, followed by a successful physical suspend/resume test.

    Tested patch (based on the 0.167.0 tag): vitek@7d01dc2

    Branch: https://github.com/vitek/codex/tree/fix/resume-websocket-reconnect

    Scope: this probes an idle socket before reuse. It does not change the timeout for a connection that dies during an active response.

  12. Ragnoroct commented on Nov 10, 2026

    @Ragnoroct

    Workaround
    On Linux, I use ip monitor to watch for removed addresses and close established TCP sockets using them. Codex can then reconnect without waiting for the idle timeout. This affects all matching TCP connections.

    /etc/systemd/system/codex-netwatch.service:

    [Unit]
    Description=Close TCP sockets when their source address is removed
    
    [Service]
    ExecStart=/usr/local/libexec/codex-netwatch
    Restart=always
    RestartSec=1
    DynamicUser=yes
    AmbientCapabilities=CAP_NET_ADMIN
    CapabilityBoundingSet=CAP_NET_ADMIN
    NoNewPrivileges=yes
    
    [Install]
    WantedBy=multi-user.target

    /usr/local/libexec/codex-netwatch:

    #!/usr/bin/env bash
    set -euo pipefail
    
    while read -r event _index _interface family cidr _rest; do
        [[ "$event" == "Deleted" ]] || continue
        address="${cidr%/*}"
    
        case "$family" in
            inet)  flag=-4; source="$address" ;;
            inet6) flag=-6; source="[$address]" ;;
            *) continue ;;
        esac
    
        /usr/bin/ss -H -n -t "$flag" -K state established src "$source"
    done < <(/usr/sbin/ip -o monitor address)

    Make the script executable, then run sudo systemctl enable --now codex-netwatch.service

  13. szafranski commented on Nov 23, 2026

    @szafranski

    I hit this once on macOS 27.2.1 with the native Codex app-server in T3 Code Beta 0.1.11 (gpt-6.2-sol). I asked Codex to list the numbers 1 through 1,000, one per line, without tools. Once the response started, I switched between two Wi-Fi networks.

    macOS had an IPv4 address and DNS on the new network within 0.6 s of disconnecting from the old one. T3 still showed Thinking. Codex logged its first retry 299.8 s after the disconnect with stream disconnected before completion: idle timeout waiting for websocket. The new Responses WebSocket returned HTTP 101 about 0.7 s later, and the same turn finished on its own. I expected Codex to retry within a few seconds of the network coming back.

    In a separate run, I sent a prompt after Wi-Fi associated, while DHCP was still in progress. Codex first retried about 38 s after turn/start with Can't assign requested address (os error 49), then completed the turn. I'm unsure whether that error shares the same cause.

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

    bugconnectivity

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions