Skip to content

Do not rely on startup OSC probing for the composer background #23489

Closed

Description

@haowang02

What version of Codex CLI is running?

codex-cli 0.131.0

What subscription do you have?

ChatGPT Pro 20x

Which model were you using?

gpt-5.5

What platform is your computer?

Linux 6.8.0-90-generic x86_64 x86_64

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

iTerm2 (ssh)

Codex doctor report

What issue are you seeing?

Codex uses startup OSC 10/11 probing to detect terminal colors for the TUI composer background. This is unreliable over SSH because the response has to round-trip through the local terminal emulator.

Relevant code:

  • Startup probe timeout is 100ms: codex-rs/tui/src/terminal_probe.rs
    pub(crate) const DEFAULT_TIMEOUT: Duration = Duration::from_millis(100);
  • Default colors require both OSC 10 and OSC 11:
    fn parse_default_colors(buffer: &[u8]) -> Option<DefaultColors> {
        let fg = parse_osc_color(buffer, /*slot*/ 10)?;
        let bg = parse_osc_color(buffer, /*slot*/ 11)?;
        Some(DefaultColors { fg, bg })
    }
  • Composer background depends on user_message_style():
    pub fn user_message_style_for(terminal_bg: Option<(u8, u8, u8)>) -> Style {
        match terminal_bg {
            Some(bg) => Style::default().bg(user_message_bg(bg)),
            None => Style::default(),
        }
    }

In my SSH session, OSC 10/11 are supported, but the responses always arrive after 100ms. As a result, the composer background appears locally, but disappears when running Codex over SSH.

Image

Please consider removing this startup probe as a hard dependency for the composer background. Possible alternatives:

  • use a theme/default composer background without probing;
  • probe asynchronously and update later;
  • retry instead of caching failure;
  • allow users to configure the composer background.

Increasing the timeout would help some cases, but the core issue is that fixed startup OSC probing is fragile over SSH.

What steps can reproduce the bug?

  1. Run Codex on the remote machine.
  2. Observe that the composer/input background is missing.

The bug is reproducible when OSC 10/11 are supported but the response arrives after Codex's 100ms startup probe timeout.

What is the expected behavior?

No response

Additional information

No response

Activity

  1. added
    bug
    on May 19, 2026
  2. added
    CLI
    TUI
    on May 19, 2026
  3. github-actions commented on May 19, 2026

    @github-actions
    Contributor

    Potential duplicates detected. Please review them and close your issue if it is a duplicate.

    Powered by Codex Action

  4. removed
    CLI
    on May 19, 2026
  5. ssirois commented on Jun 20, 2026

    @ssirois

    I think this issue also has a more severe startup-input failure mode than missing composer background colors.

    I can reproduce a case where Codex exits before the user can interact with startup dialogs, including the project trust selector and session selector, when started inside GNU screen running under rxvt-unicode (urxvt). The same Codex build works when started directly in urxvt, and it also works in xterm both with and without GNU screen.

    Reproduced with:

    • OS: Debian GNU/Linux 11 (bullseye)
    • kernel: Linux 5.10.0-44-amd64 x86_64
    • Codex CLI: codex-cli 0.141.0
    • Codex path: $HOME/.nvm/versions/node/v20.20.0/bin/codex
    • terminal emulator: rxvt-unicode (urxvt) v9.22, released 2016-01-23
    • multiplexer: GNU screen 4.08.00, released 2020-02-05
    • startup dialog affected: project trust selector, and the same behavior is expected for other startup dialogs
    • a local build from a focused patch fixes the observed behavior in this environment

    The same Codex CLI version is interactive when run directly in the same urxvt window without GNU screen. In the same local environment, xterm also works both with and without GNU screen (xterm reported XTerm(366) in the captured environment).

    Relevant environment from the working direct-urxvt run:

    TERM=rxvt-unicode-256color
    COLORTERM=rxvt-xpm
    STY=
    WINDOW=
    WINDOWID=23068681
    CODEX_TUI_DISABLE_KEYBOARD_ENHANCEMENT=
    

    Relevant environment from the failing urxvt + screen run in the same window:

    TERM=screen-256color-bce
    COLORTERM=rxvt-xpm
    STY=114447.pts-1.<redacted hostname>
    WINDOW=0
    WINDOWID=23068681
    CODEX_TUI_DISABLE_KEYBOARD_ENHANCEMENT=1
    

    CODEX_TUI_DISABLE_KEYBOARD_ENHANCEMENT=1 was an early negative-control test in this specific environment. The goal was to check whether Codex's keyboard enhancement path was responsible for the observed input problem. The failure still reproduced with keyboard enhancement disabled, and the later strace comparison pointed instead to delayed terminal response bytes from the startup OSC 10/11 default-color probe. I included the variable above only because it documents that the keyboard-enhancement path was evaluated and did not explain this failure.

    The failure mechanism appears to be in the startup OSC 10/11 default-color probe, not in the dialog code itself.

    From strace comparison between the failing urxvt + screen run and a working direct-urxvt run:

    • Codex writes a startup probe containing cursor-position query plus OSC 10/11 default-color queries.
    • The OSC 10/11 queries are terminated with ST (ESC \).
    • In the failing urxvt + screen path, Codex reads the cursor response and an incomplete OSC 11 body before the bounded startup-probe timeout expires.
    • After the trust selector is already drawn and the normal TUI input path is active, the remaining ST terminator contributes a standalone ESC byte to input.
    • The dialog correctly treats Escape as cancel/quit, so Codex exits immediately before the user can select anything.

    This is related to this issue because it is another consequence of relying on startup OSC probing with a short deadline. The symptom is different from the composer background disappearing: the delayed terminal response leaks into the interactive input stream and triggers an actual dialog action.

    I tested a minimal local fix that keeps the OSC 10/11 default-color probe but terminates those queries with BEL (\x07) instead of ST (ESC \). The parser already accepts both BEL and ST responses. With BEL termination, the same urxvt + screen startup trust selector becomes interactive again in my environment.

    This also matches existing precedent in the repository: PR #18261 changed terminal title OSC updates from ST to BEL because an ST terminator could leak through terminal integrations. This startup color-probe case appears to be the same class of robustness issue, but on the input side of startup probing.

    Related context:

    • #20654 introduced bounded startup terminal probes, including OSC 10/11 default-color probing.
    • #23175 optimized/batched startup terminal probes.
    • #28342 handled terminal response byte injection after suspend/resume.
    • #18261 changed OSC title updates to BEL termination to avoid leaked ST behavior.
    • Older OSC reply leakage reports such as #4945, #5107, #4960, #5852, and #6081 look related historically, but they were about visible 10;rgb / 11;rgb text entering input and were closed as fixed by older work.

    The focused patch I tested locally changes only the OSC 10/11 query terminator from ST to BEL in the startup default-color probe. It does not disable default-color probing, does not special-case urxvt, GNU screen, or $TERM, and does not change dialog handling.

  6. ssirois commented on Jun 20, 2026

    @ssirois

    As per contributing.md, I did not open a PR but you can inspect the patch that I have tested locally within the above described environment

  7. mehulparmariitr commented on Jul 26, 2026

    @mehulparmariitr

    Implementation update for the shared OSC 10/11 subsystem:

    The focus fix replaces sequential multi-second Crossterm waits with the existing batched probe under one shared 100 ms deadline, pauses/recreates the event source around that probe, and preserves previously cached colors when refresh times out.

    It does not change the startup deadline or solve a missing initial color cache over high-latency SSH. This issue therefore remains the relevant appearance/remote tradeoff when reviewing the bounded focus change.

  8. adaex commented on Aug 16, 2026

    @adaex

    Additional data point: intermittent total probe failure over VS Code Remote SSH (not just slow OSC 10/11)

    I'm hitting this on VS Code Remote SSH (Linux, codex-cli 0.147.0) and want to add evidence for a failure mode that's a bit different from the "OSC responses always arrive after 100ms" case in the original report.

    Symptom: the composer/UI background is intermittently dark — sometimes light, sometimes dark, across otherwise-identical launches in the same terminal.

    Instrumented both sides. I enabled log_dir to capture codex's own terminal startup probes completed line, and separately confirmed (via an external TIOCSTI pre-fill of OSC 10/11 replies before launch) whether a reply was sitting in the tty input queue. Aligned by timestamp:

    # codex side (codex-tui.log)
    05:03:12  duration_ms=99  cursor_position=false default_colors=false keyboard_enhancement_supported=None   <- DARK
    05:03:15  duration_ms=55  cursor_position=true  default_colors=true  keyboard_enhancement_supported=Some(true)
    05:03:21  duration_ms=59  cursor_position=true  default_colors=true  ...
    05:03:24  duration_ms=76  cursor_position=true  default_colors=true  ...
    05:03:27  duration_ms=86  cursor_position=true  default_colors=true  ...
    05:03:38  duration_ms=99  cursor_position=false default_colors=false keyboard_enhancement_supported=None   <- DARK
    

    Two observations that I think are new relative to the current thread:

    1. When it fails, all three probes fail together — cursor_position, default_colors, and keyboard_enhancement are simultaneously false and the read window burns the full ~99ms. Cursor position (ESC[6n) is answered by the local terminal and doesn't need an OSC round-trip, so a failure that also loses the cursor response points to the whole read window getting nothing, rather than only the OSC 10/11 reply being slow.

    2. Pre-injecting a complete OSC 10/11 reply into the tty does not reliably rescue it. At 05:03:12 a full 48-byte OSC 10/11 reply was confirmed present in the tty queue, yet codex still reported default_colors=false. This suggests the fd codex actually reads (it dups STDIN) can become decoupled from the terminal that answers queries — note stdout is not a TTY in this environment (VS Code shell integration wraps it), so STDIN and /dev/tty are not guaranteed to be the same endpoint.

    Rough failure rates (small sample, my machine, simulating the same 100ms-bounded probe):

    • plain VS Code integrated terminal over SSH: ~3/36 launches fail
    • inside tmux (tmux-256color): 6/6 fail, and they still fail with a 600ms timeout — consistent with tmux not forwarding OSC 10/11 by default.

    Why this matters for the fix direction: since the failure is intermittent and can survive a correct pre-injected reply, workarounds that race the probe (injecting replies, bumping the timeout) reduce the frequency but can't make it deterministic. In line with this issue's title, it would help to let users declare the background explicitly and skip the probe entirely — e.g. an env/config like CODEX_TUI_ASSUME_BG=light|dark|<hex> (or a tui.assume_background setting) that seeds default_bg() and bypasses startup color detection. That gives remote/multiplexer users a deterministic escape hatch without changing probe behavior for everyone else.

    Happy to share the raw logs or the probe-simulation script if useful.

  9. liby commented on Oct 22, 2026

    @liby

    Additional evidence for retrying after an initially failed palette probe: late color replies did not restore the composer background, and a real terminal can make its colors available only after a later UI action.

    With Codex CLI 0.163.0 on macOS, I ran Codex in a standalone Python PTY without Rex, SSH or tmux. The harness answers cursor, keyboard and device-attribute queries immediately and delays only OSC 10/11 replies. TERM=xterm-256color, COLORTERM=truecolor, NO_COLOR unset.

    OSC 10/11 reply delay Composer background Color queries after startup
    35 ms RGB(65, 67, 78) fill none
    1.04 s no fill none

    Each run sent one OSC 10 and one OSC 11 query. After the composer appeared, the harness sent focus out/in (Codex had enabled focus reporting), Ctrl+L and a resize. Neither run queried again. The delayed run still had no fill about 6.3 seconds after launch, well after both complete replies had arrived. Both processes exited normally. The portable script below was also rerun from a trusted directory with the same result.

    In Rex, a pane created from its CLI while its session is not displayed can initially have no OSC 10/11 replies. Once the app supplies colors, the running Codex remains unshaded; resuming the same Codex conversation in the same pane with a new process restores the fill. Increasing the timeout alone cannot guarantee recovery when colors become available only after a later UI action.

    The startup probe has a 250 ms deadline, and the palette cache records an unavailable result as already attempted. Retrying after a miss and repainting on success would cover this recovery case.

    Standalone PTY reproduction (Python 3, run from a trusted directory with Codex installed)

    The script launches two empty Codex TUIs, answers the color queries immediately or after one second, then sends focus out/in, Ctrl+L and a resize before exiting. It writes raw output and timestamped events to a new temporary directory. It uses your normal Codex configuration and login and sends no prompt; run it from a directory Codex already trusts, so the trust dialog does not replace the composer.

    import errno
    import fcntl
    import json
    import os
    from pathlib import Path
    import pty
    import re
    import select
    import signal
    import struct
    import termios
    import time
    import tempfile
    
    ROOT = Path(tempfile.mkdtemp(prefix="codex-pty-colors-"))
    print("Records:", ROOT, flush=True)
    COMMAND = ["codex", "--no-alt-screen", "--no-daemon"]
    QUERY = re.compile(rb"\x1b\](10|11);\?(?:\x07|\x1b\\)|\x1b\[6n|\x1b\[\?u|\x1b\[c|\x1b\[>c")
    
    
    def placeholder_background(data):
        position = data.rfind(b"Ask Codex to do anything")
        if position < 0:
            return {"placeholder_found": False}
        background = None
        for match in re.finditer(rb"\x1b\[([0-9;]*)m", data[:position]):
            values = [int(x or b"0") for x in match[1].split(b";")]
            i = 0
            while i < len(values):
                value = values[i]
                if value in (0, 49):
                    background = None
                elif value in (38, 48) and i + 1 < len(values):
                    if values[i + 1] == 2 and i + 4 < len(values):
                        if value == 48:
                            background = values[i + 2:i + 5]
                        i += 4
                    elif values[i + 1] == 5 and i + 2 < len(values):
                        if value == 48:
                            background = {"indexed": values[i + 2]}
                        i += 2
                elif 40 <= value <= 47 or 100 <= value <= 107:
                    background = {"ansi": value}
                i += 1
        return {"placeholder_found": True, "background": background, "byte_offset": position}
    
    
    def run_case(name, delay):
        events = []
        started = time.monotonic()
        pid, master = pty.fork()
        if pid == 0:
            environment = dict(os.environ)
            for key in ("REX_SESSION", "REX_BLOCK", "SSH_TTY", "SSH_CONNECTION", "TMUX", "STY"):
                environment.pop(key, None)
            environment.pop("NO_COLOR", None)
            environment.update(TERM="xterm-256color", COLORTERM="truecolor")
            os.execvpe(COMMAND[0], COMMAND, environment)
        fcntl.ioctl(master, termios.TIOCSWINSZ, struct.pack("HHHH", 40, 130, 0, 0))
        raw = bytearray()
        seen = set()
        queued = []
        first_color = None
        ready = None
        performed = set()
        status = None
    
        def record(kind, **values):
            events.append({"seconds": time.monotonic() - started, "kind": kind, **values})
    
        def send(value, kind):
            os.write(master, value)
            record(kind, bytes=value.decode("ascii"))
    
        try:
            while time.monotonic() - started < 45:
                now = time.monotonic()
                readable, _, _ = select.select([master], [], [], 0.03)
                if readable:
                    try:
                        data = os.read(master, 65536)
                    except OSError as error:
                        if error.errno == errno.EIO:
                            break
                        raise
                    if not data:
                        break
                    previous_size = len(raw)
                    raw.extend(data)
                    for match in QUERY.finditer(raw, max(0, previous_size - 32)):
                        if match.start() in seen:
                            continue
                        seen.add(match.start())
                        query = bytes(match[0])
                        record("query", bytes=query.decode("ascii"))
                        if match[1]:
                            first_color = first_color or time.monotonic()
                            color = b"efef/f0f0/ebeb" if match[1] == b"10" else b"2828/2a2a/3636"
                            response = b"\x1b]" + match[1] + b";rgb:" + color + b"\x1b\\"
                            queued.append((max(time.monotonic(), first_color + delay), response))
                        elif query == b"\x1b[6n":
                            send(b"\x1b[1;1R", "cursor_reply")
                        elif query == b"\x1b[?u":
                            send(b"\x1b[?0u", "keyboard_reply")
                        elif query == b"\x1b[c":
                            send(b"\x1b[?62;4c", "device_reply")
                        elif query == b"\x1b[>c":
                            send(b"\x1b[>1;0;0c", "secondary_device_reply")
                    if ready is None and b"Ask Codex to do anything" in raw:
                        ready = time.monotonic()
                        record("composer_ready", **placeholder_background(bytes(raw)))
                for due, response in list(queued):
                    if now >= due:
                        send(response, "color_reply")
                        queued.remove((due, response))
                if ready:
                    age = now - ready
                    for at, label, value in [(1, "focus_out", b"\x1b[O"), (2, "focus_in", b"\x1b[I"), (3, "redraw", b"\x0c"), (6, "exit_first", b"\x03"), (7, "exit_second", b"\x03"), (8, "exit_third", b"\x03")]:
                        if age >= at and label not in performed:
                            if label == "exit_first":
                                record("final_composer", **placeholder_background(bytes(raw)))
                            send(value, label)
                            performed.add(label)
                    if age >= 4 and "resize" not in performed:
                        fcntl.ioctl(master, termios.TIOCSWINSZ, struct.pack("HHHH", 40, 131, 0, 0))
                        os.kill(pid, signal.SIGWINCH)
                        record("resize")
                        performed.add("resize")
                    if age > 10:
                        break
                ended, status = os.waitpid(pid, os.WNOHANG)
                if ended:
                    record("exit", status=status)
                    break
        finally:
            try:
                ended, found_status = os.waitpid(pid, os.WNOHANG)
                if not ended:
                    os.kill(pid, signal.SIGTERM)
                    record("terminate_owned_test")
                    _, found_status = os.waitpid(pid, 0)
                status = found_status
            except ChildProcessError:
                pass
            os.close(master)
            (ROOT / (name + ".vt")).write_bytes(raw)
            result = {"case": name, "color_reply_delay_seconds": delay, "command": COMMAND, "simulated_environment": {"TERM": "xterm-256color", "COLORTERM": "truecolor", "NO_COLOR": None}, "pid": pid, "events": events, "composer": placeholder_background(bytes(raw)), "focus_reporting_enabled": b"\x1b[?1004h" in raw, "process_status": status, "raw_bytes": len(raw)}
            (ROOT / (name + ".json")).write_text(json.dumps(result, indent=2) + "\n")
            print(json.dumps({k: v for k, v in result.items() if k != "events"}), flush=True)
    
    
    for case, delay in [("pty-immediate", 0), ("pty-delayed", 1)]:
        run_case(case, delay)
  10. bc-openai commented on Oct 27, 2026

    @bc-openai
    Contributor

    Thanks for the report! A fix has been merged and should be included in 0.167.0.

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

    TUIbugremote

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions