Skip to content

fix(agent): run a tool batch only once every approval is answered - #1727

Merged
edenreich merged 3 commits into
mainfrom
fix/issue-1713-approve-before-running
Nov 6, 2026
Merged

edenreich merged 3 commits into
mainfrom
fix/issue-1713-approve-before-running

Conversation

@edenreich

@edenreich edenreich commented Nov 6, 2026 •

Copy link
Copy Markdown
Contributor

Part of #1713. Stacked on #1725.

Summary

The agent now asks for every approval in a tool batch before it runs any of the calls. Before, an approved call started at once, while the user was still deciding on the next one, and its progress and result were reported behind the open prompt.

That made the views disagree. The chat TUI reading the agent directly showed the first tool's result while the second approval was open. Any client of the AG-UI stream did not: an approval suspends the run, RunEncoder waits for the answer, and whatever the running tool reported in the meantime arrived only after it. It is the gap that kept #1725 a draft.

Changes

  • internal/agent/loop/states/approving_tools.go: a call the user or the judge approved, or one the policy does not gate, is recorded as cleared instead of spawned. finishApprovals runs the cleared calls once the round is decided. They still overlap, bounded by the same semaphore, and their results are still flushed in tool-call order as they complete.
  • A cancelled session runs none of the cleared calls. The conversation validator already answers calls left without a result.
  • An approval that fails ends the turn before anything ran. Before, calls approved earlier in the round were already executing.
  • A round that ends early drops the approval entries of the calls it will not run. Only running a call clears its entry, so the chat kept showing a call as approved although it never ran.
  • The status says Tool approved: <tool> instead of claiming the tool is executing while the next prompt is open.

Behavior change

This applies to every user and reverses behavior added on purpose: #609 made approved tools run concurrently while later prompts were open, and #1289 asserted the first result is visible while the second approval is open.

  • With a gated call in a batch, no call of that batch runs until the last prompt is answered. That includes ungated calls such as Read or TodoWrite batched with a gated one, and a background job.
  • The cost: a long first tool does not start until the user has answered every prompt.
  • Rejecting a later call leaves an earlier approval standing, so that call still runs.
  • A single gated call, auto-accept mode, and fully ungated batches behave as before.

What this does not change

Tools can still open a prompt during execution: sandbox access, RequestApproval escalations and AskUserQuestion. A read-only sibling can overlap such a prompt, so on the AG-UI stream its reports still wait for the answer. This PR only covers the prompts of the approval round.

Verification

  • New TestApprovingToolsState_RunsNothingWhileAPromptIsOpen on the fake clock, for an approved call and an ungated one. It fails on the old behavior.
  • New TestApprovingToolsState_ForgetsApprovedCallsItWillNotRun, for a failed approval and a cancelled session. It fails without the fix.
  • New TestChatTUIBackgroundJobWaitsForItsBatch fails on main with the job started while the second approval was open, and passes here on both paths.
  • New TestChatTUIRejectingACallStillRunsTheApprovedOne passes on main and here.
  • TestChatTUIApprovalBoxFollowsTail now asserts the first Write has not run while the second approval is open, and shows once both are answered.
  • The stale approval entry and the false status were reproduced by hand in tmux with INFER_AGENT_MAX_DURATION_MINUTES=1, and are gone with the fix.
  • go test -race ./..., task precommit:run, and the full e2e suite with -race on both paths.

Seen while testing, not changed here

  • After a run ended by its time budget, the next approval box stays open.
  • The n and s plan keys in config/keybindings.go do nothing on main either. The screen offers arrows and Enter.

Downstream

@edenreich
edenreich requested a review from a team as a code owner November 6, 2026 19:30
@github-project-automation github-project-automation Bot moved this to Todo in 2026 Nov 6, 2026
@edenreich
edenreich added this pull request to stack #1726 November 6, 2026 21:02
@edenreich
edenreich force-pushed the fix/issue-1713-approve-before-running branch from f961970 to dda1860 Compare November 6, 2026 21:03
@edenreich
edenreich force-pushed the fix/issue-1713-approve-before-running branch 4 times, most recently from d74e0f5 to f29e572 Compare November 6, 2026 22:31
Base automatically changed from refactor/issue-1713-local-loopback to main November 6, 2026 22:32
An approved call used to start at once, while the user was still deciding on
the next one, and reported its progress and result behind the open prompt. A
client of the AG-UI stream never saw that: an approval suspends the run, so
everything the running tool reported arrived only after the answer. The round
now clears each call first and executes the cleared ones together, so no tool
reports while a prompt is open and every view shows the same thing.
Approved calls now wait for the rest of the round, and only running a call
clears its approval entry. When a later prompt timed out or the session ended,
the chat kept showing the call as approved although it never ran. The round now
drops those entries when it ends early.

The status also claimed the approved tool was executing while the next prompt
was open, so it now only says the tool was approved.
A background job batched with a gated call now starts once the whole batch is
decided, and an ungated call waits the same way. Rejecting a later call leaves
the approval of an earlier one standing, so that call still runs.
edenreich added a commit that referenced this pull request Nov 6, 2026
…#1725)

Part of #1713. Stacked on #1724.

## Summary

A local chat can now render its agent runs through AG-UI, the path a
daemon chat takes, behind an opt-in. With `chat.agui_loopback: true`
(`INFER_CHAT_AGUI_LOOPBACK=true`) the in-process agent is wrapped: each
run is written by the `RunEncoder` the serve worker uses and read back
by `tui/runview.Reducer`. The default is unchanged.

## Changes

- `internal/presentation/tui/loopback` (new): `Agent` decorates the
in-process `AgentService`. `RunWithStream` pipes the agent's events
through the encoder into the reducer, in memory and in the same
goroutine as the encoder, one frame at a time. A suspended run is
resumed with the user's answer to its approval or question. Everything
else (cancel, metrics, system prompt, reasoning effort) goes straight to
the agent.
- A plan skips the run. The agent does not wait on it and the chat
restarts the run itself, so the event goes straight to the chat's
existing direct path. It can become an interrupt once the handlers stop
deciding plans.
- The encoder gets the background task registry's `Snapshot`, like the
serve worker. That patch is what hands a step's tool results to the
reducer.
- `chat.agui_loopback` is a config key, read through the usual config
layers and listed in `docs/configuration-reference.md`.
- `container.NewLoopbackChatContainer` wraps the agent, and `infer chat`
picks it when the opt-in is set.
- e2e: `TestMain` reads the opt-in before it drops the caller's
`INFER_*` variables and the local chat launches pass it on, so
`INFER_CHAT_AGUI_LOOPBACK=true task test:e2e` runs the same local chat
tests through the new path.
- New e2e tests: an accepted plan runs, the status shows the model is
working after a tool, and a background job followed through a chat
(finishing while idle, finishing during a reply, and in a daemon chat).
- The e2e `go test` timeout goes from 5 to 8 minutes in `ci.yml` and the
Taskfile. The suite took 208s in CI and these tests add about 70s.

## Plan change

The plan had a separate step that made the serve loop run over any
reader and writer, so a local thread could host it. The decorator needs
no turn loop at all: it wraps the agent's event channel. That step is
dropped.

## Verification

- `go test -race ./...`, and the full e2e suite with `-race` on both
paths, at the top of the stack.
- The accepted plan and working status tests fail against this PR's
first commit under the opt-in and pass on the default path.
- The background job tests pass on `main`, on this stack and under the
opt-in.
- A one-off sweep with tmux and tokenless compared final screens on
`main`, this stack and the opt-in. Question form, Esc cancel, queued
message, `!command`, todos, reasoning, provider error, auto-approve,
plan reject and plan accept-standard all matched.

## Known gaps

To close before the loopback can become the default:

- An unanswered prompt holds the run open, because the loopback has no
cancel path while the encoder is suspended. After the 5 minute approval
timeout the direct path shows an error, while here the prompt stays open
and the error arrives after the answer.
- CI never runs with the opt-in on, so nothing guards this path between
manual runs.
- The sweep's flows have no permanent test under the opt-in, since CI's
e2e budget is tight.
- A run that hits max turns should end as a sticky error here and
complete on the direct path. This comes from reading the code and has
not been run.

`TestChatTUIApprovalBoxFollowsTail` passes only 1 run in 8 under the
opt-in on this PR alone. #1727 closes that.

## Downstream

- no docs ticket: internal-only refactor
@edenreich
edenreich force-pushed the fix/issue-1713-approve-before-running branch from f29e572 to 953f486 Compare November 6, 2026 22:32
@edenreich
edenreich merged commit 6713e5f into main Nov 6, 2026
@edenreich
edenreich deleted the fix/issue-1713-approve-before-running branch November 6, 2026 22:32
edenreich added a commit that referenced this pull request Nov 6, 2026
Part of #1713. Stacked on #1727.

## Summary

`infer chat` now renders its runs through AG-UI by default, the path a
daemon chat takes: the encoder writes each run and the reducer reads it
back, so both chats share one mapping. `chat.agui_loopback: false`
(`INFER_CHAT_AGUI_LOOPBACK=false`) falls back to the handlers reading
the agent directly.

This also closes the gaps #1725 listed, and one it did not know about.

## Gaps closed

- **A judge rejection printed over the screen.** `RunEncoder` wrote it
to stderr while the TUI owned the terminal, which only showed in
Auto+Judge mode. `RunEncoderDeps.Quiet` keeps a run off stderr for such
a host.
- **An unanswered prompt held the run.** The encoder waited for an
answer nobody needed any more, so a timeout or a spent time budget only
showed once the user answered. `ToolApprovalRequestedEvent` and
`UserQuestionRequestedEvent` now carry a `Done` channel that closes when
the agent stops waiting, and `render.AnswerApproval` and
`render.AnswerQuestions` let go on it.
- **A run that hit a limit failed with a sticky error.** A local chat
now completes it, as it does without AG-UI. A serve worker still fails
it for its exit code.
- **CI never ran this path.** The e2e job now covers it by default, and
a second step runs the local chat tests on the direct path for as long
as the fallback exists.
- **Common flows had no permanent test.** See below.

## Changes

- `internal/presentation/tui/loopback`: a prompt's wait ends once the
encoder has moved past it, so a late answer goes nowhere. A completion
loses its limit flags before the encoder sees it.
- `internal/platform/render`: both answer functions select on `Done` as
well as the broker. A nil `Done` never fires, so other emitters behave
as before.
- `internal/agent/loop`: the approval, sandbox and question prompts
close `Done` when they return.
- `config`: `chat.agui_loopback` defaults to `true`, and `infer init`
writes it to new config files.
- `tests/e2e/chat_tui_flows_test.go` (new): question form, cancel,
queued message, todos, provider error, auto-approve, plan reject, plan
approve-each-step, sandbox prompt, judge rejection and a time budget
ending a run with a prompt open.
- `startLocalChat` runs its tests in parallel, which keeps the added CI
time small.

## Verification

- The judge rejection and time budget tests failed only with the
loopback on before the fixes, and pass now on both settings.
- The new unit tests failed before the fixes: a `synctest` deadlock on
the answer functions, the stream staying open, and
`max_duration_reached` surfacing as an error.
- `go test -race ./...` on all 120 packages, `task precommit:run`, and
the full e2e suite with the loopback on and off.
- By hand with tmux and tokenless: an interactive subagent, whose child
runs `infer chat` and writes its result file, gives the same result on
`main` and here. It has no permanent test.
- Everything ran against the mock gateway. It has not been tried against
a real model.

## Behavior change

- After a tool finishes, the status reads `Tools completed (1/1
successful) - preparing response...` instead of `Starting response...`,
because the wire has no step start event.

## Still different from a daemon chat

- A plan skips the run in a local chat, and is an interrupt in a daemon
chat.
- A run hitting its time budget or turn limit completes quietly in a
local chat, and shows an error in a daemon chat.

## Not in this PR

- Removing the `ChatEvent` dispatch from the TUI handlers, the last step
of #1713, and the plan bypass with it.
- Removing the fallback.

## Seen while testing, not changed here

- A daemon chat's `/tasks` reports it is unavailable, the same as on
`main`.

## Downstream

- `chat.agui_loopback` is listed in `docs/configuration-reference.md`. A
docs follow-up for `inference-gateway/docs` is not filed.
@inference-gateway-releaser

Copy link
Copy Markdown
Contributor

🎉 This PR is included in version 0.246.0 🎉

The release is available on:

Your semantic-release bot 📦🚀

@inference-gateway-releaser inference-gateway-releaser Bot added the released Shipped in a release label Nov 7, 2026
@edenreich edenreich moved this from Todo to Done in 2026 Nov 7, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

released Shipped in a release

Projects

Status: Done

Development

Successfully merging this pull request may close these issues.

1 participant