Commit Graph
13289 Commits
Author SHA1 Message Date
Dylan Hurd b6065c6128 Stabilize the TUI worktree test during fork startup (#65109)
## Why

The fork can acknowledge its working directory before startup finishes.
MCP startup can also make the composer busy between the test seeing
`Ready` and pressing Enter, causing `/cd` to be rejected.

## What changed

Wait for the fork's own `Ready` status and a complete terminal update
showing the pasted `/cd` command before submitting it. Retry only when
a new busy rejection appears and the fork is ready again. Require a
complete terminal update showing the directory change before continuing.

GitOrigin-RevId: eceb98b3376977dcc60963e3733bf45559b88ae0
2026-12-01 23:38:53 +00:00
Benjamin Carlsson 7b680b178a Keep TUI background work tied to its originating app server (#65108)
## Why

App servers can reuse the same request IDs. Tracking dynamic tool calls by
request ID alone lets one server's cleanup affect another server's call.
Background title and recap events also need to reach their originating server
when the TUI is displaying a different session.

## What changed

- Track dynamic tool calls by backend and request ID, and match completions
  to the specific call. Send replies through the original reply handle in the
  background and give pending writes time to finish on shutdown.
- Route background task registrations and title and recap events by backend.
  Check ownership before registering temporary threads or forwarding their
  notifications, and use the original connection for temporary-thread cleanup.

## Testing

Regression coverage checks that closing a side thread preserves another
backend's tool call with the same request ID, that a disconnected backend
cannot register a task thread, and that a title helper cannot replace a
temporary thread owned by another backend.

GitOrigin-RevId: 0878efba94f317c814ee131403f0c6e793dfc2c0
2026-12-01 23:22:59 +00:00
Felipe Coury fbb04fca5f Share composer copy handling across keyboard and mouse input (#65107)
## What changed

- Route keyboard and mouse copies of composer selections through the same
  plain-text copy helper.
- Check composer visibility separately when completing clipboard work
  and canceling primary selection. Use the overlay input check when
  deciding whether to end a composer drag.
- Convert external transcript links to view actions through the shared
  `ReaderLink` conversion.

GitOrigin-RevId: 7285acfe6d8911da806adbba7da8b79393389b08
2026-12-01 23:13:10 +00:00
iceweasel-oai 80d0a67185 Share runtime registration across app-server startup clients (#65106)
## Why

Statsig starts before the model catalog. When runtime agent instances are
enabled, separate auth managers can cause Statsig and model discovery to
register the same app-server runtime twice.

## What changed

Pass a shared runtime auth slot to Statsig and model discovery in both
standalone and in-process app-server startup so they use the same runtime
registration.

## Testing

Extend the CLI startup integration test to require exactly one runtime
registration and verify that both Statsig evaluations and model discovery
send `AgentAssertion` authorization headers.

GitOrigin-RevId: 132521b685c5c7c617e7067c648de65b9a4287b2
2026-12-01 23:12:29 +00:00
Tom 47e1cf4fe4 Link startup prewarm to the first turn's OpenTelemetry trace (#65105)
## Why

Startup prewarm runs in the session startup trace, while the first turn
can run in a separate trace. The first-turn trace needs a way to show
which prewarm task it resolved, including when the wait times out.

## What changed

Record `startup_prewarm.resolve` at info level under the first-turn span.
Capture the startup prewarm span context when scheduling the task and
attach it as an OpenTelemetry span link during resolution. If the prewarm
span is filtered out, omit the link.

## Testing

Check exported spans for first-turn parentage, link behavior with the
prewarm span enabled or filtered out, and no second resolution on a
later turn. Add a regression test for retaining the link on timeout.

GitOrigin-RevId: ef4a19be64ecf145b17527081960e50adca3b92e
2026-12-01 23:11:46 +00:00
Eric Traut 75c48af16f Support --search with the shared background server (#65103)
## Why

Launching Codex with `--search` forced the TUI into embedded mode, even when the shared background server was available.

## What changed

Treat `--search` as a per-thread request for live web search. Check daemon eligibility before applying the flag, and restore the launch setting when reconnecting to an unloaded conversation or reopening an unloaded saved side chat.

## Testing

Cover daemon startup with `--search` and verify that a conversation retains its history and search behavior across a daemon restart. Check that worktree launches honor the flag per invocation and that reattaching to an already loaded side chat leaves its search settings intact.

GitOrigin-RevId: 9d15ec3d103383d80442e07845442341f6da6727
2026-12-01 23:03:41 +00:00
Ben Romano 1aeab9e3d5 Overlap remote MCP config reads with capability discovery (#65101)
## Why

MCP runtime refreshes waited for capability discovery and host MCP
configuration to finish before requesting HTTP MCP servers from the selected
remote environment. That serialized two reads that can be in flight together.

## What changed

Start the remote environment config read alongside host MCP configuration,
including executor capability discovery. Start the read's 10-second timeout
after host configuration is ready so a serial executor can queue the read
behind discovery without consuming its timeout. Merge the results with host
server precedence and requirements still enforced.

## Testing

Add V1 and V2 integration cases that hold both executor replies until both
requests arrive, then verify host precedence and requirements. Add a
paused-clock test that covers a queued read and confirms a stalled read
times out 10 seconds after discovery completes.

GitOrigin-RevId: d974f0f575559bfe6b756de11aa460399fdabf25
2026-12-01 22:57:35 +00:00
Eric Traut 6cc6cee6c5 Make local codex exec interruptible when output blocks (#65099)
## Why

On Unix, a caller that stops draining an output pipe can stall
`codex exec` in a write, preventing it from interrupting the turn
and cleaning up running commands.

## What changed

Move human-readable output, JSON events, and `--output-last-message`
writes to a dedicated thread for local Unix runs. Handle `SIGTERM`
alongside `SIGINT`, and bound the time spent waiting for output after
an interrupt. Allow local turn cancellation before the server marks
the turn active, and exit with status 1 if output is cut short.

## Testing

Add regression tests that send `SIGTERM` with JSON stdout or human
stderr blocked and check that the running command and its child exit.
Also cover interruption while writing the last message to a blocked pipe.

GitOrigin-RevId: fd9a3621d340cefc9af589c605596d2b178aaa9f
2026-12-01 22:49:30 +00:00
Eric Traut 997204b7f9 Make /diff worktree-wide from subdirectories (#65094)
## Why

Running `/diff` from a subdirectory can omit untracked files elsewhere in
the worktree. With `diff.relative` enabled, it can also omit unstaged
changes to tracked files outside that subdirectory.

## What changed

Run Git from the discovered worktree root while retaining the session
directory for permission resolution. Pin the Git directory and worktree so
relative Git environment settings keep resolving to the same repository.

Decode Git's quoted untracked paths before generating patches. If a path
cannot be represented as UTF-8, warn that the diff is incomplete and
continue with the remaining files.

## Testing

Cover matching output from the root and a subdirectory with
`diff.relative` enabled and with an explicit Git directory and worktree.
Cover quoted UTF-8 filenames and warnings for invalid UTF-8 paths.

GitOrigin-RevId: 7dd604f543976f4ba88ae0facf9e9b573baa9c0f
2026-12-01 21:56:27 +00:00
Eric Traut a183b449e6 Use model-specific speeds for /model --speed (#65092)
## Why

Speed completion always suggested `flex`, even for models that did
not advertise it, and omitted other available tiers such as `priority`.

## What changed

Offer `standard` and the enabled service tiers advertised for the model
named in `/model`. When the command omits the model, use the current
model. Use the same choices in unavailable-speed errors.

Allow explicit use of unadvertised `flex` in `/model` and quick dials
when using the OpenAI provider with an API key. Keep completion limited
to `standard` and advertised tiers.

## Testing

Add coverage for model-specific completion and validation, including
clearing stale suggestions when the model catalog is cleared. Cover
saving and recalling a quick dial with unadvertised Flex using an
OpenAI API key and rejecting that speed on another provider.

GitOrigin-RevId: b5139d03561842eaf00511f018f6e626cf695bc5
2026-12-01 21:39:35 +00:00
Eric Traut a0676149ff Show custom provider rate limits in /status (#65091)
## Why

Custom providers can report quota during a turn, but `/status` only cached
quota from ChatGPT account usage. Users could see a quota warning while
`/status` showed no corresponding limits.

## What changed

Use provider turn snapshots and rolling updates from custom providers using
a saved API key to populate `/status`. Merge partial updates by limit ID,
preserving omitted windows with their original timestamps and carrying
forward an unexpired reset time when the window duration matches. ChatGPT
account usage remains authoritative for its status display.

## Testing

Extend TUI tests to cover weekly and five-hour limits after partial
updates, immediate status rendering for custom providers using a saved API
key, and preservation of ChatGPT account limits after a streamed update.

GitOrigin-RevId: acaed9880c020885cea97307d66d78f79c5b4c65
2026-12-01 21:38:53 +00:00
Eric Traut 6801507507 Preserve --add-dir when starting local TUI threads (#65087)
## Why

Selecting a permission profile for a new local thread could drop directories
explicitly supplied with `--add-dir`. Starting a thread in a different
directory could also lose those additions.

## What changed

Carry explicit additions into local thread starts. When a permission profile
is selected, send the working directory and the explicit additions as
runtime workspace roots. Require the app server to confirm each added
directory before accepting the thread. Decode local workspace roots as
native paths so tabs and newlines in directory names survive.

## Testing

Extend tests for startup, managed worktree creation, and permission-profile
selection. Cover an added directory with a tab in its name on Unix and the
error for an unconfirmed directory.

GitOrigin-RevId: 97beb528aa396b97d6d0ad664fde8abe3b9e2bbf
2026-12-01 21:18:55 +00:00
Eric Traut 1e832a92c2 Fix granular approval defaults at projectless TUI startup (#65086)
## Why

An `approval_policy` in the client's config could suppress the granular
default when starting a projectless session with server-owned defaults.

## What changed

Make the granular default available at startup so the launch code can
apply it when the invocation leaves the policy unset and the server
allows it.

## Testing

Extend the server-defaults startup test to set the client's policy to
`never` and verify that `thread/start` still requests granular approval.

GitOrigin-RevId: 770aa978e2372e1e30fe778b670ea25f9c3c1cd0
2026-12-01 21:01:05 +00:00
Eric Traut be972c162c Preserve the thread's selected workspace when the TUI starts a turn (#65084)
## Why

Another client can change a thread's workspace after startup. When the
TUI sends its local working directory with the next prompt, it can reset
the thread's selected environments before the TUI receives the update.

## What changed

Omit `cwd` and `runtimeWorkspaceRoots` from TUI `turn/start` requests
for both regular prompts and misalignment continuations so the turn
uses the thread's current workspace.

## Testing

Add a regression test that changes the thread's workspace before the
TUI receives the update and checks that the first prompt sent to the
model includes the newly selected working directory.

GitOrigin-RevId: b5cc23bce787f91058ede6aa7ee825e0e7a9518c
2026-12-01 20:47:55 +00:00
Felipe Coury 10cab5fad3 Keep the TUI responsive during WSL image paste (#65083)
## Why

A slow or stalled Windows clipboard helper can block the TUI while it
reads a pasted image.

## What changed

Read and stage clipboard images on a background worker in WSL. Give each
paste a five-second deadline and stop and reap the PowerShell helper if
the read is cancelled or times out.

Keep the draft editable while the paste is pending. Insert the image at
the original cursor or selection, preserve later edits outside that
range, and cancel the paste if an edit overlaps the range or the draft
is no longer current. Block submission while the paste is pending and
show a reminder to review the draft before sending.

## Testing

Add regression tests for insertion after continued typing, submission
blocking, stale completions, temporary file cleanup, and timeouts.
Cover helper cleanup after cancellation or timeout and rejection of
oversized clipboard output.

GitOrigin-RevId: d7b1d520b242244f9749f02e9d62a57d17821340
2026-12-01 20:45:18 +00:00
Felipe Coury eb79af452e Load TUI image previews in the background and downscale large JPEGs (#65079)
## Why

Composer thumbnails and transcript tool previews read and decoded files
during rendering. A JPEG whose decoded pixels exceeded the 32 MiB
allocation budget could lose its preview even when the encoded file fit
within the file size limit.

## What changed

- Load visible composer thumbnails and transcript previews on background
  workers and request a redraw when the result is ready. Reuse prepared
  tool previews when the viewport changes size.
- Share the sidebar's scaled JPEG fallback with composer and transcript
  previews. Preserve the oriented source aspect ratio and enforce the
  encoded file size limit separately from the decode budget.
- Check that the owning thread has a local workspace before reading an
  inspected image. Generated artifacts can still load from the daemon host.

## Testing

Cover large JPEG previews in the composer and transcript, thumbnail
refresh after an attachment is replaced, text fallback for oversized
PNGs, and an inspected path shared by local and remote workspaces.

GitOrigin-RevId: f2c8948a9abaa2527932423224b6ebeda3e122ae
2026-12-01 20:29:37 +00:00
Aismit 624fdeecee Run patch hooks for intercepted apply_patch commands (#65077)
## Why

Codex can intercept an `apply_patch` heredoc passed to `exec_command`
and apply the patch directly. That path ran shell hooks but bypassed
`apply_patch` hooks, so patch-specific rules could miss the same edit
when it was submitted through the shell tool.

## What changed

- Run `apply_patch` `PreToolUse` after shell hooks and before file
  verification. Hooks can block or rewrite the patch, and the final
  patch is checked against the selected environment's permissions.
- Report the executed patch through `apply_patch` `PostToolUse`. Link
  the patch hook events to the outer shell call with
  `parent_tool_use_id` and provide working-directory and filesystem
  metadata for hooks that inspect patch targets.
- Apply the same block and rewrite rules in recorded Guardian reviews.
  Mark those hook requests with `review_only` and review the resulting
  patch without executing it or publishing hook-provided context.

## Testing

Add coverage for hook blocks and rewrites, effective working directories,
environment permissions, and cancellation before and after a patch write.
Cover recorded reviews of rewritten patches and reviews stopped by a hook.

GitOrigin-RevId: 2115f26261a20d4a512669bc9e277a764b8f42f4
2026-12-01 20:18:13 +00:00
jif b9cbe0d977 Require V3 workers to report results with send_message (#65076)
## Why

A V3 worker can resume its conversation after stopping. Reporting results
explicitly lets the worker decide when to send a result to its parent,
independently of when a turn ends.

## What changed

Stop forwarding V3 workers' final answers as automatic success results.
Continue forwarding failures and preserve automatic results for V2. Update
V3 prompts and tool descriptions to tell workers to send their result and
call `stop_agent` to release their slot.

Keep `send_message` available in the V3 native tool set even when
`disable_direct_message` is set. When native tools are enabled, require both
`send_message` and `stop_agent` to survive tool policy filtering for V3
workers, including on resume.

Track accepted worker-to-parent reports until they are written to the
parent's rollout. Preserve unread reports for the next turn if a turn
triggered by a report is interrupted.

## Testing

Extend the idle eviction scenario to verify that a resumed V3 worker's
explicit report reaches the parent's rollout exactly once after turn
admission is deferred and the subsequent wake is interrupted.

GitOrigin-RevId: 9bf95a4358bca9778797c7064f9eaf20c8679a81
2026-12-01 20:16:42 +00:00
felixxia-oai 84b853b217 Allow larger text entries in Guardian context budgets (#65071)
## Why

Guardian context delivery can split a text entry across multiple bounded
parts. Capping each entry at the size of one part prevented configurations
from allocating more room to a single entry, even when the section budget
could accommodate it.

## What changed

Allow `max_section_entry_tokens` to exceed the per-part delivery limit
when it fits within `min_total_section_tokens`.

## Testing

Exercise elastic budgeting with a large transcript tool entry and a file
image. Verify that the delivered text parts respect the part limit and
reassemble into the original text, that the image is preserved, and that
the budget estimate covers the delivered message.

GitOrigin-RevId: a303180bc90dce1a21fc91cd12e2eded90eaad8e
2026-12-01 19:59:49 +00:00
karlr-openai 808630f1b3 Allow OTLP HTTP exports to approved destinations (#65070)
## Why

Destination restrictions blocked OTLP exports even when the HTTP collector
was allowed because the exporter applied the same guard as SDK transports
that cannot check request destinations.

## What changed

Use the managed HTTP client to enforce the current destination policy on
each OTLP request and redirect for logs, traces, and metrics. Bind the
client to the account active when the exporter is created so stale
exporters cannot send after an account switch. Keep the SDK guard for
gRPC and other transports that cannot enforce the policy per request.

## Testing

Add a local TLS integration test that verifies delivery of all three
signals to an approved collector and checks that unready policy, stale
exporters, denied destinations and redirects, and raw gRPC are blocked.

GitOrigin-RevId: 400c9cb9870cc1a3f47f4447348ce50f4b934b00
2026-12-01 19:58:09 +00:00
Dmitriy Kovalenko 18e2471c33 Reduce repeated work in filesystem sandbox path checks (#65069)
## Why

Checking multiple paths against the same sandbox policy repeats root
resolution and protected metadata path construction. URI containment
checks also allocate segment lists and check for escaped separators
even when paths contain no escapes.

## What changed

- Lazily cache resolved policy roots, lexical depths, protected metadata
  paths, and the full-disk write decision in the path matcher. Reuse the
  matcher across checks against the same prepared local policy.
- Compare URI path segments directly from iterators and skip decoding
  for plain POSIX segment comparisons. Keep checking the full path for
  encoded separators, including the suffix beyond a matched prefix.

## Testing

Exercise one prepared matcher against protected metadata and an ordinary
writable file. Extend URI prefix tests to cover a candidate shorter than
its base and paths with repeated or trailing separators.

GitOrigin-RevId: 34425d018516e24c36e1c87ea51bfbd344137cd8
2026-12-01 19:57:25 +00:00
Tom 848d7ffbe3 Trace per-step preparation for each tool contributor (#65067)
Add an info-level `tool_contributor.prepare_for_step` span so traces
show how long each contributor spends preparing before tools are built.
Label the span with the contributor's `trace_name()`, which defaults to
its concrete Rust type name, and skip recording the preparation inputs.

GitOrigin-RevId: cc644deb2d7c1a00e8eea68698516ad1c2e102da
2026-12-01 19:34:56 +00:00
vishnu-oai 4c75131c9c Validate config server policy before replacing login credentials (#65066)
## Why

An explicit `codex login` can reuse a saved config server grant, leaving
users without a way to switch accounts through that command. Saving a new
grant before validating its managed configuration can also displace a
working session if the policy fetch or validation fails.

## What changed

- Start a fresh config server sign-in for explicit browser and device-code
  logins, even when a grant is already saved.
- Hold the new grant in memory while fetching and validating its managed
  configuration. Save the grant and then update the policy cache after
  validation succeeds.
- Recheck config server and proxy settings and reload local network rules
  before fetching policy. Reject logout while a config server sign-in owns
  the login lock, including during the first sign-in.

## Testing

Cover successful grant replacement and preservation of the saved grant
when authorization, policy fetch, or policy validation fails. Verify that
network restrictions can block the policy fetch and that logout detects
an in-progress first sign-in.

GitOrigin-RevId: 427a70d556f92fd96c43f6e8737371aa3651e70c
2026-12-01 19:33:48 +00:00
Benjamin Carlsson 854e723882 Add --cloud to launch interactive Codex sessions on Cloud (#65063)
## What changed

- Select the Codex Cloud backend at startup with `codex --cloud`,
  `codex agents --cloud`, or `codex resume --cloud`.
- Use `--env <ENV_ID>` to select a saved Cloud environment for new
  threads. Resume by picker, most recent session, ID, or name using the
  thread's saved environment and model.
- Reject local execution overrides and managed execution requirements
  that Cloud cannot enforce. Recheck managed requirements for the
  ChatGPT workspace selected when connecting.

## Testing

Cover initial prompt delivery, resume by ID and name, and rejection of
unsupported settings, including managed execution requirements from a
workspace selected after startup configuration was loaded.

GitOrigin-RevId: 6144decb9679f903607a586466cff37e402ab4a4
2026-12-01 19:17:41 +00:00
Tom 78f1e86b44 Trace per-server MCP startup waits during binding capture (#65062)
## Why

The aggregate `mcp.binding.startup_wait` span measures how long binding
capture waits for MCP startup. It gives no breakdown of which servers
account for that time or how their waits end.

## What changed

Add an INFO-level `mcp.binding.server_startup_wait` child span for each
server registration. Each span measures that server's wait independently
and records its name and outcome. Outcomes distinguish readiness,
startup that already completed, a cached catalog, expiration of the
optional startup grace period, startup failure or cancellation, and
interruption when binding capture is dropped.

## Testing

Add trace export tests that use the production filter and check parentage,
overlapping waits, and outcome reporting. The tests also check that
environment identifiers and startup error details stay out of span
attributes.

GitOrigin-RevId: e5ebc7d92a511271f2004ab34fa3a0be6a4e926d
2026-12-01 19:17:01 +00:00
jif 9f02599a9a Add stop_agent for multi-agent V3 (#65061)
## Why

When a worker's current turn is no longer needed, the caller needs to
know when that turn has released its execution slot. Previously,
`interrupt_agent` returned without waiting for the slot to be released.

## What changed

Replace `interrupt_agent` with `stop_agent` in V3. When stopping a loaded
worker, the tool waits for the interrupted turn to release its slot.
A message can resume the worker, and queued input can reclaim the slot
immediately.

Workers can target their own path to stop after the current tool batch
if no new input is waiting and no send failed.

## Testing

Extend the V3 mailbox test to cover self-stop freeing the only worker
slot, a message waking another worker, and the parent stopping that
worker and observing its interrupted status.

GitOrigin-RevId: b066d10e4221fabe49b07ed126752e2e88e9517b
2026-12-01 19:16:25 +00:00
Tom 278dd6cafd Trace each MCP tool-list page and its retries (#65060)
## Why

A tool-list page can take multiple attempts. Tracing the whole page
keeps retry warnings tied to the page that triggered them.

## What changed

Wrap each `tools/list` page request in an `mcp.tools.list_page` span
that covers the retry loop. Record whether the request has a cursor
via `mcp.has_cursor`.

## Testing

Extend the trace propagation test in both MCP protocol modes. Return
HTTP 503 on the first request for the second page and verify that the
requests carry the page span context, the cursor flag reflects the
request, and the retry warning appears on the page span.

GitOrigin-RevId: e4b695731d037f71c15660a826c9f2e59d02e55f
2026-12-01 19:13:34 +00:00
Krish Chainani 71f99fca5d Overlap Noise handshakes with remote environment provisioning (#65057)
## Why

Deferred remote environments previously waited for provisioning to succeed
before looking up the executor and starting the Noise handshake. Starting
that work while provisioning is pending can shorten the wait for a usable
exec-server session.

## What changed

When a deferred Noise environment is selected, start executor lookup and
the handshake with a bounded retry window. After provisioning succeeds,
refresh the connection bundle and reuse the early connection if it is
still live and matches the current environment, executor registration,
and public key. Otherwise, establish a fresh connection. Exec-server
session initialization still waits for provisioning success, and a
provisioning failure cancels the early connection.

## Testing

Cover early connection reuse, fallback when the executor changes or the
socket closes, and cancellation on provisioning failure. Verify that
malformed handshake replies surface as protocol errors and that connection
resets remain retryable.

GitOrigin-RevId: 658135338672f0c02c33d9203299b05ba15d1fc2
2026-12-01 18:56:52 +00:00
viyatb-oai 312c85a399 Allow hosts to bind JWT bearer grants to proxy routes (#65054)
## What changed

Add `NetworkProxyState::bind_jwt_bearer_grant` so trusted host code
can attach a grant for a specific environment, host, and exact path.
Binding requires an enabled proxy with credential brokering and TLS
interception, plus an existing rule that strips guest authorization
headers. Replacing the policy requires a fresh binding.

## Testing

Add TLS forwarding tests with separate issuer and resource origins.
Cover token refresh and reuse, alias scoping, and grant replacement.
Verify that revocation or policy reload during the upstream TLS
handshake prevents the request from reaching the resource.

GitOrigin-RevId: 5ccf058d04980ef79aca1cbae91ff558b9d71be1
2026-12-01 18:41:32 +00:00
Felipe Coury 4bc6a0ea93 Render web URLs in TUI file citations as hyperlinks (#65052)
## Why

The TUI treated URLs in file citations as local paths. This could prepend
the working directory and escape parts of the URL needed to reach the
cited resource.

## What changed

Render HTTP and HTTPS `codex-file-citation` paths as web links, preserving
percent escapes, query strings, and fragments in the displayed URL and
hyperlink destination.

## Testing

Regression tests compare file citations with equivalent Markdown links
with and without a working directory. A snapshot covers the rendered
text and hyperlink metadata for a spreadsheet URL.

GitOrigin-RevId: 2f3213192fced0e92ae87062d086a9015113b862
2026-12-01 18:23:08 +00:00
Eric Traut b6a53810db Add failure stages and OS error kinds to daemon startup metrics (#65049)
## Why

The TUI's daemon auto-start metric reports a failure reason, but broad
reasons such as `other` leave it unclear which startup step failed.

## What changed

Add `failure_stage` and `os_error_kind` to failed `codex.daemon.start`
attempts. For example, a missing executable reports `spawn` at
`process_spawn` with `not_found`. The metric uses a fixed set of error
categories and keeps raw OS codes and diagnostic text local.

Report Windows detached-launch restrictions as
`windows_detach_restricted`, matching the reason recorded when the TUI
falls back to an embedded app server.

## Testing

Cover missing executables, Windows launch restrictions, and preservation
of the underlying I/O error. An in-memory metrics test checks that a failed
attempt increments the counter once and maps an unknown OS code to `other`.

GitOrigin-RevId: c5976517e1178fb8d65257362a893ad6254a2ddd
2026-12-01 18:08:05 +00:00
Eric Traut b6087365cd Repair app-server daemon packages with update --from-cli (#65046)
## Why

A daemon with a dangling package selection or a missing executable can
fail to start, and leftover logs can make an absent installation look
like an existing one.

## What changed

- Let `codex app-server daemon update --from-cli` install or repair and
  pin the daemon from a complete CLI package. Point missing-executable
  errors to that command. Repair checks that the daemon and updater are
  stopped and that the package selection has stayed unchanged.
- Let `codex app-server daemon start` bootstrap a missing installation
  even when old daemon logs remain. Use legacy logs to infer a stopped
  standalone installation only when its package selection still exists
  and dedicated daemon logs are absent.
- Allow repair to replace a dangling Windows junction whose target is
  directly under the daemon's releases directory.

## Testing

Extend coverage for startup with leftover logs, package repair after
losing the selection or executable, repair blocked by a starting
daemon or updater, and replacement of a dangling Windows junction.

GitOrigin-RevId: 679266cc22b7ff7a34bbd41c2bf0659d3068eb75
2026-12-01 17:56:54 +00:00
Eric Traut 09984ca85d Fix app-server daemon startup with BusyBox ps (#65043)
## Why

BusyBox `ps` can reject the arguments Codex uses to read a process start
time. That failure prevents the managed app-server daemon and updater
from starting even when Linux can identify both processes through `/proc`.

## What changed

On Linux, allow startup to proceed when the `ps` lookup fails and
`/proc` identifies a live process. Store that identity in the PID record
with an empty legacy start timestamp.

## Testing

Add a Linux CLI regression test that substitutes a failing `ps`, checks
both PID records for a process identity and an empty legacy timestamp,
and verifies that `daemon version` reports the daemon running and
`daemon stop` stops it.

GitOrigin-RevId: fc82e0e32a62ffbb1dc1683403757f3ab109000a
2026-12-01 17:52:27 +00:00
Eric Traut 51f546979e Keep Sixel pets visible during composer sparkle redraws (#65040)
## Why

When composer stars fade, the terminal can clear to the end of the row and erase part of the Sixel pet image.

## What changed

Leave a strip of default background at the right edge of the composer where the Sixel pet is drawn, so star redraws can update the composer without clearing through the image.

## Testing

Add a terminal regression test that uses text markers to stand in for Sixel pixels. It checks that the markers survive while the stars are visible and after they disappear, and that disabling the pet restores the composer background in that area.

GitOrigin-RevId: 0f55d1e5594fa503edeb13d2d262e3c73bb0366b
2026-12-01 17:37:47 +00:00
Eric Traut e14750e0b9 Preserve the exit summary when Ctrl+C is pressed again on Windows (#65038)
## Why

Once the TUI restores the terminal, another Ctrl+C becomes a Windows
console event and can terminate Codex before it prints the exit summary,
including the resume hint when available. The npm launcher can also
force-terminate the child by forwarding a Ctrl+C that Windows already
delivered to it.

## What changed

Register a Windows Ctrl+C listener before restoring the terminal and keep
it alive until the CLI or standalone TUI finishes printing the exit
summary. Skip forwarding `SIGINT` from the npm launcher on Windows.

## Testing

Add a Windows regression test that simulates `SIGINT` in the npm launcher
and checks that the child can finish and report its own exit code.

GitOrigin-RevId: cd73a4a2ecc22812bc301787e67c349f7720a93b
2026-12-01 17:07:18 +00:00
jif 3da5a55b5b Abort pending terminal writes when their turn is cancelled (#65036)
## Why

A `write_stdin` call can resume after its turn is cancelled if approval was still pending. It can then send stale input to a running terminal or consume the final output of a remote process that has already exited.

## What changed

After approval, check both tool-call and turn cancellation before a non-empty `write_stdin` request can send input or drain output. Report cancelled writes as aborted and surface the abort as an error to Code Mode cells that are still running. Empty polls can still collect buffered output.

## Testing

Regression tests cover cancellation during stdin approval for direct and Code Mode calls, reuse of the same terminal on the next turn, and retrieval of final remote output after a cancelled write.

GitOrigin-RevId: 735bdd7ed0e892467647039ba72eb9a4d177a560
2026-12-01 16:54:12 +00:00
Eric Traut 214b9007dd Restore token usage after compaction on paginated thread resume (#65035)
## Why

A compaction checkpoint can leave the turn's `TurnStarted` event outside
the replay window. When `thread/resume` excludes turns, the app server
can then miss the turn ID and omit the saved token usage update.

## What changed

Fall back to the latest saved `TurnContext` in the active turn when
that turn starts at a compaction checkpoint. Use its turn ID to replay
the saved `thread/tokenUsage/updated` notification.

## Testing

Extend cold resume tests to check the turn ID, total and last token
counts, and context window after compaction. Cover a rollback that
leaves the usage owner unknown and verify that replay is skipped.

GitOrigin-RevId: 4ea4f5e7a561fbba00fbe6b063f632a23193bc5a
2026-12-01 16:53:34 +00:00
Benjamin Carlsson 949cdb56ef Rank TUI slash commands by recent usage (#65034)
## Why

The slash menu uses a fixed order within each match tier, so frequently used commands can stay buried among equally good matches.

## What changed

Rank commands within each match tier by frequency over the last 50 dispatches, keeping the existing order for ties. Count `/quit` toward `/exit` and `/btw` toward `/side`. Store slash command usage locally in `slash_command_usage.json`, separate from `$` picker history, when history persistence is enabled.

If `/exit`, `/quit`, or `/logout` ranks first, require its full name or explicit menu navigation before Enter can run it.

## Testing

Cover ranking after queued and disconnected dispatches, exact-match priority, persistence after widget handoff, and explicit selection of shutdown commands.

GitOrigin-RevId: 152f2b642dcac1ece9c3347eb4541d03fc3a425c
2026-12-01 16:52:56 +00:00
Benjamin Carlsson 5c865592f4 Remember the TUI's Cloud environment choice per project (#65033)
## Why

Selecting a saved Cloud environment for a draft did not set a default
for future conversations in the same project.

## What changed

- Save the environment selected for a Cloud draft in the local user
  configuration under `tui.default_cloud_environments`, keyed by project
  and local user identity. Selecting Default clears the preference.
- Reuse the preference at startup, when creating a new Cloud conversation,
  and when switching to Cloud. Use the normal Cloud environment selection
  when the saved environment is absent from the catalog or the catalog
  cannot be loaded.
- Use the v2 environment catalog, filter for eligible saved environments,
  and deduplicate entries across personal and workspace results.

## Testing

Cover preference persistence and clearing, project scoping, reuse after a
config reload, fallback when the catalog is unavailable, and catalog
pagination, filtering, and deduplication.

GitOrigin-RevId: bc4f66842c5c83dc75c5b10840fd596feedd44df
2026-12-01 16:51:26 +00:00
Felipe Coury dcafb4c96f Honor the session directory when resuming after /cd (#65030)
## Why

Changing directories with `/cd` could force in-app resume to use the current
directory even when the saved preference was to use the session's directory.

## What changed

Use the `/cd` directory for the remembered Current choice. Explicit CLI and
remote directory overrides still select Current. If reloading configuration
fails, reuse the existing configuration only when it already belongs to the
resume directory.

## Testing

Update the in-app resume and agents overview cold-resume tests to cover using
the session directory after `/cd`.

GitOrigin-RevId: d87bc2ba96f7ca10d6fd0d5ec0414712d44238e6
2026-12-01 16:41:22 +00:00
malsamiri-oai 791cf84282 Accept LF and CRLF checksums for SQLite migrations (#65029)
## Why

SQLx hashes migration SQL byte for byte. A database migrated by a build
with CRLF SQL can fail to open in a build with LF SQL, even when the
migration statements are identical.

## What changed

On a checksum mismatch, retry validation using the stored checksum for
each migration whose SQL matches with either line ending. Preserve
stored checksums and continue to reject unrelated mismatches and failed
migrations.

Repair state databases that recorded the recency migration as version
`38` by moving its record to `39` for either line ending. Apply the
actual version `38` migration in the same transaction.

## Testing

Cover upgrades and reopening with an active writer, legacy recency
repair with either line ending, and rejection of wrong-version checksums
and dirty migration records.

GitOrigin-RevId: e8d481811a5150379777340eb355168ee60c41d7
2026-12-01 16:40:37 +00:00
felixxia-oai 8ea32990bc Add message-count batching to the Guardian v3 housekeeper (#65028)
## What changed

Set `batch_limit = { mode = "messages", limit = 9 }` in the housekeeper
configuration to route up to nine new evidence records per batch. Each tool
call and each tool result counts separately. In this mode, batches can exceed
the default 100,000 estimated tokens while still fitting within the routing
model's input limit.

## Testing

Add a housekeeping test that routes nine large records in the first batch
and defers the tenth to the next batch.

GitOrigin-RevId: 99fdfc71f432007958c793a46b251f2e32a3e8ba
2026-12-01 16:39:54 +00:00
felixxia-oai 1b3eee5af3 Make Guardian V3 housekeeper batch size configurable (#65027)
## Why

The housekeeper used the model's tool-output truncation limit to size
routing batches, tying how much evidence it could route at once to a
setting intended for tool output.

## What changed

Add `guardianv3.housekeeper.batch_limit` to cap the estimated tokens in
the serialized channel catalog and new evidence. It defaults to 100,000
estimated tokens. The housekeeper packs whole evidence records into each
batch and splits batches further as needed to fit the model's context
window.

```toml
[guardianv3.housekeeper]
batch_limit = { mode = "tokens", limit = 50000 }
```

## Testing

Cover parsing a positive limit and rejecting zero. The routing tests
check that the default groups eight 44 KiB evidence records into one
batch and routes the ninth in a separate batch.

GitOrigin-RevId: 2480afb8b64ed042fa41d75513aea8186e2a578e
2026-12-01 16:38:27 +00:00
jif 18cf9ef6e7 Let V3 workers stop after their tool calls finish (#65025)
## Why

A worker can send a message and ask to stop in the same response. It
needs to see any send failure before going idle so it can respond to
the error.

## What changed

When a V3 worker targets itself with `interrupt_agent`, finish the
current tool batch and skip the automatic model follow-up if no
`send_message` call in that batch failed. Pending input can still
trigger another model request. Scope the stop to the sampling attempt
so it cannot carry over to a retry.

## Testing

Extend the mailbox integration test to cover a truncated response, a
send failure alongside a self-stop, and a subsequent self-stop that
runs the `SubagentStop` hook and frees the worker slot.

GitOrigin-RevId: 62e377026d32ffc59d1ea5b88030ce9148d414b4
2026-12-01 16:23:27 +00:00
Felipe Coury eb1c5108a3 Reject oversized remote sidebar file previews before reading (#65022)
## Why

A remote preview can exceed the WebSocket client's 128 MiB message limit
once the file is base64-encoded and wrapped in a JSON-RPC response.

## What changed

Check the file size with `fs/getMetadata` before calling `fs/readFile` for
remote previews. Allow for base64 expansion and reserve room for the
JSON-RPC envelope. If the reported size exceeds that budget, show a
preview error with the file's size.

Continue with the read if the server lacks `fs/getMetadata` or omits
`sizeBytes`. Apply the sidebar's existing path error handling to metadata
failures as well as read failures.

## Testing

Extend the remote preview test to cover an image at the size limit,
oversized image and text files, and both metadata compatibility fallbacks.

GitOrigin-RevId: a284b3b76d9c56fe7e80445d880ccc17d575681c
2026-12-01 16:07:34 +00:00
Dylan Hurd 697f9e5a5e Wait for complete PTY input in the TUI startup test (#65021)
## Why

A completed write to the PTY master can reach the slave in fragments.
The startup test could run its zero-time poll or input discard before
the full sequence arrived.

## What changed

Use `FIONREAD` to wait until the full paste boundary and the subsequent
action input are each queued on the PTY slave. The wait leaves the bytes
unread and reports how many arrived if it times out.

GitOrigin-RevId: 077715814c4e11e6dfd42e63238222b0204aff4d
2026-12-01 15:55:25 +00:00
jif 30c23ded92 Avoid delaying sandboxed process exits after output closes (#65017)
## Why

The exec server can wait up to 20 ms for sandbox denial output even
when all output streams have already closed. If the last stream closes
during that wait, the close alone does not wake the exit watcher.

## What changed

Skip the wait when all streams are closed and wake the exit watcher
when the last stream closes. Register for notifications under the
process lock so the exit watcher can observe stream closure and
`process/read` can observe the exit as soon as it is published.

## Testing

Add paused-clock regression tests for streams closing before exit,
the final stream closing during the wait, and denial output arriving
after the first stream closes.

GitOrigin-RevId: 22715a0fbe4e582d82abcba8eab4802c42353f69
2026-12-01 15:43:47 +00:00
Dylan Hurd 55c37f6b80 Wait for an attached thread in TUI job-control tests (#65012)
## Why

The `/status` palette can appear during startup, before the TUI attaches
to a thread. Waiting for the palette alone can let the test suspend the
TUI too early.

## What changed

Use the bundled model catalog to avoid model fetch delays during test
startup. Configure the status line to show `thread-id` and `run-state`,
then wait for ` · Ready` before opening the `/status` palette and
suspending the TUI.

GitOrigin-RevId: adfe1163082dca64c76791f38cee29791ea774b5
2026-12-01 15:28:04 +00:00
jif aadf113445 Wait for V3 workers to release their slots when stopped (#65008)
## Why

With only one worker slot, starting a replacement can fail while the
interrupted worker is still cleaning up its turn.

## What changed

Add `CodexThread::stop_worker` for V3 workers. Enable interruption at
sampled item boundaries for V3 and make the stop call wait until the
interrupted turn releases its execution slot. The stopped thread can
still accept later messages.

## Testing

Add an integration test that holds a worker during sampling and abort
cleanup, checks that the stop call remains pending at both points, and
starts a replacement worker in the only worker slot after stop returns.

GitOrigin-RevId: da78de02d8c32a0f6e62b0487b49cf4908c01de5
2026-12-01 15:16:03 +00:00
Felipe Coury 8a8708c657 Preview large JPEGs in the TUI sidebar (#65007)
## Why

A JPEG can exceed the sidebar's 32 MiB decode budget even when its
thumbnail would fit comfortably.

## What changed

When a full JPEG decode hits the allocation limit, try building a
preview from JPEG block averages within the same budget. The fallback
supports sequential and progressive JPEGs, applies EXIF orientation,
and preserves the oriented source dimensions in the sidebar label.

## Testing

Add tests for a 6544 × 1721 sequential JPEG that produces a 768 × 202
preview and for a progressive fixture that exercises scan refinement,
restart markers, EXIF rotation, and allocation limits.

GitOrigin-RevId: 232b37d8c239fbaa602930d9032c9a784bd030e2
2026-12-01 15:14:52 +00:00