Skip to content

feat(chat): render a local chat's runs through AG-UI behind an opt-in - #1725

Merged
edenreich merged 5 commits into
mainfrom
refactor/issue-1713-local-loopback
Nov 6, 2026
Merged

edenreich merged 5 commits into
mainfrom
refactor/issue-1713-local-loopback

Conversation

@edenreich

@edenreich edenreich commented Nov 6, 2026 •

Copy link
Copy Markdown
Contributor

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

@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 19:03
@edenreich
edenreich force-pushed the refactor/issue-1713-local-loopback branch from 1a47fdb to 46d01af Compare November 6, 2026 19:37
@edenreich
edenreich marked this pull request as ready for review November 6, 2026 20:34
@edenreich
edenreich requested a review from a team as a code owner November 6, 2026 20:34
@edenreich
edenreich force-pushed the refactor/issue-1713-local-loopback branch from 46d01af to 9abf21f Compare November 6, 2026 21:03
@edenreich
edenreich force-pushed the refactor/issue-1713-local-loopback branch 3 times, most recently from 59aaad7 to eea4123 Compare November 6, 2026 22:31
Base automatically changed from refactor/issue-1713-tui-reducer to main November 6, 2026 22:31
INFER_CHAT_AGUI_LOOPBACK=true wraps the in-process agent so each run is
written by the encoder the serve worker uses and read back by the reducer a
daemon chat uses. A local chat then takes the same path as a daemon chat. It
is off by default while the path is proven against the direct one: the e2e
suite passes the opt-in on, and one local TUI test still differs under it.
The opt-in was read with os.Getenv, so it bypassed the config layers every
other INFER_* key goes through. It is now chat.agui_loopback, with the same
environment name. The new function had also split StartChatSession from its
doc comment, which is back in place.
…UI opt-in

Accepting a plan ran nothing. The reducer hands the chat a plan with a response
channel, which tells the chat a daemon worker runs it, and on this path no
worker does. The agent does not wait on a plan, so the event now goes straight
to the chat, whose direct path restarts the run. render.PlanActionName has no
other caller on this path, so the daemon chat keeps its private copy.

The encoder had no job source either, so nothing closed a step's tool results.
ToolExecutionCompletedEvent waited for the next model token, and until then the
status read Completed successfully with no spinner while the model worked.

The publish option is gone. Those events reach the TUI through the notifier,
never this stream. So is the context guard, since chat runs on a context that
never ends.
Nothing asserted that a finished job's note lands in the chat and drives the
next turn. These cover a job that ends while the chat is idle, one that ends
during a reply, and one a daemon chat's worker runs. They pass on the default
path, the AG-UI opt-in and the daemon chat alike.
The suite took 208s in CI against a 5 minute limit, and the tests this stack adds
take about 70s more, which leaves too little margin on a slow runner.
@edenreich
edenreich force-pushed the refactor/issue-1713-local-loopback branch from eea4123 to c4442a9 Compare November 6, 2026 22:31
@edenreich
edenreich merged commit 3930ded into main Nov 6, 2026
@edenreich
edenreich deleted the refactor/issue-1713-local-loopback branch November 6, 2026 22:32
edenreich added a commit that referenced this pull request Nov 6, 2026
)

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

- Clients of the AG-UI stream need no change. They already saw nothing
between an interrupt and its answer.
- Docs follow-up: inference-gateway/docs#1110
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