Skip to content

fix(agent): harden pair-mode cancel, tool paths, reads and turn status - #406

Merged
fcoury merged 7 commits into
mainfrom
fix/agent-pair-hardening
Oct 17, 2026
Merged

fcoury merged 7 commits into
mainfrom
fix/agent-pair-hardening

Conversation

@fcoury

@fcoury fcoury commented Oct 17, 2026 •

Copy link
Copy Markdown
Contributor

A review of the Agent pane found two ways it could lose work around Cancel and two path-safety gaps in the agent's tools. It also found that plain reads had side effects and that turn state was hard to follow. This PR fixes all four areas, one commit each.

Cancel:

  • A prompt sent just after Ctrl-c could vanish.
    • The editor marked the session idle immediately, but Codex keeps running the turn until it confirms turn/interrupt.
    • The worker silently skipped turn/start for a busy thread, and the interrupted turn's completion was then recorded as the new prompt finishing.
  • Every cancel threw the Codex thread away. The next message started a new thread seeded only with the last ~6,000 characters of the transcript. This rotation was added for the ACP adapters (feat(agent): add the native agent foundation #100), which the direct app-server (ADR 0003) does not need.
  • Queued follow-ups also ran straight after a cancel or an error, in that replacement thread.

Paths:

  • write_file .git/hooks/pre-commit (or .red/, red.toml, .vscode/tasks.json) passed path resolution. It replaced a buffer's contents and returned "applied, not saved", leaving a dirty hook buffer behind. Only the save step checked protected paths, and the non-Unix save fallback didn't check them at all.
  • The agent's file walker didn't skip .git. Object files used up the 65k-entry and 5-second walk budget and crowded real files out of the first list_files page, and read_file could read .git/config, which can hold credential URLs.

Reads: every read_file opened a buffer that was never closed and switched the active buffer twice. Each switch requested diagnostics and redrew the screen, so long sessions flooded the buffer list and the screen flickered even with follow mode off.

Turn state:

  • The editor tracked turns in two separate sets (active and stopping).
  • Completion, cancel and error events carried no turn ID, so the pane couldn't tell a late event from an earlier turn apart from the current one.
  • The agent_activity statusline field said "following" for any running turn, even with follow mode off, and it wasn't in the default statusline.
  • Nothing told you when a turn finished while the pane was hidden.

What changed

Cancel handling (src/editor.rs, src/editor/agent_manager.rs, src/codex/mod.rs):

  • A cancelled session stays busy until its Completed or Failed event arrives; its editor tools still stop immediately.
  • Prompts for a busy session are queued in the editor and sent in order when the turn ends. This replaces the old "already active" message, which also dropped the prompt.
  • If the app-server dies while prompts are still queued in the editor, they come back to the pane in a new agent:prompts_returned event and are kept as paused follow-ups, so nothing you typed is lost.
  • The worker now emits Failed instead of skipping a turn without a word.
  • A rejected turn/interrupt now produces a new CancelFailed event instead of Failed. It doesn't end the turn: held prompts keep waiting, the pane says the stop failed, and Ctrl-c retries.

Agent pane (plugins/agent.hk):

  • Cancelling keeps the thread, so the next prompt continues with full context and no recap.
  • Queued follow-ups pause after a stopped or failed turn, including a cancel that lost the race to completion. The status line shows N queued · paused.
  • New commands :AgentSendQueued and :AgentDiscardQueued resume or drop the held follow-ups.

Path safety (src/lsp/workspace_edit.rs, src/editor.rs, src/codex/mod.rs, src/inline_context.rs):

  • The protected-path check is now shared. write_file, apply_edits and create_directory run it before any buffer is opened, and so does the non-Unix save fallback.
  • Version-control metadata (.git, .hg, .jj, .svn) is refused by path resolution and skipped by the agent and inline-context file walkers.

Reads without buffers (src/editor.rs, src/editor/agent_annotations.rs, src/editor/agent_lsp.rs):

  • read_file returns an open buffer's live contents without switching to it.
  • An unopened file is read from disk with a content-derived revision token, so no buffer is created.
  • Write, edit, annotation and LSP tools accept that token only while the buffer still holds the same contents. A file that changed after the read is still rejected as stale.
  • Annotations still open the buffer on purpose, because they move the cursor to the new comment.
  • LSP tools (lsp_prepare_rename, lsp_preview_rename, file diagnostics) load an unopened file's buffer in the background, without switching to it.

Turn phases and status (src/editor/agent_manager.rs, src/editor/rendering.rs, src/config.rs, plugins/agent.hk):

  • Each session has a single AgentTurnPhase (Running or Stopping). The turn ID is kept until the turn really ends.
  • agent:completed, agent:cancelled and agent:error now carry turn_id, and the pane ignores events from an earlier turn.
  • agent_activity shows agent working, agent following or agent stopping, plus any queued count, and is empty when idle. It is now in the default right-hand statusline; while the agent is idle the layout looks the same as before.
  • A turn that finishes while the pane is hidden prints Agent finished · Space A to view.

docs/AGENT_WORKFLOW.md documents the new behaviour and commands.

How to Test

  1. Thread is kept across a cancel. Run red in a git repo and press Space A.
    • Send: "Remember the codeword PELICAN. Then read every .rs file one at a time and write a long essay about each function."
    • While it's working, press Ctrl-c and immediately send: "Reply with only the codeword I asked you to remember."
    • Expected: "Agent stopped: interrupted", then "PELICAN".
    • The workspace's newest ~/.codex/sessions/**/rollout-*.jsonl should hold both turns in one thread (turn_aborted interrupted, then task_complete), with no second thread file.
  2. Queue pauses.
    • Start a long turn, submit a follow-up while it runs, then press Ctrl-c.
    • Expected: the follow-up is not sent, and the pane status reads 1 queued · paused · :AgentSendQueued or :AgentDiscardQueued.
    • :AgentSendQueued sends it to the same thread; :AgentDiscardQueued removes it from the pane.
  3. Protected writes (regression). Ask the agent to "create .git/hooks/pre-commit containing echo hi".
    • Expected: the tool call fails with "cannot write protected control or secret path", no .git/hooks/pre-commit buffer appears in the buffer list, and the file isn't created.
  4. .git is never read. Ask the agent to read .git/config. Expected: refused with "inside version-control metadata".
  5. Reads don't touch buffers.
    • With follow mode off, ask the agent to read five files and summarise them.
    • Expected: the buffer list (:ls) and the active buffer are unchanged afterwards, and nothing flickers.
    • Regression check: edit a file on disk after the agent has read it, then ask the agent to edit that file. Expected: it fails as stale, rereads, and only then writes.
  6. Turn status.
    • While a turn runs, the statusline's right side shows agent working, or agent following with follow mode on. After Ctrl-c it shows agent stopping until the turn ends, then it disappears.
    • Run :AgentClose during a turn. When the turn finishes, Agent finished · Space A to view appears (it's also in :messages).

Targeted tests:

  • prompt_sent_during_a_cancel_runs_after_the_interrupted_turn_ends (fails on main)
  • busy_turn_rejects_prompts_and_a_failed_interrupt_can_be_retried
  • bundled_agent_pauses_queued_follow_ups_after_a_stopped_turn
  • agent_writes_to_protected_paths_fail_before_touching_a_buffer
  • file_listing_skips_version_control_metadata
  • agent_reads_of_unopened_files_leave_buffers_alone_and_guard_later_writes
  • statusline_agent_activity_reports_turn_phase_and_queue
  • bundled_agent_ignores_terminal_events_from_an_earlier_turn
  • bundled_agent_announces_turns_that_finish_while_the_pane_is_hidden
  • a_lost_bridge_returns_prompts_held_behind_a_stopping_turn
  • bundled_agent_keeps_prompts_returned_by_a_lost_app_server_as_paused
  • agent_lsp_works_on_files_read_from_disk_without_switching_buffers (tests/lsp_lazy.rs)
  • bundled_agent_explains_a_failed_cancel_and_keeps_the_turn_running

Existing tests updated:

  • The four bundled_agent_rotates_* tests now assert that the thread is kept.
  • Three read/write tests now open the file first, because reads no longer open buffers.
  • The default-statusline test now includes agent_activity.

Not covered here:

  • The Agent pane plugin's own state is still spread across many flags (session_starting, restoring, pending_prompt, …) with a string ui_phase. Folding those into one phase type is a larger refactor of plugins/agent.hk, left for a follow-up.

…buffers

Agent tool path resolution only blocked sensitive and gitignored paths, so
write_file to .git/hooks/pre-commit, .red/, red.toml or .vscode/tasks.json
replaced a buffer and returned applied-but-unsaved, leaving a dirty buffer a
later user save could persist. Writes now share the LSP protected-path check
before any buffer is opened, reads refuse version-control metadata (which can
hold credential URLs), and the agent file walkers no longer descend into .git,
.hg, .jj or .svn, which crowded real files out of the walk budget.
… ends

Cancelling marked the session idle in the editor immediately, but Codex keeps
running the turn until it confirms the interrupt. A prompt sent in that window
was dropped by the worker, which skipped turn/start for a busy thread without
reporting anything, and the interrupted turn's completion was then recorded as
the new turn finishing. The editor now keeps a cancelled session busy until its
Completed or Failed event and queues prompts for busy sessions, the worker fails
loudly instead of silently skipping a turn, and a rejected interrupt can be
retried.

The Agent pane also closed the Codex thread after every cancel and restarted
from a 6,000-character transcript recap, an ACP-era workaround that the direct
app-server does not need. Cancelling now keeps the thread. Queued follow-ups
pause after a stopped or failed turn instead of running unattended, and
:AgentSendQueued / :AgentDiscardQueued resume or drop them.
Every agent read_file pushed a buffer that was never closed and switched the
active buffer twice, each switch requesting diagnostics and repainting. A long
session flooded the buffer list and made the screen flicker even with follow
mode off. Reads now report an open buffer's live contents in place, and read
unopened files from disk with a content-derived revision token. Write, edit,
annotation and LSP tools accept that token only while the buffer still holds the
same contents, so a file that changed after the read is still rejected as stale.
…urface turn state

The editor tracked a turn's lifecycle in separate active and stopping sets, and
terminal events carried no turn id, so the pane could not tell a late event from
an earlier turn apart from the one on screen. Sessions now have a single
Running/Stopping phase, the turn id survives until the turn really ends, and
completed/cancelled/error events carry it so the pane ignores stale ones.

The agent_activity statusline field said "following" for any running turn even
with follow mode off and was not in the default layout. It now reports working,
following, or stopping plus queued prompts, hides when idle, and sits on the
right by default. A turn that finishes while the pane is hidden prints a notice.
@fcoury fcoury changed the title fix(agent): keep the thread on cancel and refuse protected agent paths fix(agent): harden pair-mode cancel, tool paths, reads and turn status Oct 17, 2026
@fcoury

fcoury commented Oct 17, 2026

Copy link
Copy Markdown
Contributor Author

@codex review

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Oct 17, 2026 •

Copy link
Copy Markdown

Codex Review Summary

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-10-17T17:08:24.235999Z 98924ee Manual request
ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 98924eef58

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread src/editor.rs Resolved
Comment thread src/editor.rs Resolved
Prompts queued in the editor behind a stopping turn were dropped and only
logged if the Codex app-server died before the turn ended. The editor now hands
them back in an agent:prompts_returned event, and the Agent pane keeps them as
paused follow-ups that :AgentSendQueued can send once Codex restarts.
read_file no longer opens buffers, so lsp_prepare_rename, lsp_preview_rename and
file diagnostics failed with "read_file must open this file" for any file the
user had not opened. The LSP path now loads the buffer in the background, without
changing the active buffer, and accepts the disk revision token from the read.
A rejected turn/interrupt was reported as a turn failure, so the editor ended
the turn and sent the next held prompt while Codex was still running the old
one; the worker then refused that prompt. The worker now emits CancelFailed for
a rejected interrupt, which leaves the turn stopping, keeps held prompts
waiting, and lets the pane explain the failure and offer Ctrl-C to retry.
@fcoury
fcoury merged commit 50719dd into main Oct 17, 2026
31 of 33 checks passed
@fcoury
fcoury deleted the fix/agent-pair-hardening branch October 17, 2026 19:34
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant