Repository navigation
Description
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
DrainQueueTickEventticker to fix the/modelflicker" 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 defaultinternal/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)
-
Queue-drain — delete
DrainQueueTickEvent,DrainQueueTickInterval(internal/constants/timing.go:12), theInittick (chat.go:412), and the self-reschedule (chat_handler.go:486). Adddomain.DrainQueueEvent{}, pushed from three event sources, each at most once:- background-job completion —
internal/services/jobs/supervisor.goenqueue()(already tea-free) calls the injected notifier; - turn completion —
chat_handler.goHandleChatCompleteEventwhen terminal (Cancelled || len(ToolCalls)==0) and the queue is non-empty; - re-entering chat —
chat.goUpdateon transition intoViewStateChatwith a non-empty queue.
HandleDrainQueueEventbecomes gate-only:view==Chat && !IsAgentBusy() && !IsEmpty()→SetChatPending()+startChatCompletion(), else returnnil(regression guard against re-introducing a ticker). - background-job completion —
-
Agent-status — delete the
Inittick (chat.go:404) and thetime.Sleepre-arm (chat_handler.go:468-471). PushAgentStatusUpdateEvent{}from the readiness-mutation site (internal/domain/state.go:1385, whereReadyAgents++) via the notifier — the state is already updated there; the poll was just observing it. -
MCP status — delete
waitForMCPStatusUpdateandmcpStatusUpdateWithChannel(chat.go:431-451,471-476). Have the MCP monitor (internal/services/mcp_manager.goStartMonitoring) pushMCPServerStatusUpdateEventvia the notifier instead of returning a channel the app re-arms. -
/tasks+ inline rows — adddomain.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.) -
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 onToolExecutionCompletedEvent/BashCommandCompletedEvent(the agent's own writes /gitcommands 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. -
Computer-use — route the EventBridge→TUI leg of
forwardControlEventsToBubbleTea(cmd/chat.go:421-442) through the same notifier soprogram.Sendlives in exactly one place.EventBridgestays 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
Updatedispatch (internal/app/chat.go) with a duration measurement;logger.Warn("slow update", "event", fmt.Sprintf("%T", msg), "ms", d)when it exceedsSlowUpdateThreshold. A slow handler in the single-threaded loop is a UI freeze, so this is the highest-value signal. - Long-running job — add a
startedAtto the supervisor'ssupervisedrecord; in the existing cleanup sweep (supervisor.Start(interval, …)) warn once per job whenelapsed > 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/tasksUI change.
Out of scope / unchanged
- One-shot, self-terminating, pure-UI
tea.Tickdeferrals (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. EventBridgefloating-window multicast semantics.
Notes
- Adding
UINotifiertointernal/domain/interfaces.gotriggers counterfeiter mock regen (task mocks:generate); add acounterfeiterline undermocks:generateinTaskfile.ymlif 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.Sendis called in exactly one place (theUINotifierimpl incmd/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).
-
HandleDrainQueueEventis gate-only and returnsnilin every no-op branch; asserted ininternal/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./tasksrefreshes 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 stickCmdpolls 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
DrainQueueEventon terminal+non-empty and none on non-terminal/empty; readiness mutation pushesAgentStatusUpdateEvent. - Observability: a handler exceeding
SlowUpdateThresholdand a job exceedingJobRunningLongThresholdeach emit a singlelogger.Warn(asserted with an observed zap core). -
task build,task test,task lint,task fmtgreen;go test -raceclean on touched packages.
Verification
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/....- Run
./infer chat: open/modeland idle — confirm no periodic re-render (no recurringUpdatefordomain.*events in debug logs; CPU at rest). - 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
/modelis open → drains on return to chat. - Open
/taskswhile a job is running → row updates live as status changes. - 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. - Force a slow handler (temporary
time.Sleep) and a long job → confirm theslow update/job running longwarn logs fire once each.
Metadata
Metadata
Assignees
Type
Projects
- StatusShow more project fieldsDone
Activity
[-][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[/+]inference-gateway-releaser commentedon Jun 30, 2026
🎉 This issue has been resolved in version 0.126.0 🎉
The release is available on:
Your semantic-release bot 📦🚀