Skip to content

refactor(tui): single event-loop ingress - one notifier, no self-rescheduling pollers - #700

Merged
edenreich merged 8 commits into
mainfrom
refactor/688-ui-notifier-ingress
Jun 30, 2026
Merged

edenreich merged 8 commits into
mainfrom
refactor/688-ui-notifier-ingress

Conversation

@edenreich

@edenreich edenreich commented Jun 30, 2026 •

Copy link
Copy Markdown
Contributor

Summary

Replaces every self-rescheduling loop that fed the single Bubble Tea Update loop with one push ingress: a tea-free domain.UINotifier backed by (*tea.Program).Send, injected into every background producer via a thread-safe container holder. The Update loop is now purely reactive — it renders on real events, not on a clock — and because there is exactly one ingress, it's instrumented in exactly one place.

Closes #688. no docs ticket: internal-only refactor.

What was removed (all re-arming pollers)

Ingress Was Now
Queue-drain forever tea.Tick(500ms) → DrainQueueTickEvent, self-re-arming DrainQueueEvent pushed once per real trigger; gate-only handler
Agent-status time.Sleep(500ms) Cmd re-arm pushed from the container status callback on change
MCP status StartMonitoring returned a channel the app re-armed (waitForMCPStatusUpdate/mcpStatusUpdateWithChannel) monitor pushes MCPServerStatusUpdateEvent through the notifier
File explorer / diff viewer tea.Tick(1s) git/fs re-poll refresh off in-loop ToolExecutionCompletedEvent/BashCommandCompletedEvent + view-entry + manual ctrl+r
Computer-use forwarder bespoke program.Send ×2 routed through the one notifier

The only tea.Ticks left are the three one-shot UI deferrals the design keeps (todo auto-collapse, two background-row removals).

Design

  • internal/domain/ui_notifier.go — UINotifier interface{ Notify(any) } + NoopUINotifier (useful zero value) + NotifierFunc (test adapter). any, not tea.Msg, so the domain stays tea-free.
  • internal/container — a thread-safe uiNotifierHolder (RWMutex + swappable inner, default Noop) is the single synchronized primitive. Producers capture it at construction and never lock; SetUINotifier swaps the inner once at startup.
  • cmd/chat.go — programNotifier{program} is the only place (*tea.Program).Send is ever called; services.SetUINotifier(...) runs after tea.NewProgram and before program.Run.

Correctness notes

  • No-strand guarantee. HandleDrainQueueEvent is a pure gate (returns nil in every no-op branch — regression guard against re-introducing a ticker). Drains are pushed from three sources: supervisor enqueue, terminal turn completion (HandleChatCompleteEvent), and a single central chat-re-entry edge in Update. Added the symmetric EndToolExecution() on terminal completion so the agent is reliably idle when the drain runs — nothing strands without a poller.
  • No deadlock. (*tea.Program).Send is unbuffered and blocks until Run consumes, so Notify is only ever called from producer goroutines; the MCP initial-status emit now runs in a goroutine.
  • Interface change. MCPManager.StartMonitoring drops its channel return → mcp_manager_test.go rewritten to assert notifier pushes via a recording notifier (MCPManager has no generated counterfeiter fake).

Observability

One slow-update warn around the Update dispatch (SlowUpdateThreshold) and a one-time long-running-job warn in the supervisor cleanup sweep (JobRunningLongThreshold, reusing meta.StartedAt).

Acceptance

  • program.Send called in exactly one place (grep-proven).
  • Zero self-rescheduling pollers / re-arming wait-Cmds remain; only one-shot deferrals survive.
  • HandleDrainQueueEvent is gate-only; asserted in chat_handler_drain_test.go.
  • Agent-status, MCP-status, /tasks update on real change pushed through the notifier — no clock.
  • Explorer/diff refresh off in-loop tool/bash events + view-entry + manual key; 1s tickCmds deleted; no fsnotify in the TUI.
  • New tests: supervisor fires on enqueue and on status change; terminal-emit decision; readiness/MCP push; EndToolExecution symmetry; slow-update + long-job warns via an observed zap core.
  • task build, task test, task lint (0 issues), task fmt green; go test -race clean on touched packages.

Verification left for review

The interactive runtime checks from the issue (idle on /model shows no periodic re-render, drain-while-modal scenarios, live /tasks, diff/explorer refresh off agent edits) need a running gateway + TTY and are best confirmed manually; the behavior is covered by the unit tests above.

Out of scope / unchanged

One-shot UI deferrals (todo auto-collapse, background-row removal), the agent state-machine CheckingQueue in-turn drain, and EventBridge's floating-window multicast.

…p self-rescheduling pollers

Replace the queue-drain ticker, agent-status poll, MCP channel-wait, and the
file-explorer/diff-viewer 1s git/fs polls with a single push ingress: a tea-free
domain.UINotifier backed by (*tea.Program).Send, injected into every background
producer via a thread-safe container holder. The Bubble Tea Update loop is now
purely reactive (renders on real events, not on a clock) and program.Send lives
in exactly one place (programNotifier in cmd/chat.go).

- Queue drain: delete DrainQueueTickEvent + the 500ms ticker; add DrainQueueEvent
  pushed from supervisor enqueue, terminal turn completion, and chat re-entry.
  HandleDrainQueueEvent is a pure gate (nil in every no-op branch). Add the
  symmetric EndToolExecution() on terminal completion so the agent is reliably
  idle when the drain runs - nothing strands without a poller.
- Agent status: push AgentStatusUpdateEvent from the container status callback
  instead of a 500ms time.Sleep re-arm.
- MCP: StartMonitoring pushes MCPServerStatusUpdateEvent through the notifier
  (initial emit from a goroutine to avoid the unbuffered-Send deadlock); drop the
  channel return from the MCPManager interface.
- /tasks + explorer/diff: refresh off BackgroundTasksChangedEvent and in-loop
  ToolExecutionCompletedEvent/BashCommandCompletedEvent (+ a manual ctrl+r),
  deleting the 1s tickCmds; no fsnotify added to the TUI.
- Computer-use forwarder routed through the same notifier.
- Observability: one slow-update warn around the Update dispatch and a one-time
  long-running-job warn in the supervisor cleanup sweep.

One-shot UI deferrals (todo auto-collapse, background-row removal) are unchanged.

no docs ticket: internal-only refactor

Closes #688
@edenreich
edenreich requested a review from a team as a code owner June 30, 2026 19:32
@edenreich edenreich changed the title refactor(tui): single event-loop ingress — one notifier, no self-rescheduling pollers refactor(tui): single event-loop ingress - one notifier, no self-rescheduling pollers Jun 30, 2026
@edenreich edenreich added this to 2026 Jun 30, 2026
@edenreich edenreich moved this to QA in 2026 Jun 30, 2026
…n /tasks

Two issues found while testing the single-notifier refactor:

- Queue drain: HandleDrainQueueEvent was a pure one-shot gate, so a
  background-job completion event dropped at a momentarily-busy instant stranded
  the queue forever - the deleted 500ms ticker's repetition had been the de-facto
  retry. Re-arm a single bounded retry, but ONLY while work is genuinely stranded
  on the chat view (queue non-empty); it stops the moment the queue drains, so
  there is no idle clock and no /model flicker regression.

- /tasks: stop gating the task view on A2A and wire the real BackgroundTaskRegistry
  into it directly (passed through NewChatApplication) instead of the fragile
  GetA2ATaskTracker().(BackgroundTaskRegistry) assertion, so background shells and
  subagents show whether or not A2A is enabled. Drop the "requires A2A" gate and
  fallback copy. Add a debug log of the per-source /tasks row counts to pinpoint
  any remaining empty-list case (supervisor snapshot vs A2A poller vs retention).
…l refresh

The Elapsed column was frozen until the user pressed 'r', because the view only
reloaded on status changes (BackgroundTasksChangedEvent) while elapsed time
advances on the wall clock with no event.

Add a bounded refresh tick: while the view is open and a task is actually
running, a 1s tick reloads (recomputing Elapsed and catching status changes) and
re-arms; the moment nothing is running it stops, so it is a contained animation
tick like the spinner, not a resurrected idle poller. With the table now live,
remove the now-redundant manual 'r' refresh key and its help-bar entry.

Also drops the temporary /tasks diagnostic log added to pin the empty-list cause
(now confirmed fixed by the direct registry wiring).
The app log dir was derived from viper's ConfigFileUsed(), which returns the home
~/.infer/config.yaml when both a home and a project config exist - so app logs went
to ~/.infer/logs while the gateway logged to ./.infer/logs. Default the app log dir
to config.DefaultLogsPath (./.infer/logs, relative to the working dir) so app and
gateway logs sit together and follow the project. An explicit logging.dir still wins.
Comment thread internal/services/jobs/supervisor.go Resolved
@edenreich

Copy link
Copy Markdown
Contributor Author

@claude Can you review this? make sure you use the skills /go /go-concurrency /cobra-viper /go-spec-reviewer /bubbles-v2 /bubbleteas-v2 and some other skills that might be relevant

@inference-gateway-maintainer

inference-gateway-maintainer Bot commented Jun 30, 2026 •

Copy link
Copy Markdown
Contributor

Claude finished @edenreich's task in 10m 3s —— View job


Review: single event-loop ingress refactor

I reviewed this through the lens of /go, /go-concurrency, /cobra-viper, /bubbletea-v2, /bubbles-v2, and /go-spec-reviewer. I read all 28 files, traced the concurrency invariants against the actual bubbletea v2.0.7 source, and verified routing/lock-discipline. I could not run task build/task test/go test -race locally (sandbox blocked the build), so I leaned on static analysis plus the PR's CI claims.

Verdict: this is a well-executed refactor. The hard parts - the deadlock-safety argument and the lock discipline - are correct, not just plausible. I found no blocking issues; two minor behavioral gaps and a few nits below.


What I verified as sound ✅

  • Deadlock safety holds. (*tea.Program).Send is genuinely unbuffered (msgs: make(chan Msg), tea.go:598) and blocks on p.msgs <- msg until the loop consumes (tea.go:1183). So the whole design rests on "Notify is never called from the Update goroutine." I traced every producer - the forward... forwarder, supervisor.Submit (only from tool Execute, which runs in tea.Cmd goroutines), the monitor/probe goroutines, and the agent-status callback (agent-manager goroutines) - all are off-loop. ✔
  • Lock discipline is correct. Every s.notify(...) in the supervisor fires after s.mu.Unlock() (supervisor.go:164, 194, 224, 321), and uiNotifierHolder.Notify copies inner under RLock then releases before the blocking send. So a monitor goroutine blocked in Send can never wedge the Update loop calling Snapshot()/CountRunning(). This is the one subtle deadlock this design could have had, and it's avoided. ✔
  • The go m.sendInitialStatusUpdate() fix is right and can't leak: Send's select has a case <-p.ctx.Done(), so blocked emits unblock on shutdown. The MCP lock refactor (collect connected names under the lock, emit after release) is correct. ✔
  • Component refresh routing works. handleViewSpecificMessages dispatches every message to the active view, so ToolExecutionCompletedEvent/BashCommandCompletedEvent reach diffViewer/fileExplorer Update while open, and reopen re-runs Init() → loadCmd(). Refreshing off real in-loop events instead of a 1s clock is the correct Bubble Tea pattern. ✔
  • EndToolExecution() symmetry is safe - it just nils toolExecution (state.go:760), idempotent, no underflow.
  • No dangling references to any removed symbol; MCPServerStatusUpdateEvent is handled in exactly one place (no double-dispatch).
  • Idiomatic zero-value design (NoopUINotifier, NotifierFunc) and small single-method interface - textbook /go. Tests use thread-safe recorders + observed zap cores and barrier on Stop() before asserting - solid.

Minor issues

1. The live "Elapsed" tick in /tasks can strand. internal/ui/components/task_management_view.go

refreshTickCmd is armed at Init and re-armed only by itself. When activeTasks empties, the next taskRefreshTickMsg returns nil (:280) and the chain dies - correct. But if a new job then starts while the view stays open, both handleTasksLoaded (:304, returns nil) and the BackgroundTasksChangedEvent handler (:270, only loadTasksCmd) repopulate activeTasks without re-arming the tick. The new task's elapsed column then freezes until the next status-change event. Suggest a tickLive bool guard, re-arming when activeTasks goes 0→>0 (the guard prevents duplicate overlapping chains). Fix this →

2. Drain retry chains aren't deduplicated. internal/handlers/chat_handler.go:HandleDrainQueueEvent

Each DrainQueueEvent that arrives while busy + queue-non-empty arms its own tea.Tick(300ms) retry. Because the supervisor pushes one per enqueue, N background jobs landing during a single busy turn → up to N concurrent 300ms retry tickers. They do all collapse when the queue drains (verified: the post-completion drain empties the queue, every chain then returns nil within 300ms), so it's bounded and self-healing, not a leak - but it's a transient poller-multiplication in the one PR whose thesis is "no self-rescheduling pollers." A single drainRetryArmed bool on the handler (single-threaded loop ⇒ race-free), set when arming and cleared when the retry fires, keeps it to one chain. Fix this →


Nits (non-blocking)

  • Instrumentation can't see the one fatal failure mode. logSlowUpdate runs in a defer, so it only fires if Update returns. A true invariant violation (someone later calls Notify synchronously from the loop) deadlocks and never returns - the warn never prints. The "never Notify from the Update goroutine" rule is load-bearing and unguarded; worth a prominent comment on programNotifier.Notify/UINotifier (you have good comments already, but this specific hazard deserves a one-liner at the call boundary).
  • uiNotifierHolder could be an atomic.Pointer/atomic.Value (swap-once, read-many) per the /go "typed atomic" guidance - but the RWMutex is correct and clearly commented, so this is purely taste. No change needed.
  • Redundant nil-checks: supervisor.notify/MCPManager.notify guard s.notifier != nil, yet both constructors already default a nil arg to NoopUINotifier. Defensible for zero-value test construction (&Supervisor{}), just slightly belt-and-suspenders.
  • cmd/root.go swaps the logDir default to config.DefaultLogsPath (project-local ./.infer/logs). It's correct and verified-present, but it rode in via the main merge and is orthogonal to the notifier refactor - just confirming it's intended to be part of this PR's diff.
  • The inline warnedLong bool suggestion on supervisor.go is already applied (supervisor.go:51). ✔

Tests / scope

Coverage matches the acceptance checklist well: the gate-only HandleDrainQueueEvent table test, the shouldDrainAfterComplete decision matrix, supervisor enqueue/status pushes, the EndToolExecution symmetry assertion, and the slow-update + long-job warns via an observed core. One note: the PR body says the MCPManager counterfeiter mock was regenerated, but there's no FakeMCPManager under tests/ - the MCP tests drive the real manager with a recording notifier instead (which is better, just a doc mismatch).

Nice work - the deadlock reasoning in the description checks out against the source, which is the part that's easy to get wrong.
· refactor/688-ui-notifier-ingress

Addresses the ultrareview on PR #700:

- /tasks live-elapsed: re-arm the refresh tick when a task appears while the
  view stays open, guarded by tickLive + a tickEpoch so a stale tick from a
  fast reopen can't form a second chain.
- drain retry: collapse the N-pushes-per-busy-turn case to one timer via a
  dedicated DrainQueueRetryEvent + drainRetryArmed guard, which distinguishes a
  retry firing from a fresh external push.
- uiNotifierHolder: swap the RWMutex for atomic.Pointer (swap-once, read-many).
- supervisor/MCPManager notify(): drop the redundant nil-check (constructors
  already default a nil notifier to NoopUINotifier).
@edenreich
edenreich merged commit 2ab8854 into main Jun 30, 2026
1 check passed
@edenreich
edenreich deleted the refactor/688-ui-notifier-ingress branch June 30, 2026 22:18
@edenreich edenreich moved this from QA to Done in 2026 Jun 30, 2026
inference-gateway-releaser Bot added a commit that referenced this pull request Jun 30, 2026
## [0.126.0](v0.125.0...v0.126.0) (2026-06-30)

### 🚀 Features

* add persistent memory tool for agent ([#679](#679)) ([a487b13](a487b13))
* **agent:** interactive subagent management and unified background-work tracking ([#684](#684)) ([343e083](343e083))

### 🐛 Bug Fixes

* **chat:** bind opt+backspace and ctrl+backspace to delete-word-backward ([#697](#697)) ([173fe83](173fe83)), closes [#689](#689) [#576](#576)
* **a2a:** retain completed background tasks in /tasks ([#691](#691)) ([#701](#701)) ([43b8e13](43b8e13))
* **autocomplete:** surface arguments for one-of/all-optional tool schemas ([#698](#698)) ([655b2e4](655b2e4))

### ♻️ Code Refactoring

* add .gitignore by default to the projects dir ([4717deb](4717deb))
* enable memory by default ([86c2158](86c2158))
* make infer config userspace-first ([#682](#682)) ([1e77e42](1e77e42)), closes [#680](#680)
* **tui:** single event-loop ingress - one notifier, no self-rescheduling pollers ([#700](#700)) ([2ab8854](2ab8854))
* standardize comment punctuation by replacing em dashes with hyphens ([78f53a8](78f53a8))

### 📚 Documentation

* fix docs/ drift found by the README-to-codebase audit ([#687](#687)) ([413047a](413047a)), closes [#572](#572) [#686](#686)
* sync README and reference docs with the codebase ([#685](#685)) ([c328423](c328423)), closes [#572](#572) [#684](#684) [#684](#684)

### 👷 CI/CD

* **deps:** update CLAUDE workflow to version 0.14.5 ([eaba2b3](eaba2b3))

### 🧹 Maintenance

* add .infer to .gitignore ([08ef319](08ef319))
* **deps:** bump infer CLI v0.124.0 -> v0.125.0, infer-action v0.19.0 -> v0.19.1 ([#681](#681)) ([e9e7e21](e9e7e21))
* remove agent definitions ([4f7fd7d](4f7fd7d))
* remove unused configuration and shortcut files ([4c611db](4c611db))
* update claude-code to 2.1.191 ([729e81c](729e81c))
@inference-gateway-releaser

Copy link
Copy Markdown
Contributor

🎉 This PR is included in version 0.126.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 Jun 30, 2026
edenreich added a commit that referenced this pull request Sep 2, 2026
One background goroutine in cmd/chat pushes agentdomain.HeartbeatEvent through
the UI notifier every 10 seconds. It is the only clock feeding the Update loop,
so periodic freshness checks subscribe to it instead of re-arming private
tea.Ticks (the pattern PR #700 removed). The input view uses it to refetch git
status for changes made outside the TUI; the git call stays in a tea.Cmd and is
skipped entirely when the git_branch indicator is disabled.
edenreich added a commit that referenced this pull request Sep 2, 2026
…npushed (#1164)

Closes #1157

- New `tui.GitStatusResolvedEvent{Dirty, Unpushed}` and
`fetchGitStatusCmd` (mirrors `fetchGitPRCmd`, uses `utils.RunGit`).
- Refetched on `Init`, `BashCommandCompletedEvent`, every
`ToolExecutionCompletedEvent` (PR refetch stays gated on Bash), and the
new app heartbeat.
- **Single app heartbeat**: `runUIHeartbeat` in `cmd/chat` pushes
`agentdomain.HeartbeatEvent` through the UI notifier every 10s
(`constants.UIHeartbeatInterval`) and stops on context cancel. It is the
one clock feeding Update, in line with #700's no-self-rearming-ticks
design; components that need periodic freshness subscribe to it.
Handlers only return a `tea.Cmd`, no inline I/O.
- `RenderInputField` takes an `iconColor`; only the leading `⎇` rune is
colored, applied after truncation so long branch names and the PR number
behave as before.
- Warning color = uncommitted changes (wins), accent = unpushed commits
or no upstream, default status color = clean.
- Not a repo: `git status` fails, zero event returned, `rev-list`
skipped, nothing rendered. `git_branch: false` skips the git process
entirely.
- Tests in `input_view_test.go`, `provider_test.go`,
`cmd/chat/heartbeat_test.go`; docs updated.
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

No open projects
Status: Done

Development

Successfully merging this pull request may close these issues.

[TASK] Single event-loop ingress: route every background→TUI update through one notifier, remove all self-rescheduling pollers

1 participant