End-to-end: what happens when a Claude Code hook fires, when a transcript file gets a new line, or when you toggle a tray menu item.
Input sources and data flow
flowchart LR
CC["Claude Code<br/>hook forwards raw payload"]
TR["transcript<br/><session>.jsonl"]
UI["Svelte UI"]
CFG["config.json"]
PEER["peer dashboard<br/>(another device)"]
AX["axum (Rust) :9077"]
SYNC["axum (Rust) :9078<br/>bearer-gated sync"]
CMD["commands.rs"]
CW["config_watcher"]
AS[("AppState<br/>sessions: Mutex<Vec<AgentSession>><br/>remote: Mutex<BTreeMap<device, RemoteDevice>>")]
NATIVE["Window / TrayIcon<br/>native APIs"]
SV["Svelte (listen)"]
TT["terminal tab title<br/>(Win32 console / tty)<br/>+ agwinterm / agterm context line"]
CC -->|"POST /api/event"| AX
AX -->|"adapters::dispatch -> apply_set / remove_session"| AS
TR -->|"notify::Event"| AS
PEER -->|"POST /api/sync"| SYNC
SYNC -->|"sync::ingest -> remote map"| AS
PEER -->|"POST /api/sync/attention"| SYNC
SYNC -->|"attention::observe -> local row"| AS
PEER -->|"POST /api/sync/attach"| SYNC
SYNC -->|"attach_started -> terminal tab"| TT
AS -->|"pusher: local sessions"| PEER
UI -->|"#[tauri::command]"| CMD
CMD -->|"attention::observe"| AS
CMD --> NATIVE
CFG -->|"file change event"| CW
CW -->|"emit(config_updated)"| SV
AS -->|"app.emit(sessions_updated)"| SV
AS -->|"terminal_title::sync (local only)"| TT
Hook events reach local session state through state::apply_set, which enforces the sticky-label rules, the working-time accumulator and the task boundary in one place regardless of origin. The other writers each own one narrow transition and never choose a label: the watcher’s promotion to working and its Esc-cancel revert, the WAIT backstop, row removal, a restart’s restore, and a subagent’s permission prompt, whose release writes back what the main agent’s own events left. Remote sessions arrive pre-enriched from the device that ran them (its own apply_set already applied those rules) and live in the separate remote map — commands::resolved_snapshot is the single point where the two sets combine. Anything a person looks at goes one step further, through commands::display_snapshot, which is that merge plus commands::stamp_read: the read flag saying whether a finished row has already been looked at. Only the frontend and the terminal titles ask for it, so it never reaches /api/agents. It does reach a peer, on the sync push and nowhere else, so one row reads the same on every dashboard — and the stamp behind it stays on the machine that made it. stamp_read decides a local row’s verdict outright and ORs a synced row’s: that row arrives with its origin’s verdict on it (sync::ingest, from SessionSync::attended), and this machine may additionally have observed a read of its own — an SSH or tmux tab here rendering that agent, told apart by terminal_title::REMOTE_BADGE and reported back over POST /api/sync/attention. The pushed half is never recomputed here: re-deriving it would compare the origin’s stamp against a content_at whose dialog term is this device’s lagging copy, which answers “read” for an answer the origin still calls unread — the one direction the feature refuses. The same step’s other arm, commands::forget_read, is how a dashboard whose user turned attention_tracking off declines to draw either kind. Whichever device holds the row is authoritative for it, exactly as it is for the row’s status. The same step stamps each row’s row_line, task_lines and dialog_messages (AgentSession::row_line / task_lines / dialog_messages), the text of its task line, of its hover tooltip and of the agent messages its History window shows, so what a row says is decided in Rust and the frontend only draws it.
Path 1 — Hook POSTs event
- Claude Code fires a lifecycle event (
UserPromptSubmit,Stop, etc.). The hook command spawnspython claude_hook.pyand pipes the event payload to stdin. claude_hook.pyreads the payload, extractshook_event_name, and POSTs{client: "claude", event: <name>, payload: <verbatim>, console_pids: [...], agent_pid: <pid>}to$TAURI_DASHBOARD_URL/api/event(defaulthttp://127.0.0.1:9077/api/event). The hook does no classification or config reading — both fields come off one bounded walk up its own ancestor chain, which stops at the owning Claude Code process.console_pidsis pure environment gathering (that chain, plus the processes attached to its console on Windows, used later for terminal tab titles);agent_pidis theclaude/claude.exeimage the walk stopped on, used later to detect a session that exited without aSessionEnd. The bound keeps the walk inside its own session, but the walk is no longer how a tab is found — see step 9.POST /api/eventhits the axum handler. Origin guard rejects any request carrying anOriginheader.adapters::dispatchroutes byclient;adapters::claude::dispatchmatches oneventand produces anAdapterOutput:Set { input, transcript_path, reason, subagent, agent_message },SubagentStopped { id, agent_id },ModelSwitched { id, model },Clear { id },Boundary { id }orIgnore. All chat-id derivation, prompt cleaning, and transcript question-detection happen here.- For
Set, a prompt another agent wrote (agent_message, the envelopepeer_message::parse_agent_messageread) is settled first:prompt_origin::for_arrivallooks up the sender’s own task, or falls back to the message’s first line, and puts it on the input asdelegated_taskormessage_line, loggeddecision = "prompt_origin". Thenlabel_policy::selectdecides the label and the task,original_promptwith thedelegated_task/message_linedescribing it. - Session-boundary marking and row membership. Claude
/clearfiresSessionEnd→SessionStart; the chat_id (derived from cwd) is unchanged but the JSONL is a new file. The handler covers this in two places: (a) onClear,commands::remove_session→AppState::take_sessionappends aSeparatorto the in-memory dialog, persists it viaPromptHistoryStore, and drops the session — atomically, under one lock — the followingSessionStartthen takes the “new” branch inapply_setand restores a dialog that already ends with the separator, so the upcoming user entry lands after it. The sameremove_sessionbacks the liveness reaper (Path 6), both reaching it throughcommands::apply_departure, so the two removal paths can’t diverge. A chat_id is cwd-derived, so every Claude Code instance in that directory addresses the same row — a--fork-session --resumemigration leaves two resident, and so does a short-lived probe started there. So the handler admits every event’s sender as a member of the row (membership::Members) and lets only the row’s main change it: another member’s event is recorded, loggeddecision = "member_event", and not applied. A prompt does not change that: a headlessclaude -prun from inside a session firesSessionStart, a prompt,StopandSessionEndfrom a second process, and all four are recorded without touching the row. The main changes only when a row’s first member founds it, when exactly one member remains, and when the main leaves: with one member left the row passes to that member, and with several it has no main, each member driving it until only one is left. Either way the row settlesdonebehind a separator, since what it showed was the departed session’s. The row is chosen pid first, so a process already in a row stays in it across a/clearafter acd. An end signal is matched to its member bysession_idrather than the hook’sagent_pid, because a shutting-down session resolves no liveclaudeancestor and so reports no pid. A non-main member’s end changes nothing the row shows, and an end from a session that is no member of a row that has members is refused, loggeddecision = "end_unmatched". Both hooks are async, so theSessionStartcan reach the server first: the member then moves to the new session id, the start removes the row on the end’s behalf (loggedsession_clear), and the late end, matching the member’s previous session id, logsdecision = "clear_superseded". Each hook event is applied under a per-row lock (commands::RowLocks), which the reaper (Path 6) also takes, so one event’s writes across the row’s stores land as a unit. (b)PreCompactemitsBoundary, which appends a separator without ending the session — context compaction is a history boundary but not a new session. Each separator carries astate::BoundaryKind(clear/compact/ended) saying which of the three produced it, because only a/clearlicenses the cleanidlea laterresumemay claim (see Classification → Session starts). AppState::apply_setruns: if status transitions out ofworking, it accumulates elapsed time intoworking_accumulated_ms; if the transition is a task boundary (done/idle/working/waiting→working), it zeroes the accumulator; otherwise existing timers are preserved. A subagent’sPermissionRequesttakesAppState::open_subagent_promptinstead — see Path 8.- If
transcript_pathis present,WatcherRegistry::startspawns a per-session tokio task with anotify::RecommendedWatcheron the transcript’s parent directory. Its first read grafts the transcript’s last reply onto the row only where the row had no watcher (Graft::IfFresh); a change of main restarts it withGraft::Never, so the new main’s earlier reply is not added to a row that was just handed over. emit_sessions_updatedbroadcasts the fresh snapshot on thesessions_updatedevent, with the ticket it was taken under, so the frontend drops a payload older than one it has already shown. The same emit reconciles terminal tab titles (terminal_title::sync): every session whose status or display name changed gets its circle re-pushed onto its terminal. The target comes fromsession_registry, which matches the row’s cwd against Claude Code’s own list of live sessions and returns the pid of the one that owns a terminal there. The process tree can’t answer this — a session Claude Code runs in the background executes inside a detached daemon that hosts several conversations at once, so its ancestors lead to whichever terminal spawned the daemon rather than to its own tab. Only an unambiguous cwd resolves, and the pid must still be a live Claude Code process; anything else falls back to the hook’sconsole_pids, and a row with no answer at all is simply left untitled. A write that fails — no console would attach, or one attached and refused the title — is retried on its own, by a background thread that runsterminal_title::syncalone, not a whole emit, over a fresh snapshot on a doubling 1 s to 60 s backoff, giving up after ten attempts until the row’s next state change. On a terminal whose sessions carry a field of their own beside the title — agwinterm’s context line on Windows, agterm’s on macOS — the emit also hands each row’s task toterminals::labelsthroughterminal_title::request_labels, whose worker thread writes it there and clears it when the row leaves. Synced rows are handed over too, for the⇄tab rendering each one, so the remote emit makes the same call. The fitted length is the terminal’s own:LabelTarget::budgetnames the unit as well as the number, since agwinterm’s 200 UTF-16 units are a display cap while agterm’s 256 UTF-8 bytes are enforced and an over-long write is refused outright. The same worker pass tints each session’s sidebar row on agterm (terminals::tints, agterm 0.39.0 or newer) from this machine’sconfig.tab_tints: a session whose row’s model is off the defaultenv.ANTHROPIC_MODELin Claude Code’s user settings takes themodeltint, a⇄tab otherwise takes theremotetint, and any other agent tab is cleared.- The Svelte frontend’s
listencallback replaces its$statesessions array, Svelte’s reactivity re-renders the list, the row updates within a frame.SessionList.sveltefilters out local rows that have beenidlefor longer thanconfig.clean_hide_after_ms(nullor0keeps them all) — a clean row has nothing to come back to, so after a while it stops taking space from the rows that want something. The filter runs here because it needs the widget’s own ticking clock to drop a row on time, and because the snapshot it would otherwise filter is the one the terminal titles are written from. Hiding is display-only: the row stays inAppState, keeps syncing, keeps its tab title, and still answers on/api/agents.
Path 2 — Transcript-driven updates
- The watcher task from Path 1 is listening to filesystem events on the transcript’s parent directory.
- Claude Code writes a new JSONL line to the transcript.
notifyfires aModifyevent; the watcher filters to events matching the exact transcript path. - The task sends a drain signal over an mpsc channel to itself. A 150ms debouncer collapses bursts (editors / streaming writes often produce several events per logical change).
drainreads the new bytes from the tracked byte offset, joins with leftover content from the previous drain, and splits into complete JSONL lines + a new leftover for the next call.infer_statewalks the new lines newest-first, skipping non-conversational entries (metadata, sidechains, synthetic errors). An unansweredAskUserQuestion/ExitPlanModecall decides no state: its line is written while the dialog is still on screen, wherePreToolUsehas already marked the rowblocked. Returns the currentstate, latestmodel, latest summed input-side token count, and the latest assistant text block.apply_watcher_updatemerges the inference into the session as a promote toworkingonly: when the transcript shows the main turn resumed (a tool call or its result, or a fresh user prompt), such as the user answering anAskUserQuestion, it carries the row back toworking; it also updatesmodelandinput_tokens. It never rolls a session todone,idle,blocked,waiting, orerror— those come from lifecycle hooks and the adapter’sStop-time classification, which stay authoritative. This avoids the race where the watcher reads a trailing assistant text as “done” while a fresh turn is already in flight.infer_stateskipssystemand sidechain (Task subagent / background-agent) entries when resolving state, so background work can’t flip awaitingrow back toworking. Thewaitingstate itself is set up front by the adapter’sclassify_stopfrom the hook’sbackground_tasksarray (see the classification step andadapters/claude.rs), not inferred here — and the old too-early-Stopcorrection machinery (aflushed_turn_verdictre-judge plus thepromote_done_to_blocked/demote_scanned_blocked_to_donecorrections and thestatus_from_transcript_scanflag) was removed onceStopbegan carryinglast_assistant_message+background_tasksand could settle the question-vs-done verdict authoritatively atStoptime. The watcher also recognizes the[Request interrupted by user]marker an Esc-cancel writes:infer_stateflags the turnendedandapply_and_emitcallsstate::revert_cancelled_turnto carry the row back to its pre-turn status, fromworkingor from ablockeddialog the Esc dismissed. If the chunk produced assistant text,AppState::apply_text_entriesreplaces the latest Assistant entry within the current turn (appends if none exists yet) andPromptHistoryStorepersists the change. The watcher owns dialog text because Claude Code’sStophook fires before the final assistant turn is flushed to JSONL — reading from the hook records the prior turn’s text.- If anything changed, the session’s
updatedtimestamp refreshes andemit_sessions_updatedfires exactly as in Path 1.
The initial drain on watcher startup suppresses the inferred state AND the latest assistant text — a resume would otherwise snap to a stale “done” from the prior turn and duplicate the last assistant entry already in the restored dialog. Model and token counts still surface.
Tauri commands target native window/tray APIs (hide_window, show_window, quit_app); session state is only read from the frontend (get_sessions) — every local-session mutation arrives through the HTTP event path above, and remote sessions only through the sync path below.
Path 3 — Tray toggles
- User clicks “Always on top” in the tray menu.
mudafires aMenuEventwith the item’s id. - The tray handler calls
window.set_always_on_top(new_state)directly on the native window — no IPC round-trip. ConfigState::with_mutflipsalways_on_topin the managed config.ConfigState::save_to_diskwritesconfig.json.- The tray’s
CheckMenuItem::set_checkedsyncs the visual checkmark. emit_config_updatedbroadcasts the new config. The frontend picks up the updated color thresholds, token-window lookup, and (future-proof) any UI-driving fields.
Path 4 — External config edits
- User edits
config.jsondirectly (via the “Open config/logs location” tray shortcut or any editor). config_watcher— anotify::RecommendedWatcheron the config directory — receives aModifyevent.- The 150ms debouncer waits for any rename-based atomic writes to settle.
Config::load_or_defaultre-reads the file. Serde serializes both the new and current in-memory configs to JSON strings; if they’re byte-identical, the reload is skipped — this is how our own tray writes avoid re-triggering the reload path.apply_config_to_windowapplies runtime-safe changes (always-on-top, saved window position). Port changes are intentionally ignored on hot-reload and require a restart.config_updatedis emitted and the tray check marks re-sync.
Path 5 — Peer sync (multi-device)
Dashboards on other devices push their sessions here, and this dashboard pushes its own to them — see Features → multi-device sync for the user-facing behavior and HTTP API → sync API for the wire contract.
Outbound: every emit_sessions_updated pokes the SyncDirty notify, as do a fresh usage reading, a project rename and a dev server announced or forgotten; the pusher task debounces 300ms (a 30s heartbeat fires regardless) and POSTs to each config.sync.peers entry a full metadata snapshot of the local sessions — with each session’s dialog reduced to a dialog_tip (its newest timestamp), the usage timeline to a device-wide usage_tip and the token records to a device-wide token_tip, alongside this machine’s registry_sessions (Claude Code’s own list of live local sessions, which the receiver’s roster has no other way to learn), the projects it renames, and its dev_servers that carry a row, which the receiver shows on the ⇄ tab rendering that row. No dialog, usage or token content rides the push. The body therefore depends only on local data: it is byte-identical for every peer on every cycle, so there is no per-peer bookkeeping to keep, nothing to chunk or drain, and a failed push (offline peer) costs a retry and nothing else — the next one carries the same snapshot and the receiver re-derives what it needs. Received remote sessions are never re-broadcast — and remote-driven changes deliberately skip the poke (see inbound below): content can’t echo, but the poke itself would, ping-ponging pushes between two devices at the debounce period.
Two other things leave this device for a peer, each on its own rather than on the push. sync::report_attention fires POST /api/sync/attention when attention::observe credits a read of a synced row — a tab here reaching that agent over SSH or tmux. And on the machine running the remote-session holder, sync::offer_tab fires POST /api/sync/attach when a message reaches a holder session that no terminal on another machine shows, a relayed one from that peer’s agent or a local SendMessage from a holder session the peer watches; the receiver, once sync.peer_identity attests the sender, opens a background ⇄ tab on it through http_server::attach_started, unless a tab there already attaches. Both are fire-and-forget with no retry: a lost report only leaves the row showing on the machine that owns it, and a lost tab request leaves the session reachable through the attach picker.
Inbound: POST /api/sync (bearer-gated, port sync.listen_port) namespaces incoming ids to {device}/{raw_id}, stamps origin, wholesale-replaces that device’s metadata (absence = removal), carries over the dialog already accumulated for each session, and stores the sender’s attended verdict on the row’s read flag. That wholesale replace is what makes the verdict need no bookkeeping: the sender re-advertises it every cycle, so its own teardown, its feature switch and a fresh turn on the row all arrive as the next push. Whether this dashboard draws it is a separate decision, taken on the display path where the same attention_tracking switch already decides the local half. It then compares every advertised tip against what it actually holds and pulls the difference itself: GET /api/sync/dialog?id=&since=<newest held> per lagging session, and GET /api/sync/usage?since=<newest held> when the usage tip is ahead, each merged via sync::merge_synced_dialog / RemoteUsageStore::merge_device. The since is derived from the stored entries at the moment of asking rather than tracked alongside them, so it cannot drift, and a dropped fetch is self-correcting — nothing recorded that the range arrived, so the next push re-advertises the same tip and it is requested again. Then emit_sessions_updated_remote re-emits — without the SyncDirty poke or the terminal-title pass of Path 1’s emit, so a received push can never trigger a push back, but with the label hand-off, so each push refreshes the context line of the ⇄ tab rendering a synced row and withdraws it once that row is reaped; each landed pull re-emits the same way. A pull that turns out to carry nothing this device lacks neither rewrites the device file nor re-emits — the file is rewritten whole and the emit carries every dialog on it, and finding nothing new is the ordinary outcome of both a re-advertised range and the catch-up below. A reaper drops devices silent for 90s (also emitting the remote variant).
Accumulated remote dialogs are persisted one file per device (remote_history/<device>.json in the app data dir, mirroring prompt_history.json for local sessions) and re-seeded at ingest, so a dashboard restart keeps them. When the history window opens a remote session, open_history additionally fires a catch-up against the origin for its full dialog rather than the incremental range — the merge places every entry at its own timestamp, so re-sending the overlap costs nothing, and asking whole covers what a since structurally cannot: a gap below the newest entry already held, which no incremental range reaches however it got there. The fetch is bracketed in history_loading events, which the history window renders as a loading hint until the catch-up lands or fails. Notifications, persistence, terminal titles, and the watcher never see remote sessions — they read AppState::sessions directly, and remote rows live only in the remote map.
Pulled usage records are merged per device into RemoteUsageStore (remote_usage/<device>.json in the app data dir), which commands::merged_usage_records unions with the local history when building three parts of the Work intensity chart: the quota figures beside it, the colour of its bars (the weekly limit left during each slot) and the lines marking each weekly limit reset — the 5h/7d counter is account-wide, so a peer’s polls fill the windows this device was closed. The bars’ heights come from the token history, not from here. A non-empty merge also re-emits usage_limits_updated, so an open intensity window re-fetches the merged chart live.
Path 6 — Exited-session reaper
Claude Code’s SessionEnd hook (Path 1’s Clear) fires reliably on /clear but not on exit / Ctrl-D / closing the terminal, so a session quit that way never reaches the dashboard and its row strands — often in working if the quit happened mid-turn. liveness_reaper (src-tauri/src/liveness_reaper.rs) is the backstop.
- On every event, the hook resolves
agent_pid— the owning Claude process, picked from its ancestor chain by image name — andmembership::Memberskeys the session’s place in its row by that pid (Path 1, step 6). - A 2 s-tick task takes one process enumeration (
liveness::process_images— a Toolhelp32 snapshot on Windows,pson macOS) and checks every pid-keyed member of every row, including a member inside a/cleargap whose row is momentarily gone. Liveness is image-confirmed, so pid reuse can’t read as alive and an elevated Claude isn’t misread as dead. A member keyed by session id, because its hook resolved no pid, is never judged. - A member is dropped only after its pid reads dead for
DEAD_STREAK_TO_REAPconsecutive ticks, counted per (row, pid) pair — a still-alive (merely slow) session keeps its process alive and is never dropped. The drop holds the row’sRowLocksentry and removes only the pids judged dead, so a session that joined the row since the last read keeps it. It then goes through the samecommands::apply_departureas Path 1’sSessionEnd: the last member gone removes the row throughcommands::remove_session(loggeddecision = "reap_exited"), the death of the session whose state the row shows (the main, or the last writer while there is no main) settles the rowdonebehind a separator and passes it to the remaining member where only one is left, and any other member’s death logs onlymember_leave. Thereap_exited_sessionsconfig flag (default on) gates only removing the row; dead members are dropped either way. Cross-platform.
Path 7 — Startup session restore
session_restore::spawnstarts a thread atReady. It retries every 3 s until one pass gets an answer from both sources, then exits — the concern is a startup race (the dashboard and the terminal both start at login, in no fixed order), not a recurring gap, so nothing polls afterwards. Bounded at 20 attempts, thenwarns. Gated byrestore_sessions, and inert whereterminals::for_platformreturnsNone, which is Linux only.SessionRegistry::live_sessionsanswers which agents are alive here — pid-backed and image-confirmed. Not the terminal: a tab outlives the agent in it, so a tab-driven restore would resurrect rows for sessions that have exited.TerminalAdapter::sessionsanswers what each session is showing: on macOS the tabs agterm reports, on Windows each session’s own console object, read per pid withterminal_title::read_titleoversession_registry::live_records, since on Windows the title lives on the console and the terminal only renders it.terminal_title::parse_titlereads back what this dashboard wrote into that glyph — the only durable copy of a row’s status, and a (status, read) pair rather than a status alone. Titles are written fromcommands::display_snapshot, which runscommands::stamp_readfirst, so 🟢 comes back as finished-and-unread and ⚪ as finished-and-read; ⚫ comes back as a clean row, whichidle_closecan then close on schedule. A tab with no title we recognize is skipped, which is also the anti-resurrection guard:terminal_title::syncblanks the tab when a row is removed, except inside a/cleargap, where the session lives on and its next start recreates the row. Withterminal_titlesoff the tabs are not read at all, since nothing has been writing or blanking them.session_restore::planpairs them.Working/Waitingsurvive only where the registry independently reportsBusy, else they degrade toDone— the evidence-free landing place, which claims only that a turn ended, and never toIdle, which a stale glyph cannot support.Idleitself survives only where the registry reports the session idle, or reports it busy with no prompt in its transcript since it went busy (a!shell command, which fires no hook; the row’s clock then dates from its last transcript entry before the command, so the command does not restartidle_close’s hour. A session resumed CLEAN usually writes no transcript entry at the resume, so for one of those that entry is the cleared conversation’s last line, possibly days old, andidle_closecan close the session on its first tick after the restart), and degrades toDoneotherwise.state_entered_atcomes from the registry’sstatusUpdatedAt, or for a clean row from the later of that andupdatedAt, since a/clearmoves only the latter, so the row’s age is real rather than fabricated. One case skips the title: a session whose registrystartedAtis later than the previous run’s last heartbeat (alive_stamp::AliveStamp,alive_stamp.json, rewritten every 30 s) fired itsSessionStartat nothing, so it is restored as that event would have left it (replayed_status:Workingwhere the registry reports busy,Idlewhere the row’s persisted dialog ends at a/clear, or where the row has no persisted dialog and the session id is unanchored, elseDone; an unanchored id alone is not enough, since everySessionEndforgets the anchor and a--continueafter one would otherwise come back CLEAN), whatever its tab shows and before the terminal has answered. This is the only restore that works after a Windows reboot, which destroys every console and the title on it.AppState::restore_rowcreates the row under one lock, leaving an existing one untouched — the axum server is already accepting hook events by then, andapply_set’s existing-row branch would overwrite a live status. Both paths build the row through the sharedstate::new_session. Dialog, prompt and task clock come fromPromptHistoryStore.- Every record the registry collapsed into the row is seeded as a member (
Members::seed, under the row’sRowLocksentry together withrestore_row); without this a restored row is unreapable. Only a single record is made main: with two, the speaker is merely the freshest, so the row has no main, and every member drives it, until only one of them remains. The pid is registered withTerminalTitlesonly for a single record.notifications::state_observed_herethen suppresses pings for these states, which the previous process already had its chance to announce. Loggedrestore_row/restore_scan.
Path 8 — Subagent permission prompts
A subagent’s tool-permission dialog blocks the row until Claude Code records how it ended, while the main agent’s own state carries on underneath. The rules for when a prompt is released are in Classification → Subagent permission prompts.
- A subagent hits a tool-permission dialog. Its
PermissionRequestreachesPOST /api/eventas in Path 1, carrying the subagent’sagent_id, the tool’s name and input, and the main session’stranscript_path. adapters::claude::dispatchclassifies itblockedand attachesSubagentEffect::PromptOpened, which carries the tool, its input, the label and the subagents directory beside the main transcript (<transcript minus .jsonl>/subagents).- The handler calls
AppState::open_subagent_promptinstead ofapply_set: the prompt is not the main agent’s event, so it has no task boundary, sticky label or working time to update. Under one lock it mints a request id, adds the prompt to the row’ssubagent_gate, and showsblocked. The first open prompt also captures the main agent’sstatus,label,waiting_backstop_armedandstate_entered_atas the gate’s base. Loggedsubagent_prompt_open. - The main agent’s own events keep arriving meanwhile.
apply_set, the watcher’s promotion (Path 2) andrevert_cancelled_turnall run throughstate::with_base, so they move the base and the row keeps showingblocked. subagent_gate::spawnruns a 2 s tick that lists the open prompts and finds each agent’sagent-<agent_id>.jsonlunder its subagents directory. Off the async runtime and without the sessions lock, it re-reads every file that has grown and runsgate_verdictover its complete lines. When the gated call’stool_resultis there, the tick callssettle_subagent_promptsfor that one request.- Two hook exits settle prompts without the tick.
SubagentStopsettles every prompt from itsagent_id, and a mainStopwith no background work settles every prompt its own session raised, after thatStop’s ownapply_set. Removing the row drops its prompts with it. - When the last prompt settles, the base is written back as it was stored, clock included, and
emit_sessions_updatedpushes the row as in Path 1. Loggedsubagent_prompt_settled, withvianaming the exit.
The gate is held in memory only (#[serde(skip)], like status_before_working), so peers and /api/agents see the blocked it shows and never the base underneath. A restart loses it, and the restored row keeps its blocked until the main agent’s next event.
Sticky-label state machine
The (label, original_prompt) decision rules and the UI display rule live in Sticky labels. Every apply_set call funnels through src-tauri/src/label_policy.rs::select, so the rules are enforced in one place regardless of which path fired the event.