Skip to content

Skip rebuilding the tab list on every terminal agent step when only the desktop window is listening - #51247

Merged
brennanb2025 merged 7 commits into
mainfrom
brennanb2025/hook-status-tabs-scope
Nov 28, 2026
Merged

brennanb2025 merged 7 commits into
mainfrom
brennanb2025/hook-status-tabs-scope

Conversation

@brennanb2025

@brennanb2025 brennanb2025 commented Nov 27, 2026 •

Copy link
Copy Markdown
Contributor

ELI5

Every time a terminal agent reports a step (a tool call, a prompt, a stop), the app's background process rebuilt the whole tab list for that workspace and sent it to the desktop window, even though the desktop window only uses that feed for chat tabs and already learns terminal status another way. Now the background process skips that work unless a phone or a paired desktop that actually shows terminal status is connected. Nothing changes on screen.

Files Added Deleted Net
Test 2 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​104 0 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​104
Prod 16 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​163 $\color{#cf222e}{\Huge{\mathbf{−}}}$​46 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​117

What Changed

  • The desktop window's chat-tab feed (session.tabs.subscribeAll) now says it only reads chat tabs (scope: 'agent-sessions'). Phones, paired desktops and the CLI subscribe without it and keep getting everything.
  • Terminal-pane hook status, its freshness heartbeat, and the window's own status echo (syncRendererAgentStatus) now build and send a tabs frame only when some listener reads terminal tabs. Otherwise they only owe the version bump, which the next frame built for anyone pays, so late subscribers still see the latest status. Chat-pane status (the structured-agent-session- pane keys the chat tab projection reads) still goes to every listener.
  • A suppressed bump no longer moves the frame delivery mark, so a frame already queued for that workspace is still delivered (one test covers this).
  • The sender freshness check, which ran on every publication, now reads its generation and data_version in one cached statement with a schema built once, instead of rebuilding a zod schema and re-preparing a PRAGMA each call. The peer fingerprint is hashed once per key instead of per refresh.

Why

At about 1,900 workspaces with agents reporting 20 hook events per second, this tab republish and sender pass was about a third of the main process's work on the hook path, and it sent about 14 MB per two minutes to a window that ignores the terminal part of it. Making listeners declare what they read, and producing only for listeners that need it, removes the work at its source instead of deduping after building the frame.

Linked Issue

Internal perf work; no issue.

Visual Proof

N/A: no visual or interaction change. The desktop window's terminal status and chat tabs render exactly as before; only main-process work and IPC traffic change.

Testing

  • I manually tested these changes locally
  • Automated tests added/updated, or explained why not below
  • Every added test fails without this change and avoids the test anti-patterns

Benchmark on Linux at about 1,900 workspaces, hidden window, 2,400 Claude hook events over 10 terminal panes per 120 s window, two runs each of main before and after this change:

hook window before after
main → window messages 43.6/s 23.5/s
tabs frames sent to the window ~2,400 (14 MB) 0
main time in tab republish + sender pass 633 / 819 ms 0 ms
long tasks 3.2 ms/s 0.3 ms/s
idle window unchanged unchanged

Delivery check in the same app: with an unscoped session.tabs.subscribeAll stream attached (what a phone or paired desktop uses), 60 hook events produced 60 updates for that workspace, 50 carrying tool status, identical before and after.

The added test (mobile-session-tabs-delivery.test.ts) fails if the suppressed branch moves the delivery mark again.

Performance

Less work on a hot path: each terminal agent hook no longer builds a tabs frame, runs a sender pass, or sends IPC when only the desktop window is listening (about 0.3 ms of main per hook at this scale, plus the IPC). With a phone or paired desktop connected the cost is the same as before, minus the cheaper sender freshness check. The new listener check scans the subscriber set (a handful of entries), never the workspace list.

Risk

The risky part is deciding a listener doesn't need a frame. If a client that shows terminal status subscribed with the new scope, it would miss terminal status changes until its next frame; only the desktop window's chat-tab sync sends it. Older phones and paired desktops send no scope and are unaffected; the new param is optional, so older clients' {}/null params still validate. Back out with a plain revert.

Level: Low

AI Disclosure

Review

Agent skill upstream boundary

  • Not applicable, or this change copies or mechanically translates no upstream skill-installer source, tests, fixtures, registry entries, path tables, comments, or documentation.

Notes

Ensure no issues in: Security, Cross-platform support (Linux, Windows, Mac), Remote SSH, Mobile, general backwards compatibility, performance

Checklist

  • This PR is small and focused
  • I explained what changed and why (ELI5, the user-facing before/after, the mechanism, and why over the alternatives)
  • I stated the risk: what could break, for whom, and how to back it out
  • Before/after screenshots or videos attached for UI changes, or N/A with reason
  • Self-reviewed for correctness, security, and performance
  • Cross-platform, SSH/remote, and path/shortcut impact considered (or N/A)
  • pnpm lint, pnpm typecheck, pnpm test, and pnpm build pass (or CI will cover; local preferred)

…r sender generation read

The desktop window's session.tabs.subscribeAll stream applies chat tabs only, yet every
terminal agent hook built and sent it a full tabs frame plus a sender pass. The stream now
declares scope 'agent-sessions'; terminal-pane hook status builds a frame only when a phone
or paired client (which reads terminal tabs) is listening. The sender generation read uses one
cached statement and a hoisted schema, and the peer fingerprint is hashed once per key.
@brennanb2025
brennanb2025 marked this pull request as ready for review November 28, 2026 02:05
@brennanb2025

Copy link
Copy Markdown
Contributor Author

Perf scan: PR #51247 (head f58492a, base c996106)

Diff: git diff c9961067c44...f58492a0d46, 15 production files plus one test. Flagged surfaces: hot-path (hook status → session-tabs republish, renderer status echo, sender generation read) and subscribe (session.tabs.subscribeAll scope).

Findings

None at P0/P1. The PR only removes or gates work. Nothing it touches does more work per event than base, starts work at idle, or keeps state that grows over time.

Hot-path traces

  1. Hook status row mutation → touchMobileSessionTabsForWorktree (src/main/agent-hooks/runtime/hook-status-session-tabs-republish.ts:37-53, src/main/runtime/session-tabs/restoration/mobile-session-membership.ts:64-85)
    • Trigger: each hook status mutation. At reference fleet that is 1+/s, and the author's bench ran 20/s.
    • Owner: one runtime on Electron main.
    • Work per event, base: oweVersion plus scheduleMobileSessionTabsChanged whenever any listener existed. That built a tabs frame for each listener, including the window's own chat-only renderer subscription, so every hook event built one frame. The bench measured 2,399 frames per window over 120 s.
    • Work per event, head: one or two pane keys × hasPaneStatusListeners. Each call is one startsWith, plus at most one pass over mobileSessionTabListeners (a handful of windows, mobile and CLI clients; this does not grow with worktrees or terminals). When nobody reads the pane, it calls oweUnpublishedVersion, which is O(1) and does no scheduling. Per-mutation allocation is one Map and an array of at most two entries.
    • Bound: constant per event. It does not scale with worktrees, terminals or agents.
  2. Hook status freshness → heartbeat (mobile-session-membership.ts:117-130). Same gate. When only chat-scoped listeners exist, a terminal pane no longer schedules a heartbeat timer. This is strictly less timer work.
  3. Renderer status echo, syncRendererAgentStatus (src/main/runtime/session-graph/session-window-publisher.ts:17-43)
    • Trigger: each renderer status batch.
    • Base: per touched worktree, it stored a new snapshot object and scheduled a frame, whether or not anyone read it.
    • Head: one hasTerminalStatusListeners() pass per batch (not per worktree), then an O(1) owe per worktree when no terminal-scoped listener exists. Cost is O(touched worktrees), as in base, with cheaper work per item.
  4. readAgentSenderGeneration (src/main/runtime/agent-senders/runtime-agent-sender-history-triggers.ts:93-111)
    • Base ran two sync SQLite steps on main per publication. The PRAGMA data_version statement is not cacheable (sync-database.ts:25,30 exclude ^PRAGMA), so it was re-prepared on every call. A fresh z.object was also built each time.
    • Head runs one statement through pragma_data_version. It does not start with PRAGMA and contains no *, so it is cached by SyncDatabase.prepare (sync-database.ts:108-125). The schema is built once by lazyZodSchema.
    • Net: one fewer prepare and one fewer step per call.
  5. peerFingerprint (src/main/runtime/construction/runtime-agent-projections.ts:46-56). The hash is now memoized on the key, keeping one entry. This removes a hash from every sender refresh. Retention: one string pair.

Subscribe surface

  • session.tabs.subscribeAll now accepts {scope?: 'agent-sessions'} | null | undefined (src/shared/rpc-contract/session-tabs/session-tabs-params.ts). Older mobile and CLI callers send no params and keep full-scope behavior, so no client loses updates. This matches the author's control: an unscoped listener received 60 updates for 60 events in both builds.
  • The scope is stored on the subscription object (mobile-session-tab-subscription.ts). It adds no new listener registry, map or timer. The subscription's lifetime is unchanged (removed through the existing unsubscribe and closed path in session-tabs-inventory.ts).
  • hasTerminalStatusListeners / hasPaneStatusListeners iterate the listener Set. Population: number of windows plus paired devices plus CLI subscribers, about 1-10, and this does not grow with fleet size. At 10× fleet with 20 hook events/s that is under 200 Set steps/s, which is negligible.

Retention check (oweUnpublishedVersion, mobile-session-snapshots-by-worktree.ts:48-55)

deliveryMarks can now hold a snapshot object reference instead of a number.

  • At most one entry per worktree, keyed by worktree id.
  • Cleared by set (non-paying), delete and clear, the same teardown as its sibling maps.
  • When a pay happens under a pinned mark, the mark can keep one superseded shallow snapshot object alive per worktree until the next real change. Version-only bumps share the tabs array, so the extra memory is one small object per owed worktree: at most about 1,900 small objects at the bench's worktree count.
  • It does not grow with time or history. Not a finding.

Regression classes touched

Class Disposition
Update published when nothing changed Matched. The PR removes it: unread terminal-status bumps no longer build or send frames (bench: 2,399 → 0 frames per window). Owed versions are still paid when a frame is next built, so freshness holds.
Hidden or unheard owners keep working Matched. Improved: work is now gated on whether a listener reads the pane.
No-op store write returns new identities Matched. Improved: the renderer echo no longer stores a new snapshot object when no terminal-scoped listener exists.
Sync fs or SQLite on Electron main Matched. Improved: one cached statement replaces a cached one plus an uncached PRAGMA prepare.
Re-reading unchanged input Matched. Improved: the peer fingerprint is memoized by key.
Per-entity state outlives the entity Matched (deliveryMarks). Disproved: deleted in the same delete/clear as owedVersions.
Hot-path rescans Matched (listener Set scan per event). Disproved: the population is a few listeners, independent of fleet size.
Fixed-cadence poll / new idle wakeups No matching code. No new timer, interval or IPC. Heartbeat scheduling is only narrowed. Author bench: idle 0.2 msg/s out and 0.4 in, unchanged.
Expensive code past a gate No gate is removed or loosened. The new gate is stricter, and unscoped callers keep base behavior.
Eager startup imports No matching code. The new imports are type-only or small shared modules that were already on the graph.

Six questions

  1. Unused work before the skip gate: Reviewed. The gate now runs before oweVersion and before scheduling or building a frame. The remaining pre-gate work is O(1) per event.
  2. Ownership multiplying work: Reviewed. Frames per hook event went from one per listener (including the chat-only renderer) to zero for chat-only windows. The added check runs once per event or batch, not once per worktree or listener.
  3. Thread and storage paying: Reviewed. All on Electron main. SQLite work per sender publication is reduced (above).
  4. Growth and progress: Reviewed. Owed bumps are still paid at the next frame build (settleOwedMobileSessionSnapshotVersion). deliveryMarks is bounded per worktree.
  5. Execution host: Not applicable. No platform, SSH or subprocess code changed. Remote and mobile clients keep the unscoped default.
  6. Obsolete work stops: Reviewed. Scope lives on the subscription and dies with it. No new resources or timers.

Evidence classes

  • Source-proven counts (this review): the work-per-event changes above.

  • Benchmark (author-reported): see the status comment.

@brennanb2025
brennanb2025 marked this pull request as draft November 28, 2026 02:07
@brennanb2025
brennanb2025 marked this pull request as ready for review November 28, 2026 02:07
@brennanb2025

Copy link
Copy Markdown
Contributor Author

Review loop status (head cea4ba3, main merged once; behavioral head f58492a)

  • Regression audit (blinded, diff + one-line purpose): SAFE on f58492a. It found no dormant or flag-gated code made to run for everyone. The added work is a scan of the connected subscribers per hook event, not of the workspace list.
  • Reviews: Claude found no bugs on f58492a. Codex found one missed-update case across two rounds (a skipped status bump retired a queued chat frame); fixed in 5d21220 and f58492a, with a test that fails without the fix. Codex confirmed it resolved.
  • Perf: a fresh perf-scan reviewer reported clean (comment above, surfaces hot-path and subscribe).
  • Reference check: subscribers declare the scope they read and the producer computes only for subscribers that need it. This is the standard listen-with-scope / produce-on-first-interested-listener pattern.
  • QA: real app at ~1,900 workspaces, 2 runs each of base and this change; the build is product-identical to f58492a.

Benchmark: name=hook-stream head=f58492a0d46 gate=PASS corpus=1,901 workspaces, hidden window, 2,400 Claude hook events over 10 terminal panes per 120 s; command=pnpm perf:fleet-gate --scenarios streaming,idle,tabsproof --runs 2; main busy 3.72/3.56 s -> 2.97/2.33 s per 120 s; tabs frames to the window 2,399 -> 0 (about 14 MB -> 0 bytes); main->window messages 43.5 -> 23.5/s; time in the tab republish and sender pass about 590 ms -> 0 ms; longest main stall 128/88 -> 90/90 ms; idle unchanged (0.2 msg/s out, 0.4 in).
Benchmark: name=tabs-delivery head=f58492a0d46 gate=PASS an unscoped session.tabs.subscribeAll listener (what phones and paired desktops use) received 60 updates for 60 hook events, 50 carrying tool status, identical before and after.

@coderabbitai

coderabbitai Bot commented Nov 28, 2026 •

Copy link
Copy Markdown
Contributor

Explain Change →

No actionable comments were generated in the recent review.

Walkthrough

Session-tab subscriptions now support an optional agent-sessions scope. Status updates use pane-specific listener checks and can record unpublished snapshot versions. The change also combines agent-sender generation counters with the database data version in one query, and caches peer fingerprints by key.

Merge Risk: Minimal · up to ed242 · assessed changes only

Path filters excluded changed files. This rating applies only to the assessed changes.

Pre-merge checks: Passed 4

Check name Status Explanation
Title check Passed The title names the main change: skipping the tab list rebuild on each terminal agent step when only the desktop window listens. The changeset gates tab frame construction and delivery on terminal-tab…
Linked Issues check Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check Passed Check skipped because no linked issues were found for this pull request.
Description check Passed The description is thorough and follows the repository template. It includes the ELI5, What Changed, Why, Visual Proof (N/A with reason), Testing with a benchmark table, Performance, Risk with level a…
Full details: Title check

Explanation

The title names the main change: skipping the tab list rebuild on each terminal agent step when only the desktop window listens. The changeset gates tab frame construction and delivery on terminal-tab listeners, so the title matches the primary change. It is a long single sentence (99 characters) but still specific and accurate.

Full details: Description check

Explanation

The description is thorough and follows the repository template. It includes the ELI5, What Changed, Why, Visual Proof (N/A with reason), Testing with a benchmark table, Performance, Risk with level and back-out plan, and the checklist. The Linked Issue section says 'Internal perf work; no issue.' The template asks for 'Fixes #' or an existing issue. Maintainers may attach an existing issue, so this is a minor gap. The AI Disclosure and Review sections are empty. The Performance line is filled in. The Testing section gives a manual test note and a benchmark. It does not list the platforms tested beyond Linux, and the SSH and Mobile testing is not stated. The Risk section names the riskiest part and gives the revert plan. The 'Agent skill upstream boundary' box is checked.

  • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

Share

Recent review info

Run configuration

  • Source mode: Auto
  • Repository: Unavailable
  • Branch: Unavailable
  • File: No configuration file from this repository applied
  • Commit: Unavailable
  • Layers: Repository UI
  • Review profile: CHILL
  • Plan: Advanced
  • Run ID: 6f248ab0-3340-4083-8b69-6c4ab46a7381
Commits

Reviewing files that changed from the base of the PR and between cea4ba3 and ed242f0.

Files selected for processing: 3

  • src/main/runtime/session-tabs/restoration/mobile-session-membership.ts
  • src/main/runtime/session-tabs/restoration/mobile-session-status-touch.test.ts
  • src/main/runtime/session-tabs/restoration/mobile-session-status-touch.ts

Included review availability: This review used your included allowance. Your plan provides up to 10 included reviews per hour; 0 remain after this review.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

Review info

Run configuration

  • Source mode: Auto
  • Repository: Unavailable
  • Branch: Unavailable
  • File: No configuration file from this repository applied
  • Commit: Unavailable
  • Layers: Repository UI
  • Review profile: CHILL
  • Plan: Advanced
  • Run ID: db0733b2-aa2c-41c9-8376-ef5abb3bb663
Commits

Reviewing files that changed from the base of the PR and between ea95a40 and cea4ba3.

Files ignored due to path filters: 1

  • src/shared/rpc-contract/rpc-params-catalog.generated.ts is excluded by !**/*.generated.*
Files selected for processing: 15

  • src/main/agent-hooks/runtime/hook-status-session-tabs-republish.ts
  • src/main/runtime/agent-senders/runtime-agent-sender-history-triggers.ts
  • src/main/runtime/construction/mobile-session-tab-subscription.ts
  • src/main/runtime/construction/runtime-agent-projections.ts
  • src/main/runtime/construction/runtime-identity-state.ts
  • src/main/runtime/rpc/methods/session-tabs/session-tabs-inventory.ts
  • src/main/runtime/rpc/methods/session-tabs/session-tabs.ts
  • src/main/runtime/session-graph/session-window-publisher.ts
  • src/main/runtime/session-tabs/publication/mobile-session-snapshots-by-worktree.ts
  • src/main/runtime/session-tabs/publication/mobile-session-tab-subscriptions.ts
  • src/main/runtime/session-tabs/publication/mobile-session-tabs-delivery.test.ts
  • src/main/runtime/session-tabs/restoration/mobile-session-membership.ts
  • src/renderer/src/runtime/local-structured-session-tabs-sync/subscription.ts
  • src/shared/agent-session/view/structured-agent-session-projection.ts
  • src/shared/rpc-contract/session-tabs/session-tabs-params.ts

Included review availability: This review used your included allowance. Your plan provides up to 10 included reviews per hour; 0 remain after this review.

@brennanb2025

Copy link
Copy Markdown
Contributor Author

Perf scan: PR #51247 (hook status scoped to session-tab listeners)

  • Head: ed242f0210b. Span: git diff c9961067c44 f58492a0d46 (5 commits) plus ed242f0210b. Merge cea4ba38969 excluded.
  • Surfaces: hot-path (hook status → session-tabs publication on Electron main), subscribe (session.tabs.subscribeAll scope param, listener selection).
  • Method: static trace of target-ref code. No builds, tests or runtime on this machine. Author benchmark weighed as reported evidence only.

Findings

None at P0/P1. The PR removes work. It does not add or amplify any.

Hot-path trace

  1. Hook row mutation (hook-status-session-tabs-republish.ts:33-53)

    • Trigger: every hook status row change. At the reference fleet that is 100+ agents, above 1/s and up to ~10/s.
    • Work per event before: one Set of at most 2 worktrees, then a touch for each.
    • Work per event now: a Map<worktree, paneKey[]> with at most 2 entries and at most 2 small array spreads, then touchMobileSessionTabsForWorktree(wt, { statusPaneKeys }).
    • In the touch (mobile-session-membership.ts:73-83), hasPaneStatusListeners runs for at most 2 pane keys. It does a prefix startsWith, then either a size check or hasTerminalStatusListeners().
    • hasTerminalStatusListeners() (mobile-session-tab-subscriptions.ts:111) is O(L) over the session-tab listeners and stops at the first unscoped one. L is one per window, plus each mobile or remote stream and the WSL agent-awake stream: tens at most. L does not grow with worktrees, terminals, agents or history. At 10/s × 2 keys × L≈20 that is about 400 field reads/s, which is negligible.
    • Work saved: when only chat-scoped listeners are attached (the local renderer's default), a terminal pane's status no longer runs oweVersion + scheduleMobileSessionTabsChanged. That means no per-worktree frame build (snapshot projection, agent-sender buildForFrame including the SQLite generation read) and no main→renderer IPC frame. Before, the renderer received and discarded those frames.
    • Price before: one frame per terminal status event per window. At 10/s this was about 10 frames/s of wasted serialization and IPC.
    • Price now: 0 for terminal-only status. Chat status and unscoped listeners are unchanged.
    • Author evidence: 2,399 → 0 subscription frames per window, IPC 43.5 → 23.5 msg/s, main busy time down.
  2. Freshness heartbeat (hook-status-session-tabs-republish.ts:55-63, mobile-session-membership.ts:116-127)

    • Same per-event gate. Terminal pane freshness no longer schedules a worktree heartbeat when no terminal listener exists.
    • ed242f0210b moves observeWorktreeRefresh so that it runs only when a frame is actually scheduled (mobile-session-status-touch.ts). A skipped terminal touch therefore no longer cancels a pending chat heartbeat. That heartbeat then fires once.
    • This adds no timer. The heartbeat queue is bounded by scheduleWorktreeHeartbeat's interval gate (AGENT_STATUS_STALE_AFTER_MS/2 per worktree) and 50 ms global spacing. It is armed only by status-driven freshness, never at idle.
    • Base vs head for the chat-listener-only case:
      • Base: a terminal touch built a full frame and also suppressed the chat heartbeat.
      • Head: no terminal frame, and at most one chat heartbeat frame per worktree per half lease.
      • Net frames go down.
  3. Renderer status echo (session-window-publisher.ts:25-41)

    • Trigger: each renderer status batch.
    • Change: one hasTerminalStatusListeners() per batch, not per worktree. With no terminal listener, it calls oweUnpublishedVersion for each worktree in the batch and does not rebuild and store the snapshot or schedule a frame.
    • Work is O(worktrees in batch), the same as before but cheaper per item.
  4. Owed or unpublished versions (mobile-session-snapshots-by-worktree.ts:48-55)

    • owedVersions is a set keyed by worktree, and an add is idempotent.
    • deliveryMarks may now hold a snapshot reference rather than a number. That reference is the current snapshot, so there is no extra retention until a paying store replaces it. After that it retains one superseded snapshot shell per worktree. Version-only bumps reuse tabs, so the shell is small.
    • The mark is cleared on the next non-paying set, on delete and on clear. It is bounded by worktree count and does not grow with events or time.
    • A later payment is at most one store per owed worktree, made when a frame is next built. This matches base behaviour with zero listeners.
  5. Sender generation read (runtime-agent-sender-history-triggers.ts:92-111)

    • Reached on every sender refresh, that is on every frame build with senders.
    • Before: one cached SELECT plus a PRAGMA data_version that is never cached (sync-database.ts:30, isStatementCacheable excludes PRAGMA), so it was re-prepared on each call.
    • Now: one cached statement that uses pragma_data_version.
    • This is an improvement on main-thread SQLite: one fewer prepare and execute per refresh.
  6. Peer fingerprint (runtime-agent-projections.ts:46-56)

    • SHA-256 of the peer key is now memoized by key. fingerprintOrchestrationPeer is a pure function of the key (environment-transport.ts:52), so the cache is correct and removes one hash per sender refresh.

Subscribe trace

  • session.tabs.subscribeAll now accepts { scope?: 'agent-sessions' } | null | undefined. Only the local structured-session sync (subscription.ts:88) passes the scope.
  • Unscoped consumers keep their base behaviour and cost: web session sync, the remote or mobile relay, the WSL agent-awake stream and runtime-environment streams.
  • scope is a field on the subscription object, so it is released when the subscription is deleted. No new per-entity registry is created.
  • Listener selection (selectMobileSessionTabsListeners) is unchanged. A frame built for a chat change still goes to every listener, as before.
  • The author's control (60/60 updates with an unscoped listener, before and after) is consistent with the code: an unscoped listener makes hasTerminalStatusListeners() true, which restores the base path.

Regression classes touched

Class Disposition
Update published when nothing changed Matched, and the PR fixes it: frames that no listener reads are no longer built. A real change for a terminal listener still publishes, per the code and the author's control.
Per-row derivation per write Matched and disproved: the new per-event gate is O(listeners), not O(worktrees, terminals or agents).
Fixed-cadence poll / new idle wakeups No new timer, interval or subscription. The heartbeat path is unchanged except that a skipped touch no longer cancels it, and it stays bounded by the per-worktree interval and global spacing. Idle wakeups/s per process: base 0 from this path, head 0. The author reports idle unchanged.
Hidden or unheard owners keep working Matched, and the PR fixes it: frames for terminal status that no listener reads are no longer built.
Per-entity state outlives entity deliveryMarks and owedVersions are cleared in delete/clear with the snapshot. No new maps.
Sync SQLite on main Changed the statement shape only. Fewer prepares per refresh.
Expensive code past a removed gate No gate was loosened. All changed gates are stricter.

Six questions

  1. Unused work before the skip gate: reviewed. The gate now runs before oweVersion and before frame scheduling, so no frame is built. The only work left before it is the worktree lookup and an O(L) listener check.
  2. Ownership multiplies work: reviewed. There is one listener set per runtime, and scope is per subscription. Nothing new is created per pane, row or worktree.
  3. Thread and storage: reviewed. All of this work is on Electron main. SQLite work goes down (one cached statement replaces a statement plus an uncached PRAGMA). Hashing goes down.
  4. Growth and progress: reviewed. Owed state is bounded by worktree count and paid once when the next frame is built. Payment is unchanged from base with zero listeners.
  5. Execution host: remote, WSL and mobile streams are unscoped and keep the base path. No host probes were added. Behaviour on Windows, Linux and SSH is not measured here.
  6. Obsolete work stops: reviewed. Listener removal drops the scope with the subscription. Worktree delete clears the marks. The heartbeat keeps its removeWorktree/cancelPending/dispose cleanup.

Pre-existing (not a regression of this span)

  • PTY title, foreground and bind touches (pty-backed-session-publication.ts:193-205) and title-authority republishes call touchMobileSessionTabsForWorktree without statusPaneKeys. They therefore still build frames for chat-scoped listeners whenever any listener exists. Rate: once per terminal title change per worktree that holds that PTY, coalesced per client frame. This was already present at base, and this PR neither adds nor removes it. It is a candidate for the same scoping if terminal title churn turns out to be significant at fleet scale. Unmeasured.

Evidence classes

  • Source-proven counts: all items above.
  • Author-reported, on a product-identical build of f58492a0d46, not the exact head: IPC 43.5 → 23.5 msg/s, 2,399 → 0 frames per window, main busy time down, idle unchanged, unscoped control 60/60. The run on the exact head was still in progress. ed242f0210b only reorders the heartbeat refresh mark and can at most add one bounded chat heartbeat frame per worktree per half lease.
  • Not measured on this machine: wall-clock or CPU numbers, and Windows, WSL and SSH hosts.

@brennanb2025

Copy link
Copy Markdown
Contributor Author

Review loop status (head ed242f0)

  • New since the last status: CodeRabbit found that a skipped terminal-status touch still counted as a refresh, which could cancel a pending chat heartbeat. Fixed in ed242f0 (the refresh is recorded only when the touch publishes), with a test that fails without the fix. The thread is resolved.
  • Regression audit (blinded, diff + one-line purpose) on ed242f0: SAFE. It found no dormant or flag-gated code made to run for everyone. A delta Codex check of the fix: SAFE.
  • Reviews: Claude found no bugs (f58492a). Codex covered every repair through ed242f0.
  • Perf: a fresh perf-scan reviewer reported clean on ed242f0 (comment above, surfaces hot-path and subscribe).
  • Reference check: subscribers declare the scope they read, and the producer computes only for subscribers that need it.
  • QA: real app at ~1,900 workspaces, 2 runs each of base and this change. The build is product-identical to ed242f0.

Benchmark: name=hook-stream head=ed242f0210b gate=PASS corpus=1,901 workspaces, hidden window, 2,400 Claude hook events over 10 terminal panes per 120 s; command=pnpm perf:fleet-gate --scenarios streaming,idle,tabsproof --runs 2; main busy 5.22/4.45 s -> 2.60/2.38 s per 120 s; tabs frames to the window 3,715/3,642 -> 0; main->window messages 54.1 -> 23.5/s; longest main stall 85/87 -> 87/94 ms; idle unchanged (0.2 msg/s out, 0.4 in; busy 0.49/0.55 -> 0.62/0.47 s).
Benchmark: name=tabs-delivery head=ed242f0210b gate=PASS an unscoped session.tabs.subscribeAll listener (what phones and paired desktops use) received 60 updates for 60 hook events, 50 carrying tool status, identical before and after.

@brennanb2025

Copy link
Copy Markdown
Contributor Author

Perf scan: PR #51247 (hook status scoped to session-tab listeners)

  • Head: ed242f0210b. Span: git diff c9961067c44 f58492a0d46 (5 commits) plus ed242f0210b. Merge cea4ba38969 excluded.
  • Surfaces: hot-path (hook status → session-tabs publication on Electron main), subscribe (session.tabs.subscribeAll scope param, listener selection), publish (the frame schedule at mobile-session-membership.ts:80 inside touchMobileSessionStatus, from ed242f0210b).
  • Method: static trace of target-ref code. No builds, tests or runtime on this machine. Author benchmark weighed as reported evidence only.

Findings

None at P0/P1. The PR removes work. It does not add or amplify any.

Hot-path trace

  1. Hook row mutation (hook-status-session-tabs-republish.ts:33-53)

    • Trigger: every hook status row change. At the reference fleet that is 100+ agents, above 1/s and up to ~10/s.
    • Work per event before: one Set of at most 2 worktrees, then a touch for each.
    • Work per event now: a Map<worktree, paneKey[]> with at most 2 entries and at most 2 small array spreads, then touchMobileSessionTabsForWorktree(wt, { statusPaneKeys }).
    • In the touch (mobile-session-membership.ts:73-83), hasPaneStatusListeners runs for at most 2 pane keys. It does a prefix startsWith, then either a size check or hasTerminalStatusListeners().
    • hasTerminalStatusListeners() (mobile-session-tab-subscriptions.ts:111) is O(L) over the session-tab listeners and stops at the first unscoped one. L is one per window, plus each mobile or remote stream and the WSL agent-awake stream: tens at most. L does not grow with worktrees, terminals, agents or history. At 10/s × 2 keys × L≈20 that is about 400 field reads/s, which is negligible.
    • Work saved: when only chat-scoped listeners are attached (the local renderer's default), a terminal pane's status no longer runs oweVersion + scheduleMobileSessionTabsChanged. That means no per-worktree frame build (snapshot projection, agent-sender buildForFrame including the SQLite generation read) and no main→renderer IPC frame. Before, the renderer received and discarded those frames.
    • Price before: one frame per terminal status event per window. At 10/s this was about 10 frames/s of wasted serialization and IPC.
    • Price now: 0 for terminal-only status. Chat status and unscoped listeners are unchanged.
    • Author evidence: 2,399 → 0 subscription frames per window, IPC 43.5 → 23.5 msg/s, main busy time down.
  2. Freshness heartbeat (hook-status-session-tabs-republish.ts:55-63, mobile-session-membership.ts:116-127)

    • Same per-event gate. Terminal pane freshness no longer schedules a worktree heartbeat when no terminal listener exists.
    • ed242f0210b moves observeWorktreeRefresh so that it runs only when a frame is actually scheduled (mobile-session-status-touch.ts). A skipped terminal touch therefore no longer cancels a pending chat heartbeat. That heartbeat then fires once.
    • This adds no timer. The heartbeat queue is bounded by scheduleWorktreeHeartbeat's interval gate (AGENT_STATUS_STALE_AFTER_MS/2 per worktree) and 50 ms global spacing. It is armed only by status-driven freshness, never at idle.
    • Base vs head for the chat-listener-only case:
      • Base: a terminal touch built a full frame and also suppressed the chat heartbeat.
      • Head: no terminal frame, and at most one chat heartbeat frame per worktree per half lease.
      • Net frames go down.
  3. Renderer status echo (session-window-publisher.ts:25-41)

    • Trigger: each renderer status batch.
    • Change: one hasTerminalStatusListeners() per batch, not per worktree. With no terminal listener, it calls oweUnpublishedVersion for each worktree in the batch and does not rebuild and store the snapshot or schedule a frame.
    • Work is O(worktrees in batch), the same as before but cheaper per item.
  4. Owed or unpublished versions (mobile-session-snapshots-by-worktree.ts:48-55)

    • owedVersions is a set keyed by worktree, and an add is idempotent.
    • deliveryMarks may now hold a snapshot reference rather than a number. That reference is the current snapshot, so there is no extra retention until a paying store replaces it. After that it retains one superseded snapshot shell per worktree. Version-only bumps reuse tabs, so the shell is small.
    • The mark is cleared on the next non-paying set, on delete and on clear. It is bounded by worktree count and does not grow with events or time.
    • A later payment is at most one store per owed worktree, made when a frame is next built. This matches base behaviour with zero listeners.
  5. Sender generation read (runtime-agent-sender-history-triggers.ts:92-111)

    • Reached on every sender refresh, that is on every frame build with senders.
    • Before: one cached SELECT plus a PRAGMA data_version that is never cached (sync-database.ts:30, isStatementCacheable excludes PRAGMA), so it was re-prepared on each call.
    • Now: one cached statement that uses pragma_data_version.
    • This is an improvement on main-thread SQLite: one fewer prepare and execute per refresh.
  6. Peer fingerprint (runtime-agent-projections.ts:46-56)

    • SHA-256 of the peer key is now memoized by key. fingerprintOrchestrationPeer is a pure function of the key (environment-transport.ts:52), so the cache is correct and removes one hash per sender refresh.

Subscribe trace

  • session.tabs.subscribeAll now accepts { scope?: 'agent-sessions' } | null | undefined. Only the local structured-session sync (subscription.ts:88) passes the scope.
  • Unscoped consumers keep their base behaviour and cost: web session sync, the remote or mobile relay, the WSL agent-awake stream and runtime-environment streams.
  • scope is a field on the subscription object, so it is released when the subscription is deleted. No new per-entity registry is created.
  • Listener selection (selectMobileSessionTabsListeners) is unchanged. A frame built for a chat change still goes to every listener, as before.
  • The author's control (60/60 updates with an unscoped listener, before and after) is consistent with the code: an unscoped listener makes hasTerminalStatusListeners() true, which restores the base path.

Publish trace

This covers mobile-session-membership.ts:80, schedule: (id) => this.scheduleMobileSessionTabsChanged(id) inside touchMobileSessionStatus (mobile-session-status-touch.ts).

Cadence and coalescing

  • scheduleMobileSessionTabsChanged (session-tabs-change-publication.ts:21) records a change sequence and calls mobileSessionTabsNotifyCoalescer.schedule(worktreeId).
  • The coalescer (mobile-session-tabs-notify-coalescer.ts) is a per-worktree trailing-edge timer: 50 ms flush and 250 ms max wait. Neither the PR nor ed242f0210b changes it.
  • Under a sustained burst, one worktree flushes at least once per 250 ms. It flushes about once per burst when events are spaced under 50 ms. Each flush is one notifyMobileSessionTabsChangedNow delivery pass over the selected listeners.

Base behaviour (c9961067c44, same method)

  • Every non-immediate status touch called observeWorktreeRefresh, then oweVersion, then scheduleMobileSessionTabsChanged whenever mobileSessionTabListeners.size > 0.

Head behaviour, schedule calls per hook event

Case Base Head
No listeners 0 0 (oweUnpublishedVersion only)
Only chat-scoped listeners, terminal pane status 1 0
Only chat-scoped listeners, chat pane status 1 1
Any unscoped listener (mobile, web, WSL, remote), any pane 1 1, the same calls in the same order: refresh mark, oweVersion, schedule
Mutation whose before/after pane keys straddle chat and terminal in one worktree 1 1, because some() is true
Touches without statusPaneKeys (titles, heartbeat emit, sender refresh, favicons) 1 if size > 0 1 if size > 0, unchanged
  • In every case, head listened implies base size > 0. Head schedule calls are therefore a subset of base schedule calls. Nothing publishes more often per hook event.

Heartbeat interaction (the one behaviour change in ed242f0210b)

  • A touch that is not listened to no longer calls observeWorktreeRefresh. A chat heartbeat already pending for that worktree therefore fires, where at base the terminal touch would have cancelled it.
  • The heartbeat emit is a plain touch, so it schedules at most one coalesced frame.
  • Bound: scheduleWorktreeHeartbeat skips a worktree refreshed within AGENT_STATUS_STALE_AFTER_MS / 2 = 15 min, and the emits are spaced at 50 ms globally. Under chat-scoped freshness that is at most 1 frame per worktree per 15 min.
  • Worst case at the reference fleet: about 750 worktrees ÷ 900 s ≈ 0.8 frames/s fleet-wide. At 10× it is about 8/s, and it is spread out by the 50 ms spacing.
  • The heartbeat is armed only by chat-pane freshness events. At head, terminal-pane freshness no longer arms it when listeners are chat-only.
  • For comparison, on the same worktree base sent one coalesced frame per terminal status burst, at up to 4/s per worktree under sustained churn. The heartbeat frame replaces many of those.
  • Net frames per worktree go down. The surviving heartbeat frame is the necessary one: without it a chat status reaches its stale lease unrefreshed.
  • With no hook activity, nothing arms the heartbeat or the coalescer. Idle wakeups stay at 0/s.

Renderer echo path (session-window-publisher.ts:41)

  • It still schedules only when hasTerminalStatusListeners() is true. Otherwise it owes the version without scheduling. Head schedule calls are a subset of base.

Disposition: matched for "update published when nothing changed" and "fixed cadence that never settles", and disproved. Frames per hook event at head are at most those at base in every listener configuration. The coalescer bounds are unchanged. The only added frame source is the chat heartbeat, which is bounded to one frame per worktree per 15 min, is event-armed, and replaces frames that base built on every terminal status burst.

Regression classes touched

Class Disposition
Update published when nothing changed Matched, and the PR fixes it (see Publish trace for counts per event): frames that no listener reads are no longer built. A real change for a terminal listener still publishes, per the code and the author's control.
Per-row derivation per write Matched and disproved: the new per-event gate is O(listeners), not O(worktrees, terminals or agents).
Fixed-cadence poll / new idle wakeups No new timer, interval or subscription. The heartbeat path is unchanged except that a skipped touch no longer cancels it, and it stays bounded by the per-worktree interval and global spacing. Idle wakeups/s per process: base 0 from this path, head 0. The author reports idle unchanged.
Hidden or unheard owners keep working Matched, and the PR fixes it: frames for terminal status that no listener reads are no longer built.
Per-entity state outlives entity deliveryMarks and owedVersions are cleared in delete/clear with the snapshot. No new maps.
Sync SQLite on main Changed the statement shape only. Fewer prepares per refresh.
Expensive code past a removed gate No gate was loosened. All changed gates are stricter.

Six questions

  1. Unused work before the skip gate: reviewed. The gate now runs before oweVersion and before frame scheduling, so no frame is built. The only work left before it is the worktree lookup and an O(L) listener check.
  2. Ownership multiplies work: reviewed. There is one listener set per runtime, and scope is per subscription. Nothing new is created per pane, row or worktree.
  3. Thread and storage: reviewed. All of this work is on Electron main. SQLite work goes down (one cached statement replaces a statement plus an uncached PRAGMA). Hashing goes down.
  4. Growth and progress: reviewed. Owed state is bounded by worktree count and paid once when the next frame is built. Payment is unchanged from base with zero listeners.
  5. Execution host: remote, WSL and mobile streams are unscoped and keep the base path. No host probes were added. Behaviour on Windows, Linux and SSH is not measured here.
  6. Obsolete work stops: reviewed. Listener removal drops the scope with the subscription. Worktree delete clears the marks. The heartbeat keeps its removeWorktree/cancelPending/dispose cleanup.

Pre-existing (not a regression of this span)

  • PTY title, foreground and bind touches (pty-backed-session-publication.ts:193-205) and title-authority republishes call touchMobileSessionTabsForWorktree without statusPaneKeys. They therefore still build frames for chat-scoped listeners whenever any listener exists. Rate: once per terminal title change per worktree that holds that PTY, coalesced per client frame. This was already present at base, and this PR neither adds nor removes it. It is a candidate for the same scoping if terminal title churn turns out to be significant at fleet scale. Unmeasured.

Evidence classes

  • Source-proven counts: all items above.
  • Author-reported, on a product-identical build of f58492a0d46, not the exact head: IPC 43.5 → 23.5 msg/s, 2,399 → 0 frames per window, main busy time down, idle unchanged, unscoped control 60/60. The run on the exact head was still in progress. ed242f0210b only reorders the heartbeat refresh mark and can at most add one bounded chat heartbeat frame per worktree per half lease.
  • Not measured on this machine: wall-clock or CPU numbers, and Windows, WSL and SSH hosts.

@brennanb2025
brennanb2025 merged commit eae54a4 into main Nov 28, 2026
57 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant