Skip to content

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

Closed

Description

@edenreich

Summary

Today, several independent self-rescheduling loops each poke the single Bubble Tea Update loop their own way — a forever 2 Hz queue-drain tea.Tick, a 500 ms agent-status poll, a re-arming MCP channel-wait Cmd, 1 s git/filesystem polls in the diff/explorer views, and a bespoke computer-use forwarder goroutine. They are independently wired, independently tested, and easy to get subtly wrong (the queue-drain ticker is the one that caused the now-fixed /model flicker — #684 / 208f65a8).

Replace all of them with one injected ingress: a tea-free domain.UINotifier backed by (*tea.Program).Send, called by every background producer. The Update loop becomes purely reactive — it renders only when a real event arrives. Because there is now exactly one ingress, we instrument it in exactly one place to log when a handler or a background job runs too long.

Goals: one way to add work to the loop (today queue-drain, tomorrow anything), least friction, easy to reason about and test, and rendering aligned with Bubble Tea best practice (push via program.Send; render on change, not on a clock). Pre-stable: clean break, no compatibility shims.

This reframes the issue from its original "remove the 500 ms DrainQueueTickEvent ticker to fix the /model flicker" scope. The flicker is already resolved (the tick event is excluded from the UI-component churn), but the ticker still re-arms forever at 2 Hz, and it is only one of several self-rescheduling loops. The flicker is now a non-regression guard, not the headline.

Current state — inventory of "multiple loops" feeding the single Update

# Ingress Where Pattern Fate
1 Queue-drain internal/app/chat.go:412 + internal/handlers/chat_handler.go:486-498 forever tea.Tick(500ms) → DrainQueueTickEvent, always re-arms event-driven
2 Agent-status chat.go:404-407 + chat_handler.go:455-472 bounded poll: time.Sleep(500ms) Cmd, self-terminates when ready push from readiness mutation
3 MCP status chat.go:416-425,471-476 waitForMCPStatusUpdate channel-wait Cmd, re-arms via mcpStatusUpdateWithChannel push from MCP monitor
4 /tasks + rows internal/ui/components/task_management_view.go:134 (GetBackgroundTasks() at render); conversation_view.go:1115/1123 pull at render + one-shot removal ticks; stale while modal open push on job status change
5 File explorer internal/ui/components/file_explorer.go:430-434 tickCmd() forever tea.Tick(1s), re-reads expanded dirs refresh off in-loop tool/bash events + manual key
6 Diff viewer internal/ui/components/diff_viewer.go:1024-1028 tickCmd() forever tea.Tick(1s), re-polls git staged/unstaged refresh off in-loop tool/bash events + manual key
7 Computer-use cmd/chat.go:421-442 forwardControlEventsToBubbleTea → program.Send (×2: lines 431,435) goroutine bridge — already the right push pattern, but bespoke fold onto the one notifier

The only correct template already in the tree is #7 (a goroutine that calls program.Send). The bubbletea-v2 guidance endorses exactly this: "From outside the loop, push messages with program.Send." Everything else reinvented a re-arming timer instead.

Stays as-is (not pollers): one-shot pure-UI deferrals — todo auto-collapse (todo_box_view.go:325, 3 s) and background-row removal (conversation_view.go:1475/1611, 5 s). They fire once, don't re-arm, and carry no background work; tea.Tick is the idiomatic tool for a one-shot delay. The agent state-machine CheckingQueue (internal/agent/states/checking_queue.go) is the in-turn drain (a different layer) and is unchanged.

Design — one ingress

internal/domain (tea-free; keeps services free of any tea import):

// UINotifier delivers a background-originated event to the single Bubble Tea
// Update loop. The only implementation wraps (*tea.Program).Send (cmd/chat.go);
// services depend on this interface, never on bubbletea.
type UINotifier interface{ Notify(event any) }

// NoopUINotifier is the useful zero value: producers can always call Notify
// even before the program exists or after shutdown (no nil checks).
type NoopUINotifier struct{}
func (NoopUINotifier) Notify(any) {}

cmd/chat.go — the only place program.Send is ever called:

program := tea.NewProgram(application)
container.SetUINotifier(uiNotifier{program}) // wraps program.Send; replaces the Noop default

internal/container — holds a UINotifier (defaults to NoopUINotifier), adds SetUINotifier(UINotifier), and injects it into every background producer at construction. The Update loop stays single-threaded, so Notify-then-handle is race-free; program.Send is goroutine-safe and no-ops cleanly on shutdown.

Per-source migration (delete every self-rescheduler)

  1. Queue-drain — delete DrainQueueTickEvent, DrainQueueTickInterval (internal/constants/timing.go:12), the Init tick (chat.go:412), and the self-reschedule (chat_handler.go:486). Add domain.DrainQueueEvent{}, pushed from three event sources, each at most once:

    • background-job completion — internal/services/jobs/supervisor.go enqueue() (already tea-free) calls the injected notifier;
    • turn completion — chat_handler.go HandleChatCompleteEvent when terminal (Cancelled || len(ToolCalls)==0) and the queue is non-empty;
    • re-entering chat — chat.go Update on transition into ViewStateChat with a non-empty queue.

    HandleDrainQueueEvent becomes gate-only: view==Chat && !IsAgentBusy() && !IsEmpty() → SetChatPending() + startChatCompletion(), else return nil (regression guard against re-introducing a ticker).

  2. Agent-status — delete the Init tick (chat.go:404) and the time.Sleep re-arm (chat_handler.go:468-471). Push AgentStatusUpdateEvent{} from the readiness-mutation site (internal/domain/state.go:1385, where ReadyAgents++) via the notifier — the state is already updated there; the poll was just observing it.

  3. MCP status — delete waitForMCPStatusUpdate and mcpStatusUpdateWithChannel (chat.go:431-451,471-476). Have the MCP monitor (internal/services/mcp_manager.go StartMonitoring) push MCPServerStatusUpdateEvent via the notifier instead of returning a channel the app re-arms.

  4. /tasks + inline rows — add domain.BackgroundTasksChangedEvent{}, pushed by the supervisor whenever a job's status changes (submit/signal/finish). /tasks (task_management_view.go) and the conversation rows (conversation_view.go) re-render on that event instead of only on incidental re-renders or removal ticks. (One-shot removal-after-delay ticks may remain — they are deferred UI, not polling.)

  5. File explorer / diff viewer — delete the 1 s tickCmd() re-arms (file_explorer.go:430, diff_viewer.go:1024). Refresh these views from signals already in the loop instead of a clock: re-read on view-entry, and on ToolExecutionCompletedEvent / BashCommandCompletedEvent (the agent's own writes / git commands are exactly what change the tree and the staged/unstaged diff), plus a manual refresh key. No ticker, no new notifier events, and no fsnotify in the TUI — that dependency stays only in the scheduler. Trade-off: edits made in a separate terminal while the view is open refresh on the next interaction / manual refresh rather than within 1 s — acceptable for an agent tool, where the changes that matter pass through the loop anyway.

  6. Computer-use — route the EventBridge→TUI leg of forwardControlEventsToBubbleTea (cmd/chat.go:421-442) through the same notifier so program.Send lives in exactly one place. EventBridge stays for the macOS floating-window multicast (its real purpose, internal/domain/interfaces.go:242) — that is a separate concern, not folded into the queue/UI ingress.

Observability (logs only)

One ingress ⇒ instrument once:

  • Slow handler — wrap the single Update dispatch (internal/app/chat.go) with a duration measurement; logger.Warn("slow update", "event", fmt.Sprintf("%T", msg), "ms", d) when it exceeds SlowUpdateThreshold. A slow handler in the single-threaded loop is a UI freeze, so this is the highest-value signal.
  • Long-running job — add a startedAt to the supervisor's supervised record; in the existing cleanup sweep (supervisor.Start(interval, …)) warn once per job when elapsed > JobRunningLongThreshold: logger.Warn("job running long", "kind", k, "label", l, "elapsed_s", n).
  • New constants in internal/constants/timing.go: SlowUpdateThreshold, JobRunningLongThreshold. (zap is the repo logger.) No /tasks UI change.

Out of scope / unchanged

  • One-shot, self-terminating, pure-UI tea.Tick deferrals (todo auto-collapse, row removal) — they don't re-arm and inject no background work.
  • Agent state-machine CheckingQueue (in-turn queue drain) — different layer, untouched.
  • EventBridge floating-window multicast semantics.

Notes

  • Adding UINotifier to internal/domain/interfaces.go triggers counterfeiter mock regen (task mocks:generate); add a counterfeiter line under mocks:generate in Taskfile.yml if a fake is needed (handler/producer tests can also use a trivial func-backed stub). (This corrects the original framing's "no counterfeiter regeneration" note.)
  • no docs ticket: internal-only refactor.

Acceptance Criteria

  • program.Send is called in exactly one place (the UINotifier impl in cmd/chat.go); grep proves it.
  • Zero self-rescheduling pollers / re-arming wait-Cmds remain. Deleted: queue-drain ticker (+ DrainQueueTickEvent, DrainQueueTickInterval), agent-status poll, waitForMCPStatusUpdate/mcpStatusUpdateWithChannel, file_explorer.tickCmd, diff_viewer.tickCmd. (Only one-shot, non-re-arming UI deferrals survive — list them in the PR.)
  • Queued work still drains reliably: background-job completion while idle on chat; message/job queued while busy (drains at turn end); job completed while in a modal (drains on return to chat).
  • HandleDrainQueueEvent is gate-only and returns nil in every no-op branch; asserted in internal/handlers/chat_handler_drain_test.go (renamed from the tick test).
  • Agent-status, MCP-status, and /tasks/rows update on real change pushed through the notifier — no clock. /tasks refreshes live while open when a background job changes state.
  • Explorer and diff views refresh off in-loop ToolExecutionCompletedEvent / BashCommandCompletedEvent (+ view-entry + a manual refresh key); the 1 s tickCmd polls are deleted and no fsnotify is added to the TUI.
  • New tests: supervisor fires the notifier on enqueue and on status change; turn-completion emits exactly one DrainQueueEvent on terminal+non-empty and none on non-terminal/empty; readiness mutation pushes AgentStatusUpdateEvent.
  • Observability: a handler exceeding SlowUpdateThreshold and a job exceeding JobRunningLongThreshold each emit a single logger.Warn (asserted with an observed zap core).
  • task build, task test, task lint, task fmt green; go test -race clean on touched packages.

Verification

  1. flox activate -- task build && flox activate -- task test && flox activate -- task lint && flox activate -- task fmt; flox activate -- go test -race ./internal/handlers/... ./internal/services/jobs/... ./internal/app/....
  2. Run ./infer chat: open /model and idle — confirm no periodic re-render (no recurring Update for domain.* events in debug logs; CPU at rest).
  3. Trigger a background job (e.g. a background shell), stay idle on chat → it drains immediately on completion; queue a message while the agent is busy → drains at turn end; complete a job while /model is open → drains on return to chat.
  4. Open /tasks while a job is running → row updates live as status changes.
  5. With the diff/explorer view open, have the agent edit a file / run git add → the view refreshes from the tool/bash event (no 1 s poll); an edit from a separate terminal refreshes on next interaction or the manual refresh key.
  6. Force a slow handler (temporary time.Sleep) and a long job → confirm the slow update / job running long warn logs fire once each.

Activity

  1. added
    refactor
    on Jun 30, 2026
  2. added theissue type on Jun 30, 2026
  3. moved this to Todo in 2026on Jun 30, 2026
  4. changed the title [-][TASK] Refactor queue-drain to an event-driven single loop (fixes /model flicker regression)[/-] [+][TASK] Single event-loop ingress: route every background→TUI update through one notifier, remove all self-rescheduling pollers[/+] on Jun 30, 2026
  5. moved this from Todo to QA in 2026on Jun 30, 2026
  6. moved this from QA to Done in 2026on Jun 30, 2026
  7. inference-gateway-releaser commented on Jun 30, 2026

    @inference-gateway-releaser
    Contributor

    🎉 This issue has been resolved in version 0.126.0 🎉

    The release is available on:

    Your semantic-release bot 📦🚀

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    refactorreleased

    Type

    Projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions